Skip to content

Components of your own ​

The standard types cover most forms. When one does not, a page adds a type of its own: a row of stars, a postcode lookup, a map pin. The form draws it, and the builder offers it on the palette and edits it like any standard type.

A type is one object, a component definition. The page's script holds all of it, so the example below is the whole page.

index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Customer survey</title>
    <link rel="stylesheet" href="/datum/datum-form.css">
    <script type="module" src="/datum/datum-form.js"></script>
  </head>
  <body>
    <datum-form id="survey" src="/forms/customer-survey.json"></datum-form>

    <script type="module">
      // The bundle exports what a component type is built from, and the page's plugin registry.
      import { plugins, standardFieldCapabilities } from "/datum/datum-form.js";

      // A component type the bundle does not know: a row of stars, stored as a number.
      const rating = {
        type: "star-rating",
        version: "1.0.0",
        // The standard type it reads as, so the definition can be validated without this code.
        base: "number",
        // What lands on the canvas when the type is picked from the palette.
        createDefault: () => ({ id: "rating", type: "star-rating", configuration: { label: "Rating", max: 5 } }),
        // The inspector fields every field type shares (label, required, hidden, CSS classes)...
        capabilities: standardFieldCapabilities({ placeholder: false, description: false }),
        // ...and one of its own.
        propertyEditor: {
          mode: "extend",
          fields: [{ id: "max", type: "number", propertyPath: "max", label: "Stars", min: 1, max: 10 }]
        },
        // How it draws, on the form and on the builder's canvas. It is handed the renderer's own
        // lit, so the page loads none, and answers the field with the number of the star pressed.
        adapter: ({ html }) => ({
          kind: "field",
          template: (state, on) => {
            const max = Number(state.model.node.configuration.max) || 5;
            const stars = Array.from({ length: max }, (_, index) =>
              html`<button type="button" class=${index < Number(state.answer) ? "star-rating__star is-on" : "star-rating__star"} aria-label=${`${index + 1} of ${max}`} @click=${() => on.input(index + 1)}>★</button>`
            );
            return html`<div class="star-rating" role="group" aria-labelledby=${state.labelId}>
              <span class="star-rating__label" id=${state.labelId}>${state.label}</span>
              <span class="star-rating__stars">${stars}</span>
            </div>`;
          }
        }),
        // Its own rules, adopted into the form after the design system's.
        css: [
          ".star-rating__stars { display: inline-flex; gap: 0.25rem; }",
          ".star-rating__star { font: inherit; font-size: 1.5rem; border: 0; background: none; color: inherit; cursor: pointer; }",
          ".star-rating__star.is-on { color: #b45309; }"
        ]
      };

      // The type, beside the standard catalogue.
      survey.componentDefinitions = [rating];
    </script>
  </body>
</html>
ResultThis page, running. Addresses under /forms//api/ are answered by the example.
What the page did

Nothing yet.

Try the form first. Press a star and the log shows the answer as a number. Then give the type to the builder: Rating sits on the palette under Survey, its inspector has a Stars field, and the canvas draws the stars with the same adapter.

Adding a type ​

The way to add a type is plugins.register. A plugin carries the definition with its palette entry, and registering it once serves every <datum-form> and <datum-form-builder> on the page, including ones added later.

js
import { plugins, standardFieldCapabilities } from "./datum-form.js";

plugins.register({
  id: "survey",
  version: "1.0.0",
  components: [{
    type: "star-rating",
    version: "1.0.0",
    base: "number",
    createDefault: () => ({ id: "rating", type: "star-rating", configuration: { label: "Rating", max: 5 } }),
    capabilities: standardFieldCapabilities({ placeholder: false }),
    palette: { label: "Rating", icon: "★", group: "Survey" },
    adapter: ({ html }) => ({ kind: "field", template: (state, on) => html`...` })
  }]
});

A plugin can bring more than types: hooks, validators, a submission handler, formula functions and data sources. See Plugins.

Two lower routes exist for a single element:

  • componentDefinitions on one element adds definitions to that element alone: form.componentDefinitions = [definition]. A builder lists a type from componentDefinitions only if a palette entry exists, which componentTypes gives: builder.componentTypes = [{ type: "star-rating", label: "Rating", icon: "★", group: "Survey" }]. Without it the type draws but is not on the palette.
  • plugins on one element takes a plugin for that element alone: element.plugins = [plugin].

What a definition holds ​

FieldWhat it is
typeThe name a definition uses for it, such as "star-rating". A name that matches a standard type replaces that type.
versionThe version of the type.
baseThe standard type it reads as, an answer type or fieldset, panel or tabs. See Base and the kinds map.
createDefaultA function returning the component the builder adds when the type is picked from the palette.
capabilitiesThe inspector fields the type shares with others. See Capabilities.
propertyEditorThe inspector fields of the type's own. See The inspector.
childrenFor a container: { slots: [...] }, the named places children go. A slot has an id, multiple, and optionally min, max, allowedTypes, allowReorder, allowNested and emptyHint (the words on the canvas while the slot is empty).
adapterHow the type draws, on the form and on the builder's canvas. See The adapter.
cssA list of CSS rules for what the adapter draws, adopted into the form after the design system's, so the type looks the same under every design system.
paletteHow the builder lists it: { label, group?, icon?, binding? }. group defaults from the type's name (Fields, Choices, Layout, Content, Actions, else Other). icon is a short text glyph. binding offers the type only while that design-system binding draws the canvas.
pdf{ renditions, defaultRendition }: the ways the type appears in a PDF. See Plugins.
validatorsValidation stages that belong to the type.
fixedMarks a component that stands for something outside the author's hands, such as a field of a PDF template: its properties edit, but there is no Delete and it is never on the palette.

Capabilities ​

A capability is a set of inspector fields with the code that writes them into configuration. standardFieldCapabilities(options) returns the usual set for a value-bearing field, in the order the inspector shows them. Label, tooltip, hide label and disabled are always in it. The options turn the rest on or off:

OptionDefaultAdds
descriptiononDescription.
placeholderonPlaceholder. Off for a control with no text box.
requiredonRequired. Off for a component that holds no value.
dataKeyfollows requiredThe data key: the name the answer is stored under.
messagesonValidation messages per code.
cssClassonCSS classes.
pdfonPDF rendition and leave out of PDFs.
printonHow it prints from the live form.
patternoffPattern and its message, for free text.
lengthoffMinimum and maximum length and the character count.
rowsoffVisible rows, for a multi-line control.
autocompleteoffThe autocomplete token.
inputModeoffThe keyboard and spell-check settings.
affixoffPrefix and suffix.
attachFilesoffAttach uploaded files to a PDF, for a file type.

cssClassCapability is exported too, for a container that lists its fields itself.

The inspector ​

propertyEditor is { mode, fields?, sections?, features? }.

modeMeaning
defaultThe capabilities' fields only.
extendThe capabilities' fields, then these.
replaceThese fields instead of the capabilities'. A container does this and lists the fields it wants.
noneNo fields.

A field is { id, type, propertyPath, label?, description?, ... }. propertyPath is a path inside the component's configuration ("max", "tabs.0.label"). The field types:

typeEdits
text, number, booleanA string, a number (with min, max, step), a switch.
selectOne of choices: [{ value, label }].
localized-textA text the form translates.
colorA colour.
expression, formulaA formula, in the Logic workspace's formula editor.
component-selectorA component of the form.
data-source-selectorOne of the data sources.
options-editorInline { value, label } options.
messages-editorValidation text per error code.
chrome-editorA region's header or footer parts.
fileA file kept in the configuration (accept, and assetChoices for ready-made values).
pathA value path, with the form's saved paths offered.
value-mapA table that translates one set of values to another.
customDrawn by the definition's own render.

Any field takes defaultValue (what the editor shows while the property is unset; nothing is written until the author changes it), visibleWhen and disabledWhen ({ propertyPath, equals }, reading another property of the same component). sections group fields: { id, title?, fieldIds, hideWhenEmpty? }.

The adapter ​

adapter is an adapter object, a list of them told apart by when, or a function (lit, datum) => entry. A function receives the renderer's own lit namespace ({ html, ... }), so the page loads no template library, and Datum's own binding. A type that nothing draws shows the renderer's unknown-component note. An adapter is laid over whichever binding draws the form, so the type draws under every binding.

The kind says what it draws:

kindDrawstemplate receives
fieldA leaf: input, choice, date, file, button, static content.(state, on)
groupA container around its children.(state, children)
tabsA tabs container.(state)
gridA data grid or repeating section.(state)
stepsA steps container.(state)

For a field, the renderer builds state and the adapter returns a template. The members a custom control uses:

stateHolds
answer, valueThe stored answer as it is, and as text.
label, labelId, hideLabelThe label and an id for it, so a group can name itself with aria-labelledby.
hint, hintIdThe description and the id it must carry.
id, name, valuePathThe control's id, a name for grouped controls, and where the answer is stored.
required, readOnly, disabled, invalid, pending, busyThe field's states. Set aria-invalid="true" only while invalid.
errors, errorId, notices, noticeIdThe worded blocking errors and warnings, and the ids their elements carry.
describedByThe ids that describe the control, in order. Write them as aria-describedby.
locale, dir, mode, classNamesLanguage, direction, interactive, readonly or disabled, and the author's classes.
wordsThe form's words for the locale, for any text the adapter draws.
text(property)One of the component's own configuration texts, in the locale.
modelThe engine's model: model.node.configuration holds the properties the inspector wrote.

on reports what the person did. The renderer ignores writes while the form is read-only or disabled.

onReports
input(value, { interim?, badInput?, typed? })A new answer. interim: true while typing.
commit()The field was left or its value settled. It runs the leave-field check.
parts({ day, month, year })A date typed in parts.
files(list), remove(id), download(id)A file field's picks, removals and downloads.

The adapter's capabilities answer, per drawing capability, whether it draws it: drawn, degraded or none. The members and answers are the same as a design-system binding's; Writing a binding has the full contract, including after, ready, connect, focusTarget and idsWrittenBy.

Base and the kinds map ​

The engine knows what a number is, how to validate it, how to print it and how a sandbox reads it. It knows nothing of star-rating. A definition's base says the standard type a type reads as, here "number". Types that hold an answer can have an answer type as a base, and containers can have fieldset, panel or tabs.

The builder copies the base into the form's kinds map, which is part of the saved definition:

json
{
  "id": "customer-survey",
  "kinds": { "star-rating": "number" },
  "root": { "id": "root", "type": "form", "children": { "content": [] } }
}

With the map in the definition, validation, the sandbox and the PDF treat a star-rating as a number without any of the type's code. The form can be checked on a server that has never heard of it. The definition below is the one the example loads:

json
{
  "id": "customer-survey",
  "version": "1.0.0",
  "schemaVersion": "1",
  "localization": {
    "defaultLocale": "en",
    "supportedLocales": [{ "code": "en", "label": "English" }]
  },
  "kinds": { "star-rating": "number" },
  "root": {
    "id": "root",
    "type": "form",
    "configuration": { "title": "Customer survey" },
    "children": {
      "content": [
        { "id": "fullName", "type": "text", "configuration": { "label": "Full name", "required": true } },
        { "id": "experience", "type": "star-rating", "configuration": { "label": "How was your experience?", "max": 5 } },
        { "id": "comments", "type": "textarea", "configuration": { "label": "Anything else?", "maxLength": 500 } },
        { "id": "submit", "type": "button", "configuration": { "label": "Submit", "action": "submit" } }
      ]
    }
  }
}

Next ​

MIT licence. Your forms, your data, your keys.