Skip to content

@itsy/html/util ​

ts
import { join, map, range, when, choose, wrap, comment, json } from '@itsy/html/util';

Opt-in helpers with no shared state, one export each, so a bundler keeps only what is imported.

Everything except comment and json returns a plain array or the result of a thunk, and renders and escapes nothing: the template it lands in does that, for the context it lands in. comment and json return a whole node as Html, with what is inside made safe for it.

join ​

ts
join<I, J>(items: Iterable<I> | undefined, joiner: J): (I | J)[]

Puts joiner between the items.

ts
html`<p>${join(tags.map(Tag), ', ')}</p>`;

The joiner is a value like any other, so a string is escaped and an Html is not. undefined items give an empty array.

map ​

ts
map<T>(items: Iterable<T> | undefined, f: (item: T, index: number) => Renderable): Renderable[]

Array.prototype.map for anything iterable, with an index.

ts
html`<ul>${map(ids, (id, i) => html`<li>${i}: ${id}</li>`)}</ul>`;

TIP

This is for a Set, a Map.values() or a generator — things with no .map of their own. For an array, call .map and skip the import.

range ​

ts
range(end: number): number[]
range(start: number, end: number, step?: number): number[]

The integers from start up to but not including end. One argument means range(0, end). A negative step counts down.

ts
range(5); // [0, 1, 2, 3, 4]
range(1, 10, 3); // [1, 4, 7]
html`<p>${map(range(5), Star)}</p>`;

when ​

ts
when<T, F>(condition: unknown, trueFn: () => T, falseFn?: () => F): T | F | undefined

One branch or the other, and only the chosen branch is built.

ts
html`${when(user, () => Profile(user), () => Login())}`;

With no falseFn, a false condition renders nothing - so it is usually cleaner to just do && in those cases.

choose ​

ts
choose<T, V>(value: T, cases: readonly (readonly [T, () => V])[], fallback?: () => V): V | undefined

A switch as an expression. The first case that matches (strict equivalence) will be rendered.

ts
html`${choose(status, [
  ['ok', () => Ok()],
  ['err', () => Err()],
], () => Unknown())}`;

wrap ​

ts
wrap(items: Iterable<Renderable>, tag: string, attributes?: Record<string, AttrValue>): Renderable[]

Each item inside a <tag>, with optional attributes.

ts
html`<ul>${wrap(['a', 'b'], 'li', { class: 'name' })}</ul>`;
html
<ul><li class="name">a</li><li class="name">b</li></ul>

Items are rendered by the surrounding template, so text is escaped and Html is not. Attributes go through attrs() with the default URL guard, not one from createHtml. A tag name that is not a legal tag name throws code 17.

Inside <script> and <style> every item must itself be Html, and anything else throws code 6: escaping keeps text from ending the block, but not from running.

comment ​

ts
comment(text: string): Html

An HTML comment the text cannot close early.

ts
html`${comment('closes early? --> no')}`;
html
<!-- closes early? - -> no -->

json ​

ts
json(value: unknown, attributes?: Record<string, AttrValue>): Html

A <script type="application/json"> with value in it as JSON, which nothing in the value can end early.

ts
json({ q: '</script><script>alert(1)</script>' }, { id: 'state' });
html
<script type="application/json" id="state">{"q":"\u003c/script\u003e\u003cscript\u003ealert(1)\u003c/script\u003e"}</script>

<, > and & in the data become \u003c, \u003e and \u0026, and so do U+2028 and U+2029. JSON writes them only inside strings, where the escape is the same character, so JSON.parse gives back exactly what went in. undefined and a function are written as null, as JSON.stringify writes them in an array. A BigInt or a cycle throws JSON.stringify's own TypeError.

It is the whole element, so it goes where an element goes: in a template, or in a frame part.

ts
html`<main>${content}</main>${json(state, { id: 'state' })}`;
frame({ lang: 'en', title, content, scripts: [json(state, { id: 'state' }), ...scripts] });

In the browser, find it as a <script>:

ts
const state = JSON.parse(document.querySelector('script#state')?.textContent ?? 'null');

Not getElementById

getElementById('state') returns the first element with that id. A sanitizer leaves ids on the markup it lets through, so a user's <div id="state"> earlier in the page wins. It never lets a <script> through.

Attributes go through attrs(). type is application/json unless one is given, as for structured data or an import map:

ts
json(article, { type: 'application/ld+json' });
json({ imports }, { type: 'importmap', nonce });

A data block runs nothing, so a content security policy does not apply to it. An import map is checked like a script and needs the nonce, and frame does not add one to ready-made Html.

It returns the element rather than the JSON because the JSON is only safe as the whole block. In a string inside a <script>, a ' in the data would end the string and the rest would run.

For a few values on one element, an attribute is enough, since the template escapes it: data-props="${JSON.stringify(props)}", read back with JSON.parse(el.dataset.props).

MIT licensed.