Human client extensions
The first human UI slice registers trusted native addon frontend code before the shell starts.
A get_views field node selects a registered widget identity; an unknown identity or incompatible
field kind fails explicitly. This does not grant ORM access. The server still authorizes descriptors,
reads, onchange and writes for the actual principal.
Put this manifest in addons/<addon>/static/client.json:
{"schema":1,"entry":"src/client.ts","templates":["src/note-title.xml"]}Optional styles lists CSS files relative to the same static directory. Paths cannot escape that
directory. A deployment links an explicit addon set with
ERP_UI_COMPILER=/path/to/erp-ui-compile node web/scripts/build-human-ui.mjs --addons web,acceptance_notes.
The producer uses the existing trusted XML compiler, then bundles registration entries before boot.
It writes web/dist/human-ui/manifest.json and content-addressed JS/CSS; publication belongs to the
server. It never compiles database text in the browser.
Register a field component from the manifest’s entry. This is a source example; the acceptance addon and its compiled/runtime evidence are maintained separately by the lead.
import { Component, elangFieldWidget, registerFieldWidget } from "@erpforall/client";import type { FieldWidgetProps } from "@erpforall/client";
class NoteTitle extends Component<FieldWidgetProps> { static override template = "acceptance_notes.NoteTitle"; get textValue(): string { const value = this.props.value; if (value === false || value === null || value === undefined) return ""; if (typeof value !== "string") throw new Error("Invalid note title value."); return value; } onChange(event: Event): void { if (this.props.field.readonly) return; const input = event.currentTarget; if (!(input instanceof HTMLInputElement)) throw new Error("Expected title input."); this.props.change(input.value); }}registerFieldWidget("acceptance_notes.note_title", { kinds: ["char"], render: elangFieldWidget(NoteTitle),});<templates> <t t-name="acceptance_notes.NoteTitle"> <label class="field-label"> <span t-out="this.props.field.label"/> <input type="text" t-att-name="this.props.field.name" t-att-value="this.textValue" t-att-required="this.props.field.required" t-att-disabled="this.props.field.readonly" t-on-change="this.onChange"/> </label> </t></templates>Use change to let the generic form run real onchange and preserve its dirty/save state. Do not send
independent writes from field components. elangFieldWidget mounts the component with the compiled
addon template set and unmounts it when the form redraws, navigation succeeds, or the shell expires.
The template compiler’s own attribute/event fixture demonstrates t-att-value, t-att-disabled and
t-on-input="this.onInput" (crates/erp-ui-compiler/tests/fixtures/basic.xml:27); named methods retain
the component receiver (web/tests/contract.test.ts:72).
For an additive control-panel component, call
registerControlPanelExtension("addon.extension", {model: "acceptance.note", component: MyPanel}).
Its compiled component receives ControlPanelProps {title, model} and mounts at the core control
panel’s data-control-extension anchor. This is an additive extension, not a replacement of another
addon’s registration. Duplicate identities reject; there is no last-registration-wins override.
For a data-aware header placed above an action’s list view (above the dashboard strip and rows;
list views only), call registerListHeaderExtension("addon.header", {model, create}). create
receives ListHeaderEnvironment {model, title, rpc, context} and returns a ListHeaderHandle
{element, refresh(domain, {signal}), dispose()}. refresh runs on every load with its own copy
of the active domain and an AbortSignal that aborts on a newer load or view disposal; failures
are reported through the client error surface without blocking row loads. Duplicate keys reject.
registerServiceController registers a model-bound service form factory with explicit option
validation and a dirty/busy/save/discard contract. Core Settings and Addons use this same registry.
Record forms use web_save; service forms never fall through to record creation.
The generic view renderers covered here are list and form. Modifier expressions, search controls, relations and embedded record forms use their admitted typed metadata and expression contracts; they are not all rejected simply because an expression or subform is present. Consult Views and Human form layout for the supported declarations. An unsupported node, widget or expression still fails explicitly rather than silently becoming a normal value. Other generic renderer families, Studio and full UI translation remain outside this page’s delivered scope. The compiler’s current English-only translation notice remains visible; unknown compiler diagnostics are refused. Ordinary user, group, company and language forms use the generic controller, not privileged client endpoints.
Wizard action forms and widget lifetime
Section titled “Wizard action forms and widget lifetime”An exposed object method can return the bounded window/close/notification subset in
ADR 0088. A window result opens one independent record-form dialog without changing
the caller URL. Declare a last, direct form footer containing object buttons and
special="cancel"; the main-route form omits this footer. The dialog uses the same
field widgets, default_get, initial onchange and save path as ordinary record forms.
Only admitted default_<field> context entries cross the action-result boundary;
session/company context and caller active IDs come from the client binding.
An object footer button confirms, validates and saves before executing its exposed method. Explicit footer cancel never saves. Escape/close/replacement/navigation discard wizard edits without a prompt; a pending or uncertain write keeps the dialog open (SPEC-WIZ-016). Close or a no-action result refreshes the caller once. Notifications are text only. A lost method response or failed result presentation keeps the operation read-only; readback never authorizes method replay. Uncertain root methods also block guarded navigation and keep the current form read-only; a record reload cannot clear that operation guard. An ambiguous existing-record save can recover through readback; defaults cannot establish whether a new record was created. Installed native/WASM business-process acceptance belongs to the integration slice; client fixture evidence is partial.
See Wizard dialogs for native/WASM declarations, the action subset and current installed-acceptance limitations.
WidgetEnvironment.signal is optional for compatibility with existing owners. When
present it identifies the record controller’s lifetime. A widget that opens a child
overlay must remove it on abort, suppress late read completions and avoid flushing
staged changes into a disposed owner. Ordinary widget rerenders still use the widget
handle’s dispose; read operations must not outlive their owner scope.
Shared appearance tokens
Section titled “Shared appearance tokens”Addon CSS should inherit the client font and use semantic custom properties rather than fixed
light backgrounds or text colors. The supported presentation roles are --text, --muted,
--canvas, --surface, --surface-subtle, --line, --input-line, --hover, --accent,
--accent-hover, --on-accent, --selected, --selected-text, --focus, --danger,
--danger-bg, --danger-line, --warning, --warning-bg, --warning-line,
--success, --success-bg, --success-line, --info, --info-bg, and --info-line.
Use --on-accent for text on a filled accent button; it differs from the panel surface in dark
mode. Focus must remain visible and selected controls must retain semantic state attributes.
The acceptance Notes addon uses these roles for its title accent and help text.
The palette follows prefers-color-scheme before boot. An embedding document can explicitly set
data-theme="light" or data-theme="dark" on its root; these are document presentation overrides,
not server preferences. Do not introduce per-addon theme persistence. Test extensions with both
palettes, long labels, narrow widths and prefers-reduced-motion: reduce.
Office Blue groups declared record-header actions with route commands and may place
sheet-level notebook navigation above its content. Editable title widgets remain in
their declared form/sheet location; titles and nested notebooks in groups or pages
retain that scope. Widget identity, field policy, values, change callbacks and
disposal remain unchanged. Default and dialog presentations keep their existing
placement. No addon view rewrite is required for this presentation.
Main-route title inputs keep their native form owner inside the form DOM. Use the
supplied change/open/run callbacks for business behavior; readonly, required and
validation semantics still come from admitted field metadata. A selection statusbar
is never selected as a character title, even when its field is named name.
List category metadata and paging
Section titled “List category metadata and paging”The human list renderer reads optional category metadata from the action’s resolved, inherited search view. Declare the standard structure, using an actual stored selection field on the model:
<search> <field name="name"/> <searchpanel> <field name="priority" string="Priority" select="one" enable_counters="1" expand="1"/> </searchpanel></search>This is the first supported search-panel subset: one visible single-select category,
1–32 static selection choices, static invisibility, field/view groups, a label,
view_types, enable_counters, expand, a nonnegative limit (selection choices are
not truncated by it), and the context key
searchpanel_default_FIELD. Counters and zero-choice visibility are computed with the
caller’s grouped-read permissions, company context and current search domain. A category
condition affects rows but is excluded from its own count domain. An unset optional
selection contributes to All; it does not create a fabricated choice. No field name or
business model is special-cased. search_view_id on a window action selects that action’s
search view, including inherited changes. Install or upgrade the addon after adding XML
records; merely copying a new XML file does not update an installed database.
ADR 0131 adds typed version-one metadata for ordered categories and multi-select filters, including stored selection/many2one/many2many fields. This metadata does not activate their controls: the client shows a message saying that search panel categories and filters are not available yet and issues no section range RPC or panel predicate. The single-selection subset above retains its tabs. Do not rely on extended declarations as interactive filters until that slice ships.
Extended declarations retain view_types, single-token icon, static flags and display limit
(omitted: 200; zero: no display cap, with safety admission unchanged). Category hierarchize
defaults true. A filter domain uses comodel criterion paths and bare declared category names
on the RHS; it never evaluates arbitrary expressions. Empty category selection binds false.
groupby is a field on the relation’s actual comodel. The host checks all model/path scopes,
removes unreadable sections and dependent filters, then overlays caller defaults outside cached
structural metadata. Filter defaults are bounded unique scalar arrays; categories take one scalar
or false. Category counters are disabled with an explicit generic notice while a retained filter
domain is active. icon_class, panel class, category depth and dynamic booleans remain explicit
unsupported syntax. The internal contract and SPEC-SPANEL define the exact admission matrix;
addon authors should use this declared subset until the broader renderer is delivered.
Ordinary search fields and filters retain the existing search implementation; this change
does not claim that all XML search grammar is supported. See ADR 0103 for precise limits
and observed behavior.
The optional data-control-categories node in the inherited
web.HumanControlPanel template owns category placement. Existing replacement templates
without that node retain a fallback to the control-panel root. The category content is
data-driven; addons should inherit the template rather than patch a model-specific
controller.
A positive XML list limit overrides the window action limit; XML zero defers to the
action. Without either, the historical 40-row fallback remains. Page sizes are positive
JSON-safe integers (at most 9,007,199,254,740,991), matching the browser representation
and staying within the server’s signed SQL limit. No 200-row cap is introduced. The
selector offers 20, 40, 50 and 80 plus the declared custom default, preserves the selected
value, and resets the offset on change. Invalid declared sizes fail with validation;
they are never silently clamped.
Record header presentation ownership
Section titled “Record header presentation ownership”The internal record presentation can give declared XML header buttons a separate
headerActionsHost. It is optional: ordinary/default and dialog callers retain
the existing header renderer. RecordForm owns disposal, focus restoration and
busy controls across this host just as it does for header fields, title, tabs and
aside. App presentation may group existing route controls and that XML toolbar
in one visual command row; their handlers, XML order, confirmation and pending
method guards remain unchanged. Breadcrumb text comes from the authorized menu
ancestry and admitted visible display/name fields, with the actual record ID as
fallback. No new XML or model naming convention is introduced.
Main record routes keep declared XML titles inside their form/sheet. The legacy first-character-field fallback also stays in the form at its existing occurrence; there is no second editable title in the header. Title inputs therefore use the native form owner for edit/required validation. Office places the existing control-panel context/help slot in the sheet while preserving its component bindings; empty slots remain hidden. No addon XML rewrite is required.
Office breadcrumbs distinguish the originating menu route from a method-returned
current-window action. The latter retains its declared action name and filtered
back route; the source menu remains a separate authorized navigation link. Desktop
sidebar indentation is bounded independently of XML menu depth. The semantic
details hierarchy, disclosure controls, native labels and focus targets remain intact;
only repeated decorative icons inside nested menus are hidden.
Browser message services
Section titled “Browser message services”The human app supplies an optional messages?: MessageServices handle in both
WidgetEnvironment and ServiceEnvironment. This is application-owned browser UI, with no ORM
or authorization capability. A custom host can omit it; check for its presence and report a clear
unsupported-host error if your extension requires it. Do not construct a second application-wide
message owner inside each widget. elangFieldWidget forwards field props and change to its
component; it does not automatically add a messages component prop. A custom widget renderer
that needs services can use its WidgetEnvironment or explicitly pass the handles to its component.
The public @erpforall/client entry exports MessageServices, the notification/dialog option and
handle types, selectCreateDialog, exportDialog, SelectCreateDialogOptions and
ExportDialogOptions. Notification, dialog, effect, blocking, network, popover and tooltip services
are reached through the supplied facade. The public entry does not export every underlying service
class or the fixture-only ribbon/permission component templates.
Service handles live for their owning application. Your widget still owns its child handles and
must release them from dispose; pass environment.signal to APIs that accept it. Close child UI
on owner abort, stop timers/listeners, and ignore late reads rather than applying values into an
unmounted form. Disposing UI does not cancel or replay a mutation that was already sent. Preserve
the controller’s dirty, pending and uncertain-write guards before normal navigation or close.
Notifications and feedback services
Section titled “Notifications and feedback services”messages.notifications.add(message, options) renders plain text and returns an idempotent close
function. NotificationOptions accepts optional title, level (info, success, warning,
danger), sticky, className, delay in milliseconds, actions ({label, run}) and onClose. The default is
an information notification with a 4,000 ms timer. A positive-delay nonsticky notice closes on timer
completion; zero delay schedules no automatic close. Optional className supplies addon CSS identifier hooks: at most 512 raw UTF-8 bytes, eight distinct tokens, each at most 64 bytes matching [A-Za-z_][A-Za-z0-9_-]*, separated only by ASCII spaces. Repeated spaces canonicalize; malformed values are refused before replacing a notice. Class hooks do not select severity or actions. Hover pauses its timer and leaving restarts a
full interval. Action buttons and Close are separate native controls. An asynchronous action is
locked while it runs; action failures are reported to the application’s error presenter. Closing a
notice invokes onClose once; a failing close callback is reported after the notice is removed.
Equal message text replaces its predecessor while distinct messages coexist. The service admits at
most 32 notices and 65,536 UTF-8 bytes of combined message/title/action-label/class text. An overflow
summary remains visible and the attempted addition throws a validation error. This is not permission
to treat an operation failure as success because its notice could not be displayed. Notifications
move into the active dialog scope so wizard feedback is not left behind the native modal’s inert
background. messages.notice remains a compatibility entry; an empty string closes its most recent
compatibility notice, not every notification.
import type { WidgetEnvironment } from "@erpforall/client";
function showResult(environment: WidgetEnvironment): () => void { const messages = environment.messages; if (!messages) throw new Error("This host does not supply message services."); return messages.notifications.add("The document is ready for review.", { title: "Review ready", level: "success", sticky: true, });}messages.block.begin({delay?, message?}) returns an idempotent release function. Acquire before the
explicitly blocked operation and release in finally; nested work retains the pointer shield until
the final release. The shield begins immediately even when visible spinner/message feedback is
delayed. This is separate from ordinary nonblocking request-loading feedback. messages.block.blocked
lets a controller refuse another operation; the shield itself is not a claim of keyboard trapping.
messages.effects.show("default", {message, enabled}) uses the original default effect when enabled,
or a success notification when disabled. Trusted code can register(key, callback); the callback
must return cleanup. Unknown/duplicate identities fail explicitly. The enabled choice is supplied by
the caller, not a new persisted preference API. Reduced motion removes the default decorative
animation. messages.network.set("online" | "offline" | "syncing" | "error") changes presentation
only: the owning controller must report actual transport/recovery state. It does not start a refresh,
queue a write or retry one. HumanApp uses the paired transport observer to settle cancelled recovery reads: other active reads keep syncing visible, and the final cancellation restores offline/error without claiming success. A successful concurrent safe read remains connected.
Dialog and selection services
Section titled “Dialog and selection services”messages.dialogs.open({title?, body, size?, header?, footer?, dismiss?, signal?, onClose?}) returns
DialogHandle {dialog, close, dispose}. body is plain text or a trusted DOM element, and footer
is a trusted element. Sizes are sm, md, lg and xl; native modal and shared focus handling keep
only the top dialog active. The service permits eight dialogs. Its own shells have unique accessible
heading IDs, scrollable content and responsive sizing. attach(dialog, options) adopts an existing
native shell into the same stack; it does not add controller-specific save or close policy.
confirm({title?, message, confirm?, cancel?, dismiss?, confirmLabel?, cancelLabel?, contentClass?, signal?})
and alert(...) return a ConfirmationHandle, whose result resolves to confirm, cancel or
dismiss. Alerts offer only acknowledgement unless a cancel callback is supplied. Escape uses
dismiss, falling back to cancel. The selected callback is invoked at most once while pending;
returning false retains the dialog and restores controls, and normal completion closes it. A callback
failure closes the confirmation, rejects result and is reported once through the application’s error
presenter. Handle close/dispose and scope abort release UI; they are not substitutes for the owning
operation’s pending/uncertain guards. An onClose failure is reported after removal.
selectCreateDialog(options) receives dialogs, rpc, model, an explicit domain and context,
and a required select callback. Its search calls the existing authorized web_name_search path.
Desktop displays readonly rows; small screens use cards. A createEdit capability is optional and
must resolve only after its embedded editor saves successfully, returning {id, display_name} or
undefined for cancellation. It receives the same domain/context. A returned saved record is validated
and passed to select; pending selection/create work prevents duplicate actions. The component
supplies no model-specific editor, grants no create rights and does not change the field picker’s
canonical search contract. Optional report and signal connect errors and owner teardown.
exportDialog(options) receives dialogs, declared fields ({name, label}), declared formats
({key, label}), a required download(fields, format) promise callback and a required notice
callback. Empty field selection sends a danger notice without calling download. A nonempty request
locks the controls until it completes; rejection remains visible, is sent to optional report, and
restores controls. The caller owns the authorized download implementation. This reusable component
does not create an export RPC, export templates or a complete ERP export feature by itself.
Popover, tooltip and declarative message boundaries
Section titled “Popover, tooltip and declarative message boundaries”messages.popovers.open(anchor, content, options) accepts a connected anchor and trusted DOM content,
and returns {node, close}. Options include placement (top, bottom, left, right), role,
dismissOnOutside, restoreFocus, signal, onClose and opt-in presentation: "sheet". Supported roles are dialog, tooltip,
menu, listbox, region and status. Overlays follow their anchor on resize/scroll and fit the
viewport; allowed outside clicks, successful navigation, abort or target removal close them. Focus
restoration is an explicit option and is off by default. A popover anchored inside an active native
dialog mounts there. Content belongs to the overlay after opening. Close-callback failures propagate;
navigation() cleans the whole popover set before reporting an aggregate close failure. Escape closes the eligible top popover before its owning modal; another Escape can then reach that modal.
Close callbacks receive the typed reason: explicit, escape, outside, navigation, abort,
anchor-removed or dispose. Existing callbacks that take no argument remain compatible.
Editors use the distinction to avoid applying drafts during teardown. A sheet is the same shared
popover owner with viewport-fitting bottom presentation; it does not assert modal/inert behavior.
messages.tooltips.attach(anchor, {text?, content?, delay?, touch?}) returns a detach function.
Supply plain text or a trusted synchronous content factory. The default delay is 400 ms; admitted
delays are finite values from zero to 60,000 ms. Pointer entry schedules opening, leave/click closes,
and touch start/end/cancel use the same scoped lifecycle unless touch is disabled. Redundant visible
plain text can be suppressed. The tooltip owns its aria-describedby reference and releases it with
its timers, observers and event handlers. Deferred content/admission failures are cleaned up and reported through the application error presenter; disposal suppresses late factory results. Keyboard-triggered tooltip behavior has not been established
as parity by this slice. Callbacks provide trusted content; do not evaluate database template strings
or interpolate untrusted HTML into them.
Record forms admit the bounded web_ribbon and notification_alert display declarations
documented in views, separate from Settings/Addons service widgets (SPEC-MSG-018/019).
The permission component explains a
denied state and never requests or grants permission. Onchange warnings already present title,
message and dialog-versus-notification type after applying returned values; producer className/sticky options are carried by the warning package (SPEC-MSG-022), with the bounded identifier grammar above. Distinct warnings aggregate into the existing ordered dialog without choosing one notification style. Warning bodies are limited to 8192 UTF-8 bytes so admitted dialog warnings can be presented unchanged. An oversized warning returns an explicit server-boundary error after ordinary onchange values have been applied; stale warning feedback is cleared, with no truncation or silent success. Keep those cases partial when reporting
installed behavior.
Embedded relation-editor object/footer commands, service widgets and nested record navigation remain outside this slice; errors say the feature is not available yet. Use the full record screen for those actions.
Date and time editor components
Section titled “Date and time editor components”The public client entry exports createDateTimeEditor, createDateTimeRangeEditor,
createTimeEditor, their option/handle types, and the date/time value and locale contracts.
WidgetEnvironment.editorLocale carries the existing bootstrap language, timezone, date format
and time format separately from RPC context. The builtin date and datetime adapters require both
that locale and messages.popovers; a custom interactive host must supply them explicitly.
The application validates locale member structure at bootstrap, so an unsupported editor-format directive does not prevent startup or unrelated forms from working. Each component checks the formats it consumes: date uses the date format, time uses the time format, and datetime uses both. A recognized unsupported locale produces a labelled unavailable control with the original ClientError kind and message; it preserves the represented value, applies no replacement and opens no overlay. Updating its value does not dismiss the configuration error. Correct the configuration and construct a new control to resume editing. The public editorLocale(raw) validator remains strict for callers that explicitly request full admission. Invalid options, malformed represented values and unrelated errors retain their established failure behavior.
import { createDateTimeEditor, registerFieldWidget } from "@erpforall/client";
registerFieldWidget("example.delivery_date", { kinds: ["date"], render(environment) { if (!environment.editorLocale || !environment.messages) { throw new Error("This date widget requires editor locale and message services."); } const value = environment.value === null || environment.value === undefined ? false : environment.value; if (value !== false && typeof value !== "string") { throw new Error("Expected an ISO date or an empty value."); } return createDateTimeEditor({ kind: "date", name: environment.field.name, label: environment.field.label, value, locale: environment.editorLocale, popovers: environment.messages.popovers, readonly: environment.field.readonly, required: environment.field.required, ...(environment.signal ? { signal: environment.signal } : {}), onApply: environment.change, report: environment.report, }); },});Factories return a labelled node, its input, an explicit setValue and idempotent dispose.
Parent value replacement is not a user edit. onApply receives an ISO date, UTC SQL datetime or
false; the existing field owner runs onchange and save. false is the browser’s empty value;
the existing RecordState boundary serializes an empty non-Boolean scalar as JSON null for
onchange/write RPCs. Keep this distinction when implementing a field adapter. A standalone time editor instead uses
canonical HH:mm:ss values and an invalid callback. Do not send independent writes from these
callbacks. Timezone conversion is explicit; unsupported configuration fails rather than using the
host timezone. Invalid date/datetime conversion restores the represented display, while invalid
standalone time text remains visibly invalid and invokes onInvalid on change.
min, max, isDateValid, showSeconds and rounding are trusted component options. A range
component receives two names, labels and values and emits the complete tuple through its own
application callback. These code APIs do not add paired-field or picker-option declarations to
the current server view wire; those gaps remain open. There is no new server
time field kind. Required/save policy stays with the owner and each endpoint retains its own
required state.
Hidden seconds are preserved where the editing operation leaves them unspecified. An unchanged datetime retains its represented instant even in a repeated DST hour. Newly entered nonexistent or ambiguous local times are refused unless an explicit ISO offset resolves them; this explicit conversion policy is recorded in accepted ADR 0112, with the actual lead r1 authority and correction dispositions. No permissive normalization or complete Odoo parsing equivalence is claimed.
Use the supplied shared popovers and lifetime signal. Do not construct a second overlay owner. Escape restores a draft; navigation, abort, owner removal and disposal never apply it. Keyboard departure must continue focus rather than reopening the picker. Desktop time suggestions and the native phone time route are separate presentations. Calendar sheets use the same owner as desktop popovers, and readonly controls cannot open them. Test light/dark, required/invalid/empty states, keyboard operation, nested record dialogs and owner disposal in the compiled browser.
Modal editor popovers require the browser native manual-popover API (showPopover and
hidePopover). The shared service uses its top layer to keep the calendar visible inside
scrolling dialogs; unsupported browsers receive an explicit error. There is no clipped fallback.
The internal node-only fieldControl date/time helper requires an owner AbortSignal,
because it returns no disposer. Callers retaining a handle may use createFieldControl and
call dispose explicitly. If complete main datetime text and a picker draft are both pending,
complete main text takes precedence on outside departure, including an empty value.
Code editor components
Section titled “Code editor components”createCodeEditor(options) composes a disposable browser source editor through the trusted client
entry. Supply a nonempty label, primitive-string value, sessionId, onChange and report.
A session identity is a string or finite safe integer; the number 1 and string "1" identify
different sessions. Source containing tags is still plain source text. Markup, boxed strings,
coercible objects, unknown options and invalid declarations are refused without coercion.
import { createCodeEditor } from "@erpforall/client";
const source = createCodeEditor({ label: "Automation source", value: "print('Ready')", sessionId: "automation-draft", mode: "python", onChange({ sessionId, value }) { drafts.set(sessionId, value); }, report(error) { showError(error); },});host.append(source.node);// The screen's owner registers cleanup and persists drafts through its own authorized operation.onOwnerDispose(() => source.dispose());The example’s drafts, showError, host and onOwnerDispose belong to the caller. The editor
selects no RPC, field wire declaration or durable storage. SPEC-WIDGET-030 owns field and view-source
adapters, and Studio report state is outside this reusable component. Choosing a language mode does
not authorize or execute source. Keep all durable writes in the surrounding screen.
Admitted modes are text (default), javascript, xml, qweb, scss, python, json and bash.
theme accepts auto, light or dark; automatic appearance follows the interface tokens.
lineWrapping defaults to false, showLineNumbers to true, and maxLines to 20 (positive integers
up to 200). A visible-line setting is presentation rather than document-size admission. The optional
readonly, disabled and required flags default to false; invalid supplies caller-owned inline
feedback. Arbitrary engine modes, remote module URLs, protected-attribute options and source-language
semantic validators are not public options.
The handle exposes getValue, getSessionId, setValue, setSession, setReadonly, setDisabled,
setPresentation, focus, releaseSession, history and idempotent dispose, together with node.
Pass setSession({sessionId, value, mode?}) to activate a source. Switching retains the outgoing
selection even if no text changed. Returning with the same retained value preserves that session’s
history and cursor. An authoritative replacement emits no user change; a genuinely different value
sets a fresh undo baseline, while an identical echo preserves selection and history. Explicitly release
inactive sessions when their owner no longer needs them; releasing the active session is refused.
onChange({sessionId, value}) identifies the originating session for user edits, paste, undo and redo.
The owner may update or dispose the editor inside a callback; stale work cannot replace newer owner
state. Optional onBlur observes departure. history.canUndo and history.canRedo describe the active
session, undo() and redo() return false for empty editable history, and subscribe(listener) returns
an unsubscribe function. The initial supplied value is not undoable. A new edit after undo invalidates
redo. Readonly and disabled history commands fail with a typed validation error. Authoritative owner
value/session and presentation updates remain allowed under those policies; they are not user edits.
Disposed commands fail explicitly. History disconnects on disposal and owner abort.
Readonly keeps source selectable/copyable while hiding editing affordances and blocking every edit route. Disabled additionally removes editing focus. Labels, required/invalid presentation and inline errors belong to this component; the surrounding screen owns record validity. Expected local admission failures retain the last admitted document and show precise inline feedback. Unrelated callback failures remain observable through the supplied reporter.
Optional lower-only limits use maxDocumentBytes, maxSessions, maxTotalDocumentBytes,
maxHistoryBytes and maxHistoryGroups. They retain finite browser safety bounds: 1 MiB UTF-8 per document, 8 sessions,
4 MiB aggregate document text, 8 MiB retained undo/redo payload and 100 history groups per session.
Zero never means unlimited. History accounting includes retained edit and selection records; group count
alone is not a byte bound. Pruning old history is visible and never silently discards current source.
These are intentional client safety policies under ADR 0114, not upstream admission limits or a substitute
for server-side validation.
History granularity also intentionally differs under ADR 0114: each flushed native edit batch creates one
group, with no word- or time-based typing merge. Separate keyboard events commonly create separate groups;
synchronous native changes before a flush can share one. Both undo and redo groups count toward the group
cap. The aggregate byte budget spans all retained sessions and conservatively charges each group as
max(before UTF-8 bytes, 2 × before UTF-16 length) + max(after UTF-8 bytes, 2 × after UTF-16 length) + 128.
This is admission accounting rather than measured heap usage. Larger snapshots or additional retained
sessions can reduce available depth below the group cap; pruning remains visible and retains current drafts.
Pass an owner signal and dispose on unmount. The engine has no worker, remote module loader or browser
source evaluation. Its pinned base stylesheet is packaged externally, and presentation uses ERPForAll
semantic tokens so the existing shell CSP does not require injected style elements or eval. The component
introduces no new server configuration, migration or shared authoritative state. Browser evidence remains
separate from installed field, backend authorization and deployment acceptance.
Construction errors propagate synchronously and release the editor’s allocated sessions, listeners, observer and owned surface. A failed construction does not return a handle for the caller to dispose. Teardown failures remain observable instead of replacing them with a successful construction result.
Code-editor presentation patches treat undefined optional members as absent, preserving the existing settings.
A history command returns false when no history is available or a reentrant owner update supersedes it.
Void updates instead throw ClientError kind validation with Code editor operation was superseded by an owner update.
Identical parent value echoes preserve the current operation. History pruning may also remove dependent redo steps;
it never changes the current source merely to make room.
File editors and upload ownership
Section titled “File editors and upload ownership”createFileEditor<T>(options) returns {node, select(files), dispose}. Its required options are
label, limits: {maxFiles, maxFileBytes, maxTotalBytes}, messages, report, transport and
onComplete. Limits are positive safe integers and apply to every selected file and the batch,
both before and after optional preprocessing. multiple defaults to false; accept forwards a
native selection hint and does not authorize content. readonly disables selection. Unknown
options and invalid declarations fail explicitly.
The trusted compiled caller owns transport(files, {signal, progress}) => Promise<T>, including
its authorized route, request construction, response validation and typed HTTP/RPC failure mapping.
Call progress(loaded, total?) with actual byte counters; omit total when it is unknown. No route,
credentials, HTML response parser, retry or mutation authority is supplied by the component.
onComplete(result, files) receives the caller’s typed successful result and may return a
promise. select waits for it and propagates rejection without retrying transport. The
error presenter report follows the existing synchronous message-service contract. A
completion callback already running must retain its own owner-lifetime checks for its
asynchronous side effects. Completion cannot
establish persistence beyond what that transport guarantees. Errors remain observable through
select rejection; native event handlers report them. displayErrors: false suppresses the sticky
danger notice only. It does not turn a failed operation into success.
Optional beforeOpen can refuse native chooser activation; prepare(files, signal) can return
replacement files. Controls lock during preparation and transfer. blockPreparation opts into the
existing balanced block service for the preparation phase, releasing it before transport and the
owner callback. The cancellable transfer remains inline. Confirmed Cancel aborts locally and does
not replay requests; a remote write may still have committed. Pass environment.signal and always
call dispose from the widget’s cleanup to abort local work and suppress late callbacks.
createDropzone({target, onDrop, signal?, disabled?}) returns {node, refresh, dispose}. Mount the
node in the target’s owning scope. It aligns to the target rectangle and tracks resize/scroll;
call refresh after an explicit host layout change. Its handler receives the original drop event.
Route event.dataTransfer.files to the same editor’s select method and report rejection. Keep the
native chooser as the keyboard alternative. The dropzone itself stores nothing and selects no route.
This delivery exposes reusable helpers to trusted addon frontend code. Binary field registration, base64 file bytes through JSON-2, and installed attachment persistence are deferred (ADR 0089). ADR 0041’s transport policy remains unchanged; a generated binary type alone does not make a Binary model field available. See ADR 0111 and the task’s behavior matrix for the client proof.
import { createFileEditor } from "@erpforall/client";import type { WidgetEnvironment, UploadTransport } from "@erpforall/client";
function fileControl(environment: WidgetEnvironment, transport: UploadTransport<string>) { if (!environment.messages) throw new Error("This host does not supply message services."); return createFileEditor({ label: "Supporting file", limits: {maxFiles: 1, maxFileBytes: 1_048_576, maxTotalBytes: 1_048_576}, messages: environment.messages, signal: environment.signal, report: environment.report, transport, onComplete: result => environment.change(result), });}The example’s string is a caller-defined result, such as a future authorized reference; it is not base64 and does not enable a binary field. Mount the returned node and return its dispose handle. The caller still declares which field/value contract receives that result.
Reusable choice editors
Section titled “Reusable choice editors”The trusted client entry exports createModelSelector, createModelFieldSelector, createSelectMenu,
createAutocomplete, createEmojiPicker, createColorPalette, createTagsList and createSignaturePad.
These are reusable browser components. Registering a wire widget for a model field remains a separate
WIDGET/view declaration; missing declarations remain open. The component fixture
is not evidence of installed model-field support or backend authorization.
Overlay components receive an EditorEnvironment: the caller’s existing messages facade, required
report(error) and optional owner signal. Each returns a disposable handle. Pass the owner signal
and call dispose() on rerender or unmount. No late source result may change a disposed owner.
Popover and touch-sheet presentation reuse the shared services. An editor does not create a second
application-wide service owner. Labels are text; never supply executable database markup.
A model selector receives {technical,label} descriptors and returns the chosen descriptor. A model
field selector receives model, path, a fields(model,signal) provider, optional filter/sort/relation
policy and a change callback. Supply validated get_views field maps from the existing authorized
metadata path. Menus alone are not a complete model catalogue. Missing metadata must reject clearly,
not resolve as an empty successful map. Field paths have at most 32 segments and 1024 UTF-8 bytes.
Select-menu choices use string, finite-number or boolean values independent of labels. Optional groups,
search, required single choice and multiple selection are explicit policies. Autocomplete sources return
immediate or asynchronous discriminated options: selectable {kind:"option",label,select} entries or
nonselectable {kind:"heading"|"status",label} entries. The default input debounce is 150 ms; admitted
delays are finite values from 0 to 10,000 ms. Supply represented text and cancellation policy separately
from draft input. focusFirst controls the initial highlighted option independently of cancellation
normalization; relational suggestions keep that highlight off until navigation. The relational field adapter retains the existing search and quick-create protocol.
Shared autocomplete admission is 32 sources, 1024 returned options, 262144 aggregate UTF-8 bytes and 4096 bytes per label/query. Local select/field metadata collections also enforce finite count and byte limits. Limits reject invalid input; they do not authorize records or replace server admission.
import { createTagsList } from "@erpforall/client";
const tags = createTagsList({ tags: [{id: "sales", label: "Sales"}, {id: "service", label: "Service"}], limit: 3,});host.append(tags.node);// Release the component with its owning widget.tags.dispose();createColorPalette({value?,excludeNone?,disabled?,select}) emits an index from 0 to 11. The no-colour
entry is index 0. createTagsList({tags,limit,label?}) accepts unique supplied tag identities, preserves
order and expands overflow without mutating records; limits are positive integers up to 1000.
createEmojiPicker accepts the editor environment, selection callback and optional catalogue/load,
label, readonly, touch and removal policies. The default catalogue’s independently authored labels,
keywords and categories are MIT OR Apache-2.0 (emoji-data.LICENSE); glyphs use installed platform fonts.
It is deliberately a curated subset. Do not copy upstream emoji datasets into an addon. Returning false
from selection or Shift-selecting preserves the picker; optional removal emits false.
Bounded signature editor
Section titled “Bounded signature editor”createSignaturePad receives a required report, change(state) callback and optional label, name,
mode (type, draw, upload), initial image, readonly and signal. Its handle exposes node, canvas,
state(), setMode, clear, loadFile, exportPng and dispose. exportPng() returns null when empty
and rejects pending/invalid states. Initial image validation follows the upload path. Image errors are
visible and reported; event handlers drain already-reported rejections rather than retrying writes.
Only PNG/JPEG raster input is admitted: at most 2 MiB and 2048 pixels per axis, checked from byte headers before decoding. The browser decoder rejects corrupted image content beyond that preflight. The backing canvas is 1024 by 256; exported PNG data URLs are capped at 2 MiB. Names are capped at 1024 UTF-8 bytes. No external image URL, SVG, downloaded font, upload endpoint, signer authorization, consent or document approval is supplied. The host owns server validation, persistence and workflow. No new server setting, installation step, shared-state mechanism or database migration is introduced by these editors.
Structured domain and expression editors
Section titled “Structured domain and expression editors”Trusted addon code imports createDomainEditor, createExpressionEditor and createTreeEditor
from the human-client public entry. Each factory takes an options object and returns
{node, ready, setValue, dispose}. Await ready before inspecting initialized metadata; metadata failure is reported and shown as an error state even though ready resolves; call
setValue for owner replacements (it never emits a user change), and dispose with the owning
screen. Pass the owner AbortSignal through environment. The supplied field maps must already be
authorized for the caller. Choosing a field does not authorize reading it.
const editor = createDomainEditor({ environment, label: 'Record rules', model: 'res.partner', value: '[]', fields: (model, signal) => authorizedFields(model, signal), change(result) { draftSource = result.source; draftStatus = result.status; },});host.append(editor.node);await editor.ready;// On owner replacement: await editor.setValue(ownerSource).// On teardown: editor.dispose().The source editor callbacks return a discriminated CodecResult: supported input has an
editor-local tree; unsupported or invalid input has a precise error and retains its authored
source. These objects are authoring results, never executable WireDocument or permission tokens.
Raw/debug edits can be unsupported or invalid; keep that status visible and obtain canonical server
validation before any execution or persistence. A rejected callback preserves the represented value and reports the error once; it is not retried. Raw text remains editable while a callback is pending: only the latest admitted newer draft is published after settlement, and intermediate drafts are coalesced. A rejection cannot overwrite a newer draft. Owner replacement discards drafts from the previous owner generation; disposal suppresses late work. An obsolete metadata response cannot replace a newer owner value.
The domain grammar admits condition triples, prefix AND/OR/NOT, implicit top-level AND and
constants, including bare True/False. The server domain constructor explicitly accepts boolean values (crates/erp-domain/src/domain.rs, Domain::from_value_inner); this does not make a raw source string a JSON-2 domain value. Outside quoted literals, whitespace is restricted to space, tab, CR and LF. Other whitespace is refused with its code point. The default controls author scalar equality, ordering, membership and text comparisons
where compatible with the field. Dynamic operands, internal bypass operators and advanced domain
operators without a control are refused explicitly. Expression authoring admits declared bare fields,
boolean connectives and field-to-literal comparisons. Properties fields are excluded and expression
field choices do not traverse relations. Reserved keywords cannot identify expression fields. Calls, arbitrary attributes, arithmetic and comprehensions
remain unsupported source. Runtime expression parsing/evaluation stays with the canonical server AST
and existing client interpreter.
Literal integers retain signed i64 decimal identity, including values beyond JavaScript’s safe integer range; integer and float kinds are distinct. None remains None in expressions and becomes false only at the domain-value boundary. Strings are literal text, never markup or code. Membership controls take literal lists or tuples. Date/datetime scalar literals use explicit text values; no timezone is invented.
createTreeEditor accepts a ConditionNode, model and field provider plus a change callback.
The optional typed provider supplies compatible operators, initial values, value admission,
readonly descriptions and an optional disposable value control. Providers run as trusted addon code,
not expressions received in JSON. Metadata callbacks can run per row on redraw; callers should cache their authorized metadata within the owning lifetime. A pending structured mutation refuses a concurrent mutation with a validation ClientError, rather than queueing it. Provider-owned disabled controls remain disabled after edits. Each path change installs a compatible operator and value atomically.
Binary, JSON and collection-field authoring require a compatible explicit provider. Unknown metadata
or unavailable defaults fail visibly; the editor never invents a field.
Optional readonly, debug and touch configure source editors. Readonly removes mutation/reset
controls. Explicit reset emits [] for domains or True for expressions. Conversion failures do not
reset values. Archived inclusion is separately represented only for the exact active membership
marker at the whole-domain or top-level conjunctive boundary; nested OR/NOT filters remain intact.
ADR 0115 admits at most 65536 UTF-8 source/output bytes, 1024 tree/literal nodes and 32 levels.
Positive limits may lower sourceBytes, outputBytes, nodes and depth; unknown keys, zero and
raised limits refuse. Existing metadata/path limits also apply. Admission is a functional safety
contract, not a benchmark. These components introduce no server settings, installation steps,
migrations, discovery routes or persistence services. Generic domain/expression field-widget wiring
and Studio authoring remain separately owned. The task report records the executed component/browser
proof and remaining limitations.
Reusable HTML editor
Section titled “Reusable HTML editor”createHtmlEditor(options) is a disposable authoring component for trusted compiled addon code.
It returns node, editable, exportHtml, setValue, focus, undo, redo, state and dispose.
Required options are environment, label, ordinary string value and change. Optional
readonly, disabled, required and invalid control presentation; clipboardMode is rich
or plain-text. Unknown keys and wrong types are errors. Markup wrapper objects are refused as
source values. setValue validates atomically, emits no change callback and resets history.
import {createHtmlEditor, type EditorEnvironment} from "@erpforall/client";
export function richNotes(environment: EditorEnvironment, changed: (html: string) => void) { return createHtmlEditor({ environment, label: "Notes", value: "<p>Draft notes</p>", change: changed, clipboardMode: "rich", });}The public-contract test and compiled browser fixture exercise this factory shape. The component
returns an ordinary untrusted HTML string, never runtime Markup or a server sanitizer token.
The caller owns record validation, save/discard, transport and error presentation. HTML metadata
and general field-widget admission remain unavailable until the canonical field integration.
A failed owner callback retains the draft. Pending asynchronous notifications keep one in-flight
callback and one latest draft; replacement and disposal suppress stale completion presentation.
A callback’s completion is not a saved-record acknowledgment, and uncertain writes are not retried.
The editor’s own chrome is two floating surfaces, both position: fixed and placed from viewport
rectangles by the pure helpers in html-editor-float.ts (placeFloating, toolbarVisible,
slashTrigger, filterCommands), so no form ancestor clips them:
- a
role="toolbar"insidenode(buttons keepdata-html-command=bold,italic,underline,strike,undo,redo) shown only for a non-collapsed selection of visible text in an editable editor, hidden while the pointer drags, on collapse, on blur and on Esc, and re-placed on scroll and resize; - a
role="listbox"command list opened by/at the start of a text run or after a space. Its commands (BLOCK_COMMANDS) rewrite only the caret’s top-level paragraph, heading or bare inline run, and only use tags in the vocabulary below. The list is not offered inside a list item or a quote, or when readonly.
An empty editor sets data-empty="true" on editable and shows data-hint through CSS.
Styling uses tokens only; there is no setting to bring back a permanent strip.
Supported structure is p/div/br, strong/b, em/i, u/s, blockquote/pre/code, ul/ol/li and h1–h6.
The component reconstructs admitted DOM with new nodes and no arbitrary attributes. Unsupported
initial content refuses with its source still held by the caller; paste can simplify formatting
with visible feedback. Block content nested beneath an inline formatting wrapper is refused atomically with an unsupported error saying the case is not available yet; valid list-item, blockquote and nested-division destinations remain supported. Browser import admission protects the editing surface. Clone-based export
cleanup only removes editor presentation hints; it is not the authoritative storage sanitizer.
Do not call markup(editor.exportHtml()) or use the editor to relax ADR 0042 policies. Do not use
its private clipboard MIME as a trust indication. Knowledge article comments, embeddings and
collaboration are application features outside this component contract.
limits may lower positive defaults: inputBytes/outputBytes 1,000,000, nodes 10,000,
depth 64, historyEntries 100 and historyBytes 4,000,000. Bytes are UTF-8 serialized data,
including retained history snapshot data; these figures are safety admission choices, not measured
heap budgets or performance claims. Native inert-parser heap usage has no proved exact byte cap.
Editor lifetime and history are local to the browser owner. No service installation, database
migration, background job or new runtime configuration is introduced.
Panel metadata producers retain the existing visible unsupported-panel boundary for list companions. Unsupported XML presentation attributes do not suppress the list, and the client applies no panel predicate or panel data RPC in that state. Standalone search metadata still rejects the declaration. See panel admission diagnostics for native overlay and wire construction restrictions. Extended section rendering is planned.