@embeddables/forms
v0.5.1
Published
Schema-driven form state, local persistence, and analytics events for Embeddables funnels.
Keywords
Readme
@embeddables/forms
Schema-driven form state for Embeddables funnels. Composes on
@embeddables/core for
identity; optionally accepts an analytics client on initForms to emit events
on .set() and .submit(). When core resolves a publishable key, project id,
and app user id, durable R2 writes run automatically on successful .set() and
.submit() — best-effort and independent of analytics.
Install
npm install @embeddables/forms @embeddables/coreFor React apps, also install react (peer dependency) and wrap your tree in
EmbeddablesProvider from @embeddables/core/react. Register the static module
through modules, then pass its runtime configuration through the provider's
top-level forms prop.
React
Import hooks from @embeddables/forms/react:
Example:
import { EmbeddablesProvider } from '@embeddables/core/react'
import { analytics } from '@embeddables/analytics/react'
import { forms, useForm, useFormField, useFormFileUpload } from '@embeddables/forms/react'
import { config } from './embeddables/_dist/config.ts'
function SignupField() {
// No type arguments: the id narrows the form, and the schema map comes from
// the registry `em build` writes into embeddables/_dist/register.ts.
const { form } = useForm({ formId: 'signup' })
const { value, error, setValue, onBlur } = useFormField({ form, key: 'email' })
return (
<label>
Email
<input value={value ?? ''} onChange={(event) => setValue(event.target.value)} onBlur={() => void onBlur()} />
{error?.[0]}
</label>
)
}
export function App() {
return (
<EmbeddablesProvider
config={config}
modules={[forms(), analytics()]}
forms={{
customValidations: [
{
formId: 'signup',
customValidations: {
// Return a message to fail, or null to pass.
email: ({ value }) =>
typeof value === 'string' && value.endsWith('@example.com')
? 'example.com addresses are not accepted.'
: null,
},
},
],
}}
>
<SignupField />
</EmbeddablesProvider>
)
}customValidationsandserverFormDatago on the provider'sformsprop.- Form schemas come from Core (
config.forms, populated byem build) — they are not passed to the provider. - A custom validator receives
{ value, values }and returns a message to fail ornullto pass.valuesis the whole form, so a validator can read sibling fields. - When
analytics()is enabled, form events are tracked automatically — the order ofmodulesdoes not matter. Add'forms'toexcludeAnalyticsInModulesto turn that off. useFormFieldgives you two ways to write.setValue+onBluris commit-on-blur, for text inputs: typing updates local state andform.set()runs on blur.commit(value)writes immediately, for controls with no meaningful blur —select, checkboxes, radios.form.set({ field: undefined })clears one field;form.clear()clears the whole form.- One live
FormInstanceperschema.idis shared across hooks in the same client. - Imperative consumers can also call
form.subscribe(listener)to observe value and error changes.
Steppers and option steps
A step built from buttons or option cards must read its selected state from the
form, not from component state. useForm({ formId }) returns reactive values,
so writes from the Workbench Data panel, another hook, or form.set() show up
on the page immediately. Keep useState for UI-only state (open/closed,
animation), never for the answer.
Example:
function FeelingStep({ onNext }: { onNext: () => void }) {
const { form, values } = useForm({ formId: 'check_in' })
const field = form?.getFieldByKey('feeling')
return (
<div role="radiogroup">
{field?.options?.map((option) => (
<button
key={option.key}
type="button"
role="radio"
aria-checked={values.feeling === option.key}
onClick={() => void form?.set({ feeling: option.key })}
>
{option.display_text}
</button>
))}
<button type="button" disabled={values.feeling === undefined} onClick={onNext}>
Next
</button>
</div>
)
}useFormField({ form, key }) is also reactive. For controls with no meaningful
blur, read its value and call commit(value) on click. Use setValue plus
onBlur for text inputs.
Anti-pattern — the selection lives in component state, so a value written from outside never reaches the screen, and nothing is stored until the handler runs:
const [answer, setAnswer] = useState<string | null>(null)
// ...
<button aria-checked={answer === option.key} onClick={() => setAnswer(option.key)} />File inputs
For value_type: file fields, use useFormFileUpload. It uploads through the publishable-key API, commits the returned FormFileRef, and exposes inputProps for a native <input type="file">.
Example:
function IdPhotoField() {
const { form } = useForm({ formId: 'intake' })
const { value, error, isLoading, uploadError, inputProps } = useFormFileUpload({
form,
key: 'id_photo',
})
return (
<label>
ID photo
<input {...inputProps} accept="image/jpeg,image/png" />
{isLoading && <span>Uploading…</span>}
{uploadError && <span>{uploadError}</span>}
{error?.[0]}
{value?.name && <span>{value.name}</span>}
</label>
)
}Imperative equivalent: const ref = await form.uploadFile({ key: 'id_photo', file }) then await form.set({ id_photo: ref }).
Quick start
import { initEmbeddables } from '@embeddables/core'
import { initForms, type FormSchema } from '@embeddables/forms'
const schema = {
id: 'signup',
name: 'Signup',
fields: [
{
key: 'email',
label: 'Email',
value_type: 'email',
field_type: 'user_input',
validations: { required: true },
},
],
} as const satisfies FormSchema
const core = initEmbeddables({
projectId: 'proj_…',
forms: { [schema.id]: schema },
experiments: [],
})
const { getForm } = initForms({ core })
const form = getForm({ formId: 'signup' })
const result = await form.set({ email: '[email protected]' })
if (!result.ok) console.log(result.errors)
const email = form.get('email')
await form.submit()Use as const satisfies FormSchema on hand-authored schemas so field keys and
value types flow into .set(), .get(), and .getAll(). CLI-generated schemas
from embeddables/_dist are already typed.
Schema
Each form is one object: id, optional name, and fields. Each field has a
value_type (text, email, number, boolean, select, multiselect,
json, file).
Use getFieldByKey(fieldKey) for presentation metadata (display_text,
display_description, option display_text, field_type) instead of
duplicating copy in markup. local_only values still persist but are omitted
from data:updated / field:updated analytics patches.
const plan = form.getFieldByKey('plan')
plan?.display_text
plan?.options?.[0]?.display_textDeclarative rules: required, minLength, maxLength, min, max,
pattern, oneOf, and optional synchronous validations.custom. File fields
also accept validations.accept (MIME list) and validations.maxSize (bytes).
Compatible field types may declare protocolFieldId to link a form field to a
protocol question. json fields cannot. FormFileRef is exported for typed
file values.
A select or multiselect field declares its choices in a field-level options
array of { key, display_text, display_description?, exclusive? }. The field's
value_type — not the name of a rule — decides whether one or many of them may
be selected. An option marked
exclusive on a multiselect cannot coexist with any other value: selecting it
clears the rest, and selecting a regular option afterwards clears it. Those two
types no longer accept validations.oneOf, which stays available on every other
field type. em build migrates it with a warning, carrying across the unique
non-empty string entries and dropping the rest — an entry that is not a string
could never have matched a stored value — so a field whose entries are all
unusable keeps no constraint at all. A schema that reaches initForms still
carrying oneOf on either type throws a SchemaError.
Use string patterns, not RegExp objects. Regex flags go in an optional leading
(?flags) prefix inside pattern — (?u)^\p{L}+$ — using any of dgimsuvy;
g and y are stripped before compilation. For YAML/JSON schemas without inline
functions, pass validators via customValidations: [{ formId, customValidations }]
on initForms / forms().
Form API
| Method | Purpose |
| ------ | ------- |
| set({ … }) | Validate and persist a patch atomically; optional analytics; best-effort durable R2 write when configured |
| get(key) / getAll() | Read declared fields from storage |
| getFieldByKey(key) | Read resolved schema metadata for one declared field |
| getValueByProtocolFieldId(protocolFieldId) | Read by schema protocolFieldId (typed like get() for the backing field; undefined if unknown or unset) |
| validate({ … }) | Check values without writing or tracking |
| submit() | Validate all fields, best-effort durable R2 write, and emit form:submitted when analytics is configured |
| uploadFile({ key, file, fileName? }) | Upload bytes for a value_type: file field; returns FormFileRef (caller commits with .set()) |
| errors() | Current validation messages |
| clear() | Remove this form's stored values |
.set() applies all keys in one call or writes nothing. Bind it to change,
blur, or a step button — not per-keystroke input. .submit() is not
idempotent; guard against double-clicks in your UI.
Returned promises from set, submit, and validate never reject for
validation failures — check result.ok and result.errors instead. Durable
backend writes are also best-effort: a failing persistence request never rejects
.set() or .submit().
Options
initForms
| Option | Purpose |
| ------ | ------- |
| core | Initialized @embeddables/core instance with form schemas in forms (required) |
| customValidations | Optional { formId, customValidations }[] for schemas that need runtime validators |
| serverFormData | Optional { formId, serverFormData }[]; SSR hydration overrides localStorage on overlapping keys |
| analyticsInstance | Optional analytics client for event tracking only |
getForm({ formId })
| Argument | Purpose |
| ------ | ------- |
| formId | Id of a schema registered on Core (required); an unknown id throws FormsError |
getForm returns one instance per form id: the first call builds it, every
later call returns that same one, so two handles can never race each other for
the same storage entry. The cache lives on the client, so hold one client per app.
Server (@embeddables/forms/server)
import { initEmbeddablesServer } from '@embeddables/core/server'
import { initFormsServer } from '@embeddables/forms/server'
import { schema as signupSchema } from './embeddables/_dist/forms/<form-id>/schema.js'
const server = initEmbeddablesServer({
projectId: '…',
forms: { [signupSchema.id]: signupSchema },
experiments: [],
})
const forms = initFormsServer({ server })
await forms.getForm({ formId: signupSchema.id }).set({ email: '[email protected]' })
const serverFormData = forms.getServerFormData()
// Pass serverFormData into client initForms({ serverFormData: [{ formId: signupSchema.id, serverFormData: serverFormData[signupSchema.id] }] })Server form instances expose set, get, getAll, and
getValueByProtocolFieldId only. Storage is in-memory; nothing is written to
localStorage or durable backends.
Analytics
To track form events, install @embeddables/analytics and pass initAnalytics({ core }) as analyticsInstance on initForms.
When analyticsInstance is provided, a successful .set() emits data:updated
and one field:updated per changed field; .submit() emits form:submitted.
Analytics failures surface as trackError on the result — local field values
are still persisted. Omitting analytics disables event tracking only; durable
R2 writes still occur when core resolves persistence configuration.
Errors
| When | Error |
| ---- | ----- |
| Bad core at init | FormsError (thrown) |
| Bad schema at init | SchemaError (thrown) |
| Validation / bad patch | { ok: false, errors } on the result |
| Analytics failure | trackError on the result |
All SDK errors extend FormsError. Custom validators that throw propagate
synchronously from .set() and .submit().
