API reference

Every tag is a function with builder methods, and a plain call takes the same data object. This page covers the builder, the four keys, event handling, all exported tag functions and the package entry points.

Source of truth: lib/core and lib/types

Overview

The package creates DOM elements from function calls. Every tag has its own named function, such as div. Call it directly, or start a builder with one of its methods and create the element with .create(). element(name) returns the tag function of any HTML element by name; the SVG and MathML entry points each export their own element.

element<T extends keyof HTMLElementTagNameMap>(
  name: T,
): HTMLTag<T>

A tag is typed per element. For example, div('Hello') and div.props({ className: 'card' }).create() both return HTMLDivElement.

import { div } from 'fiorejs';

const card = div.props({ className: 'card' }).create('Hello');

document.body.appendChild(card);
Return value. .create() and the plain call return the native element. There is no wrapper object to unwrap before appending it.

Install and imports

npm install -D fiorejs

The package is ESM. Each entry point maps to a module in lib/, and the package has no runtime dependencies.

Specifier Module Exports
fiorejs lib/html.js element, LIVE, 112 HTML tag functions, default object
fiorejs/html lib/html.js Same as the root entry
fiorejs/global lib/index.js html, svg, math, deprecatedHtml
fiorejs/svg lib/svg.js element (SVG), 63 SVG tag functions, default object
fiorejs/math lib/math.js element (MathML), 31 MathML tag functions, default object
fiorejs/html/deprecated lib/html-deprecated.js element (deprecated), 29 tag functions, default object
fiorejs/type/* lib/types/* Type declaration files

Named, default and namespace imports are all available:

import { div, button } from 'fiorejs';
import html from 'fiorejs';
import { html, svg, math } from 'fiorejs/global';

html.div('Default object');
svg.circle.attrs({ r: '8' }).create();

element()

element(name) returns the tag of any HTML element by name, with the same methods as the named export. The tag creates the element with document.createElement, applies the data in a fixed order and returns the node. Use it with the builder, element('div').props({ … }).create(), or call it directly, element('div')(data).

  1. props is assigned first, except value, selectedIndex and checked.
  2. attrs is applied with setAttribute.
  3. children are inserted; empty values are skipped.
  4. value, selectedIndex and checked are assigned, so they can refer to the attributes and children.
  5. on listeners are attached.
  6. also callbacks run last, with the created element.

The order is the same for a plain call and for a builder, whatever the order of the builder calls.

import { element } from 'fiorejs';

const panel = element('section')
  .props({ className: 'panel' })
  .attrs({ 'aria-label': 'Details' })
  .on({ click: () => console.log('clicked') })
  .create(['Plain text', element('span')('and a node')]);

Plain calls

A tag can also be called directly. A plain object is the data object, with the same names as the builder; anything else is the children:

p();
p('Hello');
p([strong('Hi'), ' there']);
p({ props: { className: 'lead' }, attrs: { title: 'Intro' }, on: { click: select }, children: 'Hello' });

Because a plain object is read as the data object, pass a value that does not come from your own code, such as parsed JSON, storage or a message, through .create(value) or { children: value }. Otherwise an object like { "props": { "innerHTML": "…" } } sets properties instead of showing text.

The data object

Key Type Applied by
props ElementProps<T> own keys, merged into nested objects
attrs HTMLElementsAttributesMap[T] setAttribute
children Children inserted in order
on ElementEventData<T> addEventListener

Every key is optional and accepts undefined or null.

Builder

Every tag carries builder methods. Each method returns a new builder and leaves the old one unchanged, and the top level of each map is copied when you call the method; nested objects such as style are used as they are when the element is created. .create() creates the element and returns it.

Method Takes Repeated calls
props(map) JavaScript properties of the element, such as className, value or style. undefined leaves the element's property unchanged, but a later undefined replaces an earlier value of the same builder. Combine: later keys win, so a later style object replaces an earlier one.
attrs(map) Attributes, set with setAttribute. Inline event handlers such as onclick, in any case, are ignored. Merge: later keys win, and null removes an earlier value.
on(map) Listeners: { click: fn } or { click: { handler, options } }. Add listeners; they never replace each other.
with(fn) A function that gets the builder and returns a builder. Each call applies its function.
also(fn) A function that gets the created element, after the listeners. The element is not in the document yet, so focusing or measuring does not work there. Add callbacks, run in order.
create(children) The children, like the children key: a node, a string, a number, or an array of these. Creates the element and returns it.

Because a builder never changes, it can serve as a template:

const card = div.props({ className: 'card' }).on({ click: select });

card.create(h2('A'));
card.attrs({ 'aria-label': 'B' }).create(h2('B'));

with applies reusable settings, left to right, or a condition:

const shadow = (b) => b.props({ style: { boxShadow: '0 1px 4px #0003' } });

div.with(shadow).with((b) => (isAdmin ? b.attrs({ 'data-admin': '' }) : b)).create('Settings');

Typed modifiers

In TypeScript, type a modifier that works on every HTML tag as HTMLModifier (SVGModifier for SVG). It keeps the type of the tag it is used on:

import { button, div, type HTMLModifier } from 'fiorejs';

const card: HTMLModifier = (b) => b.props({ className: 'card' });

div.with(card).create(); // HTMLDivElement
button.with(card).props({ type: 'submit' }).create('Save'); // HTMLButtonElement

Source: lib/core/builder.js

props

props uses JavaScript property names. It is typed as ElementProps<T>, which keeps the writable properties of the element and makes them recursively partial.

div
  .props({
    className: 'card',
    textContent: 'Hello',
    style: {
      padding: '16px',
      background: 'white',
    },
  })
  .create();

A plain object such as style or dataset is merged into the element's existing object; any other value is assigned whole. Only own keys are copied, and __proto__, constructor and prototype are skipped. undefined leaves a property unchanged. Repeated props calls on a builder combine: later keys win, so a later style object replaces an earlier one. A nested object such as style is merged into the element after the other keys of its map.

Read-only DOM properties are excluded by the type. To set a read-only value, use a writable property or an attribute instead.

Source: lib/core/base.js

attrs

attrs uses HTML attribute names and calls setAttribute(key, value) for each entry. null, undefined and false leave the attribute out; every other value, including 0 and '', is set. aria-*, data-*, contenteditable, draggable and spellcheck keep false as "false". Inline event handlers such as onclick, in any case, are ignored, so no handler string is ever run; use on for listeners. Other names that start with on, such as online, are set. Repeated attrs calls on a builder merge: later keys win, and null removes an earlier value.

input
  .attrs({
    type: 'email',
    required: 'true',
    'aria-label': 'Email address',
    class: 'field',
  })
  .create();
Boolean attributes. Pass '' or true to set a boolean attribute, and false or null to leave it out.

Property names and attribute names differ for some elements. Use the attribute column with attrs and the property column with props.

Attribute Property Example
class className .attrs({ class: 'card' })
for htmlFor .props({ htmlFor: 'email' })
tabindex tabIndex .props({ tabIndex: 0 })
aria-label ariaLabel .attrs({ 'aria-label': 'Close' })

Per-tag attribute types come from lib/types/attributes.d.ts. Global HTML attributes, ARIA, RDFa and tag-specific attributes are included.

Source: lib/core/base.js

children

children accepts nodes, strings, numbers and arrays of them. null, undefined, true and false are skipped, so user.isAdmin && badge() works. With a builder, the children are the argument of .create(); in a plain call they are the argument itself or the children key.

type Child = Node | string | number | boolean | null | undefined
div.create(['Status:', span('ready'), isAdmin && badge()]);

Numbers are inserted as text. Text nodes and document fragments are inserted as they are.

Source: lib/core/base.js

on

on maps native event names to a handler. The key is the event name used by addEventListener, such as click, not the property name onclick.

A value can be a function or an object with handler and options:

button
  .on({
    click: (event) => console.log(event.currentTarget),
    keydown: {
      handler: onKeyDown,
      options: { once: true, capture: false },
    },
  })
  .create('Save');

Each element accepts the events of its own event map, so body takes window events such as popstate. In a handler, this and event.currentTarget are typed as the element. The options value is the same boolean | AddEventListenerOptions that addEventListener accepts.

Custom event names that contain a hyphen are accepted on every element and typed as CustomEvent. Annotate the parameter to type its detail:

div.on({ 'cart-add': (event: CustomEvent<{ sku: string }>) => console.log(event.detail.sku) }).create();
Listener order. Listeners are attached after props, attributes and children, and before the also callbacks. Repeated on calls on a builder add listeners; they never replace each other. An entry with no handler is skipped.

Common event keys

The type accepts any key from HTMLElementEventMap for HTML elements, with matching event maps for SVG and MathML. These are the common keys by category.

Mouse
click, dblclick, mousedown, mouseup, mouseenter, mouseleave, mousemove, mouseover, mouseout, contextmenu, auxclick
Pointer
pointerdown, pointerup, pointermove, pointerenter, pointerleave, pointerover, pointerout, pointercancel, gotpointercapture, lostpointercapture
Keyboard
keydown, keyup, keypress
Focus
focus, blur, focusin, focusout
Form
input, beforeinput, change, submit, reset, invalid, select
Clipboard
copy, cut, paste
Drag
drag, dragstart, dragend, dragenter, dragleave, dragover, drop
Touch
touchstart, touchend, touchmove, touchcancel
Wheel and scroll
wheel, scroll, scrollend
Media
play, pause, playing, ended, timeupdate, volumechange, loadedmetadata, canplay, canplaythrough, waiting, stalled
Animation and transition
animationstart, animationend, animationiteration, animationcancel, transitionstart, transitionend, transitionrun, transitioncancel
Toggle and dialog
toggle, beforetoggle, close, cancel
Fullscreen
fullscreenchange, fullscreenerror
Load and error
load, error, abort

Event reference: MDN HTMLElement events

Source: lib/core/base.js

Tag functions

Every tag has a named export that fixes the tag and returns the matching element type. When the tag name is a variable, element(name) returns its tag function.

235 tag functions, all entry points

Deprecated tags

The deprecated entry point exports element and one function per deprecated HTML tag. Every function is marked @deprecated in the declarations.

import { element, center } from 'fiorejs/html/deprecated';
Show 29 deprecated functions

TypeScript types

Declaration files are generated next to every module and referenced by the types field. These are the public types behind the tag functions.

Type Declaration Shape
HTMLTag<T> lib/types/html.dom.d.ts A tag function: callable with a data object or children, with the builder methods
HTMLBuilder<T> lib/types/html.dom.d.ts A builder of any HTML element
HTMLModifier lib/types/html.dom.d.ts A reusable function for with that works on every HTML tag and keeps its element type
ElementData<T> lib/types/html.dom.d.ts The data object: props, attrs, on and children
DeprecatedElementData<T> lib/types/html.dom.d.ts The four keys for deprecated tags
ElementEventData<T, E> lib/types/html.dom.d.ts Event map with function or options values
DomEventListener<T, K, E> lib/types/html.dom.d.ts (this: T, ev: E[K] & { currentTarget: T }) => unknown
DomEventListenerOption<T, K, E> lib/types/html.dom.d.ts { handler, options }
Children lib/types/base.dom.d.ts Child | Child[], where Child is Node | string | number | boolean | null | undefined
ElementProps<T> lib/types/base.dom.d.ts Writable, recursively partial element properties
BaseElement lib/types/base.dom.d.ts Element
SVGElementData<T, E> lib/types/svg.dom.d.ts The four keys for SVG tags
SVGModifier lib/types/svg.dom.d.ts A reusable function for with that works on every SVG tag
MathElementData<T, E> lib/types/math.dom.d.ts The four keys for MathML tags

Package entry points

The exports field in package.json defines every public specifier. The package ships lib/ only, with JavaScript and declaration files side by side.

Specifier JavaScript Types
fiorejs lib/html.js lib/html.d.ts
fiorejs/html lib/html.js lib/html.d.ts
fiorejs/global lib/index.js lib/index.d.ts
fiorejs/svg lib/svg.js lib/svg.d.ts
fiorejs/math lib/math.js lib/math.d.ts
fiorejs/html/deprecated lib/html-deprecated.js lib/html-deprecated.d.ts

Release notes are on the GitHub releases page.

Upgrading from 1.x

Version 2 renames two keys of the data object and adds the builder; everything else works as before. Fiore was published as html-dom-js up to version 1.1.2.

1.x 2.x
div({ attributes: { … } }) div({ attrs: { … } }) or div.attrs({ … }).create()
div({ event: { click } }) div({ on: { click } }) or div.on({ click }).create()
div({ children: 'Hi' }) still works, or div('Hi')
element('div', data) element('div')(data)

Plugins and use() are gone: a value is live when it has a method under Symbol.for('fiorejs.live'), exported as LIVE, and signals from @fiorejs/signals 2.0.0 have one. A bare function is no longer live; wrap a getter in computed(() => …).