Overview
H3 is a microframework to build client-side single-page applications (SPAs) in modern JavaScript.
H3 is also:
- tiny, less than 4KB minified and gzipped.
- modern, in the sense that it runs only in modern browsers (latest versions of Chrome, Firefox, Edge & similar).
- easy to learn, its API is comprised of only seven methods and two properties.
I’m sold! Where can I get it?
Here, look, it’s just one file:
Download v0.11.0 (Keen Klingon)
Or get the minified version here.
Yes there is also a NPM package if you want to use it with WebPack and similar, but let me repeat: it’s just one file.
Hello, World?
Here’s an example of an extremely minimal SPA created with H3:
import { h3, h } from "./h3.js";
h3.init(() => h("h1", "Hello, World!"));
This will render a h1
tag within the document body, containing the text "Hello, World!"
.
Something more complex?
Have a look at the code of a simple todo list (demo) with several components, a store and some routing.
No, I meant a real web application…
OK, have a look at 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.
Can I use it then, no strings attached?
Yes. It’s MIT-licensed.
What if something is broken?
Go fix it! Or at least open an issue on the Github repo, pleasy.
Can I download a copy of all the documentation as a standalone HTML file?
What a weird thing to ask… sure you can: here!
Quick Start
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).
Create a basic HTML file
Start with a minimal HTML file like this one, and include an app.js
script. That will be the entry point of your application:
<!doctype html>
<html lang="en">
<head>
<title>My H3-powered App</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<body>
<script type="module" src="js/app.js"></script>
</body>
</html>
Note that the script must be marked as an ES6 module (type="module"
), otherwise your imports won’t work.
Import h3 and h from h3.js
Then, inside your app.js
file, import h
and h3
from h3.js
, which should be accessible somewhere in your app:
import { h3, h } from "./h3.js";
This will work in every modern browser except Internet Explorer. You don’t need a transpiler, you don’t need something to convert your beautiful ES6 code back to clunky ES5.
Unless your company tells you to, do yourself a favor and don’t support IE. It’s 2020, even Microsoft moved on, and now ES6 modules work in all major browsers.
Create your SPA
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:
// A simple component printing the current date and time
// Pressig the Refresh button causes the application to redraw
// And updates the displayed date/dime.
const Page = () => {
return h("main", [
h("h1", "Welcome!"),
h("p", `The current date and time is ${new Date()}`),
h("button", {
onclick: () => h3.redraw()
}, "Refresh")
]);
}
// Initialize your SPA
h3.init(Page);
Key Concepts
There are just a few things you should know about if you want to use H3.
Oh… and a solid understanding of HTML and JavaScript wouldn’t hurt either ;)
HyperScript
H3 uses a 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.
How, you ask? Like this:
h("div.test", [
h("ul", [
h("li", "This is..."),
h("li", "...a simple..."),
h("li", "unordered list.")
])
]);
…which will output:
<div class="test">
<ul>
<li>This is...</li>
<li>...a simple...</li>
<li>...unordered list.</li>
</ul>
</div>
Simple enough. Yes there are some quirks to it, but check the API or Usage docs for those.
Component
In H3, a component is a function that returns a Virtual Node or a string (that will be treated as a textual DOM node).
Yes that’s it. An example? here:
let count = 0;
const CounterButton = () => {
return h("button", {
onclick: () => count +=1 && h3.redraw()
}, `You clicked me ${count} times.`);
}
Router
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.
The current route is always accessible via the h3.route
property.
Screen
A screen is a top-level component that handles a route. Unlike ordinary components, screens:
- 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).
- 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.
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.
Note that: * 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. * 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. * 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. * Both methods can be asynchronous, in which case H3 will wait for their completion before proceeding.
Store
H3 essentially uses something very, very similar to 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.
The current application state is accessible via the h3.state
property.
Module
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:
const error = () => {
h3.on("$init", () => ({ displayEmptyTodoError: false }));
h3.on("error/clear", (state) => ({ displayEmptyTodoError: false }));
h3.on("error/set", (state) => ({ displayEmptyTodoError: true }));
};
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.
How everything works…
The following sequence diagram summarizes how H3 works, from its initialization to the redraw and navigation phases.
When the h3.init()
method is called at application level, the following operations are performed in sequence:
- The Store is created and initialized.
- Any Module specified when calling
h3.init()
is executed. - The $init event is dispatched.
- The preStart function (if specified when calling
h3.init()
) is executed. - The Router is initialized and started.
- The setup() method of the matching Screen is called (if any).
- The $navigation event is dispatched.
- The Screen matching the current route and all its child components are rendered for the first time.
- The $redraw event is dispatched.
Then, whenever the h3.redraw()
method is called (typically within a component):
- The whole application is redrawn, i.e. every Component currently rendered on the page is redrawn.
- The $redraw event is dispatched.
Similarly, whenever the h3.navigateTo()
method is called (typically within a component), or the URL fragment changes:
- The Router processes the new path and determine which component to render based on the routing configuration.
- The teardow() method of the current Screen is called (if any).
- The setup() method of the new matching Screen is called (if any).
- All DOM nodes within the scope of the routing are removed, all components are removed.
- The $navigation event is dispatched.
- All DOM nodes are removed.
- The Screen matching the new route and all its child components are rendered.
- The $redraw event is dispatched.
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.
Tutorial
As a (meta) explanation of how to use H3, let’s have a look at how the H3 web site itself was created.
The idea was to build a simple web site to display the documentation of the H3 microframework, so it must be able to:
- Provide a simple way to navigate through page.
- Render markdown content (via marked.js)
- Apply syntax highlighting (via Prism.js)
As far as look and feel is concerned, I wanted something minimal but functional, so mini.css was more than enough.
The full source of the site is available here.
Create a simple HTML file
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
.
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?).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>H3</title>
<meta
name="description"
content="A bare-bones client-side web microframework"
/>
<meta name="author" content="Fabio Cevasco" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="shortcut icon" href="favicon.png" type="image/png" />
<link rel="stylesheet" href="css/mini-default.css" />
<link rel="stylesheet" href="css/prism.css" />
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<script type="module" src="js/app.js"></script>
</body>
</html>
Create a single-page application
In this case the code for the SPA is not very complex, you can have a look at it here.
Normally you’d have several components, at least one file containing modules to manage the application state, etc. (see the todo list example), but in this case a single component is sufficient.
Start by importing all the JavaScript modules you need:
import { h3, h } from "./h3.js";
import marked from "./vendor/marked.js";
import Prism from "./vendor/prism.js";
Easy enough. Then we want to store the mapping between the different page fragments and their titles:
const labels = {
overview: "Overview",
"quick-start": "Quick Start",
"key-concepts": "Key Concepts",
"best-practices": "Best Practices",
tutorial: "Tutorial",
api: "API",
about: "About",
};
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 the Markdown file and render it as HTML:
const fetchPage = async ({ pages, id, md }) => {
if (!pages[id]) {
const response = await fetch(md);
const text = await response.text();
pages[id] = marked(text);
}
};
Basically this function is going to be called when you navigate to each page, and it:
- fetches the content of the requested file (
md
)) - renders the Markdown code into HTML using the marked library, and stores it in the
pages
object
We are gonna use our fetchPage
function inside the setup
of the main (and only) screen of our app, Page
:
const Page = h3.screen({
setup: async (state) => {
state.pages = {};
state.id = h3.route.path.slice(1);
state.ids = Object.keys(labels);
state.md = state.ids.includes(state.id)
? `md/${state.id}.md`
: `md/overview.md`;
await fetchPage(state);
},
display: (state) => {
return h("div.page", [
Header,
h("div.row", [
h("input#drawer-control.drawer", { type: "checkbox" }),
Navigation(state.id, state.ids),
Content(state.pages[state.id]),
Footer,
]),
]);
},
teardown: (state) => state,
});
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.
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.
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).
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.
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
.
The Header
and Footer
components are very simple: their only job is to render static content:
const Header = () => {
return h("header.row.sticky", [
h("a.logo.col-sm-1", { href: "#/" }, [
h("img", { alt: "H3", src: "images/h3.svg" }),
]),
h("div.version.col-sm.col-md", [
h("div.version-number", "v0.11.0"),
h("div.version-label", "“Keen Klingon“"),
]),
h("label.drawer-toggle.button.col-sm-last", { for: "drawer-control" }),
]);
};
const Footer = () => {
return h("footer", [h("div", "© 2020 Fabio Cevasco")]);
};
The Navigation
component is more interesting, as it takes two parameters:
- The ID of the current page
- The list of page IDs
…and it uses this information to create the site navigation menu dynamically:
const Navigation = (id, ids) => {
const menu = ids.map((p) =>
h(`a${p === id ? ".active" : ""}`, { href: `#/${p}` }, labels[p])
);
return h("nav#navigation.col-md-3", [
h("label.drawer-close", { for: "drawer-control" }),
...menu,
]);
};
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:
const Content = (html) => {
const content = h("div.content", { $html: html });
return h("main.col-sm-12.col-md-9", [
h(
"div.card.fluid",
h("div.section", { $onrender: () => Prism.highlightAll() }, content)
),
]);
};
Now, the key here is that we are only ever going to render “known” pages that are listed in the labels
object.
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
).
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.
This feature is also handy to automatically load the Overview when no fragment is specified.
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.
Initialization
Done? Not quite. We need to initialize the SPA by passing the Page
component to the h3.init()
method to trigger the first rendering:
h3.init(Page);
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.
Next steps
Made it this far? Good. Wanna know more? Have a look at the code of the todo list example and try it out here.
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. You can see it in action here: litepad.h3rald.com.
Note: the LitePad online demo will store all its data in localStorage.
API
The core of the H3 API is comprised of the following six methods and two properties.
h(selector: string, attributes: object, children: array)
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.
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.
Create an element, with an ID, classes, attributes and children
This is a complete example showing how to create a link with an href
attribute, an ID, two classes, and three child nodes.
h(
"a#test-link.btn.primary",
{
href: "#/test",
},
["This is a ", h("em", "test"), "link."]
);
↓
<a id="test-link" class="btn primary" href="#/test">
This is a <em>test</em> link.
</a>
Create an empty element
h("div");
↓
<div></div>
Create an element with a textual child node
h("span", "This is a test");
↓
<span>This is a test</span>
Create an element with child nodes
h("ol", [
h("li", "Do this first."),
h("li", "Then this."),
h("li", "And finally this."),
]);
or
h(
"ol",
h("li", "Do this first."),
h("li", "Then this."),
h("li", "And finally this.")
);
↓
<ol>
<li>Do this first.</li>
<li>Then this.</li>
<li>And finally this.</li>
</ol>
Render a component
const TestComponent = () => {
return h(
"button.test",
{
onclick: () => alert("Hello!"),
},
"Show Alert"
);
};
h(TestComponent);
↓
<button class="test">Show Alert</button>
Note: The event listener will not be added to the markup.
Render child components
const TestLi = (text) => h("li.test", text);
h("ul", ["A", "B", "C"].map(TestLi));
↓
<ul>
<li class="test">A</li>
<li class="test">B</li>
<li class="test">C</li>
</ul>
Special attributes
- Any attribute starting with on (e.g. onclick, onkeydown, etc.) will be treated as an event listener.
- 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). - The
data
attribute can be set to a simple object containing data attributes. - The special
$html
attribute can be used to set theinnerHTML
property of the resulting HTML element. Use only if you know what you are doing! - The special
$onrender
attribute can be set to a function that will executed every time the VNode is rendered and added to the DOM.
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.
For example, consider the following code snippet that can be used to initialize the InscrybMDE Markdown editor on a textarea element:
h("textarea", {
$onrender: (element) => {
const editor = new window.InscrybMDE({
element,
});
},
});
h3.screen({setup, display, teardown})
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.
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.
Consider the following example:
h3.screen({
setup: await (state) => {
state.data = state.data || {};
state.id = h3.route.parts.id || 1;
const url = `http://dummy.restapiexample.com/api/v1/employee/${id}`;
state.data[id] = state.data[id] || await (await fetch(url)).json();
},
display(state) => {
const employee = state.data[state.id];
if (!employee) {
return h("div.error", "Invalid Employee ID.");
}
return h("div.employee",
h("h2", "Employee Profile"),
h("dl", [
h("dt", "Name:"),
h("dd", data.employee_name),
h("dt", "Salary:"),
h("dd", `${data.employee_salary} €`),
h("dt", "Age:"),
h("dd", data.employee_age),
])
)
},
teardown: (state) => ({ data: state.data })
})
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.
Tip To interrupt navigation or perform redirects, return false in the setup method.
h3.dispatch(event: string, data: any)
Dispatches a event and optionally some data. Messages are typically handled centrally by modules.
h3.dispatch("settings/set", { logging: true });
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:
$init
— Dispatched when the application is initialized. Useful to initialize application state.$redraw
— Dispatched after an application redraw is triggered.$navigation
— Dispatched after a navigation occurs.$log
— Dispatched after any event (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:
- element (Element) — The DOM Element to which the Application will be attached (default:
document.body
). - modules (Array) — An array of functions used to handle the application state that will be executed once before starting the application.
- 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 theparts
property of the current route (h3.route
). - preStart (Function) — An optional function to be executed before the application is first rendered.
- postStart (Function) — An optional function to be executed after the application is first rendered.
This is an example of a simple routing configuration:
const routes = {
"/posts/:id": Post,
"/pages/:id": Page,
"/": HomePage,
};
For more a complete example of initialization, see this.
h3.navigateTo(path: string, params: object)
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
.
h3.navigateTo("/posts/", { orderBy: "date", direction: "desc" });
h3.on(event: string, handler: function)
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.
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.
Example:
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
An read-only property containing current route (Route object). A Route object has the following properties:
- path — The current path (fragment without #) without query string parameters, e.g.
/posts/134
- def — The matching route definition, e.g.
/posts/:id
- query — The query string, if present, e.g.
?comments=yes
- part — An object containing the values of the parts defined in the route, e.g.
{id: "134"}
- params — An object containing the query string parameters, e.g.
{comments: "yet"}
h3.state
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.
About
Or: everything you wanted to know about H3, but you were afraid to ask.
Why the weird release labels?
Ubuntu started naming their releases after animals in alphabetical order… In a similar way, H3 releases are named after Star Trek species.
A brief history of H3
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.
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.
No way! — I thought.
There has to be a better way. If only I could use something small like Mithril, it would take me no time! But sadly I couldn’t. Unless…
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 (with all the bonus points implemented, like localStorage support, pagination, filtering, etc.).
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 ;)
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.
Credits
The H3 web site is built with H3 itself, plus the following third-party libraries:
Special Thanks
Special thanks to the following individuals, that made H3 possible: