├── .gitignore ├── .npmignore ├── .prettierignore ├── .travis.yml ├── LICENSE ├── README.md ├── __tests__ ├── h3.js ├── router.js ├── store.js └── vnode.js ├── babel.config.js ├── description ├── docs ├── CNAME ├── H3_DeveloperGuide.htm ├── H3_DeveloperGuide.md ├── css │ ├── mini-default.css │ ├── prism.css │ └── style.css ├── example │ ├── assets │ │ ├── css │ │ │ └── style.css │ │ └── js │ │ │ ├── app.js │ │ │ ├── components │ │ │ ├── AddTodoForm.js │ │ │ ├── EmptyTodoError.js │ │ │ ├── MainView.js │ │ │ ├── NavigationBar.js │ │ │ ├── Paginator.js │ │ │ ├── SettingsView.js │ │ │ ├── Todo.js │ │ │ └── TodoList.js │ │ │ ├── h3.js │ │ │ └── modules.js │ └── index.html ├── favicon.png ├── images │ ├── h3.sequence.svg │ └── h3.svg ├── index.html ├── js │ ├── app.js │ ├── h3.js │ └── vendor │ │ ├── marked.js │ │ └── prism.js └── md │ ├── about.md │ ├── api.md │ ├── best-practices.md │ ├── key-concepts.md │ ├── overview.md │ ├── quick-start.md │ └── tutorial.md ├── h3.js ├── h3.js.map ├── h3.min.js ├── jest.config.js ├── package-lock.json ├── package.json └── scripts ├── release.js └── test-setup.js /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | coverage 3 | *.tgz -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | docs/H3_DeveloperGuide.* 2 | *.tgz -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | *.md -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | language: node_js 3 | node_js: 4 | - '12' 5 | branches: 6 | only: 7 | - master 8 | cache: 9 | directories: 10 | - node_modules 11 | before_install: 12 | - npm update 13 | install: 14 | - npm install 15 | script: 16 | - npm run coveralls -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Fabio Cevasco 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | *** 7 | 8 | ## Overview 9 | 10 | **H3** is a microframework to build client-side single-page applications (SPAs) in modern JavaScript. 11 | 12 | H3 is also: 13 | 14 | - **tiny**, less than 4KB minified and gzipped. 15 | - **modern**, in the sense that it runs only in modern browsers (latest versions of Chrome, Firefox, Edge & similar). 16 | - **easy** to learn, its API is comprised of only seven methods and two properties. 17 | 18 | ### I'm sold! Where can I get it? 19 | 20 | Here, look, it's just one file: 21 | 22 | Download v0.11.0 (Keen Klingon) 23 | 24 | Or get the minified version here. 25 | 26 | Yes there is also a [NPM package](https://www.npmjs.com/package/@h3rald/h3) if you want to use it with WebPack and similar, but let me repeat: _it's just one file_. 27 | 28 | ### Hello, World? 29 | 30 | Here's an example of an extremely minimal SPA created with H3: 31 | 32 | ```js 33 | import { h3, h } from "./h3.js"; 34 | h3.init(() => h("h1", "Hello, World!")); 35 | ``` 36 | 37 | This will render a `h1` tag within the document body, containing the text `"Hello, World!"`. 38 | 39 | ### Something more complex? 40 | 41 | Have a look at the code of a [simple todo list](https://github.com/h3rald/h3/tree/master/docs/example) ([demo](https://h3.js.org/example/index.html)) with several components, a store and some routing. 42 | 43 | ### No, I meant a real web application... 44 | 45 | OK, have a look at [litepad.h3rald.com](https://litepad.h3rald.com) — it's a powerful notepad application that demonstrates how to create custom controls, route components, forms, and integrate third-party tools. The code is of course [on GitHub](https://github.com/h3rald/litepad). 46 | 47 | ### Can I use it then, no strings attached? 48 | 49 | Yes. It's [MIT-licensed](https://github.com/h3rald/h3/blob/master/LICENSE). 50 | 51 | ### What if something is broken? 52 | 53 | Go fix it! Or at least open an issue on the [Github repo](https://github.com/h3rald/h3), pleasy. 54 | 55 | ### Can I download a copy of all the documentation as a standalone HTML file? 56 | 57 | What a weird thing to ask... sure you can: [here](https://h3.js.org/H3_DeveloperGuide.htm)! 58 | -------------------------------------------------------------------------------- /__tests__/h3.js: -------------------------------------------------------------------------------- 1 | const mod = require("../h3.js"); 2 | const h3 = mod.h3; 3 | const h = mod.h; 4 | 5 | describe("h3", () => { 6 | beforeEach(() => { 7 | jest 8 | .spyOn(window, "requestAnimationFrame") 9 | .mockImplementation((cb) => cb()); 10 | }); 11 | 12 | afterEach(() => { 13 | window.requestAnimationFrame.mockRestore(); 14 | }); 15 | 16 | it("should support a way to discriminate functions and objects", () => { 17 | const v1 = h("div", { onclick: () => true }); 18 | const v2 = h("div", { onclick: () => true }); 19 | const v3 = h("div", { onclick: () => false }); 20 | const v4 = h("div"); 21 | expect(v1.equal(v2)).toEqual(true); 22 | expect(v1.equal(v3)).toEqual(false); 23 | expect(v4.equal({ type: "div" })).toEqual(false); 24 | expect(v1.equal(null, null)).toEqual(true); 25 | expect(v1.equal(null, undefined)).toEqual(false); 26 | }); 27 | 28 | it("should support the creation of empty virtual node elements", () => { 29 | expect(h("div")).toEqual({ 30 | type: "div", 31 | children: [], 32 | props: {}, 33 | classList: [], 34 | data: {}, 35 | eventListeners: {}, 36 | id: undefined, 37 | $html: undefined, 38 | style: undefined, 39 | value: undefined, 40 | }); 41 | }); 42 | 43 | it("should throw an error when invalid arguments are supplied", () => { 44 | const empty = () => h(); 45 | const invalid1st = () => h(1); 46 | const invalid1st2 = () => h(1, {}); 47 | const invalid1st3 = () => h(1, {}, []); 48 | const invalid1st1 = () => h(() => ({ type: "#text", value: "test" })); 49 | const invalid1st1b = () => h({ a: 2 }); 50 | const invalid2nd = () => h("div", 1); 51 | const invalid2nd2 = () => h("div", true, []); 52 | const invalid2nd3 = () => h("div", null, []); 53 | const invalidChildren = () => h("div", ["test", 1, 2]); 54 | const emptySelector = () => h(""); 55 | expect(empty).toThrowError(/No arguments passed/); 56 | expect(invalid1st).toThrowError(/Invalid first argument/); 57 | expect(invalid1st2).toThrowError(/Invalid first argument/); 58 | expect(invalid1st3).toThrowError(/Invalid first argument/); 59 | expect(invalid1st1).toThrowError(/does not return a VNode/); 60 | expect(invalid1st1b).toThrowError(/Invalid first argument/); 61 | expect(invalid2nd).toThrowError(/second argument of a VNode constructor/); 62 | expect(invalid2nd2).toThrowError(/Invalid second argument/); 63 | expect(invalid2nd3).toThrowError(/Invalid second argument/); 64 | expect(invalidChildren).toThrowError(/not a VNode: 1/); 65 | expect(emptySelector).toThrowError(/Invalid selector/); 66 | }); 67 | 68 | it("should support several child arguments", () => { 69 | let vnode = h("div", { test: "a" }, "a", "b", "c"); 70 | expect(vnode.children.length).toEqual(3); 71 | vnode = h("div", "a", "b", "c"); 72 | expect(vnode.children.length).toEqual(3); 73 | vnode = h("div", "a", "b"); 74 | expect(vnode.children.length).toEqual(2); 75 | }); 76 | 77 | it("should support the creation of elements with a single, non-array child", () => { 78 | const vnode1 = h("div", () => "test"); 79 | const vnode2 = h("div", () => h("span")); 80 | expect(vnode1.children[0].value).toEqual("test"); 81 | expect(vnode2.children[0].type).toEqual("span"); 82 | }); 83 | 84 | it("should remove null/false/undefined children", () => { 85 | const v1 = h("div", [false, "test", undefined, null, ""]); 86 | expect(v1.children).toEqual([ 87 | h({ type: "#text", value: "test" }), 88 | h({ type: "#text", value: "" }), 89 | ]); 90 | }); 91 | 92 | it("should support the creation of nodes with a single child node", () => { 93 | const result = { 94 | type: "div", 95 | children: [ 96 | { 97 | type: "#text", 98 | children: [], 99 | props: {}, 100 | classList: [], 101 | data: {}, 102 | eventListeners: {}, 103 | id: undefined, 104 | $html: undefined, 105 | style: undefined, 106 | value: "test", 107 | }, 108 | ], 109 | props: {}, 110 | classList: [], 111 | data: {}, 112 | eventListeners: {}, 113 | id: undefined, 114 | $html: undefined, 115 | style: undefined, 116 | value: undefined, 117 | }; 118 | expect(h("div", "test")).toEqual(result); 119 | const failing = () => h("***"); 120 | expect(failing).toThrowError(/Invalid selector/); 121 | }); 122 | 123 | it("should support the creation of virtual node elements with classes", () => { 124 | const a = h("div.a.b.c"); 125 | const b = h("div", { classList: ["a", "b", "c"] }); 126 | expect(a).toEqual({ 127 | type: "div", 128 | children: [], 129 | props: {}, 130 | classList: ["a", "b", "c"], 131 | data: {}, 132 | eventListeners: {}, 133 | id: undefined, 134 | $html: undefined, 135 | style: undefined, 136 | type: "div", 137 | value: undefined, 138 | }); 139 | expect(a).toEqual(b); 140 | }); 141 | 142 | it("should support the creation of virtual node elements with props and classes", () => { 143 | expect(h("div.test1.test2", { id: "test" })).toEqual({ 144 | type: "div", 145 | children: [], 146 | classList: ["test1", "test2"], 147 | data: {}, 148 | props: {}, 149 | eventListeners: {}, 150 | id: "test", 151 | $html: undefined, 152 | style: undefined, 153 | type: "div", 154 | value: undefined, 155 | }); 156 | }); 157 | 158 | it("should support the creation of virtual node elements with text children and classes", () => { 159 | expect(h("div.test", ["a", "b"])).toEqual({ 160 | type: "div", 161 | children: [ 162 | { 163 | props: {}, 164 | children: [], 165 | classList: [], 166 | data: {}, 167 | eventListeners: {}, 168 | id: undefined, 169 | $html: undefined, 170 | style: undefined, 171 | type: "#text", 172 | value: "a", 173 | }, 174 | { 175 | props: {}, 176 | children: [], 177 | classList: [], 178 | data: {}, 179 | eventListeners: {}, 180 | id: undefined, 181 | $html: undefined, 182 | style: undefined, 183 | type: "#text", 184 | value: "b", 185 | }, 186 | ], 187 | props: {}, 188 | classList: ["test"], 189 | data: {}, 190 | eventListeners: {}, 191 | id: undefined, 192 | $html: undefined, 193 | style: undefined, 194 | value: undefined, 195 | }); 196 | }); 197 | 198 | it("should support the creation of virtual node elements with text children, props, and classes", () => { 199 | expect(h("div.test", { title: "Test...", id: "test" }, ["a", "b"])).toEqual( 200 | { 201 | type: "div", 202 | children: [ 203 | { 204 | props: {}, 205 | children: [], 206 | classList: [], 207 | data: {}, 208 | eventListeners: {}, 209 | id: undefined, 210 | $html: undefined, 211 | style: undefined, 212 | type: "#text", 213 | value: "a", 214 | }, 215 | { 216 | props: {}, 217 | children: [], 218 | classList: [], 219 | data: {}, 220 | eventListeners: {}, 221 | id: undefined, 222 | $html: undefined, 223 | style: undefined, 224 | type: "#text", 225 | value: "b", 226 | }, 227 | ], 228 | data: {}, 229 | eventListeners: {}, 230 | id: "test", 231 | $html: undefined, 232 | style: undefined, 233 | value: undefined, 234 | props: { title: "Test..." }, 235 | classList: ["test"], 236 | } 237 | ); 238 | }); 239 | 240 | it("should support the creation of virtual node elements with props", () => { 241 | expect(h("input", { type: "text", value: "AAA" })).toEqual({ 242 | type: "input", 243 | children: [], 244 | data: {}, 245 | eventListeners: {}, 246 | id: undefined, 247 | $html: undefined, 248 | style: undefined, 249 | value: "AAA", 250 | props: { type: "text" }, 251 | classList: [], 252 | }); 253 | }); 254 | 255 | it("should support the creation of virtual node elements with event handlers", () => { 256 | const fn = () => true; 257 | expect(h("button", { onclick: fn })).toEqual({ 258 | type: "button", 259 | children: [], 260 | data: {}, 261 | eventListeners: { 262 | click: fn, 263 | }, 264 | id: undefined, 265 | $html: undefined, 266 | style: undefined, 267 | value: undefined, 268 | props: {}, 269 | classList: [], 270 | }); 271 | expect(() => h("span", { onclick: "something" })).toThrowError( 272 | /onclick event is not a function/ 273 | ); 274 | }); 275 | 276 | it("should support the creation of virtual node elements with element children and classes", () => { 277 | expect( 278 | h("div.test", ["a", h("span", ["test1"]), () => h("span", ["test2"])]) 279 | ).toEqual({ 280 | props: {}, 281 | type: "div", 282 | children: [ 283 | { 284 | props: {}, 285 | children: [], 286 | classList: [], 287 | data: {}, 288 | eventListeners: {}, 289 | id: undefined, 290 | $html: undefined, 291 | style: undefined, 292 | type: "#text", 293 | value: "a", 294 | }, 295 | { 296 | type: "span", 297 | children: [ 298 | { 299 | props: {}, 300 | children: [], 301 | classList: [], 302 | data: {}, 303 | eventListeners: {}, 304 | id: undefined, 305 | $html: undefined, 306 | style: undefined, 307 | type: "#text", 308 | value: "test1", 309 | }, 310 | ], 311 | props: {}, 312 | classList: [], 313 | data: {}, 314 | eventListeners: {}, 315 | id: undefined, 316 | $html: undefined, 317 | style: undefined, 318 | value: undefined, 319 | }, 320 | { 321 | type: "span", 322 | children: [ 323 | { 324 | props: {}, 325 | children: [], 326 | classList: [], 327 | data: {}, 328 | eventListeners: {}, 329 | id: undefined, 330 | $html: undefined, 331 | style: undefined, 332 | type: "#text", 333 | value: "test2", 334 | }, 335 | ], 336 | props: {}, 337 | classList: [], 338 | data: {}, 339 | eventListeners: {}, 340 | id: undefined, 341 | $html: undefined, 342 | style: undefined, 343 | value: undefined, 344 | }, 345 | ], 346 | classList: ["test"], 347 | data: {}, 348 | eventListeners: {}, 349 | id: undefined, 350 | $html: undefined, 351 | style: undefined, 352 | value: undefined, 353 | }); 354 | }); 355 | 356 | it("should not allow certain methods and properties to be called/accessed before initialization", () => { 357 | const route = () => h3.route; 358 | const state = () => h3.state; 359 | const redraw = () => h3.redraw(); 360 | const dispatch = () => h3.dispatch(); 361 | const on = () => h3.on(); 362 | const navigateTo = () => h3.navigateTo(); 363 | expect(route).toThrowError(/No application initialized/); 364 | expect(state).toThrowError(/No application initialized/); 365 | expect(redraw).toThrowError(/No application initialized/); 366 | expect(dispatch).toThrowError(/No application initialized/); 367 | expect(on).toThrowError(/No application initialized/); 368 | expect(navigateTo).toThrowError(/No application initialized/); 369 | }); 370 | 371 | it("should provide an init method to initialize a SPA with a single component", async () => { 372 | const c = () => h("div", "Hello, World!"); 373 | const body = document.body; 374 | const appendChild = jest.spyOn(body, "appendChild"); 375 | await h3.init(c); 376 | expect(appendChild).toHaveBeenCalled(); 377 | expect(body.childNodes[0].childNodes[0].data).toEqual("Hello, World!"); 378 | }); 379 | 380 | it("should provide some validation at initialization time", async () => { 381 | try { 382 | await h3.init({ element: "INVALID", routes: {} }); 383 | } catch (e) { 384 | expect(e.message).toMatch(/Invalid element/); 385 | } 386 | try { 387 | await h3.init({ element: document.body }); 388 | } catch (e) { 389 | expect(e.message).toMatch(/not a valid configuration object/); 390 | } 391 | try { 392 | await h3.init({ element: document.body, routes: {} }); 393 | } catch (e) { 394 | expect(e.message).toMatch(/No routes/); 395 | } 396 | }); 397 | 398 | it("should expose a redraw method", async () => { 399 | const vnode = h("div"); 400 | await h3.init(() => vnode); 401 | jest.spyOn(vnode, "redraw"); 402 | h3.redraw(); 403 | expect(vnode.redraw).toHaveBeenCalled(); 404 | h3.redraw(true); 405 | h3.redraw(); 406 | h3.redraw(); 407 | expect(vnode.redraw).toHaveBeenCalledTimes(2); 408 | }); 409 | 410 | it("should not redraw while a other redraw is in progress", async () => { 411 | const vnode = h("div"); 412 | await h3.init({ 413 | routes: { 414 | "/": () => vnode, 415 | }, 416 | }); 417 | jest.spyOn(vnode, "redraw"); 418 | h3.redraw(true); 419 | h3.redraw(); 420 | expect(vnode.redraw).toHaveBeenCalledTimes(1); 421 | }); 422 | 423 | it("should expose a screen method to define screen-level components with (optional) setup and teardown", async () => { 424 | expect(() => h3.screen({})).toThrowError(/No display property specified/); 425 | expect(() => h3.screen({ setup: 1, display: () => "" })).toThrowError( 426 | /setup property is not a function/ 427 | ); 428 | expect(() => h3.screen({ teardown: 1, display: () => "" })).toThrowError( 429 | /teardown property is not a function/ 430 | ); 431 | let s = h3.screen({ display: () => "test" }); 432 | expect(typeof s).toEqual("function"); 433 | s = h3.screen({ 434 | display: () => "test", 435 | setup: (state) => state, 436 | teardown: (state) => state, 437 | }); 438 | expect(typeof s.setup).toEqual("function"); 439 | expect(typeof s.teardown).toEqual("function"); 440 | }); 441 | }); 442 | -------------------------------------------------------------------------------- /__tests__/router.js: -------------------------------------------------------------------------------- 1 | const mod = require('../h3.js'); 2 | const h3 = mod.h3; 3 | const h = mod.h; 4 | 5 | let preStartCalled = false; 6 | let postStartCalled = false; 7 | let count = 0; 8 | let result = 0; 9 | 10 | const setCount = () => { 11 | count = count + 2; 12 | h3.dispatch('count/set', count); 13 | }; 14 | let hash = '#/c2'; 15 | const mockLocation = { 16 | get hash() { 17 | return hash; 18 | }, 19 | set hash(value) { 20 | const event = new CustomEvent('hashchange'); 21 | event.oldURL = hash; 22 | event.newURL = value; 23 | hash = value; 24 | window.dispatchEvent(event); 25 | }, 26 | }; 27 | const C1 = () => { 28 | const parts = h3.route.parts; 29 | const content = Object.keys(parts).map((key) => h('li', `${key}: ${parts[key]}`)); 30 | return h('ul.c1', content); 31 | }; 32 | 33 | const C2 = () => { 34 | const params = h3.route.params; 35 | const content = Object.keys(params).map((key) => h('li', `${key}: ${params[key]}`)); 36 | return h('ul.c2', content); 37 | }; 38 | 39 | describe('h3 (Router)', () => { 40 | beforeEach(async () => { 41 | const preStart = () => (preStartCalled = true); 42 | const postStart = () => (postStartCalled = true); 43 | await h3.init({ 44 | routes: { 45 | '/c1/:a/:b/:c': C1, 46 | '/c2': C2, 47 | }, 48 | location: mockLocation, 49 | preStart: preStart, 50 | postStart: postStart, 51 | }); 52 | }); 53 | 54 | it('should support routing configuration at startup', () => { 55 | expect(h3.route.def).toEqual('/c2'); 56 | }); 57 | 58 | it('should support pre/post start hooks', () => { 59 | expect(preStartCalled).toEqual(true); 60 | expect(postStartCalled).toEqual(true); 61 | }); 62 | 63 | it('should support the capturing of parts within the current route', (done) => { 64 | const sub = h3.on('$redraw', () => { 65 | expect(document.body.childNodes[0].childNodes[1].textContent).toEqual('b: 2'); 66 | sub(); 67 | done(); 68 | }); 69 | mockLocation.hash = '#/c1/1/2/3'; 70 | }); 71 | 72 | it('should expose a navigateTo method to navigate to another path', (done) => { 73 | const sub = h3.on('$redraw', () => { 74 | expect(document.body.childNodes[0].childNodes[1].textContent).toEqual('test2: 2'); 75 | sub(); 76 | done(); 77 | }); 78 | h3.navigateTo('/c2', { test1: 1, test2: 2 }); 79 | }); 80 | 81 | it('should throw an error if no route matches', async () => { 82 | try { 83 | await h3.init({ 84 | element: document.body, 85 | routes: { 86 | '/c1/:a/:b/:c': () => h('div'), 87 | '/c2': () => h('div'), 88 | }, 89 | }); 90 | } catch (e) { 91 | expect(e.message).toMatch(/No route matches/); 92 | } 93 | }); 94 | 95 | it('should execute setup and teardown methods', (done) => { 96 | let redraws = 0; 97 | C1.setup = (cstate) => { 98 | cstate.result = cstate.result || 0; 99 | cstate.sub = h3.on('count/set', (state, count) => { 100 | cstate.result = count * count; 101 | }); 102 | }; 103 | C1.teardown = (cstate) => { 104 | cstate.sub(); 105 | result = cstate.result; 106 | return { result: cstate.result }; 107 | }; 108 | const sub = h3.on('$redraw', () => { 109 | redraws++; 110 | setCount(); 111 | setCount(); 112 | if (redraws === 1) { 113 | expect(count).toEqual(4); 114 | expect(result).toEqual(0); 115 | h3.navigateTo('/c2'); 116 | } 117 | if (redraws === 2) { 118 | expect(count).toEqual(8); 119 | expect(result).toEqual(16); 120 | delete C1.setup; 121 | delete C1.teardown; 122 | sub(); 123 | done(); 124 | } 125 | }); 126 | h3.navigateTo('/c1/a/b/c'); 127 | }); 128 | 129 | it('should not navigate if setup method returns false', (done) => { 130 | let redraws = 0; 131 | const oldroute = h3.route; 132 | C1.setup = () => { 133 | return false; 134 | }; 135 | h3.on('$navigation', (state, data) => { 136 | expect(data).toEqual(null); 137 | expect(h3.route).toEqual(oldroute); 138 | done(); 139 | }); 140 | h3.navigateTo('/c1/a/b/c'); 141 | }); 142 | }); 143 | -------------------------------------------------------------------------------- /__tests__/store.js: -------------------------------------------------------------------------------- 1 | const mod = require("../h3.js"); 2 | const h3 = mod.h3; 3 | const h = mod.h; 4 | 5 | describe("h3 (Store)", () => { 6 | beforeEach(async () => { 7 | const test = () => { 8 | h3.on("$init", () => ({ online: true })); 9 | h3.on("$stop", () => ({ online: false })); 10 | h3.on("online/set", (state, data) => ({ online: data })); 11 | }; 12 | return await h3.init({ 13 | modules: [test], 14 | routes: { "/": () => h("div") }, 15 | }); 16 | }); 17 | 18 | afterEach(() => { 19 | h3.dispatch("$stop"); 20 | }); 21 | 22 | it("should expose a method to retrieve the application state", () => { 23 | expect(h3.state.online).toEqual(true); 24 | }); 25 | 26 | it("should expose a method to dispatch messages", () => { 27 | expect(h3.state.online).toEqual(true); 28 | h3.dispatch("online/set", "YEAH!"); 29 | expect(h3.state.online).toEqual("YEAH!"); 30 | }); 31 | 32 | it("should expose a method to subscribe to messages (and also cancel subscriptions)", () => { 33 | const sub = h3.on("online/clear", () => ({ online: undefined })); 34 | h3.dispatch("online/clear"); 35 | expect(h3.state.online).toEqual(undefined); 36 | h3.dispatch("online/set", "reset"); 37 | expect(h3.state.online).toEqual("reset"); 38 | sub(); 39 | h3.dispatch("online/clear"); 40 | expect(h3.state.online).toEqual("reset"); 41 | }); 42 | }); 43 | -------------------------------------------------------------------------------- /__tests__/vnode.js: -------------------------------------------------------------------------------- 1 | const mod = require('../h3.js'); 2 | const h3 = mod.h3; 3 | const h = mod.h; 4 | 5 | describe('VNode', () => { 6 | it('should provide a from method to initialize itself from an object', () => { 7 | const fn = () => true; 8 | const obj = { 9 | id: 'test', 10 | type: 'input', 11 | value: 'AAA', 12 | $html: '', 13 | data: { a: '1', b: '2' }, 14 | eventListeners: { click: fn }, 15 | children: [], 16 | props: { title: 'test' }, 17 | classList: ['a1', 'a2'], 18 | style: 'padding: 2px', 19 | }; 20 | const vnode1 = h('br'); 21 | vnode1.from(obj); 22 | const vnode2 = h('input#test.a1.a2', { 23 | value: 'AAA', 24 | $html: '', 25 | data: { a: '1', b: '2' }, 26 | onclick: fn, 27 | title: 'test', 28 | style: 'padding: 2px', 29 | }); 30 | expect(vnode1).toEqual(vnode2); 31 | }); 32 | 33 | it('should provide a render method able to render textual nodes', () => { 34 | const createTextNode = jest.spyOn(document, 'createTextNode'); 35 | const vnode = h({ type: '#text', value: 'test' }); 36 | const node = vnode.render(); 37 | expect(createTextNode).toHaveBeenCalledWith('test'); 38 | expect(node.constructor).toEqual(Text); 39 | }); 40 | 41 | it('should provide a render method able to render simple element nodes', () => { 42 | const createElement = jest.spyOn(document, 'createElement'); 43 | const vnode = h('br'); 44 | const node = vnode.render(); 45 | expect(createElement).toHaveBeenCalledWith('br'); 46 | expect(node.constructor).toEqual(HTMLBRElement); 47 | }); 48 | 49 | it('should provide a render method able to render element nodes with props and classes', () => { 50 | const createElement = jest.spyOn(document, 'createElement'); 51 | const vnode = h('span.test1.test2', { title: 'test', falsy: false }); 52 | const node = vnode.render(); 53 | expect(createElement).toHaveBeenCalledWith('span'); 54 | expect(node.constructor).toEqual(HTMLSpanElement); 55 | expect(node.getAttribute('title')).toEqual('test'); 56 | expect(node.classList.value).toEqual('test1 test2'); 57 | }); 58 | 59 | it('should provide a render method able to render element nodes with children', () => { 60 | const vnode = h('ul', [h('li', 'test1'), h('li', 'test2')]); 61 | const createElement = jest.spyOn(document, 'createElement'); 62 | const node = vnode.render(); 63 | expect(createElement).toHaveBeenCalledWith('ul'); 64 | expect(createElement).toHaveBeenCalledWith('li'); 65 | expect(node.constructor).toEqual(HTMLUListElement); 66 | expect(node.childNodes.length).toEqual(2); 67 | expect(node.childNodes[1].constructor).toEqual(HTMLLIElement); 68 | expect(node.childNodes[0].childNodes[0].data).toEqual('test1'); 69 | }); 70 | 71 | it('should handle boolean props when redrawing', () => { 72 | const vnode1 = h('input', { type: 'checkbox', checked: true }); 73 | const node = vnode1.render(); 74 | expect(node.checked).toEqual(true); 75 | const vnode = h('input', { type: 'checkbox', checked: false }); 76 | vnode1.redraw({ node, vnode }); 77 | expect(node.checked).toEqual(false); 78 | }); 79 | 80 | it('should handle falsy props when redrawing', () => { 81 | const vnode1 = h('test-element', { q: 1 }); 82 | const node = vnode1.render(); 83 | expect(node.q).toEqual(1); 84 | const vnode = h('test-element', { q: 0 }); 85 | vnode1.redraw({ node, vnode }); 86 | expect(node.q).toEqual(0); 87 | expect(vnode1.props.q).toEqual(0); 88 | }); 89 | 90 | it('should handle non-string props as properties and not create attributes', () => { 91 | const v = h('div', { 92 | test: true, 93 | obj: { a: 1, b: 2 }, 94 | arr: [1, 2, 3], 95 | num: 2.3, 96 | str: 'test', 97 | s: '', 98 | title: 'testing!', 99 | value: false, 100 | }); 101 | const v2 = h('div', { 102 | test: true, 103 | obj: { a: 1, b: 2 }, 104 | arr: [1, 2, 3], 105 | s: '', 106 | title: 'testing!', 107 | value: 'true', 108 | }); 109 | const n = v.render(); 110 | expect(n.test).toEqual(true); 111 | expect(n.obj).toEqual({ a: 1, b: 2 }); 112 | expect(n.arr).toEqual([1, 2, 3]); 113 | expect(n.num).toEqual(2.3); 114 | expect(n.str).toEqual('test'); 115 | expect(n.getAttribute('str')).toEqual('test'); 116 | expect(n.s).toEqual(''); 117 | expect(n.getAttribute('s')).toEqual(''); 118 | expect(n.title).toEqual('testing!'); 119 | expect(n.getAttribute('title')).toEqual('testing!'); 120 | expect(n.value).toEqual(undefined); 121 | expect(n.getAttribute('value')).toEqual(null); 122 | v.redraw({ node: n, vnode: v2 }); 123 | expect(n.getAttribute('value')).toEqual('true'); 124 | v2.value = null; 125 | v.redraw({ node: n, vnode: v2 }); 126 | expect(n.getAttribute('value')).toEqual(''); 127 | }); 128 | 129 | it('should provide a render method able to render element nodes with a value', () => { 130 | let vnode = h('input', { value: 'test' }); 131 | const createElement = jest.spyOn(document, 'createElement'); 132 | let node = vnode.render(); 133 | expect(createElement).toHaveBeenCalledWith('input'); 134 | expect(node.constructor).toEqual(HTMLInputElement); 135 | expect(node.value).toEqual('test'); 136 | vnode = h('input', { value: null }); 137 | node = vnode.render(); 138 | expect(node.value).toEqual(''); 139 | vnode = h('test', { value: 123 }); 140 | node = vnode.render(); 141 | expect(node.getAttribute('value')).toEqual('123'); 142 | expect(node.value).toEqual(undefined); 143 | }); 144 | 145 | it('should provide a render method able to render element nodes with event handlers', () => { 146 | const handler = () => { 147 | console.log('test'); 148 | }; 149 | const vnode = h('button', { onclick: handler }); 150 | const button = document.createElement('button'); 151 | const createElement = jest.spyOn(document, 'createElement').mockImplementationOnce(() => { 152 | return button; 153 | }); 154 | const addEventListener = jest.spyOn(button, 'addEventListener'); 155 | const node = vnode.render(); 156 | expect(createElement).toHaveBeenCalledWith('button'); 157 | expect(node.constructor).toEqual(HTMLButtonElement); 158 | expect(addEventListener).toHaveBeenCalledWith('click', handler); 159 | }); 160 | 161 | it('it should provide a render method able to render elements with special props', () => { 162 | const vnode = h('div', { 163 | id: 'test', 164 | style: 'margin: auto;', 165 | data: { test: 'aaa' }, 166 | $html: '

Hello!

', 167 | }); 168 | const createElement = jest.spyOn(document, 'createElement'); 169 | const node = vnode.render(); 170 | expect(createElement).toHaveBeenCalledWith('div'); 171 | expect(node.constructor).toEqual(HTMLDivElement); 172 | expect(node.style.cssText).toEqual('margin: auto;'); 173 | expect(node.id).toEqual('test'); 174 | expect(node.dataset['test']).toEqual('aaa'); 175 | expect(node.childNodes[0].textContent).toEqual('Hello!'); 176 | }); 177 | 178 | it('should provide a redraw method that is able to add new DOM nodes', () => { 179 | const oldvnode = h('div#test', h('span')); 180 | const newvnodeNoChildren = h('div'); 181 | const newvnode = h('div', [h('span#a'), h('span')]); 182 | const node = oldvnode.render(); 183 | const span = node.childNodes[0]; 184 | oldvnode.redraw({ node: node, vnode: newvnodeNoChildren }); 185 | expect(oldvnode.children.length).toEqual(0); 186 | oldvnode.redraw({ node: node, vnode: newvnode }); 187 | expect(oldvnode).toEqual(newvnode); 188 | expect(oldvnode.children.length).toEqual(2); 189 | expect(node.childNodes.length).toEqual(2); 190 | expect(node.childNodes[0].id).toEqual('a'); 191 | expect(span).toEqual(node.childNodes[1]); 192 | }); 193 | 194 | it('should provide a redraw method that is able to remove existing DOM nodes', () => { 195 | let oldvnode = h('div', [h('span#a'), h('span')]); 196 | let newvnode = h('div', [h('span')]); 197 | let node = oldvnode.render(); 198 | oldvnode.redraw({ node: node, vnode: newvnode }); 199 | expect(oldvnode).toEqual(newvnode); 200 | expect(oldvnode.children.length).toEqual(1); 201 | expect(node.childNodes.length).toEqual(1); 202 | oldvnode = h('div.test-children', [h('span.a'), h('span.b')]); 203 | node = oldvnode.render(); 204 | newvnode = h('div.test-children', [h('div.c')]); 205 | oldvnode.redraw({ node: node, vnode: newvnode }); 206 | expect(oldvnode).toEqual(newvnode); 207 | expect(oldvnode.children.length).toEqual(1); 208 | expect(node.childNodes.length).toEqual(1); 209 | expect(oldvnode.children[0].classList[0]).toEqual('c'); 210 | }); 211 | 212 | it('should provide a redraw method that is able to figure out differences in children', () => { 213 | const oldvnode = h('div', [h('span', 'a'), h('span'), h('span', 'b')]); 214 | const newvnode = h('div', [h('span', 'a'), h('span', 'c'), h('span', 'b')]); 215 | const node = oldvnode.render(); 216 | oldvnode.redraw({ node: node, vnode: newvnode }); 217 | expect(node.childNodes[1].textContent).toEqual('c'); 218 | }); 219 | 220 | it('should provide a redraw method that is able to figure out differences in existing children', () => { 221 | const oldvnode = h('div', [h('span.test', 'a'), h('span.test', 'b'), h('span.test', 'c')]); 222 | const newvnode = h('div', [h('span.test', 'a'), h('span.test1', 'b'), h('span.test', 'c')]); 223 | const node = oldvnode.render(); 224 | oldvnode.redraw({ node: node, vnode: newvnode }); 225 | expect(node.childNodes[0].classList[0]).toEqual('test'); 226 | expect(node.childNodes[1].classList[0]).toEqual('test1'); 227 | expect(node.childNodes[2].classList[0]).toEqual('test'); 228 | }); 229 | 230 | it('should provide a redraw method that is able to update different props', () => { 231 | const oldvnode = h('span', { title: 'a', something: 'b' }); 232 | const newvnode = h('span', { title: 'b', id: 'bbb' }); 233 | const node = oldvnode.render(); 234 | oldvnode.redraw({ node: node, vnode: newvnode }); 235 | expect(oldvnode).toEqual(newvnode); 236 | expect(node.getAttribute('title')).toEqual('b'); 237 | expect(node.getAttribute('id')).toEqual('bbb'); 238 | expect(node.hasAttribute('something')).toEqual(false); 239 | }); 240 | 241 | it('should provide a redraw method that is able to update different classes', () => { 242 | const oldvnode = h('span.a.b', { title: 'b' }); 243 | const newvnode = h('span.a.c', { title: 'b' }); 244 | const node = oldvnode.render(); 245 | oldvnode.redraw({ node: node, vnode: newvnode }); 246 | expect(oldvnode).toEqual(newvnode); 247 | expect(node.classList.value).toEqual('a c'); 248 | }); 249 | 250 | it('should provide redraw method to detect changed nodes if they have different elements', () => { 251 | const oldvnode = h('span.c', { title: 'b' }); 252 | const newvnode = h('div.c', { title: 'b' }); 253 | const container = document.createElement('div'); 254 | const node = oldvnode.render(); 255 | container.appendChild(node); 256 | oldvnode.redraw({ node: node, vnode: newvnode }); 257 | expect(node).not.toEqual(container.childNodes[0]); 258 | expect(node.constructor).toEqual(HTMLSpanElement); 259 | expect(container.childNodes[0].constructor).toEqual(HTMLDivElement); 260 | }); 261 | 262 | it('should provide redraw method to detect position changes in child nodes', () => { 263 | const v1 = h('ul', [h('li.a'), h('li.b'), h('li.c'), h('li.d')]); 264 | const v2 = h('ul', [h('li.c'), h('li.b'), h('li.a'), h('li.d')]); 265 | const n = v1.render(); 266 | expect(n.childNodes[0].classList[0]).toEqual('a'); 267 | v1.redraw({ node: n, vnode: v2 }); 268 | expect(n.childNodes[0].classList[0]).toEqual('c'); 269 | }); 270 | 271 | it('should optimize insertion and deletions when redrawing if all old/new children exist', () => { 272 | const v = h('div', h('a'), h('d')); 273 | const vnode = h('div', h('a'), h('b'), h('c'), h('d')); 274 | const node = v.render(); 275 | v.redraw({ node, vnode }); 276 | expect(v.children.length).toEqual(4); 277 | }); 278 | 279 | it('should provide redraw method to detect changed nodes if they have different node types', () => { 280 | const oldvnode = h('span.c', { title: 'b' }); 281 | const newvnode = h({ type: '#text', value: 'test' }); 282 | const container = document.createElement('div'); 283 | const node = oldvnode.render(); 284 | container.appendChild(node); 285 | expect(node.constructor).toEqual(HTMLSpanElement); 286 | oldvnode.redraw({ node: node, vnode: newvnode }); 287 | expect(node).not.toEqual(container.childNodes[0]); 288 | expect(container.childNodes[0].data).toEqual('test'); 289 | }); 290 | 291 | it('should provide redraw method to detect changed nodes if they have different text', () => { 292 | const oldvnode = h({ type: '#text', value: 'test1' }); 293 | const newvnode = h({ type: '#text', value: 'test2' }); 294 | const container = document.createElement('div'); 295 | const node = oldvnode.render(); 296 | container.appendChild(node); 297 | expect(node.data).toEqual('test1'); 298 | oldvnode.redraw({ node: node, vnode: newvnode }); 299 | expect(container.childNodes[0].data).toEqual('test2'); 300 | }); 301 | 302 | it('should provide redraw method to detect changed nodes and recurse', () => { 303 | const oldvnode = h('ul.c', { title: 'b' }, [h('li#aaa'), h('li#bbb'), h('li#ccc')]); 304 | const newvnode = h('ul.c', { title: 'b' }, [h('li#aaa'), h('li#ccc')]); 305 | const node = oldvnode.render(); 306 | oldvnode.redraw({ node: node, vnode: newvnode }); 307 | expect(oldvnode).toEqual(newvnode); 308 | expect(node.childNodes.length).toEqual(2); 309 | expect(node.childNodes[0].getAttribute('id')).toEqual('aaa'); 310 | expect(node.childNodes[1].getAttribute('id')).toEqual('ccc'); 311 | }); 312 | 313 | it('should provide a redraw method able to detect specific changes to style, data, value, props, $onrender and eventListeners', () => { 314 | const fn = () => false; 315 | const oldvnode = h('input', { 316 | style: 'margin: auto;', 317 | data: { a: 111, b: 222, d: 444 }, 318 | value: null, 319 | title: 'test', 320 | label: 'test', 321 | onkeydown: () => true, 322 | onclick: () => true, 323 | onkeypress: () => true, 324 | }); 325 | const newvnode = h('input', { 326 | style: false, 327 | data: { a: 111, b: 223, c: 333 }, 328 | title: 'test #2', 329 | label: 'test', 330 | something: false, 331 | somethingElse: { test: 1 }, 332 | value: 0, 333 | placeholder: 'test', 334 | onkeydown: () => true, 335 | onkeypress: () => false, 336 | $onrender: () => true, 337 | onhover: () => true, 338 | }); 339 | const newvnode2 = h('input', { 340 | style: false, 341 | data: { a: 111, b: 223, c: 333 }, 342 | title: 'test #2', 343 | label: 'test', 344 | something: false, 345 | somethingElse: { test: 1 }, 346 | placeholder: 'test', 347 | onkeydown: () => true, 348 | onkeypress: () => false, 349 | $onrender: () => true, 350 | onhover: () => true, 351 | }); 352 | const container = document.createElement('div'); 353 | const node = oldvnode.render(); 354 | expect(node.value).toEqual(''); 355 | container.appendChild(node); 356 | oldvnode.redraw({ node: node, vnode: newvnode }); 357 | expect(oldvnode).toEqual(newvnode); 358 | expect(node.style.cssText).toEqual(''); 359 | expect(node.dataset['a']).toEqual('111'); 360 | expect(node.dataset['c']).toEqual('333'); 361 | expect(node.dataset['b']).toEqual('223'); 362 | expect(node.dataset['d']).toEqual(undefined); 363 | expect(node.something).toEqual(false); 364 | expect(node.getAttribute('title')).toEqual('test #2'); 365 | expect(node.getAttribute('placeholder')).toEqual('test'); 366 | expect(node.value).toEqual('0'); 367 | oldvnode.redraw({ node, vnode: newvnode2 }); 368 | expect(node.value).toEqual(''); 369 | }); 370 | 371 | it('should handle value property/attribute for non-input fields', () => { 372 | const v = h('test', { value: null }); 373 | const n = v.render(); 374 | expect(n.value).toEqual(undefined); 375 | expect(n.getAttribute('value')).toEqual(null); 376 | }); 377 | 378 | it('should provide a redraw method able to detect changes in child content', () => { 379 | const v1 = h('ul', [h('li', 'a'), h('li', 'b')]); 380 | const n1 = v1.render(); 381 | const v2 = h('ul', { 382 | $html: '
  • a
  • b
  • ', 383 | $onrender: (node) => node.classList.add('test'), 384 | }); 385 | const v3 = h('ul', [h('li', 'a')]); 386 | const v4 = h('ul', [h('li', 'b')]); 387 | const n2 = v2.render(); 388 | const n3 = v3.render(); 389 | expect(n2.childNodes[0].childNodes[0].data).toEqual(n1.childNodes[0].childNodes[0].data); 390 | v1.redraw({ node: n1, vnode: v2 }); 391 | expect(n1.classList[0]).toEqual('test'); 392 | expect(v1).toEqual(v2); 393 | v3.redraw({ node: n3, vnode: v4 }); 394 | expect(v3).toEqual(v4); 395 | }); 396 | 397 | it('should execute $onrender callbacks whenever a child node is added to the DOM', async () => { 398 | let n; 399 | const $onrender = (node) => { 400 | n = node; 401 | }; 402 | const vn1 = h('ul', [h('li')]); 403 | const vn2 = h('ul', [h('li'), h('li.vn2', { $onrender })]); 404 | const n1 = vn1.render(); 405 | vn1.redraw({ node: n1, vnode: vn2 }); 406 | expect(n.classList.value).toEqual('vn2'); 407 | const vn3 = h('ul', [h('span.vn3', { $onrender })]); 408 | vn1.redraw({ node: n1, vnode: vn3 }); 409 | expect(n.classList.value).toEqual('vn3'); 410 | const rc = () => h('div.rc', { $onrender }); 411 | await h3.init(rc); 412 | expect(n.classList.value).toEqual('rc'); 413 | const rc2 = () => vn2; 414 | await h3.init(rc2); 415 | expect(n.classList.value).toEqual('vn2'); 416 | }); 417 | }); 418 | -------------------------------------------------------------------------------- /babel.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | presets: [ 3 | [ 4 | "@babel/preset-env", 5 | { 6 | targets: { 7 | node: "10", 8 | }, 9 | debug: false, 10 | }, 11 | ], 12 | ], 13 | ignore: ["node_modules"], 14 | plugins: ["@babel/plugin-transform-modules-commonjs"], 15 | }; 16 | -------------------------------------------------------------------------------- /description: -------------------------------------------------------------------------------- 1 | A tiny, extremely minimalist JavaScript microframework. 2 | -------------------------------------------------------------------------------- /docs/CNAME: -------------------------------------------------------------------------------- 1 | h3.js.org -------------------------------------------------------------------------------- /docs/H3_DeveloperGuide.md: -------------------------------------------------------------------------------- 1 | % H3 Microframework Developer Guide 2 | % Fabio Cevasco 3 | % - 4 | 5 | 10 | 11 | {@ md/overview.md || 0 @} 12 | 13 | {@ md/quick-start.md || 0 @} 14 | 15 | {@ md/key-concepts.md || 0 @} 16 | 17 | {@ md/tutorial.md || 0 @} 18 | 19 | {@ md/api.md || 0 @} 20 | 21 | {@ md/about.md || 0 @} 22 | 23 | -------------------------------------------------------------------------------- /docs/css/prism.css: -------------------------------------------------------------------------------- 1 | /* PrismJS 1.20.0 2 | https://prismjs.com/download.html#themes=prism&languages=markup+css+clike+javascript */ 3 | /** 4 | * prism.js default theme for JavaScript, CSS and HTML 5 | * Based on dabblet (http://dabblet.com) 6 | * @author Lea Verou 7 | */ 8 | 9 | code[class*="language-"], 10 | pre[class*="language-"] { 11 | color: black; 12 | background: none; 13 | text-shadow: 0 1px white; 14 | font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace; 15 | font-size: 1em; 16 | text-align: left; 17 | white-space: pre; 18 | word-spacing: normal; 19 | word-break: normal; 20 | word-wrap: normal; 21 | line-height: 1.5; 22 | 23 | -moz-tab-size: 4; 24 | -o-tab-size: 4; 25 | tab-size: 4; 26 | 27 | -webkit-hyphens: none; 28 | -moz-hyphens: none; 29 | -ms-hyphens: none; 30 | hyphens: none; 31 | } 32 | 33 | pre[class*="language-"]::-moz-selection, pre[class*="language-"] ::-moz-selection, 34 | code[class*="language-"]::-moz-selection, code[class*="language-"] ::-moz-selection { 35 | text-shadow: none; 36 | background: #b3d4fc; 37 | } 38 | 39 | pre[class*="language-"]::selection, pre[class*="language-"] ::selection, 40 | code[class*="language-"]::selection, code[class*="language-"] ::selection { 41 | text-shadow: none; 42 | background: #b3d4fc; 43 | } 44 | 45 | @media print { 46 | code[class*="language-"], 47 | pre[class*="language-"] { 48 | text-shadow: none; 49 | } 50 | } 51 | 52 | /* Code blocks */ 53 | pre[class*="language-"] { 54 | padding: 1em; 55 | margin: .5em 0; 56 | overflow: auto; 57 | } 58 | 59 | :not(pre) > code[class*="language-"], 60 | pre[class*="language-"] { 61 | background: #f5f2f0; 62 | } 63 | 64 | /* Inline code */ 65 | :not(pre) > code[class*="language-"] { 66 | padding: .1em; 67 | border-radius: .3em; 68 | white-space: normal; 69 | } 70 | 71 | .token.comment, 72 | .token.prolog, 73 | .token.doctype, 74 | .token.cdata { 75 | color: slategray; 76 | } 77 | 78 | .token.punctuation { 79 | color: #999; 80 | } 81 | 82 | .token.namespace { 83 | opacity: .7; 84 | } 85 | 86 | .token.property, 87 | .token.tag, 88 | .token.boolean, 89 | .token.number, 90 | .token.constant, 91 | .token.symbol, 92 | .token.deleted { 93 | color: #905; 94 | } 95 | 96 | .token.selector, 97 | .token.attr-name, 98 | .token.string, 99 | .token.char, 100 | .token.builtin, 101 | .token.inserted { 102 | color: #690; 103 | } 104 | 105 | .token.operator, 106 | .token.entity, 107 | .token.url, 108 | .language-css .token.string, 109 | .style .token.string { 110 | color: #9a6e3a; 111 | background: hsla(0, 0%, 100%, .5); 112 | } 113 | 114 | .token.atrule, 115 | .token.attr-value, 116 | .token.keyword { 117 | color: #07a; 118 | } 119 | 120 | .token.function, 121 | .token.class-name { 122 | color: #DD4A68; 123 | } 124 | 125 | .token.regex, 126 | .token.important, 127 | .token.variable { 128 | color: #e90; 129 | } 130 | 131 | .token.important, 132 | .token.bold { 133 | font-weight: bold; 134 | } 135 | .token.italic { 136 | font-style: italic; 137 | } 138 | 139 | .token.entity { 140 | cursor: help; 141 | } 142 | 143 | -------------------------------------------------------------------------------- /docs/css/style.css: -------------------------------------------------------------------------------- 1 | footer { 2 | text-align: center; 3 | width: 100%; 4 | } 5 | 6 | #navigation { 7 | border: none; 8 | } 9 | 10 | [type="checkbox"].drawer:checked + * { 11 | padding-top: 60px; 12 | } 13 | 14 | #navigation a.active { 15 | background: #dedede; 16 | } 17 | 18 | .spinner-container { 19 | text-align: center; 20 | margin: auto; 21 | } 22 | 23 | ul, 24 | ol { 25 | padding-left: 1.5em; 26 | } 27 | 28 | pre[class*="language-"] { 29 | padding: 0.5em; 30 | line-height: 1em; 31 | border: 1px solid #dedede; 32 | } 33 | 34 | pre code[class*="language-"], 35 | pre code[class*="language-"] span.token { 36 | font-family: Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace; 37 | font-size: 0.8rem; 38 | } 39 | 40 | pre code { 41 | padding: 0; 42 | } 43 | 44 | @media screen and (min-width: 768px) { 45 | #navigation { 46 | position: sticky; 47 | top: 60px; 48 | } 49 | } 50 | @media screen and (max-width: 767px) { 51 | #navigation { 52 | border-left: 1px solid #ccc; 53 | } 54 | } 55 | 56 | .content { 57 | margin-left: 30px; 58 | } 59 | 60 | h2, 61 | h3, 62 | h4, 63 | h5, 64 | h6 { 65 | margin-left: -30px; 66 | } 67 | 68 | .logo img { 69 | width: 3em; 70 | height: 3em; 71 | margin-top: -5px; 72 | } 73 | 74 | .drawer-toggle:before { 75 | font-size: 2.5em; 76 | } 77 | 78 | .version { 79 | padding: 6px; 80 | } 81 | 82 | .version-number { 83 | font-size: 0.8em; 84 | font-weight: bold; 85 | } 86 | .version-label { 87 | font-size: 0.8em; 88 | font-style: italic; 89 | } 90 | 91 | .badge { 92 | margin: 0 2px; 93 | } 94 | 95 | h4 { 96 | font-size: 16px; 97 | } 98 | 99 | a.button { 100 | margin: 0; 101 | } 102 | -------------------------------------------------------------------------------- /docs/example/assets/css/style.css: -------------------------------------------------------------------------------- 1 | html { 2 | box-sizing: border-box; 3 | font-size: 16px; 4 | font-family: sans-serif; 5 | } 6 | 7 | *, 8 | *:before, 9 | *:after { 10 | box-sizing: inherit; 11 | } 12 | 13 | body { 14 | margin: 0; 15 | padding: 0; 16 | font-weight: normal; 17 | } 18 | 19 | h1 { 20 | margin: auto; 21 | text-align: center; 22 | } 23 | 24 | .container { 25 | padding: 15px; 26 | } 27 | 28 | .add-todo-form { 29 | margin: 10px 0; 30 | display: flex; 31 | justify-content: center; 32 | } 33 | 34 | #new-todo { 35 | font-size: 2rem; 36 | height: 3rem; 37 | width: 100%; 38 | display: flex; 39 | justify-content: space-around; 40 | } 41 | 42 | .submit-todo { 43 | height: 3rem; 44 | width: 4rem; 45 | font-size: 2.5rem; 46 | align-items: center; 47 | display: flex; 48 | justify-content: space-around; 49 | cursor: pointer; 50 | } 51 | 52 | .options { 53 | padding: 20px 0; 54 | } 55 | 56 | .navigation-bar { 57 | display: flex; 58 | justify-content: center; 59 | } 60 | 61 | .navigation-bar .nav-link { 62 | font-size: 1.5em; 63 | display: flex; 64 | margin-right: 5px; 65 | font-weight: bold; 66 | } 67 | 68 | .nav-link { 69 | cursor: pointer; 70 | } 71 | 72 | #filter-text { 73 | display: flex; 74 | justify-content: space-around; 75 | font-size: 1em; 76 | height: 2em; 77 | width: 100%; 78 | } 79 | .paginator { 80 | display: flex; 81 | align-items: center; 82 | justify-content: space-around; 83 | padding: 0 5px; 84 | font-weight: bold; 85 | } 86 | 87 | .current-page { 88 | padding: 0 5px; 89 | } 90 | 91 | .todo-list { 92 | margin: 20px 0; 93 | } 94 | 95 | .todo-content { 96 | cursor: pointer; 97 | } 98 | 99 | .todo-content.done { 100 | text-decoration: line-through; 101 | color: #666; 102 | } 103 | 104 | .todo-item { 105 | display: flex; 106 | justify-content: flex-start; 107 | padding: 5px; 108 | margin: 5px 0; 109 | border: 1px solid #ccc; 110 | } 111 | 112 | .todo-content { 113 | display: flex; 114 | justify-content: space-around; 115 | padding: 5px 10px 5px 0; 116 | width: 100%; 117 | } 118 | 119 | .todo-text { 120 | text-align: left; 121 | width: 100%; 122 | } 123 | 124 | .delete-todo { 125 | display: flex; 126 | cursor: pointer; 127 | justify-content: space-around; 128 | align-items: center; 129 | } 130 | 131 | .error { 132 | color: #ff3838; 133 | background: #ffe6cc; 134 | width: 100%; 135 | border: 1px solid #ff3838; 136 | padding: 5px; 137 | margin: 5px 0; 138 | display: flex; 139 | justify-content: center; 140 | } 141 | 142 | .error-message { 143 | display: flex; 144 | justify-content: space-around; 145 | width: 100%; 146 | } 147 | .dismiss-error { 148 | cursor: pointer; 149 | display: flex; 150 | align-items: center; 151 | justify-content: space-around; 152 | } 153 | 154 | .hidden { 155 | visibility: hidden; 156 | } 157 | 158 | .link { 159 | cursor: pointer; 160 | } 161 | .disabled { 162 | color: #cccccc; 163 | } 164 | 165 | @media (min-width: 750px) { 166 | .todo-list-container { 167 | width: 700px; 168 | margin: auto; 169 | } 170 | } 171 | -------------------------------------------------------------------------------- /docs/example/assets/js/app.js: -------------------------------------------------------------------------------- 1 | import { h3, h } from "./h3.js"; 2 | import modules from "./modules.js"; 3 | import SettingsView from "./components/SettingsView.js"; 4 | import MainView from "./components/MainView.js"; 5 | 6 | h3.init({ 7 | modules, 8 | preStart: () => { 9 | h3.dispatch("app/load"); 10 | h3.dispatch("settings/set", h3.state.settings); 11 | }, 12 | routes: { 13 | "/settings": SettingsView, 14 | "/": MainView, 15 | }, 16 | }); 17 | -------------------------------------------------------------------------------- /docs/example/assets/js/components/AddTodoForm.js: -------------------------------------------------------------------------------- 1 | import { h3, h } from "../h3.js"; 2 | 3 | export default function AddTodoForm() { 4 | const focus = () => document.getElementById("new-todo").focus(); 5 | const addTodo = () => { 6 | if (!newTodo.value) { 7 | h3.dispatch("error/set"); 8 | h3.redraw(); 9 | focus(); 10 | return; 11 | } 12 | h3.dispatch("error/clear"); 13 | h3.dispatch("todos/add", { 14 | key: `todo_${Date.now()}__${btoa(newTodo.value)}`, 15 | text: newTodo.value, 16 | }); 17 | newTodo.value = ""; 18 | h3.redraw(); 19 | focus(); 20 | }; 21 | const addTodoOnEnter = (e) => { 22 | if (e.keyCode == 13) { 23 | addTodo(); 24 | e.preventDefault(); 25 | } 26 | }; 27 | const newTodo = h("input", { 28 | id: "new-todo", 29 | placeholder: "What do you want to do?", 30 | oninput: (e) => (newTodo.value = e.target.value), 31 | onkeydown: addTodoOnEnter, 32 | }); 33 | return h("form.add-todo-form", [ 34 | newTodo, 35 | h( 36 | "span.submit-todo", 37 | { 38 | title: "Add Todo", 39 | onclick: addTodo, 40 | }, 41 | "+" 42 | ), 43 | ]); 44 | } 45 | -------------------------------------------------------------------------------- /docs/example/assets/js/components/EmptyTodoError.js: -------------------------------------------------------------------------------- 1 | import { h3, h } from "../h3.js"; 2 | 3 | export default function EmptyTodoError(data, actions) { 4 | const emptyTodoErrorClass = h3.state.displayEmptyTodoError ? "" : ".hidden"; 5 | const clearError = () => { 6 | h3.dispatch("error/clear"); 7 | h3.redraw(); 8 | }; 9 | return h(`div#empty-todo-error.error${emptyTodoErrorClass}`, [ 10 | h("span.error-message", ["Please enter a non-empty todo item."]), 11 | h( 12 | "span.dismiss-error", 13 | { 14 | onclick: clearError, 15 | }, 16 | "✘" 17 | ), 18 | ]); 19 | } 20 | -------------------------------------------------------------------------------- /docs/example/assets/js/components/MainView.js: -------------------------------------------------------------------------------- 1 | import { h3, h } from "../h3.js"; 2 | import AddTodoForm from "./AddTodoForm.js"; 3 | import EmptyTodoError from "./EmptyTodoError.js"; 4 | import NavigationBar from "./NavigationBar.js"; 5 | import TodoList from "./TodoList.js"; 6 | 7 | export default function () { 8 | const { todos, filter } = h3.state; 9 | h3.dispatch("todos/filter", filter); 10 | h3.dispatch("app/save", { todos: todos, settings: h3.state.settings }); 11 | return h("div.container", [ 12 | h("h1", "To Do List"), 13 | h("main", [AddTodoForm, EmptyTodoError, NavigationBar, TodoList]), 14 | ]); 15 | } 16 | -------------------------------------------------------------------------------- /docs/example/assets/js/components/NavigationBar.js: -------------------------------------------------------------------------------- 1 | import { h3, h } from "../h3.js"; 2 | import Paginator from "./Paginator.js"; 3 | 4 | export default function NavigationBar() { 5 | // Set the todo filter. 6 | const setFilter = (e) => { 7 | h3.dispatch("todos/filter", e.target.value); 8 | h3.redraw(); 9 | }; 10 | // Filtering function for todo items 11 | return h("div.navigation-bar", [ 12 | h( 13 | "a.nav-link", 14 | { 15 | title: "Settings", 16 | onclick: () => h3.navigateTo("/settings"), 17 | }, 18 | "⚙" 19 | ), 20 | h("input", { 21 | id: "filter-text", 22 | placeholder: "Type to filter todo items...", 23 | oninput: setFilter, 24 | }), 25 | Paginator, 26 | ]); 27 | } 28 | -------------------------------------------------------------------------------- /docs/example/assets/js/components/Paginator.js: -------------------------------------------------------------------------------- 1 | import { h3, h } from "../h3.js"; 2 | 3 | export default function Paginator() { 4 | const hash = window.location.hash; 5 | let { page, pagesize, filteredTodos } = h3.state; 6 | let total = filteredTodos.length; 7 | if (h3.route.params.page) { 8 | page = parseInt(h3.route.params.page); 9 | } 10 | // Recalculate page in case data is filtered. 11 | page = Math.min(Math.ceil(filteredTodos.length / pagesize), page) || 1; 12 | h3.dispatch("pages/set", page); 13 | const pages = Math.ceil(total / pagesize) || 1; 14 | const previousClass = page > 1 ? ".link" : ".disabled"; 15 | const nextClass = page < pages ? ".link" : ".disabled"; 16 | const setPage = (value) => { 17 | const page = h3.state.page; 18 | const newPage = page + value; 19 | h3.dispatch("pages/set", newPage); 20 | h3.navigateTo("/", { page: newPage }); 21 | }; 22 | return h("div.paginator", [ 23 | h( 24 | `span.previous-page${previousClass}`, 25 | { 26 | onclick: () => setPage(-1), 27 | }, 28 | ["←"] 29 | ), 30 | h("span.current-page", [`${String(page)}/${String(pages)}`]), 31 | h( 32 | `span.next-page${nextClass}`, 33 | { 34 | onclick: () => setPage(+1), 35 | }, 36 | ["→"] 37 | ), 38 | ]); 39 | } 40 | -------------------------------------------------------------------------------- /docs/example/assets/js/components/SettingsView.js: -------------------------------------------------------------------------------- 1 | import { h3, h } from "../h3.js"; 2 | 3 | export default function () { 4 | const toggleLogging = (e) => { 5 | const value = e.target.checked; 6 | h3.dispatch("settings/set", { logging: value }); 7 | h3.dispatch("app/save"); 8 | }; 9 | return h("div.settings.container", [ 10 | h("h1", "Settings"), 11 | h("div.options", [ 12 | h("input", { 13 | type: "checkbox", 14 | onclick: toggleLogging, 15 | checked: h3.state.settings.logging, 16 | }), 17 | h( 18 | "label#options-logging-label", 19 | { 20 | for: "logging", 21 | }, 22 | "Logging" 23 | ), 24 | ]), 25 | h( 26 | "a.nav-link", 27 | { 28 | onclick: () => h3.navigateTo("/"), 29 | }, 30 | "← Go Back" 31 | ), 32 | ]); 33 | } 34 | -------------------------------------------------------------------------------- /docs/example/assets/js/components/Todo.js: -------------------------------------------------------------------------------- 1 | import { h3, h } from "../h3.js"; 2 | 3 | export default function Todo(data) { 4 | const todoStateClass = data.done ? ".done" : ".todo"; 5 | const toggleTodo = (key) => { 6 | h3.dispatch("todos/toggle", key); 7 | h3.redraw(); 8 | }; 9 | const removeTodo = (key) => { 10 | h3.dispatch("todos/remove", key); 11 | h3.redraw(); 12 | }; 13 | return h(`div.todo-item`, { data: { key: data.key } }, [ 14 | h(`div.todo-content${todoStateClass}`, [ 15 | h( 16 | "span.todo-text", 17 | { 18 | onclick: (e) => 19 | toggleTodo( 20 | e.currentTarget.parentNode.parentNode.dataset.key 21 | ), 22 | }, 23 | data.text 24 | ), 25 | ]), 26 | h( 27 | "span.delete-todo", 28 | { 29 | onclick: (e) => 30 | removeTodo(e.currentTarget.parentNode.dataset.key), 31 | }, 32 | "✘" 33 | ), 34 | ]); 35 | } 36 | -------------------------------------------------------------------------------- /docs/example/assets/js/components/TodoList.js: -------------------------------------------------------------------------------- 1 | import { h3, h } from "../h3.js"; 2 | import Todo from "./Todo.js"; 3 | 4 | export default function TodoList() { 5 | const { page, pagesize } = h3.state; 6 | const filteredTodos = h3.state.filteredTodos; 7 | const start = (page - 1) * pagesize; 8 | const end = Math.min(start + pagesize, filteredTodos.length); 9 | return h("div.todo-list", filteredTodos.slice(start, end).map(Todo)); 10 | } 11 | -------------------------------------------------------------------------------- /docs/example/assets/js/modules.js: -------------------------------------------------------------------------------- 1 | import { h3, h } from "./h3.js"; 2 | 3 | const app = () => { 4 | h3.on("app/load", () => { 5 | const storedData = localStorage.getItem("h3_todo_list"); 6 | const { todos, settings } = storedData 7 | ? JSON.parse(storedData) 8 | : { todos: [], settings: {} }; 9 | return { todos, settings }; 10 | }); 11 | h3.on("app/save", (state, data) => { 12 | localStorage.setItem( 13 | "h3_todo_list", 14 | JSON.stringify({ todos: state.todos, settings: state.settings }) 15 | ); 16 | }); 17 | }; 18 | 19 | const settings = () => { 20 | let removeSubscription; 21 | h3.on("$init", () => ({ settings: {} })); 22 | h3.on("settings/set", (state, data) => { 23 | if (data.logging) { 24 | removeSubscription = h3.on("$log", (state, data) => 25 | console.log(data) 26 | ); 27 | } else { 28 | removeSubscription && removeSubscription(); 29 | } 30 | return { settings: data }; 31 | }); 32 | }; 33 | 34 | const todos = () => { 35 | h3.on("$init", () => ({ todos: [], filteredTodos: [], filter: "" })); 36 | h3.on("todos/add", (state, data) => { 37 | let todos = state.todos; 38 | todos.unshift({ 39 | key: data.key, 40 | text: data.text, 41 | }); 42 | return { todos }; 43 | }); 44 | h3.on("todos/remove", (state, k) => { 45 | const todos = state.todos.filter(({ key }) => key !== k); 46 | return { todos }; 47 | }); 48 | h3.on("todos/toggle", (state, k) => { 49 | const todos = state.todos; 50 | const todo = state.todos.find(({ key }) => key === k); 51 | todo.done = !todo.done; 52 | return { todos }; 53 | }); 54 | h3.on("todos/filter", (state, filter) => { 55 | const todos = state.todos; 56 | const filteredTodos = todos.filter(({ text }) => text.match(filter)); 57 | return { filteredTodos, filter }; 58 | }); 59 | }; 60 | 61 | const error = () => { 62 | h3.on("$init", () => ({ displayEmptyTodoError: false })); 63 | h3.on("error/clear", (state) => ({ displayEmptyTodoError: false })); 64 | h3.on("error/set", (state) => ({ displayEmptyTodoError: true })); 65 | }; 66 | 67 | const pages = () => { 68 | h3.on("$init", () => ({ pagesize: 10, page: 1 })); 69 | h3.on("pages/set", (state, page) => ({ page })); 70 | }; 71 | 72 | export default [app, todos, error, pages, settings]; 73 | -------------------------------------------------------------------------------- /docs/example/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | To Do List 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /docs/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/h3rald/h3/f6a08dde4c69b7e83db3d0713b094f250e5b0f13/docs/favicon.png -------------------------------------------------------------------------------- /docs/images/h3.sequence.svg: -------------------------------------------------------------------------------- 1 | H3 Sequence DiagramApplicationApplicationComponentComponentH3H3RouterRouterStoreStoreh3.init()initializeexecute modulesdispatch($init)preStart()initializestart()setup()dispatch($navigation)render()dispatch($redraw)postStart()redrawh3.redraw()redraw()dispatch($redraw)navigationh3.navigateTo()processPath()teardown()setup()dispatch($navigation)remove all DOM nodesremove all DOM nodesrender()dispatch($redraw) -------------------------------------------------------------------------------- /docs/images/h3.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 19 | 21 | 39 | 41 | 42 | 44 | image/svg+xml 45 | 47 | 48 | 49 | 50 | 51 | 56 | 60 | 64 | 65 | 69 | 73 | 74 | 75 | 76 | -------------------------------------------------------------------------------- /docs/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | H3 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /docs/js/app.js: -------------------------------------------------------------------------------- 1 | import { h3, h } from "./h3.js"; 2 | import marked from "./vendor/marked.js"; 3 | import Prism from "./vendor/prism.js"; 4 | 5 | const labels = { 6 | overview: "Overview", 7 | "quick-start": "Quick Start", 8 | "key-concepts": "Key Concepts", 9 | "best-practices": "Best Practices", 10 | tutorial: "Tutorial", 11 | api: "API", 12 | about: "About", 13 | }; 14 | 15 | const Page = h3.screen({ 16 | setup: async (state) => { 17 | state.pages = state.pages || {}; 18 | state.id = h3.route.path.slice(1); 19 | state.ids = Object.keys(labels); 20 | state.md = state.ids.includes(state.id) 21 | ? `md/${state.id}.md` 22 | : `md/overview.md`; 23 | await fetchPage(state); 24 | }, 25 | display: (state) => { 26 | return h("div.page", [ 27 | Header, 28 | h("div.row", [ 29 | h("input#drawer-control.drawer", { type: "checkbox" }), 30 | Navigation(state.id, state.ids), 31 | Content(state.pages[state.id]), 32 | Footer, 33 | ]), 34 | ]); 35 | }, 36 | teardown: (state) => state, 37 | }); 38 | 39 | const fetchPage = async ({ pages, id, md }) => { 40 | if (!pages[id]) { 41 | const response = await fetch(md); 42 | const text = await response.text(); 43 | pages[id] = marked(text); 44 | } 45 | }; 46 | 47 | const Header = () => { 48 | return h("header.row.sticky", [ 49 | h("a.logo.col-sm-1", { href: "#/" }, [ 50 | h("img", { alt: "H3", src: "images/h3.svg" }), 51 | ]), 52 | h("div.version.col-sm.col-md", [ 53 | h("div.version-number", "v0.11.0"), 54 | h("div.version-label", "“Keen Klingon“"), 55 | ]), 56 | h("label.drawer-toggle.button.col-sm-last", { for: "drawer-control" }), 57 | ]); 58 | }; 59 | 60 | const Footer = () => { 61 | return h("footer", [h("div", "© 2020 Fabio Cevasco")]); 62 | }; 63 | 64 | const Navigation = (id, ids) => { 65 | const menu = ids.map((p) => 66 | h(`a${p === id ? ".active" : ""}`, { href: `#/${p}` }, labels[p]) 67 | ); 68 | return h("nav#navigation.col-md-3", [ 69 | h("label.drawer-close", { for: "drawer-control" }), 70 | ...menu, 71 | ]); 72 | }; 73 | 74 | const Content = (html) => { 75 | const content = h("div.content", { $html: html }); 76 | return h("main.col-sm-12.col-md-9", [ 77 | h( 78 | "div.card.fluid", 79 | h("div.section", { $onrender: () => Prism.highlightAll() }, content) 80 | ), 81 | ]); 82 | }; 83 | 84 | h3.init(Page); 85 | -------------------------------------------------------------------------------- /docs/js/vendor/prism.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable */ 2 | /* ********************************************** 3 | Begin prism-core.js 4 | ********************************************** */ 5 | 6 | let _self = {}; 7 | 8 | /** 9 | * Prism: Lightweight, robust, elegant syntax highlighting 10 | * MIT license http://www.opensource.org/licenses/mit-license.php/ 11 | * @author Lea Verou http://lea.verou.me 12 | */ 13 | 14 | let Prism = (function () { 15 | // Private helper vars 16 | let lang = /\blang(?:uage)?-([\w-]+)\b/i; 17 | let uniqueId = 0; 18 | 19 | var _ = _self.Prism = { 20 | manual: _self.Prism && _self.Prism.manual, 21 | disableWorkerMessageHandler: _self.Prism && _self.Prism.disableWorkerMessageHandler, 22 | util: { 23 | encode (tokens) { 24 | if (tokens instanceof Token) { 25 | return new Token(tokens.type, _.util.encode(tokens.content), tokens.alias); 26 | } else if (_.util.type(tokens) === 'Array') { 27 | return tokens.map(_.util.encode); 28 | } else { 29 | return tokens.replace(/&/g, '&').replace(/ text.length) { 321 | // Something went terribly wrong, ABORT, ABORT! 322 | return; 323 | } 324 | 325 | if (str instanceof Token) { 326 | continue; 327 | } 328 | 329 | if (greedy && i != strarr.length - 1) { 330 | pattern.lastIndex = pos; 331 | var match = pattern.exec(text); 332 | if (!match) { 333 | break; 334 | } 335 | 336 | var from = match.index + (lookbehind ? match[1].length : 0), 337 | to = match.index + match[0].length, 338 | k = i, 339 | p = pos; 340 | 341 | for (var len = strarr.length; k < len && (p < to || (!strarr[k].type && !strarr[k - 1].greedy)); ++k) { 342 | p += strarr[k].length; 343 | // Move the index i to the element in strarr that is closest to from 344 | if (from >= p) { 345 | ++i; 346 | pos = p; 347 | } 348 | } 349 | 350 | // If strarr[i] is a Token, then the match starts inside another Token, which is invalid 351 | if (strarr[i] instanceof Token) { 352 | continue; 353 | } 354 | 355 | // Number of tokens to delete and replace with the new match 356 | delNum = k - i; 357 | str = text.slice(pos, p); 358 | match.index -= pos; 359 | } else { 360 | pattern.lastIndex = 0; 361 | 362 | var match = pattern.exec(str), 363 | delNum = 1; 364 | } 365 | 366 | if (!match) { 367 | if (oneshot) { 368 | break; 369 | } 370 | 371 | continue; 372 | } 373 | 374 | if(lookbehind) { 375 | lookbehindLength = match[1] ? match[1].length : 0; 376 | } 377 | 378 | var from = match.index + lookbehindLength, 379 | match = match[0].slice(lookbehindLength), 380 | to = from + match.length, 381 | before = str.slice(0, from), 382 | after = str.slice(to); 383 | 384 | var args = [i, delNum]; 385 | 386 | if (before) { 387 | ++i; 388 | pos += before.length; 389 | args.push(before); 390 | } 391 | 392 | var wrapped = new Token(token, inside? _.tokenize(match, inside) : match, alias, match, greedy); 393 | 394 | args.push(wrapped); 395 | 396 | if (after) { 397 | args.push(after); 398 | } 399 | 400 | Array.prototype.splice.apply(strarr, args); 401 | 402 | if (delNum != 1) 403 | _.matchGrammar(text, strarr, grammar, i, pos, true, token); 404 | 405 | if (oneshot) 406 | break; 407 | } 408 | } 409 | } 410 | }, 411 | 412 | tokenize(text, grammar, language) { 413 | var strarr = [text]; 414 | 415 | var rest = grammar.rest; 416 | 417 | if (rest) { 418 | for (var token in rest) { 419 | grammar[token] = rest[token]; 420 | } 421 | 422 | delete grammar.rest; 423 | } 424 | 425 | _.matchGrammar(text, strarr, grammar, 0, 0, false); 426 | 427 | return strarr; 428 | }, 429 | 430 | hooks: { 431 | all: {}, 432 | 433 | add (name, callback) { 434 | var hooks = _.hooks.all; 435 | 436 | hooks[name] = hooks[name] || []; 437 | 438 | hooks[name].push(callback); 439 | }, 440 | 441 | run (name, env) { 442 | var callbacks = _.hooks.all[name]; 443 | 444 | if (!callbacks || !callbacks.length) { 445 | return; 446 | } 447 | 448 | for (var i=0, callback; callback = callbacks[i++];) { 449 | callback(env); 450 | } 451 | }, 452 | }, 453 | }; 454 | 455 | var Token = _.Token = function (type, content, alias, matchedStr, greedy) { 456 | this.type = type; 457 | this.content = content; 458 | this.alias = alias; 459 | // Copy of the full string this token was created from 460 | this.length = (matchedStr || '').length | 0; 461 | this.greedy = !!greedy; 462 | }; 463 | 464 | Token.stringify = function (o, language, parent) { 465 | if (typeof o === 'string') { 466 | return o; 467 | } 468 | 469 | if (_.util.type(o) === 'Array') { 470 | return o.map((element) => { 471 | return Token.stringify(element, language, o); 472 | }).join(''); 473 | } 474 | 475 | let env = { 476 | type: o.type, 477 | content: Token.stringify(o.content, language, parent), 478 | tag: 'span', 479 | classes: ['token', o.type], 480 | attributes: {}, 481 | language, 482 | parent, 483 | }; 484 | 485 | if (o.alias) { 486 | let aliases = _.util.type(o.alias) === 'Array' ? o.alias : [o.alias]; 487 | Array.prototype.push.apply(env.classes, aliases); 488 | } 489 | 490 | _.hooks.run('wrap', env); 491 | 492 | let attributes = Object.keys(env.attributes).map((name) => { 493 | return name + '="' + (env.attributes[name] || '').replace(/"/g, '"') + '"'; 494 | }).join(' '); 495 | 496 | return `<${ env.tag } class="${ env.classes.join(' ') }"${ attributes ? ' ' + attributes : '' }>${ env.content }`; 497 | }; 498 | 499 | if (!_self.document) { 500 | if (!_self.addEventListener) { 501 | // in Node.js 502 | return _self.Prism; 503 | } 504 | 505 | if (!_.disableWorkerMessageHandler) { 506 | // In worker 507 | _self.addEventListener('message', (evt) => { 508 | var message = JSON.parse(evt.data), 509 | lang = message.language, 510 | code = message.code, 511 | immediateClose = message.immediateClose; 512 | 513 | _self.postMessage(_.highlight(code, _.languages[lang], lang)); 514 | if (immediateClose) { 515 | _self.close(); 516 | } 517 | }, false); 518 | } 519 | 520 | return _self.Prism; 521 | } 522 | 523 | // Get current script and highlight 524 | // let script = document.currentScript || [].slice.call(document.getElementsByTagName('script')).pop(); 525 | 526 | // if (script) { 527 | // _.filename = script.src; 528 | 529 | // if (!_.manual && !script.hasAttribute('data-manual')) { 530 | // if (document.readyState !== 'loading') { 531 | // if (window.requestAnimationFrame) { 532 | // window.requestAnimationFrame(_.highlightAll); 533 | // } else { 534 | // window.setTimeout(_.highlightAll, 16); 535 | // } 536 | // } else { 537 | // document.addEventListener('DOMContentLoaded', _.highlightAll); 538 | // } 539 | // } 540 | // } 541 | 542 | return _self.Prism; 543 | }()); 544 | 545 | if (typeof module !== 'undefined' && module.exports) { 546 | module.exports = Prism; 547 | } 548 | 549 | // hack for components to work correctly in node.js 550 | if (typeof global !== 'undefined') { 551 | global.Prism = Prism; 552 | } 553 | 554 | 555 | /* ********************************************** 556 | Begin prism-markup.js 557 | ********************************************** */ 558 | 559 | Prism.languages.markup = { 560 | comment: //, 561 | prolog: /<\?[\s\S]+?\?>/, 562 | doctype: //i, 563 | cdata: //i, 564 | tag: { 565 | pattern: /<\/?(?!\d)[^\s>\/=$<%]+(?:\s+[^\s>\/=]+(?:=(?:("|')(?:\\[\s\S]|(?!\1)[^\\])*\1|[^\s'">=]+))?)*\s*\/?>/i, 566 | greedy: true, 567 | inside: { 568 | tag: { 569 | pattern: /^<\/?[^\s>\/]+/i, 570 | inside: { 571 | punctuation: /^<\/?/, 572 | namespace: /^[^\s>\/:]+:/, 573 | }, 574 | }, 575 | 'attr-value': { 576 | pattern: /=(?:("|')(?:\\[\s\S]|(?!\1)[^\\])*\1|[^\s'">=]+)/i, 577 | inside: { 578 | punctuation: [ 579 | /^=/, 580 | { 581 | pattern: /(^|[^\\])["']/, 582 | lookbehind: true, 583 | }, 584 | ], 585 | }, 586 | }, 587 | punctuation: /\/?>/, 588 | 'attr-name': { 589 | pattern: /[^\s>\/]+/, 590 | inside: { 591 | namespace: /^[^\s>\/:]+:/, 592 | }, 593 | }, 594 | 595 | }, 596 | }, 597 | entity: /&#?[\da-z]{1,8};/i, 598 | }; 599 | 600 | Prism.languages.markup.tag.inside['attr-value'].inside.entity = Prism.languages.markup.entity; 601 | 602 | // Plugin to make entity title show the real entity, idea by Roman Komarov 603 | Prism.hooks.add('wrap', (env) => { 604 | 605 | if (env.type === 'entity') { 606 | env.attributes['title'] = env.content.replace(/&/, '&'); 607 | } 608 | }); 609 | 610 | Prism.languages.xml = Prism.languages.markup; 611 | Prism.languages.html = Prism.languages.markup; 612 | Prism.languages.mathml = Prism.languages.markup; 613 | Prism.languages.svg = Prism.languages.markup; 614 | 615 | 616 | /* ********************************************** 617 | Begin prism-css.js 618 | ********************************************** */ 619 | 620 | Prism.languages.css = { 621 | comment: /\/\*[\s\S]*?\*\//, 622 | atrule: { 623 | pattern: /@[\w-]+?.*?(?:;|(?=\s*\{))/i, 624 | inside: { 625 | rule: /@[\w-]+/, 626 | // See rest below 627 | }, 628 | }, 629 | url: /url\((?:(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1|.*?)\)/i, 630 | selector: /[^{}\s][^{};]*?(?=\s*\{)/, 631 | string: { 632 | pattern: /("|')(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/, 633 | greedy: true, 634 | }, 635 | property: /[-_a-z\xA0-\uFFFF][-\w\xA0-\uFFFF]*(?=\s*:)/i, 636 | important: /\B!important\b/i, 637 | function: /[-a-z0-9]+(?=\()/i, 638 | punctuation: /[(){};:]/, 639 | }; 640 | 641 | Prism.languages.css.atrule.inside.rest = Prism.languages.css; 642 | 643 | if (Prism.languages.markup) { 644 | Prism.languages.insertBefore('markup', 'tag', { 645 | style: { 646 | pattern: /()[\s\S]*?(?=<\/style>)/i, 647 | lookbehind: true, 648 | inside: Prism.languages.css, 649 | alias: 'language-css', 650 | greedy: true, 651 | }, 652 | }); 653 | 654 | Prism.languages.insertBefore('inside', 'attr-value', { 655 | 'style-attr': { 656 | pattern: /\s*style=("|')(?:\\[\s\S]|(?!\1)[^\\])*\1/i, 657 | inside: { 658 | 'attr-name': { 659 | pattern: /^\s*style/i, 660 | inside: Prism.languages.markup.tag.inside, 661 | }, 662 | punctuation: /^\s*=\s*['"]|['"]\s*$/, 663 | 'attr-value': { 664 | pattern: /.+/i, 665 | inside: Prism.languages.css, 666 | }, 667 | }, 668 | alias: 'language-css', 669 | }, 670 | }, Prism.languages.markup.tag); 671 | } 672 | 673 | /* ********************************************** 674 | Begin prism-clike.js 675 | ********************************************** */ 676 | 677 | Prism.languages.clike = { 678 | comment: [ 679 | { 680 | pattern: /(^|[^\\])\/\*[\s\S]*?(?:\*\/|$)/, 681 | lookbehind: true, 682 | }, 683 | { 684 | pattern: /(^|[^\\:])\/\/.*/, 685 | lookbehind: true, 686 | greedy: true, 687 | }, 688 | ], 689 | string: { 690 | pattern: /(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/, 691 | greedy: true, 692 | }, 693 | 'class-name': { 694 | pattern: /((?:\b(?:class|interface|extends|implements|trait|instanceof|new)\s+)|(?:catch\s+\())[\w.\\]+/i, 695 | lookbehind: true, 696 | inside: { 697 | punctuation: /[.\\]/, 698 | }, 699 | }, 700 | keyword: /\b(?:if|else|while|do|for|return|in|instanceof|function|new|try|throw|catch|finally|null|break|continue)\b/, 701 | boolean: /\b(?:true|false)\b/, 702 | function: /[a-z0-9_]+(?=\()/i, 703 | number: /\b0x[\da-f]+\b|(?:\b\d+\.?\d*|\B\.\d+)(?:e[+-]?\d+)?/i, 704 | operator: /--?|\+\+?|!=?=?|<=?|>=?|==?=?|&&?|\|\|?|\?|\*|\/|~|\^|%/, 705 | punctuation: /[{}[\];(),.:]/, 706 | }; 707 | 708 | 709 | /* ********************************************** 710 | Begin prism-javascript.js 711 | ********************************************** */ 712 | 713 | Prism.languages.javascript = Prism.languages.extend('clike', { 714 | keyword: /\b(?:as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|var|void|while|with|yield)\b/, 715 | number: /\b(?:0[xX][\dA-Fa-f]+|0[bB][01]+|0[oO][0-7]+|NaN|Infinity)\b|(?:\b\d+\.?\d*|\B\.\d+)(?:[Ee][+-]?\d+)?/, 716 | // Allow for all non-ASCII characters (See http://stackoverflow.com/a/2008444) 717 | function: /[_$a-z\xA0-\uFFFF][$\w\xA0-\uFFFF]*(?=\s*\()/i, 718 | operator: /-[-=]?|\+[+=]?|!=?=?|<>?>?=?|=(?:==?|>)?|&[&=]?|\|[|=]?|\*\*?=?|\/=?|~|\^=?|%=?|\?|\.{3}/, 719 | }); 720 | 721 | Prism.languages.insertBefore('javascript', 'keyword', { 722 | regex: { 723 | pattern: /((?:^|[^$\w\xA0-\uFFFF."'\])\s])\s*)\/(\[[^\]\r\n]+]|\\.|[^/\\\[\r\n])+\/[gimyu]{0,5}(?=\s*($|[\r\n,.;})\]]))/, 724 | lookbehind: true, 725 | greedy: true, 726 | }, 727 | // This must be declared before keyword because we use "function" inside the look-forward 728 | 'function-variable': { 729 | pattern: /[_$a-z\xA0-\uFFFF][$\w\xA0-\uFFFF]*(?=\s*=\s*(?:function\b|(?:\([^()]*\)|[_$a-z\xA0-\uFFFF][$\w\xA0-\uFFFF]*)\s*=>))/i, 730 | alias: 'function', 731 | }, 732 | constant: /\b[A-Z][A-Z\d_]*\b/, 733 | }); 734 | 735 | Prism.languages.insertBefore('javascript', 'string', { 736 | 'template-string': { 737 | pattern: /`(?:\\[\s\S]|\${[^}]+}|[^\\`])*`/, 738 | greedy: true, 739 | inside: { 740 | interpolation: { 741 | pattern: /\${[^}]+}/, 742 | inside: { 743 | 'interpolation-punctuation': { 744 | pattern: /^\${|}$/, 745 | alias: 'punctuation', 746 | }, 747 | rest: null, // See below 748 | }, 749 | }, 750 | string: /[\s\S]+/, 751 | }, 752 | }, 753 | }); 754 | Prism.languages.javascript['template-string'].inside.interpolation.inside.rest = Prism.languages.javascript; 755 | 756 | if (Prism.languages.markup) { 757 | Prism.languages.insertBefore('markup', 'tag', { 758 | script: { 759 | pattern: /()[\s\S]*?(?=<\/script>)/i, 760 | lookbehind: true, 761 | inside: Prism.languages.javascript, 762 | alias: 'language-javascript', 763 | greedy: true, 764 | }, 765 | }); 766 | } 767 | 768 | Prism.languages.js = Prism.languages.javascript; 769 | 770 | export default Prism; -------------------------------------------------------------------------------- /docs/md/about.md: -------------------------------------------------------------------------------- 1 | ## About 2 | 3 | Or: _everything you wanted to know about H3, but you were afraid to ask_. 4 | 5 | ### Why the weird release labels? 6 | 7 | Ubuntu started [naming their releases after animals](https://wiki.ubuntu.com/DevelopmentCodeNames) in alphabetical order... In a similar way, H3 releases are named after [Star Trek species](https://memory-alpha.fandom.com/wiki/Species). 8 | 9 | ### A brief history of H3 10 | 11 | A while ago, I was interviewing with several companies trying to find a new job in the JavaScript ecosystem. One of these companies asked me, as a part of their interview process, to create a simple Todo List app in JavaScript *without using any libraries*. 12 | 13 | I spent some time thinking about it, started cobbling together a few lines of code doing the usual DOM manipulation stuff (how hard can it be, right? It's a Todo List!) and then stopped. 14 | 15 | _No way!_ — I thought. 16 | 17 | There has to be a better way. If only I could use something small like [Mithril](https://mithril.js.org), it would take me no time! But sadly I couldn't. Unless... 18 | 19 | Unless I coded the whole framework myself of course. And so I did, and that's more or less how H3 was born. You can see a slightly-modified version of the resultig Todo List app [here](https://h3.js.org/example/index.html) (with all the bonus points implemented, like localStorage support, pagination, filtering, etc.). 20 | 21 | The original version only had an even smaller (and even buggier) Virtual DOM and hyperscript implementation, no routing and no store, but it did the job. After a few additional interviews I was actually offered the job, however I didn't take it, but that's another story ;) 22 | 23 | A few months after that interview, I decided to take a look at that code, tidy it up, add a few bits and bobs, package it up and release it as a *proper* microframwork. Well, kind of. 24 | 25 | ### Credits 26 | 27 | The H3 web site is [built with H3 itself](https://github.com/h3rald/h3/blob/master/docs/js/app.js), plus the following third-party libraries: 28 | 29 | * [marked.js](https://marked.js.org/#/README.md#README.md) 30 | * [Prism.js](https://prismjs.com/) 31 | * [mini.css](https://minicss.org/) 32 | 33 | ### Special Thanks 34 | 35 | Special thanks to the following individuals, that made H3 possible: 36 | 37 | * **Leo Horie**, author of the awesome [Mithril](https://mithril.js.org/) framework that inspired me to write the H3 microframework in a moment of need. 38 | * **Andrey Sitnik**, author of the beatiful [Storeon](https://evilmartians.com/chronicles/storeon-redux-in-173-bytes) state management library, that is used (with minor modifications) as the H3 store. 39 | -------------------------------------------------------------------------------- /docs/md/api.md: -------------------------------------------------------------------------------- 1 | ## API 2 | 3 | The core of the H3 API is comprised of the following six methods and two properties. 4 | 5 | ### h(selector: string, attributes: object, children: array) 6 | 7 | The `h` function is a constructor for Virtual DOM Nodes (VNodes). It can actually take from one to any number of arguments used to configure the resulting node. 8 | 9 | The best way to understand how it works is by providing a few different examples. Please note that in each example the corresponding _HTML_ markup is provided, although such markup will actually be generated when the Virtual Node is rendered/redrawn. 10 | 11 | #### Create an element, with an ID, classes, attributes and children 12 | 13 | This is a complete example showing how to create a link with an `href` attribute, an ID, two classes, and three child nodes. 14 | 15 | ```js 16 | h( 17 | "a#test-link.btn.primary", 18 | { 19 | href: "#/test", 20 | }, 21 | ["This is a ", h("em", "test"), "link."] 22 | ); 23 | ``` 24 | 25 | ↓ 26 | 27 | ```html 28 | 29 | This is a test link. 30 | 31 | ``` 32 | 33 | #### Create an empty element 34 | 35 | ```js 36 | h("div"); 37 | ``` 38 | 39 | ↓ 40 | 41 | ```html 42 |
    43 | ``` 44 | 45 | #### Create an element with a textual child node 46 | 47 | ```js 48 | h("span", "This is a test"); 49 | ``` 50 | 51 | ↓ 52 | 53 | ```html 54 | This is a test 55 | ``` 56 | 57 | #### Create an element with child nodes 58 | 59 | ```js 60 | h("ol", [ 61 | h("li", "Do this first."), 62 | h("li", "Then this."), 63 | h("li", "And finally this."), 64 | ]); 65 | ``` 66 | 67 | _or_ 68 | 69 | ```js 70 | h( 71 | "ol", 72 | h("li", "Do this first."), 73 | h("li", "Then this."), 74 | h("li", "And finally this.") 75 | ); 76 | ``` 77 | 78 | ↓ 79 | 80 | ```html 81 |
      82 |
    1. Do this first.
    2. 83 |
    3. Then this.
    4. 84 |
    5. And finally this.
    6. 85 |
    86 | ``` 87 | 88 | #### Render a component 89 | 90 | ```js 91 | const TestComponent = () => { 92 | return h( 93 | "button.test", 94 | { 95 | onclick: () => alert("Hello!"), 96 | }, 97 | "Show Alert" 98 | ); 99 | }; 100 | h(TestComponent); 101 | ``` 102 | 103 | ↓ 104 | 105 | ```html 106 | 107 | ``` 108 | 109 | Note: The event listener will not be added to the markup. 110 | 111 | #### Render child components 112 | 113 | ```js 114 | const TestLi = (text) => h("li.test", text); 115 | h("ul", ["A", "B", "C"].map(TestLi)); 116 | ``` 117 | 118 | ↓ 119 | 120 | ```html 121 | 126 | ``` 127 | 128 | #### Special attributes 129 | 130 | - Any attribute starting with _on_ (e.g. onclick, onkeydown, etc.) will be treated as an event listener. 131 | - The `classList` attribute can be set to a list of classes to apply to the element (as an alternative to using the element selector shorthand). 132 | - The `data` attribute can be set to a simple object containing [data attributes](https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes). 133 | - The special `$html` attribute can be used to set the `innerHTML` property of the resulting HTML element. Use only if you know what you are doing! 134 | - The special `$onrender` attribute can be set to a function that will executed every time the VNode is rendered and added to the DOM. 135 | 136 | The `$html` and the `$onrender` special attributes should be used sparingly, and typically only when interfacing with third-party libraries that need access to the real DOM. 137 | 138 | For example, consider the following code snippet that can be used to initialize the [InscrybMDE](https://github.com/Inscryb/inscryb-markdown-editor) Markdown editor on a textarea element: 139 | 140 | ```js 141 | h("textarea", { 142 | $onrender: (element) => { 143 | const editor = new window.InscrybMDE({ 144 | element, 145 | }); 146 | }, 147 | }); 148 | ``` 149 | 150 | ### h3.screen({setup, display, teardown}) 151 | 152 | Creates a Screen by providing a (mandatory) **display** function used to render content, an an optional **setup** and **teardown** functions, executed before and after the display function respectively. 153 | 154 | Each of these functions takes a single **screen** parameter, which is initialized as an empty object before the setup, and is (optionally) returned by the teardown function should state be preserved across different screens. 155 | 156 | Consider the following example: 157 | 158 | ```js 159 | h3.screen({ 160 | setup: await (state) => { 161 | state.data = state.data || {}; 162 | state.id = h3.route.parts.id || 1; 163 | const url = `http://dummy.restapiexample.com/api/v1/employee/${id}`; 164 | state.data[id] = state.data[id] || await (await fetch(url)).json(); 165 | }, 166 | display(state) => { 167 | const employee = state.data[state.id]; 168 | if (!employee) { 169 | return h("div.error", "Invalid Employee ID."); 170 | } 171 | return h("div.employee", 172 | h("h2", "Employee Profile"), 173 | h("dl", [ 174 | h("dt", "Name:"), 175 | h("dd", data.employee_name), 176 | h("dt", "Salary:"), 177 | h("dd", `${data.employee_salary} €`), 178 | h("dt", "Age:"), 179 | h("dd", data.employee_age), 180 | ]) 181 | ) 182 | }, 183 | teardown: (state) => ({ data: state.data }) 184 | }) 185 | ``` 186 | 187 | This example shows how to implement a simple component that renders an employee profile in the `display` function, fetches data (if necessary) in the `setup` function, and preserves data in the `teardown` function. 188 | 189 | **Tip** To interrupt navigation or perform redirects, return **false** in the **setup** method. 190 | 191 | ### h3.dispatch(event: string, data: any) 192 | 193 | Dispatches a event and optionally some data. Messages are typically handled centrally by modules. 194 | 195 | ```js 196 | h3.dispatch("settings/set", { logging: true }); 197 | ``` 198 | 199 | A event name can be any string, but keep in mind that the following names (and typically any name starting with `$`) are reserved for framework use: 200 | 201 | - `$init` — Dispatched when the application is initialized. Useful to initialize application state. 202 | - `$redraw` — Dispatched after an application redraw is triggered. 203 | - `$navigation` — Dispatched after a navigation occurs. 204 | - `$log` — Dispatched after _any_ event (except `$log` iself) is dispatched. Very useful for debugging. 205 | 206 | ### h3.init(config: object) 207 | 208 | The initialization method of every H3 application. You _must_ call this method once to initialize your application by providing a component to render or configuration object with the following properties: 209 | 210 | - **element** (Element) — The DOM Element to which the Application will be attached (default: `document.body`). 211 | - **modules** (Array) — An array of functions used to handle the application state that will be executed once before starting the application. 212 | - **routes** (Object) — An object containing routing definitions, using paths as keys and components as values. Routing paths can contain named parts like `:name` or `:id` which will populate the `parts` property of the current route (`h3.route`). 213 | - **preStart** (Function) — An optional function to be executed before the application is first rendered. 214 | - **postStart** (Function) — An optional function to be executed after the application is first rendered. 215 | 216 | This is an example of a simple routing configuration: 217 | 218 | ```js 219 | const routes = { 220 | "/posts/:id": Post, 221 | "/pages/:id": Page, 222 | "/": HomePage, 223 | }; 224 | ``` 225 | 226 | For more a complete example of initialization, see [this](https://h3.js.org/example/assets/js/app.js). 227 | 228 | ### h3.navigateTo(path: string, params: object) 229 | 230 | Navigates to the specified path. Optionally, it is possibile to specify query string parameters as an object. 231 | 232 | The following call causes the application to switch to the following URL: `#/posts/?orderBy=date&direction=desc`. 233 | 234 | ```js 235 | h3.navigateTo("/posts/", { orderBy: "date", direction: "desc" }); 236 | ``` 237 | 238 | ### h3.on(event: string, handler: function) 239 | 240 | Subscribes to the specified event and executes the specified handler function whenever the event is dispatched. Returns a function that can be used to delete the subscription. 241 | 242 | Subscriptions should be typically managed in modules rather than in components: a component gets rendered several times and subscriptions _must_ be properly cleaned up to avoid memory leaks. 243 | 244 | Example: 245 | 246 | ```js 247 | const pages = (store) => { 248 | store.on("$init", () => ({ pagesize: 10, page: 1 })); 249 | store.on("pages/set", (state, page) => ({ page })); 250 | }; 251 | ``` 252 | 253 | ### h3.redraw() 254 | 255 | Triggers an application redraw. Unlike most frameworks, in H3 redraws _must_ be triggered explicitly. Just call this method whenever you want something to change and components to re-render. 256 | 257 | ### h3.route 258 | 259 | An read-only property containing current route (Route object). A Route object has the following properties: 260 | 261 | - **path** — The current path (fragment without #) without query string parameters, e.g. `/posts/134` 262 | - **def** — The matching route definition, e.g. `/posts/:id` 263 | - **query** — The query string, if present, e.g. `?comments=yes` 264 | - **part** — An object containing the values of the parts defined in the route, e.g. `{id: "134"}` 265 | - **params** — An object containing the query string parameters, e.g. `{comments: "yet"}` 266 | 267 | ### h3.state 268 | 269 | A read-only property containing the current application state. The state is a plain object, but its properties should only be modified using event subscription handlers. 270 | -------------------------------------------------------------------------------- /docs/md/best-practices.md: -------------------------------------------------------------------------------- 1 | ## Best Practices 2 | 3 | This page lists some common tips and best practices to get the most out of H3. Some of these may sound counter-intuitive (especially if you are using to frameworks advocating absolute data immutability), but they work well with H3 because of the way it is designed. 4 | 5 | ### Embrace Mutability 6 | 7 | No, that's not a mistake. Although you should understand [why immutability is important](https://stackoverflow.com/questions/34385243/why-is-immutability-so-important-or-needed-in-javascript), you shouldn't force yourself to use it in all situations. Instead, you should go through [this article](https://desalasworks.com/article/immutability-in-javascript-a-contrarian-view/) and try to understand also a contrarian view of immutability. 8 | 9 | In H3, changes only occur when needed. Most notably, when re-rendering the Virtual DOM tree of the application will be *mutated in place*, but only where necessary. Functions as well are considered equal if their source code (i.e. string representation) is equal. While this can cause problems in some situations if you are not aware of it, it can be beneficial and actually simplify things most of the time. 10 | 11 | When managing state, if something is different you should typically *just change it*, unless it's shared across the whole application through the Store, in which case (but only in that case) you should try to manage change without side effects and following basic immutability rules. As a rule of thumb, Modules should manage shared application state in an immutable way. 12 | 13 | ### Components 14 | 15 | * Avoid nesting component definitions, to avoid creating stale closures. Only define components within other components if you are not relying on changes affecting variables defined in the outer component within the inner component. 16 | * Component should only mutate their own local state. 17 | * Pay attention when relying on captured variables in event handlers, as they may become stale. In certain situations, you can pass data to event handlers through the DOM instead. 18 | * Add identifiers to the real DOM and use `event.currentTarget` in event handlers. 19 | * Use dataset to store identfiers in the real DOM. 20 | 21 | 22 | ### Screens 23 | 24 | * Use screens for complex, stateful components orchestrating nested "dumb" components. 25 | * Store event subscription destructors in the screen state and call them in the `teardown` method. 26 | * Return an object from the `teardown` method to preserve route state across screens, only if needed. 27 | * Use the `setup` method to define local, screen-level state that will be accessible in the `display` method. 28 | 29 | ### State Management 30 | 31 | * Application state should be stored in the H3 store and should not be mutated. 32 | * Use mutable objects for non-stored local state. 33 | * Use screen state to share data among complex components hierarchies. 34 | * Define separate model classes for complex objects. 35 | * Move complex data manipulation logic to model classes. 36 | * Use url parts and params as an easy way to keep references to recreate application state. -------------------------------------------------------------------------------- /docs/md/key-concepts.md: -------------------------------------------------------------------------------- 1 | ## Key Concepts 2 | 3 | There are just a few things you should know about if you want to use H3. 4 | 5 | Oh... and a solid understanding of HTML and JavaScript wouldn't hurt either ;) 6 | 7 | ### HyperScript 8 | 9 | H3 uses a [HyperScript](https://openbase.io/js/hyperscript)-like syntax to create HTML elements in pure JavaScript. No, you are actually creating Virtual DOM nodes with it but it can be easier to think about them as HTML elements, or better, something that *eventually* will be rendered as an HTML element. 10 | 11 | How, you ask? Like this: 12 | 13 | ```js 14 | h("div.test", [ 15 | h("ul", [ 16 | h("li", "This is..."), 17 | h("li", "...a simple..."), 18 | h("li", "unordered list.") 19 | ]) 20 | ]); 21 | ``` 22 | 23 | ...which will output: 24 | 25 | ```html 26 |
    27 |
      28 |
    • This is...
    • 29 |
    • ...a simple...
    • 30 |
    • ...unordered list.
    • 31 |
    32 |
    33 | ``` 34 | 35 | Simple enough. Yes there are some quirks to it, but check the API or Usage docs for those. 36 | 37 | ### Component 38 | 39 | In H3, a component is a function that returns a Virtual Node or a string (that will be treated as a textual DOM node). 40 | 41 | Yes that's it. An example? here: 42 | 43 | ```js 44 | let count = 0; 45 | const CounterButton = () => { 46 | return h("button", { 47 | onclick: () => count +=1 && h3.redraw() 48 | }, `You clicked me ${count} times.`); 49 | } 50 | ``` 51 | 52 | ### Router 53 | 54 | H3 comes with a very minimal but fully functional URL fragment router. You create your application routes when initializing your application, and you can navigate to them using ordinary `href` links or programmatically using the `h3.navigateTo` method. 55 | 56 | The current route is always accessible via the `h3.route` property. 57 | 58 | 59 | ### Screen 60 | 61 | A screen is a top-level component that handles a route. Unlike ordinary components, screens: 62 | 63 | * may have a dedicated *setup* (after the screen is added to the DOM) and *teardown* phase (after the screen is removed from the DOM and before the new screen is loaded). 64 | * may have built-in local state, initialized during setup and (typically) destroyed during teardown. Such state is passed as the first (and only) parameter of the screen when executed. 65 | 66 | Screens are typically created using the **h3.screen** shorthand method, but they can stll created using an ordinary function returning a VNode, but you can optionally define a **setup** and a **teardown** async methods on them (functions are objects in JavaScript after all...) to be executed during each corresponding phase. 67 | 68 | Note that: 69 | * Both the **setup** method take an object as a parameter, representing the component state. Such object will be empty the first time the **setup** method is called for a given component, but it may contain properties not removed during subsequent teardowns. 70 | * If the **setup** method returns **false**, the **display** method of the screen (or the main screen function if you created it manually) will not be executed (and a **$navigation** event will be dispatched with **null** as data parameter). This can be useful in certain situations to interrupt navigation or perform redirects. 71 | * The **teardown** method can return an object, which will be retained as component state. If however nothing is returned, the component state object is emptied. 72 | * Both methods can be asynchronous, in which case H3 will wait for their completion before proceeding. 73 | 74 | ### Store 75 | 76 | H3 essentially uses something very, *very* similar to [Storeon](https://github.com/storeon/storeon) for state management *and* also as a very simple client-side event dispatcher/subscriber (seriously, it is virtually the same code as Storeon). Typically you'll only use the default store created by H3 upon initialization, and you'll use the `h3.dispatch()` and `h3.on()` methods to dispatch and subscribe to events. 77 | 78 | The current application state is accessible via the `h3.state` property. 79 | 80 | ### Module 81 | 82 | The `h3.init()` method takes an array of *modules* that can be used to manipulate the application state when specific events are received. A simple module looks like this: 83 | 84 | ```js 85 | const error = () => { 86 | h3.on("$init", () => ({ displayEmptyTodoError: false })); 87 | h3.on("error/clear", (state) => ({ displayEmptyTodoError: false })); 88 | h3.on("error/set", (state) => ({ displayEmptyTodoError: true })); 89 | }; 90 | ``` 91 | 92 | Essentially a module is just a function that typically is meant to run only once to define one or more event subscriptions. Modules are the place where you should handle state changes in your application. 93 | 94 | ### How everything works... 95 | 96 | The following sequence diagram summarizes how H3 works, from its initialization to the redraw and navigation phases. 97 | 98 | ![Sequence Diagram](images/h3.sequence.svg) 99 | 100 | When the `h3.init()` method is called at application level, the following operations are performed in sequence: 101 | 102 | 1. The *Store* is created and initialized. 103 | 2. Any *Module* specified when calling `h3.init()` is executed. 104 | 3. The **$init** event is dispatched. 105 | 4. The *preStart* function (if specified when calling `h3.init()`) is executed. 106 | 5. The *Router* is initialized and started. 107 | 6. The **setup()** method of the matching Screen is called (if any). 108 | 8. The **$navigation** event is dispatched. 109 | 9. The *Screen* matching the current route and all its child components are rendered for the first time. 110 | 10. The **$redraw** event is dispatched. 111 | 112 | Then, whenever the `h3.redraw()` method is called (typically within a component): 113 | 114 | 1. The whole application is redrawn, i.e. every *Component* currently rendered on the page is redrawn. 115 | 2. The **$redraw** event is dispatched. 116 | 117 | Similarly, whenever the `h3.navigateTo()` method is called (typically within a component), or the URL fragment changes: 118 | 119 | 1. The *Router* processes the new path and determine which component to render based on the routing configuration. 120 | 2. The **teardow()** method of the current Screen is called (if any). 121 | 3. The **setup()** method of the new matching Screen is called (if any). 122 | 4. All DOM nodes within the scope of the routing are removed, all components are removed. 123 | 6. The **$navigation** event is dispatched. 124 | 7. All DOM nodes are removed. 125 | 8. The *Screen* matching the new route and all its child components are rendered. 126 | 10. The **$redraw** event is dispatched. 127 | 128 | And that's it. The whole idea is to make the system extremely *simple* and *predictable* — which means everything should be very easy to debug, too. 129 | -------------------------------------------------------------------------------- /docs/md/overview.md: -------------------------------------------------------------------------------- 1 | ## Overview 2 | 3 | **H3** is a microframework to build client-side single-page applications (SPAs) in modern JavaScript. 4 | 5 | H3 is also: 6 | 7 | - **tiny**, less than 4KB minified and gzipped. 8 | - **modern**, in the sense that it runs only in modern browsers (latest versions of Chrome, Firefox, Edge & similar). 9 | - **easy** to learn, its API is comprised of only seven methods and two properties. 10 | 11 | ### I'm sold! Where can I get it? 12 | 13 | Here, look, it's just one file: 14 | 15 | Download v0.11.0 (Keen Klingon) 16 | 17 | Or get the minified version here. 18 | 19 | Yes there is also a [NPM package](https://www.npmjs.com/package/@h3rald/h3) if you want to use it with WebPack and similar, but let me repeat: _it's just one file_. 20 | 21 | ### Hello, World? 22 | 23 | Here's an example of an extremely minimal SPA created with H3: 24 | 25 | ```js 26 | import { h3, h } from "./h3.js"; 27 | h3.init(() => h("h1", "Hello, World!")); 28 | ``` 29 | 30 | This will render a `h1` tag within the document body, containing the text `"Hello, World!"`. 31 | 32 | ### Something more complex? 33 | 34 | Have a look at the code of a [simple todo list](https://github.com/h3rald/h3/tree/master/docs/example) ([demo](https://h3.js.org/example/index.html)) with several components, a store and some routing. 35 | 36 | ### No, I meant a real web application... 37 | 38 | OK, have a look at [litepad.h3rald.com](https://litepad.h3rald.com) — it's a powerful notepad application that demonstrates how to create custom controls, route components, forms, and integrate third-party tools. The code is of course [on GitHub](https://github.com/h3rald/litepad). 39 | 40 | ### Can I use it then, no strings attached? 41 | 42 | Yes. It's [MIT-licensed](https://github.com/h3rald/h3/blob/master/LICENSE). 43 | 44 | ### What if something is broken? 45 | 46 | Go fix it! Or at least open an issue on the [Github repo](https://github.com/h3rald/h3), pleasy. 47 | 48 | ### Can I download a copy of all the documentation as a standalone HTML file? 49 | 50 | What a weird thing to ask... sure you can: [here](https://h3.js.org/H3_DeveloperGuide.htm)! 51 | -------------------------------------------------------------------------------- /docs/md/quick-start.md: -------------------------------------------------------------------------------- 1 | ## Quick Start 2 | 3 | Getting up and running with H3 is simple enough, and you don't even need any special tool to build or transpile your application (unless you really, *really* require IE11 support). 4 | 5 | ### Create a basic HTML file 6 | 7 | Start with a minimal HTML file like this one, and include an `app.js` script. That will be the entry point of your application: 8 | 9 | ```html 10 | 11 | 12 | 13 | My H3-powered App 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | ``` 22 | 23 | Note that the script must be marked as an ES6 module (`type="module"`), otherwise your imports won't work. 24 | 25 | ### Import h3 and h from h3.js 26 | 27 | Then, inside your `app.js` file, import `h` and `h3` from `h3.js`, which should be accessible somewhere in your app: 28 | 29 | ```js 30 | import { h3, h } from "./h3.js"; 31 | ``` 32 | 33 | This will work in [every modern browser except Internet Explorer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules). You don't need a transpiler, you don't need something to convert your beautiful ES6 code back to clunky ES5. 34 | 35 | Unless your company tells you to, do yourself a favor and don't support IE. It's 2020, even [Microsoft moved on](https://www.theverge.com/2020/1/15/21066767/microsoft-edge-chromium-new-browser-windows-mac-download-os), and now ES6 modules work in all major browsers. 36 | 37 | ### Create your SPA 38 | 39 | After importing the `h3` object and the `h` function, you can start developing your SPA. A bare minimum SPA is comprised by a single component passed to the `h3.init()` method: 40 | 41 | ```js 42 | // A simple component printing the current date and time 43 | // Pressig the Refresh button causes the application to redraw 44 | // And updates the displayed date/dime. 45 | const Page = () => { 46 | return h("main", [ 47 | h("h1", "Welcome!"), 48 | h("p", `The current date and time is ${new Date()}`), 49 | h("button", { 50 | onclick: () => h3.redraw() 51 | }, "Refresh") 52 | ]); 53 | } 54 | // Initialize your SPA 55 | h3.init(Page); 56 | ``` -------------------------------------------------------------------------------- /docs/md/tutorial.md: -------------------------------------------------------------------------------- 1 | ## Tutorial 2 | 3 | As a (meta) explanation of how to use H3, let's have a look at how the [H3 web site](https://h3.js.org) itself was created. 4 | 5 | The idea was to build a simple web site to display the documentation of the H3 microframework, so it must be able to: 6 | 7 | - Provide a simple way to navigate through page. 8 | - Render markdown content (via [marked.js](https://marked.js.org/#/README.md#README.md)) 9 | - Apply syntax highlighting (via [Prism.js](https://prismjs.com/)) 10 | 11 | As far as look and feel is concerned, I wanted something minimal but functional, so [mini.css](https://minicss.org/) was more than enough. 12 | 13 | The full source of the site is available [here](https://github.com/h3rald/h3/tree/master/docs). 14 | 15 | ### Create a simple HTML file 16 | 17 | Start by creating a simple HTML file. Place a script loading the entry point of your application within the `body` and set its type to `module`. 18 | 19 | This will let you load an ES6 file containing imports to other files... it works in all major browsers, but it doesn't work in IE (but we don't care about that, do we?). 20 | 21 | ```html 22 | 23 | 24 | 25 | 26 | H3 27 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | ``` 43 | 44 | ### Create a single-page application 45 | 46 | In this case the code for the SPA is not very complex, you can have a look at it [here](https://github.com/h3rald/h3/blob/master/docs/js/app.js). 47 | 48 | Normally you'd have several components, at least one file containing modules to manage the application state, etc. (see the [todo list example](https://github.com/h3rald/h3/tree/master/docs/example)), but in this case a single component is sufficient. 49 | 50 | Start by importing all the JavaScript modules you need: 51 | 52 | ```js 53 | import { h3, h } from "./h3.js"; 54 | import marked from "./vendor/marked.js"; 55 | import Prism from "./vendor/prism.js"; 56 | ``` 57 | 58 | Easy enough. Then we want to store the mapping between the different page fragments and their titles: 59 | 60 | ```js 61 | const labels = { 62 | overview: "Overview", 63 | "quick-start": "Quick Start", 64 | "key-concepts": "Key Concepts", 65 | "best-practices": "Best Practices", 66 | tutorial: "Tutorial", 67 | api: "API", 68 | about: "About", 69 | }; 70 | ``` 71 | 72 | We are going to store the HTML contents of each page in an Object, and we're going to need a simple function to [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) the Markdown file and render it as HTML: 73 | 74 | ```js 75 | const fetchPage = async ({ pages, id, md }) => { 76 | if (!pages[id]) { 77 | const response = await fetch(md); 78 | const text = await response.text(); 79 | pages[id] = marked(text); 80 | } 81 | }; 82 | ``` 83 | 84 | Basically this function is going to be called when you navigate to each page, and it: 85 | 86 | 1. fetches the content of the requested file (`md`)) 87 | 2. renders the Markdown code into HTML using the _marked_ library, and stores it in the `pages` object 88 | 89 | We are gonna use our `fetchPage` function inside the `setup` of the main (and only) screen of our app, `Page`: 90 | 91 | ```js 92 | const Page = h3.screen({ 93 | setup: async (state) => { 94 | state.pages = {}; 95 | state.id = h3.route.path.slice(1); 96 | state.ids = Object.keys(labels); 97 | state.md = state.ids.includes(state.id) 98 | ? `md/${state.id}.md` 99 | : `md/overview.md`; 100 | await fetchPage(state); 101 | }, 102 | display: (state) => { 103 | return h("div.page", [ 104 | Header, 105 | h("div.row", [ 106 | h("input#drawer-control.drawer", { type: "checkbox" }), 107 | Navigation(state.id, state.ids), 108 | Content(state.pages[state.id]), 109 | Footer, 110 | ]), 111 | ]); 112 | }, 113 | teardown: (state) => state, 114 | }); 115 | ``` 116 | 117 | Note that this screen has a `setup`, a `display` and a `teardown` method, both taking `state` as parameter. In H3, screens are nothing but stateful components that are used to render the whole page of the application, and are therefore typically redered when navigating to a new route. 118 | 119 | The `state` parameter is nothing but an empty object that can be used to store data that will be accessible to the `setup`, `display` and `teardown` methods, and (typically) will be destroyed when another screen is rendered. 120 | 121 | The `setup` function allows you to perform some operations that should take place _before_ the screen is rendered. In this case, we want to fetch the page contents (if necessary) beforehand to avoid displaying a spinner while the content is being loaded. Note that the `setup` method can be asynchronous, and in this case the `display` method will not be called until all asynchronous operations have been completed (assuming you are `await`ing them). 122 | 123 | The `teardown` function in this case only makes sure that the existing screen state (in particular any loaded markdown page) will be passed on to the next screen during navigation (which, in this case, is still the `Page` screen), so that existing pages will not be fetched again. 124 | 125 | The main responsibility of this screen is to fetch the Markdown content and render the whole page, but note how the rendering different portions of the page are delegated to different components: `Header`, `Navigation`, `Content`, and `Footer`. 126 | 127 | The `Header` and `Footer` components are very simple: their only job is to render static content: 128 | 129 | ```js 130 | const Header = () => { 131 | return h("header.row.sticky", [ 132 | h("a.logo.col-sm-1", { href: "#/" }, [ 133 | h("img", { alt: "H3", src: "images/h3.svg" }), 134 | ]), 135 | h("div.version.col-sm.col-md", [ 136 | h("div.version-number", "v0.11.0"), 137 | h("div.version-label", "“Keen Klingon“"), 138 | ]), 139 | h("label.drawer-toggle.button.col-sm-last", { for: "drawer-control" }), 140 | ]); 141 | }; 142 | 143 | const Footer = () => { 144 | return h("footer", [h("div", "© 2020 Fabio Cevasco")]); 145 | }; 146 | ``` 147 | 148 | The `Navigation` component is more interesting, as it takes two parameters: 149 | 150 | - The ID of the current page 151 | - The list of page IDs 152 | 153 | ...and it uses this information to create the site navigation menu dynamically: 154 | 155 | ```js 156 | const Navigation = (id, ids) => { 157 | const menu = ids.map((p) => 158 | h(`a${p === id ? ".active" : ""}`, { href: `#/${p}` }, labels[p]) 159 | ); 160 | return h("nav#navigation.col-md-3", [ 161 | h("label.drawer-close", { for: "drawer-control" }), 162 | ...menu, 163 | ]); 164 | }; 165 | ``` 166 | 167 | Finally, the `Content` component takes a string containing the HTML of the page content to render using the special `$html` attribute that can be used to essentially set the `innerHTML` property of an element: 168 | 169 | ```js 170 | const Content = (html) => { 171 | const content = h("div.content", { $html: html }); 172 | return h("main.col-sm-12.col-md-9", [ 173 | h( 174 | "div.card.fluid", 175 | h("div.section", { $onrender: () => Prism.highlightAll() }, content) 176 | ), 177 | ]); 178 | }; 179 | ``` 180 | 181 | Now, the key here is that we are only ever going to render "known" pages that are listed in the `labels` object. 182 | 183 | Suppose for example that the `#/overview` page is loaded. The `h3.route.path` in this case is going to be set to `/overview`, which in turns corresponds to an ID of a well-known page (`overview`). 184 | 185 | In a similar way, other well-known pages can easily be mapped to IDs, but it is also important to handle _unknown_ pages (technically I could even pass an URL to a different site containing a malicious markdown page and have it rendered!), and if a page passed in the URL fragment is not present in the `labels` Object, the Overview page will be rendered instead. 186 | 187 | This feature is also handy to automatically load the Overview when no fragment is specified. 188 | 189 | What is that weird `$onrender` property you ask? Well, that's a H3-specific callback that will be executed whenever the corresponding DOM node is rendered... that's essentially the perfect place to for executing operations that must be perform when the DOM is fully available, like highlighting our code snippets using _Prism_ in this case. 190 | 191 | ### Initialization 192 | 193 | Done? Not quite. We need to initialize the SPA by passing the `Page` component to the `h3.init()` method to trigger the first rendering: 194 | 195 | ```js 196 | h3.init(Page); 197 | ``` 198 | 199 | And that's it. Now, keep in mind that this is the _short_ version of initialization using a single component and a single route, but still, that's good enough for our use case. 200 | 201 | ### Next steps 202 | 203 | Made it this far? Good. Wanna know more? Have a look at the code of the [todo list example](https://github.com/h3rald/h3/tree/master/docs/example) and try it out [here](https://h3.js.org/example/index.html). 204 | 205 | Once you feel more comfortable and you are ready to dive into a more complex application, featuring different routes, screens, forms, validation, confirmation messages, plenty of third-party components etc., have a look at [LitePad](https://github.com/h3rald/litepad). You can see it in action here: [litepad.h3rald.com](https://litepad.h3rald.com/). 206 | 207 | Note: the LitePad online demo will store all its data in localStorage. 208 | -------------------------------------------------------------------------------- /h3.js: -------------------------------------------------------------------------------- 1 | /** 2 | * H3 v0.11.0 "Keen Klingon" 3 | * Copyright 2020 Fabio Cevasco 4 | * 5 | * @license MIT 6 | * For the full license, see: https://github.com/h3rald/h3/blob/master/LICENSE 7 | */ 8 | const checkProperties = (obj1, obj2) => { 9 | if (Object.keys(obj1).length !== Object.keys(obj2).length) { 10 | return false; 11 | } 12 | for (const key in obj1) { 13 | if (!(key in obj2)) { 14 | return false; 15 | } 16 | if (!equal(obj1[key], obj2[key])) { 17 | return false; 18 | } 19 | } 20 | return true; 21 | }; 22 | 23 | const blank = (v) => [undefined, null].includes(v); 24 | 25 | const equal = (obj1, obj2) => { 26 | if ((obj1 === null && obj2 === null) || (obj1 === undefined && obj2 === undefined)) { 27 | return true; 28 | } 29 | if ((obj1 === undefined && obj2 !== undefined) || (obj1 !== undefined && obj2 === undefined) || (obj1 === null && obj2 !== null) || (obj1 !== null && obj2 === null)) { 30 | return false; 31 | } 32 | if (obj1.constructor !== obj2.constructor) { 33 | return false; 34 | } 35 | if (typeof obj1 === 'function') { 36 | if (obj1.toString() !== obj2.toString()) { 37 | return false; 38 | } 39 | } 40 | if ([String, Number, Boolean].includes(obj1.constructor)) { 41 | return obj1 === obj2; 42 | } 43 | if (obj1.constructor === Array) { 44 | if (obj1.length !== obj2.length) { 45 | return false; 46 | } 47 | for (let i = 0; i < obj1.length; i++) { 48 | if (!equal(obj1[i], obj2[i])) { 49 | return false; 50 | } 51 | } 52 | return true; 53 | } 54 | return checkProperties(obj1, obj2); 55 | }; 56 | 57 | const selectorRegex = /^([a-z][a-z0-9:_=-]*)?(#[a-z0-9:_=-]+)?(\.[^ ]+)*$/i; 58 | const [PATCH, INSERT, DELETE] = [-1, -2, -3]; 59 | let $onrenderCallbacks = []; 60 | 61 | // Virtual DOM implementation with HyperScript syntax 62 | class VNode { 63 | constructor(...args) { 64 | this.type = undefined; 65 | this.props = {}; 66 | this.data = {}; 67 | this.id = undefined; 68 | this.$html = undefined; 69 | this.$onrender = undefined; 70 | this.style = undefined; 71 | this.value = undefined; 72 | this.children = []; 73 | this.classList = []; 74 | this.eventListeners = {}; 75 | if (args.length === 0) { 76 | throw new Error('[VNode] No arguments passed to VNode constructor.'); 77 | } 78 | if (args.length === 1) { 79 | let vnode = args[0]; 80 | if (typeof vnode === 'string') { 81 | // Assume empty element 82 | this.processSelector(vnode); 83 | } else if (typeof vnode === 'function' || (typeof vnode === 'object' && vnode !== null)) { 84 | // Text node 85 | if (vnode.type === '#text') { 86 | this.type = '#text'; 87 | this.value = vnode.value; 88 | } else { 89 | this.from(this.processVNodeObject(vnode)); 90 | } 91 | } else { 92 | throw new Error('[VNode] Invalid first argument passed to VNode constructor.'); 93 | } 94 | } else if (args.length === 2) { 95 | let [selector, data] = args; 96 | if (typeof selector !== 'string') { 97 | throw new Error('[VNode] Invalid first argument passed to VNode constructor.'); 98 | } 99 | this.processSelector(selector); 100 | if (typeof data === 'string') { 101 | // Assume single child text node 102 | this.children = [new VNode({ type: '#text', value: data })]; 103 | return; 104 | } 105 | if (typeof data !== 'function' && (typeof data !== 'object' || data === null)) { 106 | throw new Error('[VNode] The second argument of a VNode constructor must be an object, an array or a string.'); 107 | } 108 | if (Array.isArray(data)) { 109 | // Assume 2nd argument as children 110 | this.processChildren(data); 111 | } else { 112 | if (data instanceof Function || data instanceof VNode) { 113 | this.processChildren(data); 114 | } else { 115 | // Not a VNode, assume props object 116 | this.processProperties(data); 117 | } 118 | } 119 | } else { 120 | let [selector, props, children] = args; 121 | if (args.length > 3) { 122 | children = args.slice(2); 123 | } 124 | children = Array.isArray(children) ? children : [children]; 125 | if (typeof selector !== 'string') { 126 | throw new Error('[VNode] Invalid first argument passed to VNode constructor.'); 127 | } 128 | this.processSelector(selector); 129 | if (props instanceof Function || props instanceof VNode || typeof props === 'string') { 130 | // 2nd argument is a child 131 | children = [props].concat(children); 132 | } else { 133 | if (typeof props !== 'object' || props === null) { 134 | throw new Error('[VNode] Invalid second argument passed to VNode constructor.'); 135 | } 136 | this.processProperties(props); 137 | } 138 | this.processChildren(children); 139 | } 140 | } 141 | 142 | from(data) { 143 | this.value = data.value; 144 | this.type = data.type; 145 | this.id = data.id; 146 | this.$html = data.$html; 147 | this.$onrender = data.$onrender; 148 | this.style = data.style; 149 | this.data = data.data; 150 | this.value = data.value; 151 | this.eventListeners = data.eventListeners; 152 | this.children = data.children; 153 | this.props = data.props; 154 | this.classList = data.classList; 155 | } 156 | 157 | equal(a, b) { 158 | return equal(a, b === undefined ? this : b); 159 | } 160 | 161 | processProperties(attrs) { 162 | this.id = this.id || attrs.id; 163 | this.$html = attrs.$html; 164 | this.$onrender = attrs.$onrender; 165 | this.style = attrs.style; 166 | this.value = attrs.value; 167 | this.data = attrs.data || {}; 168 | this.classList = attrs.classList && attrs.classList.length > 0 ? attrs.classList : this.classList; 169 | this.props = attrs; 170 | Object.keys(attrs) 171 | .filter((a) => a.startsWith('on') && attrs[a]) 172 | .forEach((key) => { 173 | if (typeof attrs[key] !== 'function') { 174 | throw new Error(`[VNode] Event handler specified for ${key} event is not a function.`); 175 | } 176 | this.eventListeners[key.slice(2)] = attrs[key]; 177 | delete this.props[key]; 178 | }); 179 | delete this.props.value; 180 | delete this.props.$html; 181 | delete this.props.$onrender; 182 | delete this.props.id; 183 | delete this.props.data; 184 | delete this.props.style; 185 | delete this.props.classList; 186 | } 187 | 188 | processSelector(selector) { 189 | if (!selector.match(selectorRegex) || selector.length === 0) { 190 | throw new Error(`[VNode] Invalid selector: ${selector}`); 191 | } 192 | const [, type, id, classes] = selector.match(selectorRegex); 193 | this.type = type; 194 | if (id) { 195 | this.id = id.slice(1); 196 | } 197 | this.classList = (classes && classes.split('.').slice(1)) || []; 198 | } 199 | 200 | processVNodeObject(arg) { 201 | if (arg instanceof VNode) { 202 | return arg; 203 | } 204 | if (arg instanceof Function) { 205 | let vnode = arg(); 206 | if (typeof vnode === 'string') { 207 | vnode = new VNode({ type: '#text', value: vnode }); 208 | } 209 | if (!(vnode instanceof VNode)) { 210 | throw new Error('[VNode] Function argument does not return a VNode'); 211 | } 212 | return vnode; 213 | } 214 | throw new Error('[VNode] Invalid first argument provided to VNode constructor.'); 215 | } 216 | 217 | processChildren(arg) { 218 | const children = Array.isArray(arg) ? arg : [arg]; 219 | this.children = children 220 | .map((c) => { 221 | if (typeof c === 'string') { 222 | return new VNode({ type: '#text', value: c }); 223 | } 224 | if (typeof c === 'function' || (typeof c === 'object' && c !== null)) { 225 | return this.processVNodeObject(c); 226 | } 227 | if (c) { 228 | throw new Error(`[VNode] Specified child is not a VNode: ${c}`); 229 | } 230 | }) 231 | .filter((c) => c); 232 | } 233 | 234 | // Renders the actual DOM Node corresponding to the current Virtual Node 235 | render() { 236 | if (this.type === '#text') { 237 | return document.createTextNode(this.value); 238 | } 239 | const node = document.createElement(this.type); 240 | if (!blank(this.id)) { 241 | node.id = this.id; 242 | } 243 | Object.keys(this.props).forEach((p) => { 244 | // Set attributes 245 | if (typeof this.props[p] === 'boolean') { 246 | this.props[p] ? node.setAttribute(p, '') : node.removeAttribute(p); 247 | } 248 | if (['string', 'number'].includes(typeof this.props[p])) { 249 | node.setAttribute(p, this.props[p]); 250 | } 251 | // Set properties 252 | node[p] = this.props[p]; 253 | }); 254 | // Event Listeners 255 | Object.keys(this.eventListeners).forEach((event) => { 256 | node.addEventListener(event, this.eventListeners[event]); 257 | }); 258 | // Value 259 | if (this.value) { 260 | if (['textarea', 'input', 'option', 'button'].includes(this.type)) { 261 | node.value = this.value; 262 | } else { 263 | node.setAttribute('value', this.value.toString()); 264 | } 265 | } 266 | // Style 267 | if (this.style) { 268 | node.style.cssText = this.style; 269 | } 270 | // Classes 271 | this.classList.forEach((c) => { 272 | c && node.classList.add(c); 273 | }); 274 | // Data 275 | Object.keys(this.data).forEach((key) => { 276 | node.dataset[key] = this.data[key]; 277 | }); 278 | // Children 279 | this.children.forEach((c) => { 280 | const cnode = c.render(); 281 | node.appendChild(cnode); 282 | c.$onrender && $onrenderCallbacks.push(() => c.$onrender(cnode)); 283 | }); 284 | if (this.$html) { 285 | node.innerHTML = this.$html; 286 | } 287 | return node; 288 | } 289 | 290 | // Updates the current Virtual Node with a new Virtual Node (and syncs the existing DOM Node) 291 | redraw(data) { 292 | let { node, vnode } = data; 293 | const newvnode = vnode; 294 | const oldvnode = this; 295 | if ( 296 | oldvnode.constructor !== newvnode.constructor || 297 | oldvnode.type !== newvnode.type || 298 | (oldvnode.type === newvnode.type && oldvnode.type === '#text' && oldvnode !== newvnode) 299 | ) { 300 | const renderedNode = newvnode.render(); 301 | node.parentNode.replaceChild(renderedNode, node); 302 | newvnode.$onrender && newvnode.$onrender(renderedNode); 303 | oldvnode.from(newvnode); 304 | return; 305 | } 306 | // ID 307 | if (oldvnode.id !== newvnode.id) { 308 | node.id = newvnode.id; 309 | oldvnode.id = newvnode.id; 310 | } 311 | // Value 312 | if (oldvnode.value !== newvnode.value) { 313 | oldvnode.value = newvnode.value; 314 | if (['textarea', 'input', 'option', 'button'].includes(oldvnode.type)) { 315 | node.value = blank(newvnode.value) ? '' : newvnode.value.toString(); 316 | } else { 317 | node.setAttribute('value', blank(newvnode.value) ? '' : newvnode.value.toString()); 318 | } 319 | } 320 | // Classes 321 | if (!equal(oldvnode.classList, newvnode.classList)) { 322 | oldvnode.classList.forEach((c) => { 323 | if (!newvnode.classList.includes(c)) { 324 | node.classList.remove(c); 325 | } 326 | }); 327 | newvnode.classList.forEach((c) => { 328 | if (c && !oldvnode.classList.includes(c)) { 329 | node.classList.add(c); 330 | } 331 | }); 332 | oldvnode.classList = newvnode.classList; 333 | } 334 | // Style 335 | if (oldvnode.style !== newvnode.style) { 336 | node.style.cssText = newvnode.style || ''; 337 | oldvnode.style = newvnode.style; 338 | } 339 | // Data 340 | if (!equal(oldvnode.data, newvnode.data)) { 341 | Object.keys(oldvnode.data).forEach((a) => { 342 | if (!newvnode.data[a]) { 343 | delete node.dataset[a]; 344 | } else if (newvnode.data[a] !== oldvnode.data[a]) { 345 | node.dataset[a] = newvnode.data[a]; 346 | } 347 | }); 348 | Object.keys(newvnode.data).forEach((a) => { 349 | if (!oldvnode.data[a]) { 350 | node.dataset[a] = newvnode.data[a]; 351 | } 352 | }); 353 | oldvnode.data = newvnode.data; 354 | } 355 | // Properties & Attributes 356 | if (!equal(oldvnode.props, newvnode.props)) { 357 | Object.keys(oldvnode.props).forEach((a) => { 358 | node[a] = newvnode.props[a]; 359 | if (typeof newvnode.props[a] === 'boolean') { 360 | oldvnode.props[a] = newvnode.props[a]; 361 | newvnode.props[a] ? node.setAttribute(a, '') : node.removeAttribute(a); 362 | } else if ([null, undefined].includes(newvnode.props[a])) { 363 | delete oldvnode.props[a]; 364 | node.removeAttribute(a); 365 | } else if (newvnode.props[a] !== oldvnode.props[a]) { 366 | oldvnode.props[a] = newvnode.props[a]; 367 | if (['string', 'number'].includes(typeof newvnode.props[a])) { 368 | node.setAttribute(a, newvnode.props[a]); 369 | } 370 | } 371 | }); 372 | Object.keys(newvnode.props).forEach((a) => { 373 | if (blank(oldvnode.props[a]) && !blank(newvnode.props[a])) { 374 | oldvnode.props[a] = newvnode.props[a]; 375 | node[a] = newvnode.props[a]; 376 | if (typeof newvnode.props[a] === 'boolean') { 377 | node.setAttribute(a, ''); 378 | } else if (['string', 'number'].includes(typeof newvnode.props[a])) { 379 | node.setAttribute(a, newvnode.props[a]); 380 | } 381 | } 382 | }); 383 | } 384 | // Event listeners 385 | if (!equal(oldvnode.eventListeners, newvnode.eventListeners)) { 386 | Object.keys(oldvnode.eventListeners).forEach((a) => { 387 | if (!newvnode.eventListeners[a]) { 388 | node.removeEventListener(a, oldvnode.eventListeners[a]); 389 | } else if (!equal(newvnode.eventListeners[a], oldvnode.eventListeners[a])) { 390 | node.removeEventListener(a, oldvnode.eventListeners[a]); 391 | node.addEventListener(a, newvnode.eventListeners[a]); 392 | } 393 | }); 394 | Object.keys(newvnode.eventListeners).forEach((a) => { 395 | if (!oldvnode.eventListeners[a]) { 396 | node.addEventListener(a, newvnode.eventListeners[a]); 397 | } 398 | }); 399 | oldvnode.eventListeners = newvnode.eventListeners; 400 | } 401 | // Children 402 | let childMap = mapChildren(oldvnode, newvnode); 403 | let resultMap = [...Array(newvnode.children.length).keys()]; 404 | while (!equal(childMap, resultMap)) { 405 | let count = -1; 406 | checkmap: for (const i of childMap) { 407 | count++; 408 | if (i === count) { 409 | // Matching nodes; 410 | continue; 411 | } 412 | switch (i) { 413 | case PATCH: { 414 | oldvnode.children[count].redraw({ 415 | node: node.childNodes[count], 416 | vnode: newvnode.children[count], 417 | }); 418 | break checkmap; 419 | } 420 | case INSERT: { 421 | oldvnode.children.splice(count, 0, newvnode.children[count]); 422 | const renderedNode = newvnode.children[count].render(); 423 | node.insertBefore(renderedNode, node.childNodes[count]); 424 | newvnode.children[count].$onrender && newvnode.children[count].$onrender(renderedNode); 425 | break checkmap; 426 | } 427 | case DELETE: { 428 | oldvnode.children.splice(count, 1); 429 | node.removeChild(node.childNodes[count]); 430 | break checkmap; 431 | } 432 | default: { 433 | const vtarget = oldvnode.children.splice(i, 1)[0]; 434 | oldvnode.children.splice(count, 0, vtarget); 435 | const target = node.removeChild(node.childNodes[i]); 436 | node.insertBefore(target, node.childNodes[count]); 437 | break checkmap; 438 | } 439 | } 440 | } 441 | childMap = mapChildren(oldvnode, newvnode); 442 | resultMap = [...Array(newvnode.children.length).keys()]; 443 | } 444 | // $onrender 445 | if (!equal(oldvnode.$onrender, newvnode.$onrender)) { 446 | oldvnode.$onrender = newvnode.$onrender; 447 | } 448 | // innerHTML 449 | if (oldvnode.$html !== newvnode.$html) { 450 | node.innerHTML = newvnode.$html; 451 | oldvnode.$html = newvnode.$html; 452 | oldvnode.$onrender && oldvnode.$onrender(node); 453 | } 454 | } 455 | } 456 | 457 | const mapChildren = (oldvnode, newvnode) => { 458 | const newList = newvnode.children; 459 | const oldList = oldvnode.children; 460 | let map = []; 461 | for (let nIdx = 0; nIdx < newList.length; nIdx++) { 462 | let op = PATCH; 463 | for (let oIdx = 0; oIdx < oldList.length; oIdx++) { 464 | if (equal(newList[nIdx], oldList[oIdx]) && !map.includes(oIdx)) { 465 | op = oIdx; // Same node found 466 | break; 467 | } 468 | } 469 | if (op < 0 && newList.length >= oldList.length && map.length >= oldList.length) { 470 | op = INSERT; 471 | } 472 | map.push(op); 473 | } 474 | const oldNodesFound = map.filter((c) => c >= 0); 475 | if (oldList.length > newList.length) { 476 | // Remove remaining nodes 477 | [...Array(oldList.length - newList.length).keys()].forEach(() => map.push(DELETE)); 478 | } else if (oldNodesFound.length === oldList.length) { 479 | // All nodes not found are insertions 480 | map = map.map((c) => (c < 0 ? INSERT : c)); 481 | } 482 | return map; 483 | }; 484 | 485 | /** 486 | * The code of the following class is heavily based on Storeon 487 | * Modified according to the terms of the MIT License 488 | * 489 | * Copyright 2019 Andrey Sitnik 490 | */ 491 | class Store { 492 | constructor() { 493 | this.events = {}; 494 | this.state = {}; 495 | } 496 | dispatch(event, data) { 497 | if (event !== '$log') this.dispatch('$log', { event, data }); 498 | if (this.events[event]) { 499 | let changes = {}; 500 | let changed; 501 | this.events[event].forEach((i) => { 502 | this.state = { ...this.state, ...i(this.state, data) }; 503 | }); 504 | } 505 | } 506 | 507 | on(event, cb) { 508 | (this.events[event] || (this.events[event] = [])).push(cb); 509 | 510 | return () => { 511 | this.events[event] = this.events[event].filter((i) => i !== cb); 512 | }; 513 | } 514 | } 515 | 516 | class Route { 517 | constructor({ path, def, query, parts }) { 518 | this.path = path; 519 | this.def = def; 520 | this.query = query; 521 | this.parts = parts; 522 | this.params = {}; 523 | if (this.query) { 524 | const rawParams = this.query.split('&'); 525 | rawParams.forEach((p) => { 526 | const [name, value] = p.split('='); 527 | this.params[decodeURIComponent(name)] = decodeURIComponent(value); 528 | }); 529 | } 530 | } 531 | } 532 | 533 | class Router { 534 | constructor({ element, routes, store, location }) { 535 | this.element = element; 536 | this.redraw = null; 537 | this.store = store; 538 | this.location = location || window.location; 539 | if (!routes || Object.keys(routes).length === 0) { 540 | throw new Error('[Router] No routes defined.'); 541 | } 542 | const defs = Object.keys(routes); 543 | this.routes = routes; 544 | } 545 | 546 | setRedraw(vnode, state) { 547 | this.redraw = () => { 548 | vnode.redraw({ 549 | node: this.element.childNodes[0], 550 | vnode: this.routes[this.route.def](state), 551 | }); 552 | this.store.dispatch('$redraw'); 553 | }; 554 | } 555 | 556 | async start() { 557 | const processPath = async (data) => { 558 | const oldRoute = this.route; 559 | const fragment = (data && data.newURL && data.newURL.match(/(#.+)$/) && data.newURL.match(/(#.+)$/)[1]) || this.location.hash; 560 | const path = fragment.replace(/\?.+$/, '').slice(1); 561 | const rawQuery = fragment.match(/\?(.+)$/); 562 | const query = rawQuery && rawQuery[1] ? rawQuery[1] : ''; 563 | const pathParts = path.split('/').slice(1); 564 | 565 | let parts = {}; 566 | let newRoute; 567 | for (let def of Object.keys(this.routes)) { 568 | let routeParts = def.split('/').slice(1); 569 | let match = true; 570 | let index = 0; 571 | parts = {}; 572 | while (match && routeParts[index]) { 573 | const rP = routeParts[index]; 574 | const pP = pathParts[index]; 575 | if (rP.startsWith(':') && pP) { 576 | parts[rP.slice(1)] = pP; 577 | } else { 578 | match = rP === pP; 579 | } 580 | index++; 581 | } 582 | if (match) { 583 | newRoute = new Route({ query, path, def, parts }); 584 | break; 585 | } 586 | } 587 | if (!newRoute) { 588 | throw new Error(`[Router] No route matches '${fragment}'`); 589 | } 590 | // Old route component teardown 591 | let state = {}; 592 | if (oldRoute) { 593 | const oldRouteComponent = this.routes[oldRoute.def]; 594 | state = (oldRouteComponent.teardown && (await oldRouteComponent.teardown(oldRouteComponent.state))) || state; 595 | } 596 | // New route component setup 597 | const newRouteComponent = this.routes[newRoute.def]; 598 | newRouteComponent.state = state; 599 | if (newRouteComponent.setup) { 600 | this.route = newRoute; 601 | if ((await newRouteComponent.setup(newRouteComponent.state)) === false) { 602 | // Abort navigation 603 | this.route = oldRoute; 604 | this.store.dispatch('$navigation', null); 605 | return; 606 | } 607 | } 608 | this.route = newRoute; 609 | // Redrawing... 610 | redrawing = true; 611 | this.store.dispatch('$navigation', this.route); 612 | while (this.element.firstChild) { 613 | this.element.removeChild(this.element.firstChild); 614 | } 615 | const vnode = newRouteComponent(newRouteComponent.state); 616 | const node = vnode.render(); 617 | this.element.appendChild(node); 618 | this.setRedraw(vnode, newRouteComponent.state); 619 | redrawing = false; 620 | vnode.$onrender && vnode.$onrender(node); 621 | $onrenderCallbacks.forEach((cbk) => cbk()); 622 | $onrenderCallbacks = []; 623 | window.scrollTo(0, 0); 624 | this.store.dispatch('$redraw'); 625 | }; 626 | window.addEventListener('hashchange', processPath); 627 | await processPath(); 628 | } 629 | 630 | navigateTo(path, params) { 631 | let query = Object.keys(params || {}) 632 | .map((p) => `${encodeURIComponent(p)}=${encodeURIComponent(params[p])}`) 633 | .join('&'); 634 | query = query ? `?${query}` : ''; 635 | this.location.hash = `#${path}${query}`; 636 | } 637 | } 638 | 639 | // High Level API 640 | 641 | export const h = (...args) => { 642 | return new VNode(...args); 643 | }; 644 | 645 | export const h3 = {}; 646 | 647 | let store = null; 648 | let router = null; 649 | let redrawing = false; 650 | 651 | h3.init = (config) => { 652 | let { element, routes, modules, preStart, postStart, location } = config; 653 | if (!routes) { 654 | // Assume config is a component object, define default route 655 | if (typeof config !== 'function') { 656 | throw new Error('[h3.init] The specified argument is not a valid configuration object or component function'); 657 | } 658 | routes = { '/': config }; 659 | } 660 | element = element || document.body; 661 | if (!(element && element instanceof Element)) { 662 | throw new Error('[h3.init] Invalid element specified.'); 663 | } 664 | // Initialize store 665 | store = new Store(); 666 | (modules || []).forEach((i) => { 667 | i(store); 668 | }); 669 | store.dispatch('$init'); 670 | // Initialize router 671 | router = new Router({ element, routes, store, location }); 672 | return Promise.resolve(preStart && preStart()) 673 | .then(() => router.start()) 674 | .then(() => postStart && postStart()); 675 | }; 676 | 677 | h3.navigateTo = (path, params) => { 678 | if (!router) { 679 | throw new Error('[h3.navigateTo] No application initialized, unable to navigate.'); 680 | } 681 | return router.navigateTo(path, params); 682 | }; 683 | 684 | Object.defineProperty(h3, 'route', { 685 | get: () => { 686 | if (!router) { 687 | throw new Error('[h3.route] No application initialized, unable to retrieve current route.'); 688 | } 689 | return router.route; 690 | }, 691 | }); 692 | 693 | Object.defineProperty(h3, 'state', { 694 | get: () => { 695 | if (!store) { 696 | throw new Error('[h3.state] No application initialized, unable to retrieve current state.'); 697 | } 698 | return store.state; 699 | }, 700 | }); 701 | 702 | h3.on = (event, cb) => { 703 | if (!store) { 704 | throw new Error('[h3.on] No application initialized, unable to listen to events.'); 705 | } 706 | return store.on(event, cb); 707 | }; 708 | 709 | h3.dispatch = (event, data) => { 710 | if (!store) { 711 | throw new Error('[h3.dispatch] No application initialized, unable to dispatch events.'); 712 | } 713 | return store.dispatch(event, data); 714 | }; 715 | 716 | h3.redraw = (setRedrawing) => { 717 | if (!router || !router.redraw) { 718 | throw new Error('[h3.redraw] No application initialized, unable to redraw.'); 719 | } 720 | if (redrawing) { 721 | return; 722 | } 723 | redrawing = true; 724 | requestAnimationFrame(() => { 725 | router.redraw(); 726 | redrawing = setRedrawing || false; 727 | }); 728 | }; 729 | 730 | h3.screen = ({ setup, display, teardown }) => { 731 | if (!display || typeof display !== 'function') { 732 | throw new Error('[h3.screen] No display property specified.'); 733 | } 734 | if (setup && typeof setup !== 'function') { 735 | throw new Error('[h3.screen] setup property is not a function.'); 736 | } 737 | if (teardown && typeof teardown !== 'function') { 738 | throw new Error('[h3.screen] teardown property is not a function.'); 739 | } 740 | const fn = display; 741 | if (setup) { 742 | fn.setup = setup; 743 | } 744 | if (teardown) { 745 | fn.teardown = teardown; 746 | } 747 | return fn; 748 | }; 749 | 750 | export default h3; 751 | -------------------------------------------------------------------------------- /h3.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"sources":["0"],"names":["checkProperties","obj1","obj2","Object","keys","length","key","equal","blank","v","undefined","includes","constructor","toString","String","Number","Boolean","Array","i","selectorRegex","PATCH","INSERT","DELETE","$onrenderCallbacks","VNode","[object Object]","args","this","type","props","data","id","$html","$onrender","style","value","children","classList","eventListeners","Error","vnode","processSelector","from","processVNodeObject","selector","isArray","Function","processChildren","processProperties","slice","concat","a","b","attrs","filter","startsWith","forEach","match","classes","split","arg","map","c","document","createTextNode","node","createElement","p","setAttribute","removeAttribute","event","addEventListener","cssText","add","dataset","cnode","render","appendChild","push","innerHTML","newvnode","oldvnode","renderedNode","parentNode","replaceChild","remove","removeEventListener","childMap","mapChildren","resultMap","count","checkmap","redraw","childNodes","splice","insertBefore","removeChild","vtarget","target","newList","oldList","nIdx","op","oIdx","oldNodesFound","Store","events","state","dispatch","cb","Route","path","def","query","parts","params","name","decodeURIComponent","Router","element","routes","store","location","window","route","processPath","async","oldRoute","fragment","newURL","hash","replace","rawQuery","pathParts","newRoute","routeParts","index","rP","pP","oldRouteComponent","teardown","newRouteComponent","setup","redrawing","firstChild","setRedraw","cbk","scrollTo","encodeURIComponent","join","h","h3","router","init","config","modules","preStart","postStart","/","body","Element","Promise","resolve","then","start","navigateTo","defineProperty","get","on","setRedrawing","requestAnimationFrame","screen","display","fn"],"mappings":";;;;;;;AAOA,MAAMA,gBAAkB,CAACC,EAAMC,KAC7B,GAAIC,OAAOC,KAAKH,GAAMI,SAAWF,OAAOC,KAAKF,GAAMG,OACjD,OAAO,EAET,IAAK,MAAMC,KAAO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AOmK,eAAef,GAAI,QAAS,CACjCgB,IAAK,KACH,IAAKf,OACH,MAAM,IAAIjH,MAAM,4EAElB,OAAOiH,OAAO5B,SAIlBzH,OAAOmK,eAAef,GAAI,QAAS,CACjCgB,IAAK,KACH,IAAK9C,MACH,MAAM,IAAIlF,MAAM,4EAElB,OAAOkF,MAAMd,SAIjB4C,GAAGiB,GAAK,CAAClG,EAAOuC,KACd,IAAKY,MACH,MAAM,IAAIlF,MAAM,mEAElB,OAAOkF,MAAM+C,GAAGlG,EAAOuC,IAGzB0C,GAAG3C,SAAW,CAACtC,EAAOxC,KACpB,IAAK2F,MACH,MAAM,IAAIlF,MAAM,wEAElB,OAAOkF,MAAMb,SAAStC,EAAOxC,IAG/ByH,GAAG3D,OAAU6E,IACX,IAAKjB,SAAWA,OAAO5D,OACrB,MAAM,IAAIrD,MAAM,6DAEdwG,YAGJA,WAAY,EACZ2B,sBAAsB,KACpBlB,OAAO5D,SACPmD,UAAY0B,IAAgB,MAIhClB,GAAGoB,OAAS,EAAG7B,MAAAA,EAAO8B,QAAAA,EAAShC,SAAAA,MAC7B,IAAKgC,GAA8B,mBAAZA,EACrB,MAAM,IAAIrI,MAAM,8CAElB,GAAIuG,GAA0B,mBAAVA,EAClB,MAAM,IAAIvG,MAAM,iDAElB,GAAIqG,GAAgC,mBAAbA,EACrB,MAAM,IAAIrG,MAAM,oDAElB,MAAMsI,EAAKD,EAOX,OANI9B,IACF+B,EAAG/B,MAAQA,GAETF,IACFiC,EAAGjC,SAAWA,GAETiC,kBAGMtB","file":"h3.js"} -------------------------------------------------------------------------------- /h3.min.js: -------------------------------------------------------------------------------- 1 | /** 2 | * H3 v0.11.0 "Keen Klingon" 3 | * Copyright 2020 Fabio Cevasco 4 | * 5 | * @license MIT 6 | * For the full license, see: https://github.com/h3rald/h3/blob/master/LICENSE 7 | */ 8 | const checkProperties=(e,t)=>{if(Object.keys(e).length!==Object.keys(t).length)return!1;for(const r in e){if(!(r in t))return!1;if(!equal(e[r],t[r]))return!1}return!0},blank=e=>[void 0,null].includes(e),equal=(e,t)=>{if(null===e&&null===t||void 0===e&&void 0===t)return!0;if(void 0===e&&void 0!==t||void 0!==e&&void 0===t||null===e&&null!==t||null!==e&&null===t)return!1;if(e.constructor!==t.constructor)return!1;if("function"==typeof e&&e.toString()!==t.toString())return!1;if([String,Number,Boolean].includes(e.constructor))return e===t;if(e.constructor===Array){if(e.length!==t.length)return!1;for(let r=0;r3&&(s=e.slice(2)),s=Array.isArray(s)?s:[s],"string"!=typeof t)throw new Error("[VNode] Invalid first argument passed to VNode constructor.");if(this.processSelector(t),r instanceof Function||r instanceof VNode||"string"==typeof r)s=[r].concat(s);else{if("object"!=typeof r||null===r)throw new Error("[VNode] Invalid second argument passed to VNode constructor.");this.processProperties(r)}this.processChildren(s)}}from(e){this.value=e.value,this.type=e.type,this.id=e.id,this.$html=e.$html,this.$onrender=e.$onrender,this.style=e.style,this.data=e.data,this.value=e.value,this.eventListeners=e.eventListeners,this.children=e.children,this.props=e.props,this.classList=e.classList}equal(e,t){return equal(e,void 0===t?this:t)}processProperties(e){this.id=this.id||e.id,this.$html=e.$html,this.$onrender=e.$onrender,this.style=e.style,this.value=e.value,this.data=e.data||{},this.classList=e.classList&&e.classList.length>0?e.classList:this.classList,this.props=e,Object.keys(e).filter(t=>t.startsWith("on")&&e[t]).forEach(t=>{if("function"!=typeof e[t])throw new Error(`[VNode] Event handler specified for ${t} event is not a function.`);this.eventListeners[t.slice(2)]=e[t],delete this.props[t]}),delete this.props.value,delete this.props.$html,delete this.props.$onrender,delete this.props.id,delete this.props.data,delete this.props.style,delete this.props.classList}processSelector(e){if(!e.match(selectorRegex)||0===e.length)throw new Error("[VNode] Invalid selector: "+e);const[,t,r,s]=e.match(selectorRegex);this.type=t,r&&(this.id=r.slice(1)),this.classList=s&&s.split(".").slice(1)||[]}processVNodeObject(e){if(e instanceof VNode)return e;if(e instanceof Function){let t=e();if("string"==typeof t&&(t=new VNode({type:"#text",value:t})),!(t instanceof VNode))throw new Error("[VNode] Function argument does not return a VNode");return t}throw new Error("[VNode] Invalid first argument provided to VNode constructor.")}processChildren(e){const t=Array.isArray(e)?e:[e];this.children=t.map(e=>{if("string"==typeof e)return new VNode({type:"#text",value:e});if("function"==typeof e||"object"==typeof e&&null!==e)return this.processVNodeObject(e);if(e)throw new Error("[VNode] Specified child is not a VNode: "+e)}).filter(e=>e)}render(){if("#text"===this.type)return document.createTextNode(this.value);const e=document.createElement(this.type);return blank(this.id)||(e.id=this.id),Object.keys(this.props).forEach(t=>{"boolean"==typeof this.props[t]&&(this.props[t]?e.setAttribute(t,""):e.removeAttribute(t)),["string","number"].includes(typeof this.props[t])&&e.setAttribute(t,this.props[t]),e[t]=this.props[t]}),Object.keys(this.eventListeners).forEach(t=>{e.addEventListener(t,this.eventListeners[t])}),this.value&&(["textarea","input","option","button"].includes(this.type)?e.value=this.value:e.setAttribute("value",this.value.toString())),this.style&&(e.style.cssText=this.style),this.classList.forEach(t=>{t&&e.classList.add(t)}),Object.keys(this.data).forEach(t=>{e.dataset[t]=this.data[t]}),this.children.forEach(t=>{const r=t.render();e.appendChild(r),t.$onrender&&$onrenderCallbacks.push(()=>t.$onrender(r))}),this.$html&&(e.innerHTML=this.$html),e}redraw(e){let{node:t,vnode:r}=e;const s=r,o=this;if(o.constructor!==s.constructor||o.type!==s.type||o.type===s.type&&"#text"===o.type&&o!==s){const e=s.render();return t.parentNode.replaceChild(e,t),s.$onrender&&s.$onrender(e),void o.from(s)}o.id!==s.id&&(t.id=s.id,o.id=s.id),o.value!==s.value&&(o.value=s.value,["textarea","input","option","button"].includes(o.type)?t.value=blank(s.value)?"":s.value.toString():t.setAttribute("value",blank(s.value)?"":s.value.toString())),equal(o.classList,s.classList)||(o.classList.forEach(e=>{s.classList.includes(e)||t.classList.remove(e)}),s.classList.forEach(e=>{e&&!o.classList.includes(e)&&t.classList.add(e)}),o.classList=s.classList),o.style!==s.style&&(t.style.cssText=s.style||"",o.style=s.style),equal(o.data,s.data)||(Object.keys(o.data).forEach(e=>{s.data[e]?s.data[e]!==o.data[e]&&(t.dataset[e]=s.data[e]):delete t.dataset[e]}),Object.keys(s.data).forEach(e=>{o.data[e]||(t.dataset[e]=s.data[e])}),o.data=s.data),equal(o.props,s.props)||(Object.keys(o.props).forEach(e=>{t[e]=s.props[e],"boolean"==typeof s.props[e]?(o.props[e]=s.props[e],s.props[e]?t.setAttribute(e,""):t.removeAttribute(e)):[null,void 0].includes(s.props[e])?(delete o.props[e],t.removeAttribute(e)):s.props[e]!==o.props[e]&&(o.props[e]=s.props[e],["string","number"].includes(typeof s.props[e])&&t.setAttribute(e,s.props[e]))}),Object.keys(s.props).forEach(e=>{blank(o.props[e])&&!blank(s.props[e])&&(o.props[e]=s.props[e],t[e]=s.props[e],"boolean"==typeof s.props[e]?t.setAttribute(e,""):["string","number"].includes(typeof s.props[e])&&t.setAttribute(e,s.props[e]))})),equal(o.eventListeners,s.eventListeners)||(Object.keys(o.eventListeners).forEach(e=>{s.eventListeners[e]?equal(s.eventListeners[e],o.eventListeners[e])||(t.removeEventListener(e,o.eventListeners[e]),t.addEventListener(e,s.eventListeners[e])):t.removeEventListener(e,o.eventListeners[e])}),Object.keys(s.eventListeners).forEach(e=>{o.eventListeners[e]||t.addEventListener(e,s.eventListeners[e])}),o.eventListeners=s.eventListeners);let i=mapChildren(o,s),n=[...Array(s.children.length).keys()];for(;!equal(i,n);){let e=-1;e:for(const r of i)if(e++,r!==e)switch(r){case PATCH:o.children[e].redraw({node:t.childNodes[e],vnode:s.children[e]});break e;case INSERT:{o.children.splice(e,0,s.children[e]);const r=s.children[e].render();t.insertBefore(r,t.childNodes[e]),s.children[e].$onrender&&s.children[e].$onrender(r);break e}case DELETE:o.children.splice(e,1),t.removeChild(t.childNodes[e]);break e;default:{const s=o.children.splice(r,1)[0];o.children.splice(e,0,s);const i=t.removeChild(t.childNodes[r]);t.insertBefore(i,t.childNodes[e]);break e}}i=mapChildren(o,s),n=[...Array(s.children.length).keys()]}equal(o.$onrender,s.$onrender)||(o.$onrender=s.$onrender),o.$html!==s.$html&&(t.innerHTML=s.$html,o.$html=s.$html,o.$onrender&&o.$onrender(t))}}const mapChildren=(e,t)=>{const r=t.children,s=e.children;let o=[];for(let e=0;e=s.length&&o.length>=s.length&&(t=INSERT),o.push(t)}const i=o.filter(e=>e>=0);return s.length>r.length?[...Array(s.length-r.length).keys()].forEach(()=>o.push(DELETE)):i.length===s.length&&(o=o.map(e=>e<0?INSERT:e)),o};class Store{constructor(){this.events={},this.state={}}dispatch(e,t){if("$log"!==e&&this.dispatch("$log",{event:e,data:t}),this.events[e]){this.events[e].forEach(e=>{this.state={...this.state,...e(this.state,t)}})}}on(e,t){return(this.events[e]||(this.events[e]=[])).push(t),()=>{this.events[e]=this.events[e].filter(e=>e!==t)}}}class Route{constructor({path:e,def:t,query:r,parts:s}){if(this.path=e,this.def=t,this.query=r,this.parts=s,this.params={},this.query){this.query.split("&").forEach(e=>{const[t,r]=e.split("=");this.params[decodeURIComponent(t)]=decodeURIComponent(r)})}}}class Router{constructor({element:e,routes:t,store:r,location:s}){if(this.element=e,this.redraw=null,this.store=r,this.location=s||window.location,!t||0===Object.keys(t).length)throw new Error("[Router] No routes defined.");Object.keys(t);this.routes=t}setRedraw(e,t){this.redraw=()=>{e.redraw({node:this.element.childNodes[0],vnode:this.routes[this.route.def](t)}),this.store.dispatch("$redraw")}}async start(){const e=async e=>{const t=this.route,r=e&&e.newURL&&e.newURL.match(/(#.+)$/)&&e.newURL.match(/(#.+)$/)[1]||this.location.hash,s=r.replace(/\?.+$/,"").slice(1),o=r.match(/\?(.+)$/),i=o&&o[1]?o[1]:"",n=s.split("/").slice(1);let a,l={};for(let e of Object.keys(this.routes)){let t=e.split("/").slice(1),r=!0,o=0;for(l={};r&&t[o];){const e=t[o],s=n[o];e.startsWith(":")&&s?l[e.slice(1)]=s:r=e===s,o++}if(r){a=new Route({query:i,path:s,def:e,parts:l});break}}if(!a)throw new Error(`[Router] No route matches '${r}'`);let h={};if(t){const e=this.routes[t.def];h=e.teardown&&await e.teardown(e.state)||h}const d=this.routes[a.def];if(d.state=h,d.setup&&(this.route=a,!1===await d.setup(d.state)))return this.route=t,void this.store.dispatch("$navigation",null);for(this.route=a,redrawing=!0,this.store.dispatch("$navigation",this.route);this.element.firstChild;)this.element.removeChild(this.element.firstChild);const c=d(d.state),p=c.render();this.element.appendChild(p),this.setRedraw(c,d.state),redrawing=!1,c.$onrender&&c.$onrender(p),$onrenderCallbacks.forEach(e=>e()),$onrenderCallbacks=[],window.scrollTo(0,0),this.store.dispatch("$redraw")};window.addEventListener("hashchange",e),await e()}navigateTo(e,t){let r=Object.keys(t||{}).map(e=>`${encodeURIComponent(e)}=${encodeURIComponent(t[e])}`).join("&");r=r?"?"+r:"",this.location.hash=`#${e}${r}`}}export const h=(...e)=>new VNode(...e);export const h3={};let store=null,router=null,redrawing=!1;h3.init=e=>{let{element:t,routes:r,modules:s,preStart:o,postStart:i,location:n}=e;if(!r){if("function"!=typeof e)throw new Error("[h3.init] The specified argument is not a valid configuration object or component function");r={"/":e}}if(t=t||document.body,!(t&&t instanceof Element))throw new Error("[h3.init] Invalid element specified.");return store=new Store,(s||[]).forEach(e=>{e(store)}),store.dispatch("$init"),router=new Router({element:t,routes:r,store:store,location:n}),Promise.resolve(o&&o()).then(()=>router.start()).then(()=>i&&i())},h3.navigateTo=(e,t)=>{if(!router)throw new Error("[h3.navigateTo] No application initialized, unable to navigate.");return router.navigateTo(e,t)},Object.defineProperty(h3,"route",{get:()=>{if(!router)throw new Error("[h3.route] No application initialized, unable to retrieve current route.");return router.route}}),Object.defineProperty(h3,"state",{get:()=>{if(!store)throw new Error("[h3.state] No application initialized, unable to retrieve current state.");return store.state}}),h3.on=(e,t)=>{if(!store)throw new Error("[h3.on] No application initialized, unable to listen to events.");return store.on(e,t)},h3.dispatch=(e,t)=>{if(!store)throw new Error("[h3.dispatch] No application initialized, unable to dispatch events.");return store.dispatch(e,t)},h3.redraw=e=>{if(!router||!router.redraw)throw new Error("[h3.redraw] No application initialized, unable to redraw.");redrawing||(redrawing=!0,requestAnimationFrame(()=>{router.redraw(),redrawing=e||!1}))},h3.screen=({setup:e,display:t,teardown:r})=>{if(!t||"function"!=typeof t)throw new Error("[h3.screen] No display property specified.");if(e&&"function"!=typeof e)throw new Error("[h3.screen] setup property is not a function.");if(r&&"function"!=typeof r)throw new Error("[h3.screen] teardown property is not a function.");const s=t;return e&&(s.setup=e),r&&(s.teardown=r),s};export default h3; 9 | //# sourceMappingURL=h3.js.map -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | setupFiles: ['/scripts/test-setup.js'], 3 | } -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@h3rald/h3", 3 | "version": "0.11.0", 4 | "versionName": "Keen Klingon", 5 | "description": "A tiny, extremely minimalist JavaScript microframework.", 6 | "main": "h3.js", 7 | "scripts": { 8 | "test": "jest", 9 | "coverage": "jest --coverage ", 10 | "coveralls": "npm run coverage && cat ./coverage/lcov.info | coveralls", 11 | "prebuild": "node scripts/release.js", 12 | "copy": "cp h3.js docs/js/h3.js && cp h3.js docs/example/assets/js/h3.js", 13 | "guide": "hastyscribe docs/H3_DeveloperGuide.md", 14 | "build": "npm run copy && npm run guide" 15 | }, 16 | "repository": { 17 | "type": "git", 18 | "url": "git+https://github.com/h3rald/h3.git" 19 | }, 20 | "keywords": [ 21 | "javascript", 22 | "virtual-dom", 23 | "router", 24 | "storeon", 25 | "redux", 26 | "spa", 27 | "client-side", 28 | "framework", 29 | "minimalist" 30 | ], 31 | "author": "Fabio Cevasco", 32 | "license": "MIT", 33 | "bugs": { 34 | "url": "https://github.com/h3rald/h3/issues" 35 | }, 36 | "homepage": "https://h3.js.org", 37 | "devDependencies": { 38 | "@babel/plugin-transform-modules-commonjs": "^7.13.8", 39 | "@babel/preset-env": "^7.13.15", 40 | "coveralls": "^3.1.0", 41 | "jest": "^26.6.3", 42 | "terser": "^5.7.0" 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /scripts/release.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | const path = require('path'); 3 | const terser = require('terser'); 4 | 5 | const readme = './README.md'; 6 | const overview = './docs/md/overview.md'; 7 | const app = './docs/js/app.js'; 8 | const tutorial = './docs/md/tutorial.md'; 9 | const package = './package.json'; 10 | const h3 = './h3.js'; 11 | const h3min = './h3.min.js'; 12 | const h3map = './h3.js.map'; 13 | 14 | const pkg = JSON.parse(fs.readFileSync(package, 'utf8')); 15 | 16 | // Update h3.js 17 | 18 | let h3Data = fs.readFileSync(h3, 'utf8'); 19 | const notice = h3Data.match(/\/\*\*((.|\n|\r)+?)\*\//gm)[0]; 20 | const newNotice = notice 21 | .replace(/v\d+\.\d+\.\d+/, `v${pkg.version}`) 22 | .replace(/\"[^"]+\"/, `"${pkg.versionName}"`) 23 | .replace(/Copyright \d+/, `Copyright ${new Date().getFullYear()}`); 24 | h3Data = h3Data.replace(notice, newNotice); 25 | fs.writeFileSync(h3, h3Data); 26 | const minified = terser.minify(h3Data, { 27 | sourceMap: { filename: 'h3.js', url: 'h3.js.map' }, 28 | }); 29 | fs.writeFileSync(h3min, minified.code); 30 | fs.writeFileSync(h3map, minified.map); 31 | 32 | // Update README.md 33 | let readmeData = fs.readFileSync(readme, 'utf8'); 34 | readmeData = readmeData.replace(/v\d+\.\d+\.\d+/, `v${pkg.version}`); 35 | readmeData = readmeData.replace(/Download v\d+\.\d+\.\d+ \([^)]+\)/, `Download v${pkg.version} (${pkg.versionName})`); 36 | readmeData = readmeData.replace(/v\d+\.\d+\.\d+\/h3\.min\.js/, `v${pkg.version}/h3.min.js`); 37 | fs.writeFileSync(readme, readmeData); 38 | 39 | // Remove badges and copy to overview.md 40 | const overviewData = readmeData.replace(/[^\*]+\*\*\*\s+/m, ''); 41 | fs.writeFileSync(overview, overviewData); 42 | 43 | // Update app.js and tutorial.md 44 | const updateCode = (file) => { 45 | let data = fs.readFileSync(file, 'utf8'); 46 | data = data.replace(/v\d+\.\d+\.\d+/, `v${pkg.version}`); 47 | data = data.replace(/“.+“/, `“${pkg.versionName}“`); 48 | fs.writeFileSync(file, data); 49 | }; 50 | updateCode(app); 51 | updateCode(tutorial); 52 | 53 | // Update package.json 54 | const packageData = JSON.parse(fs.readFileSync(package, 'utf8')); 55 | packageData.version = pkg.version; 56 | fs.writeFileSync(package, JSON.stringify(packageData, null, 2)); 57 | -------------------------------------------------------------------------------- /scripts/test-setup.js: -------------------------------------------------------------------------------- 1 | Object.defineProperty(window, "scrollTo", { value: () => {}, writable: true }); 2 | --------------------------------------------------------------------------------