5.2.0 • Published 7 days ago

@thi.ng/hiccup v5.2.0

Weekly downloads
222
License
Apache-2.0
Repository
github
Last release
7 days ago

hiccup

npm version npm downloads Twitter Follow

This project is part of the @thi.ng/umbrella monorepo.

About

HTML/SVG/XML serialization of nested data structures, iterables & closures.

Inspired by Hiccup and Reagent for Clojure/ClojureScript.

Forget all the custom toy DSLs for templating and instead use the full power of ES6 to directly define fully data-driven, purely functional and easily composable components for static serialization to HTML & friends.

This library is suitable for static website generation, server side rendering etc. For interactive use cases, please see companion package @thi.ng/hdom.

Features

  • Only uses arrays, functions, ES6 iterables / iterators / generators
  • Eager & lazy component composition using embedded functions / closures
  • Support for self-closing tags (incl. validation), boolean attributes
  • Arbitrary user context object injection for component functions
  • Dynamic derived attribute value generation via function values
  • CSS formatting of style attribute objects
  • Optional HTML entity encoding
  • Support for comments and XML/DTD processing instructions
  • Branch-local behavior control attributes to control serialization
  • Small (1.9KB minified) & fast

(*) Lazy composition here means that functions are only executed at serialization time. Examples below...

Use cases

  • Serverside rendering
  • Static site, feed generation
  • .innerHTML body generation
  • SVG asset creation
  • Shape trees for declarative canvas API drawing

No special sauce needed (or wanted)

Using only vanilla language features simplifies the development, composability, reusability and testing of components. Furthermore, no custom template parser is required and you're only restricted by the expressiveness of the language / environment, not by your template engine.

Components can be defined as simple functions returning arrays or loaded via JSON/JSONP.

What is Hiccup?

For many years, Hiccup has been the de-facto standard to encode HTML/XML datastructures in Clojure. This library brings & extends this convention into ES6. A valid Hiccup tree is any flat (though, usually nested) array of the following possible structures. Any functions embedded in the tree are expected to return values of the same structure. Please see examples & API further explanations...

["tag", ...]
["tag#id.class1.class2", ...]
["tag", {other: "attrib", ...}, ...]
["tag", {...}, "body", 23, function, [...]]
[function, arg1, arg2, ...]
[{render: (ctx, ...args) => [...]}, args...]
iterable

Status

STABLE - used in production

Search or submit any issues for this package

Support packages

Related packages

Blog posts

Installation

yarn add @thi.ng/hiccup

ES module import:

<script type="module" src="https://cdn.skypack.dev/@thi.ng/hiccup"></script>

Skypack documentation

For Node.js REPL:

# with flag only for < v16
node --experimental-repl-await

> const hiccup = await import("@thi.ng/hiccup");

Package sizes (gzipped, pre-treeshake): ESM: 2.26 KB

Dependencies

Usage examples

Several demos in this repo's /examples directory are using this package.

A selection:

ScreenshotDescriptionLive demoSource
Heatmap visualization of this mono-repo's commitsSource
Filterable commit log UI w/ minimal server to provide commit historyDemoSource
Various hdom-canvas shape drawing examples & SVG conversion / exportDemoSource
Hiccup / hdom DOM hydration exampleDemoSource
CLI util to visualize umbrella pkg statsSource
Generate SVG using pointfree DSLSource
Interactive grid generator, SVG generation & export, undo/redo supportDemoSource

API

Generated API docs

Tags with Zencoding expansion

Tag names support Zencoding/Emmet style ID & class attribute expansion:

serialize(
    ["div#yo.hello.world", "Look ma, ", ["strong", "no magic!"]]
);
<div id="yo" class="hello world">Look ma, <strong>no magic!</strong></div>

Attributes

Arbitrary attributes can be supplied via an optional 2nd array element. style attributes can be given as CSS string or as an object. Boolean attributes are serialized in HTML5 syntax (i.e. present or not, but no values).

If the 2nd array element is not a plain object, it's treated as normal child node (see previous example).

serialize(
    ["div.notice",
        {
            selected: true,
            style: {
                background: "#ff0",
                border: "3px solid black"
            }
        },
        "WARNING"]
);
<div class="notice" selected style="background:#ff0;border:3px solid black">WARNING</div>

If an attribute specifies a function as value, the function is called with the entire attribute object as argument. This allows for the dynamic generation of attribute values, based on existing ones. The result MUST be a string.

Function values for event attributes (any attrib name starting with "on") WILL BE OMITTED from output.

["div#foo", { bar: (attribs) => attribs.id + "-bar" }]
<div id="foo" bar="foo-bar"></div>
["div#foo", { onclick: () => alert("foo") }, "click me!"]
<div id="foo">click me!</div>
["div#foo", { onclick: "alert('foo')" }, "click me!"]
<div id="foo" onclick="alert('foo')">click me!</div>

Simple components

const thumb = (src) => ["img.thumb", { src, alt: "thumbnail" }];

serialize(
    ["div.gallery", ["foo.jpg", "bar.jpg", "baz.jpg"].map(thumb)]
);
<div class="gallery">
    <img class="thumb" src="foo.jpg" alt="thumbnail"/>
    <img class="thumb" src="bar.jpg" alt="thumbnail"/>
    <img class="thumb" src="baz.jpg" alt="thumbnail"/>
</div>

User context injection

Every component function will receive an arbitrary user defined context object as first argument. This context object is passed to serialize() and is then auto-injected for every component function call.

The context object should contain any global component configuration, e.g. for theming purposes.

const header = (ctx, body) =>
    ["h1", ctx.theme.title, body];

const section = (ctx, title, ...body) =>
    ["section", ctx.theme.section, [header, title], ...body];

// theme definition (here using Tachyons CSS classes,
// but could be any attributes)
const theme = {
    section: { class: "bg-black moon-gray bt b--dark-gray mt3" },
    title: { class: "white f3" }
};

serialize(
    [section, "Hello world", "Easy theming"],
    { theme }
);
// <section class="bg-black moon-gray bt b--dark-gray mt3"><h1 class="white f3">Hello world</h1>Easy theming</section>

Note: Of course the context is ONLY auto-injected for lazily embedded component functions (as shown above), i.e. if the functions are wrapped in arrays and only called during serialization. If you call a component function directly, you MUST pass the context (or null) as first arg yourself. Likewise, if a component function doesn't make use of the context you can either:

// skip the context arg and require direct invocation
const div = (attribs, body) => ["div", attribs, body];

serialize(div({id: "foo"}, "bar"));
// <div id="foo">bar</div>

Or...

// ignore the first arg (context) and support both direct & indirect calls
const div = (_, attribs, body) => ["div", attribs, body];

// direct invocation of div (pass `null` as context)
serialize(div(null, {id: "foo"}, "bar"));
// <div id="foo">bar</div>

// lazy invocation of div
serialize([div, {id: "foo"}, "bar"]);
// <div id="foo">bar</div>

SVG generation, generators & lazy composition

Also see @thi.ng/hiccup-svg for related functionality.

const fs = require("fs");

// creates an unstyled SVG circle element
// we ignore the first arg (an auto-injected context arg)
// context handling is described further below
const circle = (_, x, y, r) => ["circle", { cx: x | 0, cy: y | 0, r: r | 0 }];

// note how this next component lazily composes `circle`.
// This form delays evaluation of the `circle` component
// until serialization time.
// since `circle` is in the head position of the returned array
// all other elements are passed as args when `circle` is called
const randomCircle = () => [
    circle,
    Math.random() * 1000,
    Math.random() * 1000,
    Math.random() * 100
];

// generator to produce iterable of `n` calls to `fn`
function* repeatedly(n, fn) {
    while (n-- > 0) yield fn();
}

// generate 100 random circles and write serialized SVG to file
// `randomCircle` is wrapped
import { SVG_NS } from "@thi.ng/hiccup";

const doc = [
    "svg", { xmlns: SVG_NS, width: 1000, height: 1000 },
        ["g", { fill: "none", stroke: "red" },
            repeatedly(100, randomCircle)]];

fs.writeFileSync("circles.svg", serialize(doc));
<svg xmlns="http://www.w3.org/2000/svg" width="1000" height="1000">
    <g fill="none" stroke="red">
        <circle cx="182" cy="851" r="66"/>
        <circle cx="909" cy="705" r="85"/>
        <circle cx="542" cy="915" r="7"/>
        <circle cx="306" cy="762" r="88"/>
        ...
    </g>
</svg>

Data-driven component composition

// data
const glossary = {
    foo: "widely used placeholder name in computing",
    bar: "usually appears in combination with 'foo'",
    hiccup: "de-facto standard format to define HTML in Clojure",
    toxi: "author of this fine library",
};

// mapping function to produce single definition list item (pair of <dt>/<dd> tags)
const dlItem = (index, key) => [["dt", key], ["dd", index[key]]];

// Helper function: takes a function `f` and object `items`,
// executes fn for each key (sorted) in object and returns array of results
const objectList = (f, items) => Object.keys(items).sort().map((k)=> f(items, k));

// full definition list component
const dlList = (_, attribs, items) => ["dl", attribs, objectList(dlItem, items)];

// finally the complete widget
const widget = [
    "div.widget",
        ["h1", "Glossary"],
        [dlList, { id: "glossary" }, glossary]];

// the 2nd arg `true` enforces HTML entity encoding (off by default)
serialize(widget, null, true);
<div class="widget">
    <h1>Glossary</h1>
    <dl id="glossary">
        <dt>bar</dt>
        <dd>usually appears in combination with &apos;foo&apos;</dd>
        <dt>foo</dt>
        <dd>widely used placeholder name in computing</dd>
        <dt>hiccup</dt>
        <dd>de-facto standard format to define HTML in Clojure</dd>
        <dt>toxi</dt>
        <dd>author of this fine library</dd>
    </dl>
</div>

Stateful component

// stateful component to create hierarchically
// indexed & referencable section headlines:
// e.g. "sec-1.1.2.3"
const indexer = (prefix = "sec") => {
    let counts = new Array(6).fill(0);
    return (_, level, title) => {
        counts[level - 1]++;
        counts.fill(0, level);
        return [
            ["a", { name: "sec-" + counts.slice(0, level).join(".") }],
            ["h" + level, title]
        ];
    };
};

const TOC = [
    [1, "Document title"],
    [2, "Preface"],
    [3, "Thanks"],
    [3, "No thanks"],
    [2, "Chapter"],
    [3, "Exercises"],
    [4, "Solutions"],
    [2, "The End"]
];

// create new indexer instance
const section = indexer();

serialize([
    "div.toc",
    TOC.map(([level, title]) => [section, level, title])
]);
<div class="toc">
    <a name="sec-1"></a><h1>Document title</h1>
    <a name="sec-1.1"></a><h2>Preface</h2>
    <a name="sec-1.1.1"></a><h3>Thanks</h3>
    <a name="sec-1.1.2"></a><h3>No thanks</h3>
    <a name="sec-1.2"></a><h2>Chapter</h2>
    <a name="sec-1.2.1"></a><h3>Exercises</h3>
    <a name="sec-1.2.1.1"></a><h4>Solutions</h4>
    <a name="sec-1.3"></a><h2>The End</h2>
</div>

Component objects

The sibling library @thi.ng/hdom supports components with basic life cycle methods (init, render, release). In order to support serialization of hdom component trees, hiccup too supports such components since version 2.0.0. However, for static serialization only the render method is of interest and others are ignored.

const component = {
    render: (ctx, title, ...body) => ["section", ["h1", title], ...body]
};

serialize([component, "Hello world", "Body"]);

Behavior control attributes

The following attributes can be used to control the serialization behavior of individual elements / tree branches:

  • __skip - if true, skips serialization (also used by @thi.ng/hdom)
  • __serialize - if false, skips serialization (hiccup only)
serialize(["div.container", ["div", {__skip: true}, "ignore me"]]);
// <div class="container"></div>

Comments

Single or multiline comments can be included using the special COMMENT tag (__COMMENT__) (always WITHOUT attributes!).

[COMMENT, "Hello world"]
// <!-- Hello world -->

[COMMENT, "Hello", "world"]
// <!--
//     Hello
//     world
// -->

XML / DTD processing instructions

Currently, the only processing / DTD instructions supported are:

  • ?xml
  • !DOCTYTPE
  • !ELEMENT
  • !ENTITY
  • !ATTLIST

These are used as follows (attribs are only allowed for ?xml, all others only accept a body string which is taken as is):

["?xml", { version: "1.0", standalone: "yes" }]
// <?xml version="1.0" standalone="yes"?>

["!DOCTYPE", "html"]
// <!DOCTYPE html>

Emitted processing instructions are always succeeded by a newline character.

API

The library exposes these two functions:

serialize()

Signature: serialize(tree: any, ctx?: any, escape = false): string

Recursively normalizes and serializes given tree as HTML/SVG/XML string. Expands any embedded component functions with their results. Each node of the input tree can have one of the following input forms:

["tag", ...]
["tag#id.class1.class2", ...]
["tag", {other: "attrib"}, ...]
["tag", {...}, "body", function, ...]
[function, arg1, arg2, ...]
[{render: (ctx,...) => [...]}, args...]
iterable

Tags can be defined in "Zencoding" convention, e.g.

["div#foo.bar.baz", "hi"]
// <div id="foo" class="bar baz">hi</div>

The presence of the attributes object (2nd array index) is optional. Any attribute values, incl. functions are allowed. If the latter, the function is called with the full attribs object as argument and the return value is used for the attribute. This allows for the dynamic creation of attrib values based on other attribs. The only exception to this are event attributes, i.e. attribute names starting with "on".

["div#foo", { bar: (attribs) => attribs.id + "-bar" }]
// <div id="foo" bar="foo-bar"></div>

The style attribute can ONLY be defined as string or object.

["div", {style: {color: "red", background: "#000"}}]
// <div style="color:red;background:#000;"></div>

Boolean attribs are serialized in HTML5 syntax (present or not). null or empty string attrib values are ignored.

Any null or undefined array values (other than in head position) will be removed, unless a function is in head position.

A function in head position of a node acts as a mechanism for component composition & delayed execution. The function will only be executed at serialization time. In this case the optional global context object and all other elements of that node / array are passed as arguments when that function is called. The return value the function MUST be a valid new tree (or undefined).

const foo = (ctx, a, b) => ["div#" + a, ctx.foo, b];

serialize([foo, "id", "body"], { foo: { class: "black" }})
// <div id="id" class="black">body</div>

Functions located in other positions are called ONLY with the global context arg and can return any (serializable) value (i.e. new trees, strings, numbers, iterables or any type with a suitable .toString() implementation).

Please also see list of supported behavior control attributes.

escape()

Signature: escape(str: string): string

Helper function. Applies HTML entity replacement on given string. If serialize() is called with true as 2nd argument, entity encoding is done automatically (list of entities considered).

Authors

Karsten Schmidt

If this project contributes to an academic publication, please cite it as:

@misc{thing-hiccup,
  title = "@thi.ng/hiccup",
  author = "Karsten Schmidt",
  note = "https://thi.ng/hiccup",
  year = 2016
}

License

© 2016 - 2021 Karsten Schmidt // Apache Software License 2.0

5.2.0

7 days ago

5.1.30

9 days ago

5.1.29

12 days ago

5.1.28

21 days ago

5.1.27

24 days ago

5.1.26

1 month ago

5.1.25

1 month ago

5.1.24

1 month ago

5.1.23

2 months ago

5.1.22

2 months ago

5.1.21

2 months ago

5.1.20

2 months ago

5.1.19

2 months ago

5.1.18

2 months ago

5.1.17

2 months ago

5.1.16

2 months ago

5.1.15

2 months ago

5.1.14

2 months ago

5.1.13

2 months ago

5.1.12

3 months ago

5.1.9

3 months ago

5.1.8

3 months ago

5.1.11

3 months ago

5.1.10

3 months ago

5.1.7

3 months ago

5.1.6

3 months ago

5.1.5

4 months ago

5.1.4

4 months ago

5.1.3

4 months ago

5.1.2

5 months ago

5.1.1

5 months ago

5.1.0

5 months ago

5.0.9

5 months ago

5.0.8

5 months ago

5.0.7

6 months ago

5.0.6

6 months ago

5.0.5

6 months ago

5.0.4

6 months ago

5.0.3

6 months ago

5.0.2

6 months ago

5.0.1

7 months ago

5.0.0

8 months ago

4.3.2

8 months ago

4.3.1

8 months ago

4.3.3

8 months ago

4.3.0

8 months ago

4.2.43

9 months ago

4.2.44

9 months ago

4.2.45

9 months ago

4.2.46

9 months ago

4.2.47

8 months ago

4.2.42

11 months ago

4.2.41

12 months ago

4.2.40

1 year ago

4.2.39

1 year ago

4.2.35

1 year ago

4.2.36

1 year ago

4.2.37

1 year ago

4.2.38

1 year ago

4.2.33

1 year ago

4.2.34

1 year ago

4.2.31

1 year ago

4.2.32

1 year ago

4.2.30

1 year ago

4.2.28

1 year ago

4.2.29

1 year ago

4.2.26

1 year ago

4.2.27

1 year ago

4.2.20

2 years ago

4.2.21

2 years ago

4.2.22

2 years ago

4.2.23

1 year ago

4.2.24

1 year ago

4.2.25

1 year ago

4.2.17

2 years ago

4.2.18

2 years ago

4.2.19

2 years ago

4.2.16

2 years ago

4.2.15

2 years ago

4.2.10

2 years ago

4.2.11

2 years ago

4.2.12

2 years ago

4.2.13

2 years ago

4.2.14

2 years ago

4.2.7

2 years ago

4.2.9

2 years ago

4.2.8

2 years ago

4.2.6

2 years ago

4.2.5

2 years ago

4.2.3

2 years ago

4.2.2

2 years ago

4.2.4

2 years ago

4.2.1

2 years ago

4.2.0

2 years ago

4.1.4

2 years ago

4.1.3

2 years ago

4.1.0

3 years ago

4.1.2

3 years ago

4.0.1

3 years ago

4.0.0

3 years ago

4.0.3

3 years ago

4.0.2

3 years ago

3.6.22

3 years ago

3.6.21

3 years ago

3.6.20

3 years ago

3.6.19

3 years ago

3.6.18

3 years ago

3.6.17

3 years ago

3.6.16

3 years ago

3.6.15

3 years ago

3.6.14

3 years ago

3.6.13

3 years ago

3.6.12

3 years ago

3.6.9

3 years ago

3.6.11

3 years ago

3.6.10

3 years ago

3.6.8

3 years ago

3.6.7

3 years ago

3.6.6

3 years ago

3.6.5

3 years ago

3.6.4

3 years ago

3.6.3

3 years ago

3.6.2

3 years ago

3.6.1

4 years ago

3.6.0

4 years ago

3.5.8

4 years ago

3.5.7

4 years ago

3.5.6

4 years ago

3.5.5

4 years ago

3.5.3

4 years ago

3.5.4

4 years ago

3.5.2

4 years ago

3.5.1

4 years ago

3.5.0

4 years ago

3.4.0

4 years ago

3.3.0

4 years ago

3.2.26

4 years ago

3.2.25

4 years ago

3.2.24

4 years ago

3.2.23

4 years ago

3.2.22

4 years ago

3.2.21

4 years ago

3.2.20

4 years ago

3.2.19

4 years ago

3.2.18

4 years ago

3.2.17

4 years ago

3.2.16

4 years ago

3.2.15

4 years ago

3.2.14

4 years ago

3.2.13

4 years ago

3.2.12

4 years ago

3.2.11

4 years ago

3.2.10

4 years ago

3.2.9

4 years ago

3.2.8

4 years ago

3.2.7

4 years ago

3.2.6

4 years ago

3.2.5

5 years ago

3.2.4

5 years ago

3.2.3

5 years ago

3.2.2

5 years ago

3.2.1

5 years ago

3.2.0

5 years ago

3.1.9

5 years ago

3.1.8

5 years ago

3.1.7

5 years ago

3.1.6

5 years ago

3.1.5

5 years ago

3.1.4

5 years ago

3.1.3

5 years ago

3.1.2

5 years ago

3.1.1

5 years ago

3.1.0

5 years ago

3.0.3

5 years ago

3.0.2

5 years ago

3.0.1

5 years ago

3.0.0

5 years ago

2.7.2

5 years ago

2.7.1

5 years ago

2.7.0

5 years ago

2.6.1

5 years ago

2.6.0

5 years ago

2.5.0

5 years ago

2.4.3

6 years ago

2.4.2

6 years ago

2.4.1

6 years ago

2.4.0

6 years ago

2.3.0

6 years ago

2.2.1-alpha.1

6 years ago

2.2.1-alpha.0

6 years ago

2.2.0

6 years ago

2.1.2

6 years ago

2.1.1

6 years ago

2.1.0

6 years ago

2.0.11

6 years ago

2.0.10

6 years ago

2.0.9

6 years ago

2.0.8

6 years ago

2.0.7

6 years ago

2.0.6

6 years ago

2.0.5

6 years ago

2.0.4

6 years ago

2.0.3

6 years ago

2.0.2

6 years ago

2.0.1

6 years ago

2.0.0

6 years ago

1.3.16

6 years ago

1.3.15

6 years ago

1.3.14

6 years ago

1.3.13

6 years ago

1.3.12

6 years ago

1.3.11

6 years ago

1.3.10

6 years ago

1.3.9

6 years ago

1.3.8

6 years ago

1.3.7

6 years ago

1.3.6

6 years ago

1.3.5

6 years ago

1.3.4

6 years ago

1.3.3

6 years ago

1.3.2

6 years ago

1.3.1

6 years ago

1.3.0

6 years ago

1.2.5

6 years ago

1.2.4

6 years ago

1.2.3

6 years ago

1.2.2

6 years ago

1.2.1

6 years ago

1.2.0

6 years ago

1.1.3

6 years ago

1.1.2

6 years ago

1.1.1

6 years ago

1.1.0

6 years ago

1.0.2

6 years ago

1.0.1

6 years ago

1.0.0

6 years ago

0.1.7

6 years ago

0.1.6

6 years ago

0.1.5

6 years ago

0.1.4

6 years ago

0.1.3

6 years ago

0.1.2

6 years ago