@20baht/ui
v0.6.1
Published
JSON-driven form + workflow engine. Send JSON in, get an interactive form out.
Maintainers
Readme
bahtui
JSON in, interactive form out. A framework-neutral form + workflow engine shipped as Web Components (Lit, light DOM) with a pure-TypeScript rules core.
npm i @20baht/ui
npm i marked dompurify # optional peers: markdown fieldsOptional peers and the build. marked and dompurify (markdown fields) are loaded with a
dynamic import() the first time such a field is drawn. A bundler still resolves every
import('…') it sees when it builds, and <baht-form> (which can draw any field type) reaches
both, so an app that uses <baht-form> either installs them or marks them external. External
is safe when the app has no such field: the import() is never run. Date fields need no package:
the calendar is bahtui's own (0.6).
// Angular (angular.json, build options)
"externalDependencies": ["marked", "dompurify"]
// Vite: build.rollupOptions.external · esbuild: --external:marked …Quick start — one form (Level 1)
<script type="module">
import '@20baht/ui'; // registers <baht-form> / <baht-workflow>
</script>
<link rel="stylesheet" href="@20baht/ui/tokens.css" />
<baht-form id="f"></baht-form>
<script>
const el = document.getElementById('f');
el.form = {
form_id: 'f1',
form_name: 'Person',
fields: [
{ order: 1, type: 'text', key: 'firstName', label: 'First name', width: '1/2', required: true, value: '' },
{ order: 2, type: 'text', key: 'lastName', label: 'Last name', width: '1/2', required: true, value: '' },
{ order: 3, type: 'number', key: 'age', label: 'Age', width: '1/4', min: 0, value: null }
]
};
el.addEventListener('baht-change', (e) => console.log(e.detail.data));
// el.validate() / el.getData() / el.setValue({...}) / el.reset()
</script><baht-form> is a dumb controlled component: props in → UI → baht-change out. No buttons, no
cross-field logic, no fetch. Your app owns the state (mutate the JSON, feed it back).
Views — show a subset of one form
Define named display projections on the schema (e.g. per user role); select one with the
view attribute:
el.form = {
...form,
views: [{ name: 'summary', fields: ['age', 'firstName'] }], // view order = display order
};
el.view = 'summary'; // or <baht-form view="summary">; unset = full formViews are client-side display only: the view picks which fields render (and validate —
the user can only fix what they see), but getData() still returns the full form and the
server (@20baht/validator) always validates the complete schema. In a workflow, set
view: 'summary' on a step's form to pin the view that step renders.
Read-only display
<baht-form readonly> shows a submission instead of editing it: values as text, option
labels instead of keys, chips for multi-picks, Yes/No, no help text, "Not provided" for
blanks. Same grid, same widths. displayValue(field, value) from @20baht/ui/engine
gives you the same formatting for tables.
Repeater — line items / repeating rows
{ order: 5, type: 'repeater', key: 'items', label: 'Line items', min_rows: 1,
fields: [
{ order: 1, type: 'text', key: 'name', width: '1/2', required: true },
{ order: 2, type: 'number', key: 'qty', width: '1/4', min: 1 },
] }Value is an array of row objects (getData().items → [{ name, qty }, …]). Rows add/remove in
the UI (min_rows/max_rows bound the count), each row validates its sub-fields — errors come
back as items[0].name, on both the client and @20baht/validator. One level deep only.
Dependent / async dropdowns
// schema — functions never live in JSON, only registry names:
{ order: 2, type: 'dropdown', key: 'amphoe', options_from: 'amphoeFor', options_deps: ['province'] }
// registry:
el.registry = {
options: { amphoeFor: (data) => fetch(`/api/amphoe?p=${data.province}`).then(r => r.json()) },
};Options resolve from the registry with the form's current data (sync or Promise). When a dep changes, options refetch and the dependent value clears — cascading down chains (จังหวัด → อำเภอ → ตำบล).
Cross-field validation
{ order: 2, type: 'date', key: 'end',
validators: [{ type: 'compare', op: 'gte', field: 'start' }] }compare checks against a sibling field (confirm email = op: 'eq'): eq/ne are strict like a
rule's ("0123" is not "123"), the ordering ops are numeric/date-aware; it skips while either side is empty. Works inside repeater rows and on the server.
Feature flags — deploy dark, flip a JSON file
// schema: gate a field / workflow step / rule
{ order: 9, type: 'text', key: 'promoCode', flag: 'promo' } // '!promo' = the old path
// host: flags from one static file — edit it, features flip
el.flags = await fetch('/flags.json').then((r) => r.json()); // { "promo": true }Flag-off means not in the schema: no render, no validation (a dark required can't
block), nothing in the payload. Missing keys count as off, so new features stay dark until
the file turns them on. Server side: validateSubmission(applyFlags(schema, flags), data)
with the same JSON — @20baht/validator re-exports applyFlags.
File upload
// schema:
{ order: 6, type: 'file', key: 'doc', uploader: 'default', accept: '.pdf,image/*', max_size: 10_485_760 }
// registry — File in, serializable ref out:
el.registry = {
uploaders: { default: async (file) => {
const fd = new FormData(); fd.append('file', file);
return (await fetch('/api/uploads', { method: 'POST', body: fd })).json();
} },
};Picking a file uploads immediately; the value becomes { name, size, type, url } — plain
JSON, chips with remove buttons in the UI, max_size/accept validated on both client and
server. Omit uploader for the old capture-only mode.
No registry function at all? <baht-upload> talks to an endpoint straight from attributes:
the file is POSTed as multipart on pick, the endpoint returns the stored URL, and that URL is
the value (baht-change → { value, files }; progress and error events included).
<baht-upload url="/api/uploads" accept=".pdf,image/*" max-size="10485760" label="Attachment"></baht-upload>Drafts / autosave (host pattern)
The library is controlled — autosave is three lines in your app:
el.addEventListener('baht-change', (e) => localStorage.setItem(key, JSON.stringify(e.detail.data)));
// (workflow: listen to baht-data-change instead)
el.value = JSON.parse(localStorage.getItem(key) ?? '{}'); // restore on mount
// clear the key after the server accepts the submissionThe /builder page of the docs site (bun run --filter docs dev) shows the same flow live.
i18n — Thai (or any) built-in strings
All built-in strings — validation messages, Next/Submit/Back, the approval step — come from one catalog:
import { setLocale } from '@20baht/ui';
setLocale('th'); // built-ins: 'en' (default), 'th'
setLocale('th', { required: 'ห้ามว่าง' }); // locale + your own overridesCall it once before mounting. Per-field message and label attributes
(next-label, approval.approve_label, …) still win over the catalog. The server can
localize too: @20baht/validator re-exports setLocale, so validation issues come
back in the same language the client shows.
In a plain <form> (form-associated)
Every value-holding element (<baht-input> and the other field primitives, plus <baht-otp>,
<baht-upload>, <baht-choice-group> and <baht-typeahead>) is a form-associated custom element.
Give it a name and it takes part in the host's own <form> the way a native control does:
<form method="post" action="/orders">
<baht-input name="customer"></baht-input> <!-- el.field = { key: 'customer', type: 'text', … } -->
<baht-multiselect name="tags"></baht-multiselect>
<baht-otp name="code" length="6"></baht-otp>
<button>Send</button>
</form>new FormData(form)(and a native submit) carries the value undername: text as it is, a number as its digits, a ticked checkbox or toggle ason(an unticked one not at all), a list (multiselect, tags, a date range,multiplereferences or uploads) as one entry per item, dates as their ISO days, a captured file as theFile, an uploaded one as its URL, a repeater's rows as JSON. Noname, nothing is sent.requiredwith an empty value, or anerrorthe host set, holds the submit: the browser reports the message on the element's inner control and moves focus there.checkValidity(),reportValidity(),validity,validationMessage,willValidateandformread as on a native control.:invalidmatches the element;:user-invaliddoes not (browsers do not wire it for these elements).- A named element in a form keeps the user's edit in
valueitself, so a form with no script sends what was typed.baht-input/baht-changestill fire for every edit. Elsewhere (inside<baht-form>, or without aname) the element stays controlled: the host re-feedsvalue. form.reset()puts back the value the element was given before the user's first edit, and tells it as an edit (baht-input/baht-change), so a controlled host follows. A disabled<fieldset>turns the element off (it matches:disabled; its owndisabledis left alone). The browser's state restore (back/forward) hands a named element its value back.- Inner native controls are out of the host's form (
form=""): only the element is inform.elements, so an inner radio's name never reachesFormData. Enter in an inner text box still submits the form, through its default button.
<baht-form> is not form-associated: its data is nested (forms, repeaters, files) and is sent as JSON
(checkSubmission, submitTo), not as FormData.
Quick start — wizard with rules (Level 2)
document.querySelector('baht-workflow').workflow = {
workflow_id: 'wf-1',
forms: [/* {form_id, form_name, order, fields}, ... */],
rules: [
{ id: 'skip-person',
when: { field: 'Intro.kind', op: 'eq', value: 'company' },
then: [{ action: 'skipForm', target: { form: 'Person' } }] },
{ id: 'vat',
when: { field: 'Company.hasVat', op: 'eq', value: true },
then: [{ action: 'show', target: { form: 'Company', field: 'vatId' } },
{ action: 'required', target: { form: 'Company', field: 'vatId' } }],
else: [{ action: 'hide', target: { form: 'Company', field: 'vatId' } }] }
]
};<baht-workflow> walks the forms in order, evaluates the rules on every change
(show/hide/enable/disable/readonly/required/setValue/skipForm…), renders the single
Next→Submit button, and emits baht-next / baht-submit / baht-complete / baht-data-change /
baht-step-change. The runtime navigates; your app acts.
Headless core (any framework, no DOM)
import { evaluate, validateField } from '@20baht/ui/engine';
const derived = evaluate(workflow, { Intro: { kind: 'company' } });
// derived.forms -> { Person: { visible: false }, ... }
// derived.fields -> { 'Company.vatId': { visible, enabled, readonly, required, computed } }
// derived.data -> nested output (hidden/skipped values cleared + excluded)The engine is its own package, @20baht/engine (no
DOM, no Lit, no dependencies); @20baht/ui/engine re-exports it. A server that renders nothing can
install that one alone.
The engine is a pure function with fixpoint evaluation (cycle-guarded), per-rule priority
conflict resolution, and clear-on-hide/skip semantics. Build a React/Vue renderer on top of it
without touching the Web Components.
A whole run, headless
updateWorkflow is the workflow's runtime as one pure function: a run is a plain value, a press or
an edit is a message, and each step returns the next state plus the events <baht-workflow> would
dispatch, in order. No DOM, nothing kept between calls.
import { updateWorkflow, nextTarget } from '@20baht/ui/engine';
let { state } = updateWorkflow(workflow, null, { type: 'start', value: {} });
({ state } = updateWorkflow(workflow, state, { type: 'edit', form_name: 'Intro', key: 'kind', value: 'company' }));
const { state: after, events } = updateWorkflow(workflow, state, {
type: 'next',
validity: { valid: true, errors: [] }, // you validate the form (validateField); the runtime gates on it
gate: true,
});
// after.current -> 'Company'; after.history -> ['Intro']; after.derived.data -> the data
// events -> [{ name: 'baht-next', detail }, { name: 'baht-step-change', detail }]
nextTarget(workflow, after); // the step after this one, or 'end'Messages: start, edit, patch, comment, next, decide, back, gotoStart, flags, restore;
anything else changes nothing. decide takes the validity and gate of the approval step's own fields,
like next. snapshotOf(state) is the run as JSON ({ workflow_id, data, current, history, ended }), a copy
the host may change (a snapshot holds every value entered: withoutPasswords(workflow, snapshot.data) from /engine takes the password fields out before it is stored), and
restore picks it up again; a snapshot of another workflow restores as an empty run. <baht-workflow> has
the same pair as getState() / restore(snapshot), for drafts, resume and undo. Pass the workflow with its
flags applied (applyFlags). Typed-input debounce and form validation stay with the caller: they are the
renderer's business.
A run that submitted, or that a rejection ended, is ended (state.ended: 'completed' / 'rejected'):
another press, decision, back or gotoStart does nothing, so a double click submits once. start or
restore begins again. The last press does not submit while the rules never settled (a kind: 'data'
rule error, which @20baht/validator refuses): it emits baht-nav-blocked with reason: 'rule-error'.
<baht-workflow> tells every step it takes as baht-transition { msg, before, after, events }, after
the step's own events. That is a log, a replay and an undo:
const log: WorkflowTransition[] = [];
el.addEventListener('baht-transition', (e) => log.push(e.detail));
replayWorkflow(workflow, log.map((t) => t.msg)); // { state, events }: the same run, no DOM
el.restore(snapshotOf(log.at(-1).before)); // undo the last stepA replay is exact for the rules and the navigation, against the same definition: replay a log under the workflow it was recorded with. What a host script wrote during the run is in the log only as the edits it made; the script does not run again. A replay only folds states: it dispatches nothing and calls no registry function. The log is the host's to bound: each transition holds two whole states.
A form, headless
One form has the same shape: updateForm(input, state, msg) returns the next state and the events
<baht-form> would dispatch. input is what the host owns (the definition with its flags applied, the
starting value, the registry, rule-derived fieldStates, a view); state is what the form remembers
(the edits, the errors, what scripts set). input.locale gives the session its own message locale; unset,
it uses the catalog setLocale chose (withLocale(locale, fn) does the same for any synchronous call).
import { emptyFormState, formData, updateForm } from '@20baht/ui/engine';
const input = { form, value: { name: 'Ann' }, registry };
let { state } = updateForm(input, emptyFormState, { type: 'load' }); // load scripts
({ state } = updateForm(input, state, { type: 'input', key: 'age', value: 30 }));
const { state: checked, events } = updateForm(input, state, { type: 'validate' });
// checked.errors -> what is wrong; events -> [{ name: 'baht-validity', detail }]
formData(input, checked); // { name: 'Ann', age: 30, ... } the whole form, whatever the viewMessages: input, set, revert, value, form, load, validate, blur, script, reset. Formatters,
dependent options (options_deps) and client scripts run inside the step. A script handler that keeps g
past its step (after an await) needs a host that lends it one: pass { context } as the fourth argument
and forward late calls as a script message, as <baht-form> does. validateShownField and
submitScriptErrors are the two checks the browser and @20baht/validator share.
Functions never travel in JSON
Formatters and custom validators are referenced by name and resolved from a registry you pass as a prop:
el.registry = {
formatters: { uppercase: (v) => String(v).toUpperCase() },
validators: { idCardTH: (v) => isThaiId(v) ? null : 'บัตรประชาชนไม่ถูกต้อง' }
};
// JSON side: { formatter: 'uppercase', validators: [{ type: 'custom', fn: 'idCardTH' }] }Client scripts — ServiceNow-style load / change / submit
When rules JSON isn't enough, register imperative hooks the same way — by name:
// JSON side
form.scripts = [
{ on: 'change', field: 'type', handler: 'typeChanged' },
{ on: 'submit', handler: 'checkQuota' },
];
// host side — `g` is the g_form equivalent, scoped to this form
el.registry.scripts = {
typeChanged: (g, { newValue, isLoading }) => {
if (isLoading) return;
g.setRequired('doc', newValue === 'sick');
g.showFieldMsg('doc', 'แนบใบรับรองแพทย์', 'info');
},
checkQuota: (g) => {
if (g.getValue('days') > 10) { g.addErrorMessage('เกินโควตา'); return false; } // blocks submit
},
};g reads (getValue, getData), writes (setValue — cascades to that field's change
script, depth-guarded), overrides UI state (setVisible / setReadOnly / setRequired /
setDisabled, on top of rule-derived states; a repeater's cell as servers[2].disk, its column
in every row as servers[].disk) and shows messages. @20baht/validator
re-runs submit scripts on the server; load/change are UI-only. See
docs/components/baht-form.md and spec 01 §14.
Design system — 20baht
Ships themed as the 20baht design system, "ledger" retone: minimal and flat —
near-black ink (#171717) on white, hairline neutral borders, 44px controls, one indigo accent
(#444FBF), status as tint pills, hand-drawn koboyo spot illustrations for empty /
error / upload states, IBM Plex Sans Thai / IBM Plex Mono (load the
fonts yourself), borders-over-shadows, "paper" easing — plus a dark theme that follows the OS
when <html> has no theme (0.6), pinned with <html data-baht-theme="dark"> or "light". The same
sheet inside cascade layers is @20baht/ui/css/layered.css (opt-in; docs/theming.md). 64 elements:
<baht-button variant="secondary" size="sm">Cancel</baht-button>
<baht-badge tone="success" label="Running"></baht-badge>
<baht-table></baht-table> <baht-modal></baht-modal> <baht-toast></baht-toast> …- Data (server-side paging) —
baht-table·baht-list·baht-swipe-row·baht-pagination·baht-filter.baht-tableships a ServiceNow-style column picker with dot-walking into reference columns (requester.department) and emitsbaht-columns-changeso the host can persist the layout.itemsis one page;baht-page-changeasks your app to fetch the next one. - Actions —
baht-button(shortcut="alt+q": bound key + tooltip hint;loading;blockfor a phone's action stack;shape="circle|square"icon buttons;variant="link"; a 44px hit area under a finger) ·baht-split-button(main action + menu with shortcut hints) ·baht-menu(⋯ / labelled action menu) ·baht-theme-toggle(light / dark switch) - Feedback —
baht-modal·baht-panel(docked side panel; a full-screen sheet on a narrow window) ·baht-toast·baht-alert·baht-tooltip·baht-popover·baht-progress·baht-spinner·baht-skeleton·baht-save-bar(sticky "unsaved changes" bar;<baht-form>givesdirty,baht-dirty-changeandmarkClean()) - Inputs —
baht-rating·baht-range·baht-otp·baht-typeahead·baht-reference-picker·baht-keyvalue-editor·baht-upload(+ the 15 form field primitives). Typed fields debounce keystrokes (150 ms,debounce);dropdownrenders its own listbox, never the OS picker. - Stats & charts —
baht-stat·baht-stat-chart·baht-meter·baht-sparkline·baht-bar-chart·baht-line-chart·baht-donut-chart·baht-heatmap·baht-progress-ring - Structure & nav —
baht-card·baht-fieldset·baht-timeline·baht-accordion·baht-steps(variant="segments": one bar per step) ·baht-link·baht-breadcrumbs·baht-segmented-nav(links as a segmented control) ·baht-nav-list(a vertical list, one entry chosen) ·baht-tab-bar(a phone's bottom navigation) ·baht-tabs·baht-avatar·baht-code·baht-empty-state·baht-error-state·baht-loading-overlay·baht-image-preview(thumbnails that open the full image; a group steps with the arrow keys)
Touch and motion
Hover styles only apply where a pointer can hover, so a tap never leaves one behind; what a finger
presses has its own pressed state. The elements' motion uses --baht-ease and --baht-dur-fast|base|slow
and stops under prefers-reduced-motion. A host's own content can use the same, as public classes:
<p class="baht-inline-msg baht-inline-msg--error" role="alert">Could not save.</p>
<ul class="baht-stagger"><li class="baht-enter">…</li><li class="baht-enter">…</li></ul>.baht-enter (--fade, --pop) on arrival, .baht-stagger children --baht-stagger-step (40ms) apart,
and .baht-leaving + afterExit from @20baht/ui/motion to keep a node until its exit has played:
import { afterExit } from '@20baht/ui/motion';
row.classList.add('baht-leaving');
afterExit(row, () => row.remove());<baht-modal> fires baht-closed once its own exit is over, for a host that removes it (an @if). replayEnter(el) (same import) plays an element's enter animation again when only its text changed (a second "Saved").
Numbers in the locale (setLocale), from @20baht/engine: formatCount(3, { one: 'person', other: 'people' }) → "3 people", and moneyParts(-1234.5) → { text: '−฿1,234.50', tone: 'out' } to pair with .baht-money and .baht-money--in|out|zero (tabular figures; zero is never red or green).
A row of actions is .baht-actions: end-aligned, and stacked full width with the last (primary)
button on top when its own box is narrower than 30rem. A data-slot="start" child (Delete) sits at
the start of a wide row and at the bottom of a stacked one; .baht-actions--inline is one item of a
flex row at its own width, and never stacks.
<div class="baht-actions">
<baht-button data-slot="start" variant="danger">Delete</baht-button>
<baht-button variant="secondary">Cancel</baht-button>
<baht-button>Save</baht-button>
</div>Theming — design tokens + light DOM
Everything renders in light DOM and reads --baht-* CSS custom properties — override
at build time, at runtime, or inject your own sheet entirely:
.my-app {
--baht-color-primary: #047857;
--baht-radius-md: 6px;
}
.my-app .baht-label { text-transform: uppercase; } /* your CSS reaches every node */Styling API: .baht-form, .baht-field, .baht-field--w-1-2, .baht-field--hidden, .baht-label,
.baht-control, .baht-error, .baht-button, .baht-badge (+ the token list in tokens.css).
Full reference: docs/theming.md.
Charts and dashboards
The charts (<baht-bar-chart>, <baht-line-chart>, <baht-donut-chart>, <baht-heatmap>, <baht-meter>,
<baht-stat>, <baht-stat-chart>, <baht-sparkline>) and <baht-dashboard> live in
@20baht/dashboard, which draws a whole dashboard from one JSON definition. Until
0.5 this package re-exported them from their old paths (@20baht/ui/components/bar-chart, …) and its tokens.css
carried their sheet. It no longer does either: import @20baht/dashboard/element (or
@20baht/dashboard/components/<name>) and link @20baht/dashboard/dashboard.css after @20baht/ui/tokens.css.
Import only what you use
import '@20baht/ui' registers every element (~230 KB min). Three lighter routes:
// 1. per-element subpath — one module per tag, plus only what it imports
import '@20baht/ui/components/button'; // <baht-button>
import { BahtTable } from '@20baht/ui/components/table';
import '@20baht/ui/components/form'; // <baht-form> + its field elements (four of them only when a form uses one, below)
import '@20baht/ui/components/workflow';
// 2. by tag list — each tag is a dynamic import, fetched on demand
import { registerElements } from '@20baht/ui/register';
await registerElements(['baht-button', 'baht-avatar']);<baht-form> brings the element of every field type, most of them with its own module. Eight are loaded
when a form is first given a field of their type: reference (<baht-reference-picker>, which brings its
dialog and the table), repeater, date, file, markdown, tags, cron and schedule. A form without them never fetches them; a field drawn
before its element arrives is upgraded in place with its value. Import one yourself
(import '@20baht/ui/components/datepicker') when it is on the first screen and should not wait.
import '@20baht/ui', /register and /ssr define them all up front.
/* 3. split stylesheets instead of the all-in-one tokens.css (~115 KB) */
@import '@20baht/ui/css/tokens.css'; /* custom properties only, 18 KB */
@import '@20baht/ui/css/components.css'; /* .baht-* classes */@20baht/ui/tokens.css = the two sheets above in one import.
Only the styles of the elements you draw: css/components.css cut per element.
Link css/tokens.css, then css/components/base.css (what every element shares, about 13 KB gzip),
then one sheet per element, named like its module (components/button → css/components/button.css):
@import '@20baht/ui/css/tokens.css';
@import '@20baht/ui/css/components/base.css';
@import '@20baht/ui/css/components/form.css';
@import '@20baht/ui/css/components/input.css';
@import '@20baht/ui/css/components/select.css';
@import '@20baht/ui/css/components/button.css';@20baht/ui/css/components/index.json says which sheets each element needs and the order to link them in:
elements.formlists the form's own sheet,base, and the sheets of every element the form draws (input,select,button, …). Link the union of the lists for the elements your app imports.orderis the order to link them in, base first. Two rules in two sheets can style one node, so the order keeps the later rule winning, as it does incomponents.css.
Every element has a sheet, even one whose rules all sit in base, so an app can map each components/<name> import to css/components/<name>.css.
A class you write on your own markup (baht-actions, baht-enter, baht-card) comes from base.css or from the sheet of the element it is named after.
css/components/datepicker.css holds the date field's own rules; the calendar still needs css/datepicker.css.
tokens.css and css/components.css are unchanged; the per-element sheets hold the same rules. The calendar is opt-in:
/* with <baht-datepicker> / date fields — the calendar, on the tokens */
@import '@20baht/ui/css/datepicker.css';The calendar is bahtui's own (no third-party package since 0.6): it shows the date in the locale's
order and calendar (the Buddhist year in Thai) and the value stays ISO. See
docs/components/baht-datepicker.md.
With Native Federation (or any setup that shares packages by name), list @20baht/engine in the app's
own dependencies, at the same version as @20baht/ui. The element modules import the engine by its
package name rather than bundling it, so the elements, @20baht/ui/engine and @20baht/validator
share one copy (one locale catalog). Federation shares only the dependencies an app lists: without it the
import map has no @20baht/engine, the build passes, and the browser fails to load the elements.
A plain Vite, webpack or esbuild build resolves it on its own and needs nothing.
One install, typed everywhere
npm i @20baht/ui ships the runtime and the metadata every editor/framework needs —
no hand-written type declarations in your app:
| You use | What you get | Setup |
|---|---|---|
| JetBrains / WebStorm (any framework) | autocomplete + docs for every <baht-*> tag | none — web-types is auto-detected |
| VS Code (HTML / Angular templates) | tag + attribute completion | one line, see below |
| React (TSX) | full JSX typings, typed props per element | import '@20baht/ui/react' once |
| Angular | template binding on properties/events | CUSTOM_ELEMENTS_SCHEMA, see below |
| Vue 3 | keep Vue from treating baht-* as components | isCustomElement, see below |
| Phoenix / Rails / plain HTML | it's just HTML — works as-is | none |
| Tooling (Storybook, docgen, custom) | machine-readable API of all 64 elements | read dist/custom-elements.json (CEM standard) |
Your own adapter (Solid, Svelte, a framework this package has no wrapper for) — generate its
typings at build time from @20baht/ui/manifest-model, the model every generator of the family
stands on (register.ts, react.ts, @20baht/angular's directives). It is pure (no DOM, no
Lit, no fs) and no browser entry imports it:
import { readFileSync } from 'node:fs';
import { createRequire } from 'node:module';
import { dirname, join } from 'node:path';
import { elementsOf, type Manifest, type PackageManifest } from '@20baht/ui/manifest-model';
const pkgPath = createRequire(import.meta.url).resolve('@20baht/ui/package.json');
const pkg = JSON.parse(readFileSync(pkgPath, 'utf8')) as PackageManifest & { customElements: string };
const manifest = JSON.parse(readFileSync(join(dirname(pkgPath), pkg.customElements), 'utf8')) as Manifest;
for (const el of elementsOf(manifest, pkg)) {
el.entry; // '@20baht/ui/components/form': where to import the element from
el.events; // [{ name: 'baht-submit', detail: '{ data: Record<string, unknown> }', types: [], … }]
el.generic; // the type parameters a schema or a list gives it, with the texts they type
}Each element carries its props (typed as the class types them), its baht-* events, the two-way
value pair and entry, its public import specifier read from the exports map. Every type name
a detail or a generic text uses is listed in types with the entry that exports it
({ name: 'ValidValues', from: '@20baht/ui' }), so an emitter imports exactly those and never
guesses which names are the language's own. examples/portable-solid-hono/scripts/render-solid.ts
is a whole emitter.
VS Code — .vscode/settings.json:
{ "html.customData": ["./node_modules/@20baht/ui/dist/vscode.html-custom-data.json"] }React — once, in your app entry (or load it globally without a runtime import via
"types": ["@20baht/ui/react"] in tsconfig.json):
import '@20baht/ui/react'; // JSX typings for every <baht-*> elementReact 19+ sets non-string JSX props as DOM properties, so object props (form,
workflow, items, …) work inline; on React 18 set those via a ref.
Angular — the compiler must be told baht-* tags are custom elements:
@Component({ schemas: [CUSTOM_ELEMENTS_SCHEMA], /* … */ })Bind readonly as an attribute ([attr.readonly]="x ? '' : null"), not a property — Angular
rewrites [readonly] to the native readOnly. Zoneless Angular may connect an element before
binding its props; since 0.2.3 every field primitive renders empty until field arrives. Full
list of gotchas: docs/frameworks/angular.md.
Vue 3 — vite.config.ts:
vue({ template: { compilerOptions: { isCustomElement: (tag) => tag.startsWith('baht-') } } })Server-side rendering
@20baht/ui/ssr (Node) renders any Lit template with @lit-labs/ssr and moves each
baht-* element's shadow template into its light DOM, so the HTML string it returns is
exactly what the client would have rendered. @20baht/ui/hydrate (browser, imported
before @20baht/ui) picks that markup up instead of re-rendering it:
// server
import { html } from 'lit';
import { renderToString } from '@20baht/ui/ssr';
const page = await renderToString(html`<baht-button variant="primary" label="Save"></baht-button>`);
// client — import order matters
import '@20baht/ui/hydrate';
import '@20baht/ui';@lit-labs/ssr is an optional peer dependency (server only). Full guide, limitations
(light-DOM children, ids, i18n locale) and troubleshooting: docs/ssr.md.
Docs
- Per-component docs:
docs/— one .md per element + framework guides (vanilla / React / Angular) + theming + SSR. - Docs site with live specimens: https://bahtui-docs.pages.dev (source:
apps/docs). - For agents: the
bahtui-mcpserver (apps/mcp) serves these docs and runs the engine on your JSON.
Field types (22)
text · textarea · markdown · number · currency · email · password · dropdown · multiselect · tags · checkbox · radio ·
toggle · rating · range · reference · date · time (HH:mm) · file · repeater (one level of rows) · label (static) · section (divider)
Each field descriptor: { order, type, key, label, placeholder, width: '1/4'|'1/2'|'3/4'|'full',
value, disabled, required, options | options_from, max_length, min, max, validators[], formatter, flag }.
Visual Builder
The docs site ships a two-mode Visual Builder (Form mode: palette/WYSIWYG canvas/properties;
Workflow mode: sequence + rules with a live preview running the real <baht-workflow>), with
Import/Export JSON. Run it from the monorepo: bun run --filter docs dev → /builder.
Working on this package
Contributor notes (in the monorepo; not part of the published API).
- Layout:
src/components/holdsbaht-form.ts,baht-workflow.ts,base.ts(BahtElement),field-base.ts(BahtFieldBase),define.ts(customElement),layers.ts(modal stack),shortcuts.ts,menu-controller.ts,motion.tsandprimitives/(onebaht-<name>.tsper tag). Tests:tests/core/(node),tests/components/(happy-dom),tests/ssr/(real render and hydration against the built dist).dist/carriescustom-elements.jsonandweb-types.json, whichapps/docsandapps/mcpread. - Adding a component: (1) a failing test in
tests/components/<tag>.spec.tsagainst the public attribute/property/event contract (engine behaviour goes intests/core/); (2)primitives/baht-<name>.tsextendingBahtElement(orBahtFieldBasefor a field),@customElementfromdefine.ts, JSDoc on the class and every@property, exported fromprimitives/index.ts; (3) style with tokens only (--baht-color-*,--baht-radius-*,--baht-space-*), light DOM; (4)bun run --filter @20baht/ui generate, thenbun run --filter @20baht/angular generate; (5)docs/components/<tag>.md(bundled intobahtui-mcp) and the docs page, sidebar entry and catalog specimen inapps/docs; (6) build,bun run test,lint,knip,size. Raise a size budget only with the measured number and a NOTES entry. adoptChildren(): an element that places its light-DOM children overrides it (base.ts). It runs after every render and whenever a framework adds a child, so never adopt infirstUpdated/updated. Adopt into a container with no template part inside or after it: a part that re-renders clears what follows it (the<baht-button loading>bug, NOTES 2026-11-14).- A built-in field type is: the name in
BuiltInFieldType(packages/core/engine/src/types.ts) and its value inform-values.ts; one entry inBUILT_IN_TYPES(engine/src/built-in-types.ts:tag,empty,display,check,maxLength; the functions go intype-checks.ts/type-display.ts) plus i18n strings; the element; one entry inSHAPES(packages/core/validator/src/shape.ts); and spec 01. The compiler asks for both entries. The tag map, the CLI DSL andBUILT_IN_FIELD_TYPESread the table. The docs builder still wants a palette item, preview and inspector controls. An app's own field type needs none of this (registry.fieldTypes, spec 01 §5.1). - SSR: no module-level id counters (use the element
uid); guard document listeners withhasDom(); honourdefer-hydration. Every shipped tag renders deterministically intests/ssr/render.spec.ts. - Keyboard shortcuts (
<baht-button shortcut>, split-button and menu items) are bound by the library through one document listener; the topmost open modal scopes them (layers.ts). Motion is light, CSS-owned and respectsprefers-reduced-motion. - Tokens: the theme-scope and theme-light blocks in
tokens.cssare generated: after editing a token runbun run --filter @20baht/ui tokens:theme-scope, ortests/core/theme-scope.spec.tsfails. The docs site's banknote palettes (data-note) swap--baht-primary/--baht-neutraland the--baht-green-*ramp: check new styles under them and in dark. - Release: a minor bump of core moves the peer ranges of
@20baht/validatorand@20baht/angular(>=0.X.0 <0.(X+1).0) in the same release, with the adapter regenerated; a patch does not.
