all repos — h3 @ aefba437be4cdf00cf1348c0fb84d41aebbde5c7

A tiny, extremely minimalist JavaScript microframework.

Added docs.
h3rald h3rald@h3rald.com
Sun, 19 Apr 2020 18:11:02 +0200
commit

aefba437be4cdf00cf1348c0fb84d41aebbde5c7

parent

303dee419409d43361781663e7ede1b902bfbd95

M docs/css/style.cssdocs/css/style.css

@@ -17,7 +17,8 @@ text-align: center;

margin: auto; } -ul, ol { +ul, +ol { padding-left: 1.5em; }

@@ -27,8 +28,23 @@ line-height: 1em;

border: 1px solid #dedede; } -pre code[class*="language-"], -pre code[class*="language-"] span.token { - font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace; +pre code[class*="language-"], +pre code[class*="language-"] span.token { + font-family: Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace; font-size: 0.8rem; } + +@media screen and (min-width: 768px) { + #navigation { + position: sticky; + top: 60px; + } +} + +.content { + margin-left: 40px; +} + +h2, h3, h4, h5, h6 { + margin-left: -35px; +}
M docs/example/assets/css/style.cssdocs/example/assets/css/style.css

@@ -55,7 +55,7 @@ }

.navigation-bar { display: flex; - justify-content: center; + justify-content: center; } .navigation-bar .nav-link {

@@ -71,7 +71,7 @@ }

#filter-text { display: flex; - justify-content: space-around; + justify-content: space-around; font-size: 1em; height: 2em; width: 100%;

@@ -79,7 +79,7 @@ }

.paginator { display: flex; align-items: center; - justify-content: space-around; + justify-content: space-around; padding: 0 5px; font-weight: bold; }

@@ -129,10 +129,10 @@ align-items: center;

} .error { - color: #FF3838; - background: #FFE6CC; + color: #ff3838; + background: #ffe6cc; width: 100%; - border: 1px solid #FF3838; + border: 1px solid #ff3838; padding: 5px; margin: 5px 0; display: flex;

@@ -159,7 +159,7 @@ .link {

cursor: pointer; } .disabled { - color: #CCCCCC; + color: #cccccc; } @media (min-width: 750px) {

@@ -167,4 +167,4 @@ .todo-list-container {

width: 700px; margin: auto; } -}+}
M docs/example/assets/js/h3.jsdocs/example/assets/js/h3.js

@@ -501,12 +501,11 @@ }

} class Route { - constructor({ path, def, query, parts, fallback }) { + constructor({ path, def, query, parts}) { this.path = path; this.def = def; this.query = query; this.parts = parts; - this.fallback = fallback; this.params = {}; if (this.query) { const rawParams = this.query.split("&");

@@ -530,7 +529,6 @@ if (!routes || Object.keys(routes).length === 0) {

throw new Error("[Router] No routes defined."); } const defs = Object.keys(routes); - this.fallback = defs[defs.length - 1]; this.routes = routes; }

@@ -571,15 +569,12 @@ }

index++; } if (match) { - let fallback = false; - this.route = new Route({ query, path, def, parts, fallback }); + this.route = new Route({ query, path, def, parts }); break; } } if (!this.route) { - let def = this.fallback; - let fallback = true; - this.route = new Route({ query, path, def, parts, fallback }); + this.route = new Route({ query, path, def, parts }); } // Display View while (this.element.firstChild) {
M docs/js/app.jsdocs/js/app.js

@@ -30,7 +30,7 @@ let content = pages[id]

? h3("div.content", { $html: pages[id] }) : h3("div.spinner-container", h3("span.spinner")); return h3("div.page", [ - h3("header.row", [ + h3("header.row.sticky", [ h3("a.logo.col-sm", { href: "#/" }, "H3"), h3("label.drawer-toggle.button.col-sm-last", { for: "drawer-control" }), ]),

@@ -49,4 +49,4 @@ ]);

}; h3.init(Page); -h3.on('$redraw', () => Prism.highlightAll()); +h3.on("$redraw", () => Prism.highlightAll());
M docs/js/h3.jsdocs/js/h3.js

@@ -501,12 +501,11 @@ }

} class Route { - constructor({ path, def, query, parts, fallback }) { + constructor({ path, def, query, parts}) { this.path = path; this.def = def; this.query = query; this.parts = parts; - this.fallback = fallback; this.params = {}; if (this.query) { const rawParams = this.query.split("&");

@@ -530,7 +529,6 @@ if (!routes || Object.keys(routes).length === 0) {

throw new Error("[Router] No routes defined."); } const defs = Object.keys(routes); - this.fallback = defs[defs.length - 1]; this.routes = routes; }

@@ -571,15 +569,12 @@ }

index++; } if (match) { - let fallback = false; - this.route = new Route({ query, path, def, parts, fallback }); + this.route = new Route({ query, path, def, parts }); break; } } if (!this.route) { - let def = this.fallback; - let fallback = true; - this.route = new Route({ query, path, def, parts, fallback }); + this.route = new Route({ query, path, def, parts }); } // Display View while (this.element.firstChild) {
M docs/md/api.mddocs/md/api.md

@@ -1,17 +1,120 @@

## API +The core of the H3 API is comprised of the following six methods and two properties (plus a bunch of system messages). + ### h3.equal(a: any, b: any) -### h3.dispatch(event: string, data: any) +A way to determine if two object or literals are equal. This method is mainly used internally by the Virtual DOM diffing algorithm. + +Note that two functions are considered _equal_ if their source code is exactly the same. This may not be ideal in certain situations, but when it comes to diffing two nodes that may be generated dynamically through iteration it generally makes sense to behave in this way. + +### h3.dispatch(message: string, data: any) + +Dispatches a message and optionally some data. Messages are typically handled centrally by modules. + +```js +h3.dispatch("settings/set", { logging: true }); +``` + +A message name can be anything, but keep in mind that the following names (and typically any name starting with `$`) are reserved for framework use: + +* `$init` &mdash; Dispatched when the application is initialized. Useful to initialize application state. +* `$redraw` &mdash; Dispatched after an application redraw is triggered. +* `$navigation` &mdash; Dispatched after a navigation occurs. +* `$log` &mdash; Dispatched after *any* message (except `$log` iself) is dispatched. Very useful for debugging. ### h3.init(config: object)) +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: + +<table> +<thead> + <tr> + <th>Property</th> + <th>Type</th> + <th>Description</th> + </tr> + </thead> + <tbody> + <tr> + <td data-label="Property">element</td> + <td data-label="Type">Element</td> + <td data-label="Description">The DOM Element to which the Application will be attached (default: document.body).</td> + </tr> + <tr> + <td data-label="Property">routes</td> + <td data-label="Type">Object</td> + <td data-label="Description">An object containing paths as key and components as values, corresponding to the routes of the application.</td> + </tr> + <tr> + <td data-label="Property">modules</td> + <td data-label="Type">Array</td> + <td data-label="Description">An array of functions used to handle the application state.</td> + </tr> + <tr> + <td data-label="Property">preStart</td> + <td data-label="Type">Function</td> + <td data-label="Description">An optional function to be executed before the application is first rendered.</td> + </tr> + <tr> + <td data-label="Property">postStart</td> + <td data-label="Type">Function</td> + <td data-label="Description">An optional function to be executed after the application is first rendered.</td> + </tr> + </tbody> +</table> | + +Routing paths can contain named parts like `:name` or `:id` which will populate the `parts` property of the current route. + +This is an example of a possible routing configuration: + +```js +const routes = { + "/posts/:id": Post, + "/pages/:id": Page, + "/": HomePage, +}; +``` + ### h3.navigateTo(path: string, params: object) -### h3.on(event: string, cb: function) +Navigates to the specified path. Optionally, it is possibile to specify query string parameters as an object. + +The following call causes the application to switch to the following URL: `#/posts/?orderBy=date&direction=desc`. + +```js +h3.navigateTo("/posts/", {orderBy: 'date', direction: 'desc'}); +``` + +### h3.on(message: string, handler: function) + +Subscribes to the specified messages and executes the specified handler function whenever the message is dispatches. Returns a function that can be used to delete the subscription. + +Subscriptions should be typically managed in modules rather than in componnents: a component gets rendered several times and subscriptions *must* be properly cleaned up to avoid memory leaks. + +Example: + +```js +const pages = (store) => { + store.on("$init", () => ({ pagesize: 10, page: 1 })); + store.on("pages/set", (state, page) => ({ page })); +}; +``` ### h3.redraw() +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. + ### h3.route -### h3.state+An object containing the current route. A Route object has the following properties: + +* `path` &mdash; The current path (fragment without #) without query string parameters, e.g. `/posts/134` +* `def` &mdash; The matching route definition, e.g. `/posts/:id` +* `query` &mdash; The query string, if present, e.g. `?comments=yes` +* `parts` &mdash; An object containing the values of the parts defined in the route, e.g. `{id: "134"}` +* `params` &mdash; An object containing the query string parameters, e.g. `{comments: "yet"}` + +### h3.state + +An object containing the current application state. Do not modify this directly, use subscriptions in modules to modify it.
M docs/md/key-concepts.mddocs/md/key-concepts.md

@@ -1,6 +1,8 @@

## Key Concepts -There are essentially four things you need to know about if you want to use H3. Except a solid understanding of HTML and JavaScript of course ;) +There are essentially four things you need to know about if you want to use H3. + +Oh... and a solid understanding of HTML and JavaScript wouldn't hurt either ;) ### HyperScript

@@ -54,9 +56,23 @@ ```

### Store -H3 essentially uses something very, *very* similar to [StoreOn](https://github.com/storeon/storeon) for state maagemennt *and* also as a very simple client-side message dispatcher/subscriber. Typically you'll only use the defaulr store created by H3 on initialization, and you'll use the `h3.dispatch()` and `h3.on()` methods to dispatch and subscribe to actions (messages). +H3 essentially uses something very, *very* similar to [StoreOn](https://github.com/storeon/storeon) for state maagemennt *and* also as a very simple client-side message dispatcher/subscriber. 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 actions (messages). The current application state is accessible via the `h3.state` property. + +### Modules + +The `h3.init()` method takes an array of *modules* that can be used to manipulate the application state when specific messages are received. A simple module looks like this: + +```js +const error = (store) => { + store.on("$init", () => ({ displayEmptyTodoError: false })); + store.on("error/clear", (state) => ({ displayEmptyTodoError: false })); + store.on("error/set", (state) => ({ displayEmptyTodoError: true })); +}; +``` + +Essentially a module is a function that receives a reference to the H3 store as a parameter. Modules are the place where you should handle state changes in your application. ### Router
M docs/md/overview.mddocs/md/overview.md

@@ -9,6 +9,9 @@ * **bare-bones**, it contains just the bare minimum to create a fully-functional single-pace application.

* **modern**, it runs only in modern browsers (latest versions of Chrome, Firefox, Edge & similar). * **easy** to learn, its API is comprised of only 6 methods and 2 properties. +### I'm sold, where can I get it? + +Get it from [here](https://raw.githubusercontent.com/h3rald/h3/master/h3.js) and include it in your application. ### Hello, World!
M docs/md/quick-start.mddocs/md/quick-start.md

@@ -1,1 +1,48 @@

-## Quick Start+## Quick Start + +Start with a minimal HTML file like this one, and include an `app.js` script. That will be the entry point of your application: + +```html +<!doctype html> +<html lang="en"> + <head> + <meta charset="utf-8" /> + <title>H3</title> + <meta name="description" content="My little H3-powered app" /> + <meta name="author" content="Fabio Cevasco" /> + <meta name="viewport" content="width=device-width, initial-scale=1" /> + </head> + <body> + <script src="js/app.js"></script> + </body> +</html> +``` + +Then, inside your `app.js` file, import `h3.js`, which should be accessible somewhere in your app: + +```js +import h3 from "./h3.js"; +``` + +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 cluncky ES5. + +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. + +After importing the `h3` object, you can start developing your SPA. A bare minimum SPA is comprised by a single component passed to the `h3.init()` method: + +```js +// A simple component printing the current date and time +// Pressig the Refresh button causes the applicationn to redraw +// And updates the displayed date/dime. +const Page = () => { + return h3("main", [ + h3("h1", "Welcome!"), + h3("p", `The current date and time is ${new Date()}`), + h3("button", { + onclick: () => h3.redraw() + }, "Refresh") + ]); +} +// Initialize your SPA +h3.init(Page); +```
M h3.jsh3.js

@@ -501,12 +501,11 @@ }

} class Route { - constructor({ path, def, query, parts, fallback }) { + constructor({ path, def, query, parts}) { this.path = path; this.def = def; this.query = query; this.parts = parts; - this.fallback = fallback; this.params = {}; if (this.query) { const rawParams = this.query.split("&");

@@ -530,7 +529,6 @@ if (!routes || Object.keys(routes).length === 0) {

throw new Error("[Router] No routes defined."); } const defs = Object.keys(routes); - this.fallback = defs[defs.length - 1]; this.routes = routes; }

@@ -571,15 +569,12 @@ }

index++; } if (match) { - let fallback = false; - this.route = new Route({ query, path, def, parts, fallback }); + this.route = new Route({ query, path, def, parts }); break; } } if (!this.route) { - let def = this.fallback; - let fallback = true; - this.route = new Route({ query, path, def, parts, fallback }); + this.route = new Route({ query, path, def, parts }); } // Display View while (this.element.firstChild) {