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 flatpickr # peer dependency — only if you render date fields / <baht-datepicker>
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 form
Views 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 submission
The /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 overrides
Call 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.
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 (drop a password value before it is stored: a snapshot holds every value entered), 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 step
A 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 view
Messages: 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) 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 an opt-in dark theme
(<html data-baht-theme="dark">). 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> …