Guten Tag, HTML Modules!
Guten Tag, pronounced goo'tn tock, German for Good day, or in the hacker idiom, Hello, World!
Gutentag is a small library for writing HTML components as modules. HTML components should be as simple and as powerful as functions. A tag is an invocation of a component, and the fragment between the start and end tag is its argument.
greet(subject("Guten Tag"), ", ", object("Welt"), "!")
<greet>
<subject>Guten Tag</subject>,
<object>Welt</object>!
</greet>
I wrote it in 2015 and documented it on codi.sh, my catalog of the JavaScript packages I had published. That documentation survives in the codi.sh repository, and this article is drawn from it, checked against Gutentag’s code as it last stood, in Gutentag 2.2.
Why #
The missing piece of the web component story was declarative modularity. Web components had encapsulation through the shadow DOM, and a form of modularity through script tags and register functions, but no inherent means for declarative dependency.
Tags should be expressed as modules, written in HTML, with declarations for dependency on other tags, and declarations for how they will receive argument tags. A tag module exports a component constructor, and sends and receives component constructors as arguments.
Each tag should also have a lexical scope, so you can trace a component by its
identifier by following parent tags until you find a scope that contains that
identifier.
The instance of a tag is never in another file, except in the limited sense of
components that another component introduces into your scope, like
repetition:iteration.
I had spent years on MontageJS, whose components were declared in serialized JSON beside their HTML, and on its data bindings. Gutentag was what I wanted instead: the template is the module, and the bindings are yours to bring.
A tag is a module #
A guten tag is an HTML or XML file.
Its <head> says what it depends upon and how it is called, and its <body>
is the template for each instance.
<!doctype html>
<html>
<head>
<link rel="extends" href="./list">
<link rel="tag" href="gutentag/repeat.html">
<link rel="tag" href="gutentag/text.html">
</head>
<body>
<ul><repeat id="items">
<li id="item" type="a"><text id="text"></text></li>
</repeat></ul>
</body>
</html>
<link rel="tag">imports another tag module and binds it to a tag name in this document, by default the name of the file.asgives it another name, which matters forhtml.html, since<html>already means something.<link rel="extends">names a JavaScript module whose prototype the component inherits, so the template can have behavior. Trivial tags need none.<link rel="exports">goes the other way: the component is pure JavaScript, and the HTML module only declares how it is called. The built-in tags are written this way.<meta accepts>declares the calling convention, how the tag receives the content between its start and end tags.<meta exports>passes a component introduced inside the tag out to its caller, under a new name.
Gutentag translates the module to JavaScript, either on the fly in the browser
during development, or in Node.js as a build step.
The module exports a constructor that accepts a body and a caller scope.
The smallest one looks like this:
"use strict";
module.exports = Component;
function Component(body, caller) {
this.scope = caller.root.nestComponents();
body.appendChild(document.createTextNode("Guten Tag, Welt!\n"));
}
Gutentag only provides the <text>, <html>, <repeat>, <reveal>, and
<choose> tags and the system for loading tags.
Bring your own bindings, shims, data, animation, or virtual document if you
need them.
The documentation put the “Guten Tag, Welt!” application at about 15K, and 3K
after uglify and gzip.
Bodies, not boxes #
The body a component receives is a node in a very thin virtual document.
It stands for a region of the actual document that the component controls.
Bodies can be added to and removed from the virtual document, and all of their
content is added to or removed from the actual document with them,
synchronously.
But a body does not introduce a container element, like a <div>.
This matters most for the structural tags, <repeat>, <reveal>, and
<choose>, since you may or may not want a container element around them or
inside them.
Two repetitions can share a table row (in an XML module, since the HTML5
parser would carry unknown tags out of the table):
<tr>
<th><text id="rowHeader"></text></th>
<repeat id="groupOne">
<td><text id="cell"></text></td>
</repeat>
<repeat id="groupTwo">
<td><text id="cell"></text></td>
</repeat>
</tr>
In other places a wrapper would break a CSS selector, a flex layout, or the
semantics of the markup.
A body’s children are kept in an orphan <body> element while they are off
the document, and inserted before an empty text node while they are on it.
That is the service of Koerper, from
the German Körper, body, which builds on
Wizdom, a very small subset of the
DOM.
The built-in tags #
Each building block has a very simple implementation, which you can copy and
change for your own needs.
Each has a mutable value property.
<text>controls a text node. When its value isnullorundefined, it shows the text between its tags.<html>controls a run of HTML at its position. It has to be imported under another name, likeas="x-html", or used in XML.<repeat>instantiates its content once for each value in an array, and follows changes to the array.<reveal>shows or hides its content as its value is truthy or not.<choose>shows one of its named child tags, constructing it on demand:choose.value = "e"shows the<e>option.
There are also two special tags.
<this> stands for the component itself, for recursion, which is how you make
a tree.
And <sp> marks space as significant: unlike HTML, a guten tag trims
the space between tags and throws away text that is only space, except within
<sp>.
Calling conventions #
A tag declares how it receives its argument, the content between its start and
end tags, with <meta accepts>:
[body]receives the whole argument as one component constructor, which the template instantiates with the<argument>tag (or the name given byas).[entries]receives each child tag as a named component constructor, as<choose>does.[text]receives the argument’s inner text, as<text>does for its default.[html]receives the argument’s inner HTML.
This tag puts its argument in parentheses:
<!doctype html>
<html>
<head>
<meta accepts="[body]">
</head>
<body>(<argument></argument>)</body>
</html>
The argument is instantiated where the callee puts it, but evaluated in the scope of the caller, where it was written. That is the lexical scope.
Scopes and introductions #
<repeat>, <reveal>, and <choose> each create a child scope for the
components their content instantiates.
Within a scope, scope.components maps identifiers to components.
A child scope’s components inherit from its parent’s, so a component inside a
repetition can see the components around it, but not the other way around.
The structural tag also introduces a component into the child scope, named
from its own identifier: each iteration of <repeat id="items"> is
items:iteration, with a value and an index.
A <reveal id="content"> introduces content:revelation, and a
<choose id="options"> introduces options:e when it shows e.
When a component is added to a scope, Gutentag calls the hookup(id, component, scope) method of the component whose template it is in, if there
is one.
That is the place to wire things together.
Last, the component hooks up itself, with the identifier this.
An example #
Here is a list that accepts one argument component, its row, and repeats it.
Through <meta exports>, it passes each iteration of its repetition out to
whoever calls it, as row.
<!-- list.html -->
<!doctype html>
<html>
<head>
<link rel="extends" href="./list">
<link rel="tag" href="gutentag/repeat.html">
<meta accepts="[body]" as="row">
<meta exports="rows:iteration" as="row">
</head>
<body>
<ul><repeat id="rows">
<li><row></row></li>
</repeat></ul>
</body>
</html>
// list.js
"use strict";
module.exports = List;
function List() {}
Object.defineProperty(List.prototype, "value", {
get: function () { return this.scope.components.rows.value; },
set: function (value) { this.scope.components.rows.value = value; }
});
Another tag calls the list with a <text> for each row.
<!-- greetings.html -->
<!doctype html>
<html>
<head>
<link rel="extends" href="./greetings">
<link rel="tag" href="gutentag/text.html">
<link rel="tag" href="./list.html">
</head>
<body>
<list id="greetings">
<text id="greeting"></text>
</list>
</body>
</html>
Inside the list, each row is rows:iteration.
But the repetition also cuts through to the caller, making a scope for each
instance of the argument there, and the export names it after the caller’s own
identifier: greetings:row.
So greetings.js sees each row arrive, in the scope where that row’s
greeting lives, and binds one to the other.
// greetings.js
"use strict";
module.exports = Greetings;
function Greetings() {}
Greetings.prototype.hookup = function (id, component, scope) {
if (id === "greetings:row") {
scope.components.greeting.value = component.value;
}
};
Give the list an array and it draws it.
var values = ["Guten Tag, Welt!", "Auf Wiederseh'n, Welt!"];
greetings.scope.components.greetings.value = values;
<ul><li>Guten Tag, Welt!</li><li>Auf Wiederseh'n, Welt!</li></ul>
The repetition observes the array, so changing the array changes the document,
one row at a time.
values.push("Gute Nacht, Welt!") adds a third <li>, and then
values.splice(0, 1) takes the first away, leaving the other two in place.
<ul><li>Auf Wiederseh'n, Welt!</li><li>Gute Nacht, Welt!</li></ul>
Getting started #
Every Gutentag application starts as an npm package, with the System module loader, Koerper and Gutentag installed.
$ npm init
$ npm install --save system koerper gutentag
System loads CommonJS modules for the browser and Node.js, and lets a package
teach it new kinds of module.
This annotation in package.json tells it that HTML and XML files are
Gutentag modules.
{
"extensions": {
"html": "gutentag/extension",
"xml": "gutentag/extension"
}
}
System reads extensions as a mapping from a module’s file extension to a
module whose job is to translate a module’s text from one language to another,
here from HTML to JavaScript.
The extension has two steps.
analyze parses the text and finds the module’s dependencies, the tags and
prototypes its <head> links to, and translate rewrites the text as
JavaScript.
System loads the whole working set, analyzing each module as it arrives,
before it translates any of them, so the translation can run on the fly in the
browser during development, or at build time for a bundle.
An extension applies only within the package that declares it, which is why
Gutentag’s own package.json declares the same two for
its built-in tags.
Before Gutentag 2.2, in October of 2016, the annotation was called
translators, and named gutentag/translate-html.
A translator is code too, with dependencies of its own, and none of it should
ship.
Gutentag’s translator needs an HTML parser, and an application might bring one
it needs only to build, as one of its devDependencies, which System adds to
the root package’s dependencies.
So the bundler loads the application twice, as two
parallel module graphs: first a build system
for Node.js, then the browser system it will bundle, paired with the first.
Each time the browser system loads a package, it
loads the same package in the build
system beside it, so the two graphs grow together, package for package.
When a module needs analyzing or translating, the browser system
imports the extension from its twin in
the build system, and runs it there, in Node.js.
The bundle is drawn only from the browser graph, so it carries the translated
tags and not the translator.
Bundled with System 1.3.0 and Gutentag 2.2.0, an application with one tag that
uses <text> comes to four modules: its entry, its tag translated to
JavaScript, and Gutentag’s text.html and text.js.
In development there is only the one graph: the browser system is
its own build system, and fetches the
translator along with everything else.
The page boots System and names the entry module. In development, refreshing the page reloads every module, with no build step, provided npm has not deduplicated the packages.
<script src="node_modules/system/boot.js" data-import="./index"></script>
The entry module makes the virtual document, the root scope, and the root component. The root scope is also a good place to inject dependencies that every component shares, since every scope inherits from it.
var Document = require("koerper");
var Scope = require("gutentag/scope");
var App = require("./app.html");
var scope = new Scope();
var document = new Document(window.document.body);
var app = new App(document.documentElement, scope);
For production, System’s bundle command works like Browserify: it
translates every HTML module to JavaScript and rolls them up with a very
small module loader.
{
"scripts": {
"build": "bundle index.js | uglifyjs > bundle.js"
}
}
Gutentag also accepts XML modules, for where the HTML5 parser gets in the
way: it will not let a <repeat> stand within a <table>, and XML will.
The gutentags #
The gutentags organization on GitHub holds Gutentag and the small libraries and applications that grew up around it.
- System, the module loader and bundler.
- Koerper, the virtual document with body nodes, and Wizdom, the small DOM beneath it.
- Blick, an animation controller for components. It batches reads and writes to the document by coordinating measurement, transitions, animation, drawing and redrawing, each in its own part of an animation frame, and each component keeps its own part of the controller, so nothing is allocated from frame to frame.
- Kamera, which makes sure only one component has the focus. It is the sort of thing to put in the root scope.
- Ndim, points and regions in any number of dimensions.
- Applications and reusable tags: Accrete, a clone of 2048; Colorim, a full page color picker with vim-like key bindings, which you can install from npm as a tag; the Tengwar transcriber, my first Gutentag application; and codi.sh itself.
Gutentag leans on my other libraries too: Q
promises in the loader, and
pop-observe for the array
changes that <repeat> follows.
Delve, a keyboard world editor
I bundled in January of 2016, was built with Gutentag, Blick, Colorim and
Ndim.
The Tengwar transcriber is a Guten Tags application still running at tengwar.3rin.gs.
Web components did grow a way to put markup in a module, but not the one I asked for. Gutentag remains how I would want to write a component: as a function, in markup.
Upon further reflection, I would not hesitate to create a bespoke markup language catered to declaratively expressing guten tags, including attribute bindings and a data model that clarifies the interfaces and expectations for mutability or reactivity, such that a site can be compiled to a static server binary that enshrines the decade of web performance engineering that emerged and was subsequently thrown away for single page apps and client side virtual DOMs.
- Previous: A General Theory of Reactivity
- Next: SHON (SHell Object Notation)