Chapter 23
Using PixiFormUI in existing apps (HTML, React, Angular, …)
You don't need to write canvas code to embed a form. Describe the fields as data and PixiFormUI builds the controls, layout, validation and submit handling.
| You have | Use | Example |
|---|---|---|
| A plain HTML page (no build step) | <pixi-form> + pixiform.standalone.js |
examples/html/ |
| React | <PixiFormUI> wrapper (copy one file) |
examples/react/ |
| Angular | PixiFormComponent (copy one file) |
examples/angular/ |
| Vue, Svelte, Solid, Lit, … | <pixi-form> element, or mountPixiForm() in a mount hook |
§23.6 |
23.1 Build the library#
npm run build:lib
| Output | Contents | For |
|---|---|---|
dist-lib/pixiform.js |
ESM, no dependencies (≈65 KB gzip unminified; your bundler minifies it) | Apps with a bundler (React, Angular, Vue) |
dist-lib/pixiform.standalone.js |
Minified ESM; registers <pixi-form> (≈50 KB gzip) |
Plain HTML pages |
dist-lib/types/ |
TypeScript declarations | Editors and type checking |
dist-lib/package.json |
Package manifest | npm install ../path/to/dist-lib |
Install it into another app the same way the examples do:
npm install ../pixiform/dist-lib # or publish dist-lib to your private registry
23.2 The config object#
import { mountPixiForm } from 'pixiform';
const handle = await mountPixiForm(document.getElementById('signup')!, {
title: 'Create account',
subtitle: 'It takes a minute.',
theme: 'teal', // preset name, a palette { theme, text, accent }, or a full Theme
mode: 'auto', // 'light' | 'dark' | 'auto' (follows the OS live)
layout: 'auto', // 'auto': grows with content, the page scrolls | 'fill': fills the host
maxWidth: 560,
fields: [
{ type: 'text', name: 'firstName', label: 'First name', required: true, row: 'name' },
{ type: 'text', name: 'lastName', label: 'Last name', required: true, row: 'name' },
{ type: 'email', name: 'email', label: 'Email', required: true, info: 'Used to sign in.' },
{ type: 'password', name: 'password', label: 'Password', required: true, strengthMeter: true },
{ type: 'select', name: 'country', label: 'Country', options: [{ value: 'IN', label: 'India' }] },
{ type: 'otp', name: 'code', label: 'Code', length: 6, groupSize: 3 },
{ type: 'date', name: 'dob', label: 'Date of birth', max: 'today', row: 'more' },
{ type: 'phone', name: 'mobile', label: 'Mobile', defaultCountry: 'IN', row: 'more' },
{ type: 'date', name: 'call', label: 'Call me at', time: { step: 30 }, min: 'today' },
{ type: 'checkbox', name: 'terms', label: 'I accept the terms', required: true },
],
submitText: 'Create account',
resetText: 'Clear',
form: { idleTimeoutMs: 180_000, botGuard: { minFillMs: 1500 } },
onSubmit: async (values) => ({ ok: true, message: 'Welcome!' }),
});
Field types: text, email, tel, url, number, textarea, password (plus strengthMeter), otp,
date (DatePicker), phone (PhoneInput), checkbox, switch, radio, select, slider, and
heading/paragraph for static text, and group for a titled section with its own fields (see below). Each accepts the
same options as its control (§5): required, validators, info, formatters, and so on.
Fields with the same row key sit side by side and stack below 520 px.
| Config | Default | Notes |
|---|---|---|
layout |
'auto' |
'auto': the canvas height follows the form and the page scrolls natively (touch-action: pan-y). 'fill': the canvas fills the host and scrolls internally, so give the host a height. |
transparent |
true in auto |
The page background shows through around the card. |
card |
true |
Rounded surface behind the form. |
privacyScreen |
true |
Covers the form when the window loses focus. |
toasts |
true |
Built-in success/failure toasts. Set false to show messages in your own UI via events. |
id |
— | Form identifier (analytics formId). |
action |
— | Submit without code: POST the serialized form here (§25.2). onSubmit becomes optional. |
session |
— | URL returning { csrfToken, encryption }, fetched before the first submit and after a 403. |
csrfToken, encryptionKey, submitOptions |
— | Static alternatives to session, plus extra secureSubmit options. |
a11y |
follows the OS | label, textScale, highContrast, reducedMotion, forcedColors, followZoom, outline (§18). |
analytics |
off | onEvent, consent, sampleRate, events, excludeFields, trackAbandon (§24). |
Groups: wrap related fields in { type: 'group', title, fields: [...] }. Options: name, description,
info, collapsible, collapsed, variant ('outline' | 'card' | 'plain'), gap, disabled, and row
(two groups side by side). Groups nest up to four levels. Values still submit flat, with no group prefix, so
your server rules don't change. Access them via handle.groups[name] (unnamed groups are group1, group2, …):
fields: [
{ type: 'group', title: 'Contact', description: 'How we reach you.', fields: [
{ type: 'email', name: 'email', label: 'Email', required: true },
{ type: 'phone', name: 'mobile', label: 'Mobile' },
] },
{ type: 'group', name: 'prefs', title: 'Preferences', collapsible: true, collapsed: true, fields: [
{ type: 'switch', name: 'paperless', label: 'Paperless statements', value: true },
] },
]
// handle.groups.prefs.setExpanded(true)
The handle: values(), submit(), reset(), get(name), controls, groups, analytics, setTheme(theme, mode?),
toast(msg, kind), on(type, fn) / once(type, fn) → unsubscribe (typed events, §26),
state, loaded, isDirty(), plus form, ui and app for advanced use, and destroy().
Always call destroy() when the form goes away: it wipes secrets, removes listeners and releases the canvas.
23.3 Plain HTML (no build tools)#
<head>
<script type="module" src="/vendor/pixiform.standalone.js"></script>
<script type="module" src="/js/contact-form.js"></script>
</head>
<body>
<section class="sidebar">
<pixi-form id="contact"></pixi-form> <!-- width comes from your CSS -->
</section>
</body>
// /js/contact-form.js
await customElements.whenDefined('pixi-form');
const el = document.getElementById('contact');
el.config = { title: 'Contact', fields: [/* … */], submitText: 'Save' };
// Without config.onSubmit, the element asks you via an event:
el.addEventListener('pixiform-submit', (e) => {
e.detail.respondWith(fetch('/api/contact', { /* … */ }).then((r) => ({ ok: r.ok, message: 'Saved.' })));
});
el.addEventListener('pixiform-success', (e) => console.log(e.detail.result));
| Element event | detail |
|---|---|
pixiform-ready |
{ handle } |
pixiform-submit |
{ values, respondWith(result | Promise) } (only when config.onSubmit is not set) |
pixiform-success / pixiform-failure |
{ result } |
pixiform-invalid |
{ errors } |
pixiform-change |
{ name, value } (secret fields carry a Secret handle) |
Setting el.config again rebuilds the form. el.handle gives the live handle, and removing the element from the
DOM destroys it. Run the example with npm run build:lib && npm run dev, then open
http://localhost:8787/examples/html/index.html.
23.4 React#
Copy examples/react/src/PixiFormUI.tsx into your app:
const config = useMemo<PixiFormConfig>(() => ({
fields: [/* … */],
onSubmit: async (values) => { await api.save(values); return { ok: true }; },
}), []); // memoise: a new object rebuilds the form
<PixiFormUI config={config} theme={accent} mode="auto" onReady={(h) => (handleRef.current = h)} />
- Safe under
<StrictMode>: the double mount leaves exactly one canvas (verified in the example). - Changing
theme/modeprops re-themes live; only a newconfigobject rebuilds. - Keep form values out of React state. Read them in
onSubmit, or callhandle.values()when needed. Secrets staySecrethandles. - Next.js / SSR: render the wrapper on the client only (
'use client'plusdynamic(() => import(...), { ssr: false })), because the renderer needswindowanddocument.
23.5 Angular#
Copy examples/angular/src/app/pixi-form.component.ts (standalone, Angular 16+):
@Component({
imports: [PixiFormComponent],
template: `<pixi-form [config]="config" [theme]="accent()" (success)="saved($event)" (ready)="handle = $event" />`,
})
export class SignupComponent {
readonly accent = signal<'indigo' | 'teal'>('indigo');
readonly config: PixiFormConfig = { fields: [/* … */], onSubmit: async (v) => ({ ok: true }) };
}
- The component mounts the form outside the Angular zone, so animation frames don't trigger change detection.
onSubmitand all outputs re-enter the zone. - Outputs:
ready,success,failure,invalid,valueChange. - Alternative: use the
<pixi-form>web component withschemas: [CUSTOM_ELEMENTS_SCHEMA]and bind[config]. - Verified here: the component typechecks with TypeScript 6 against
@angular/core22 and the published types (cd examples/angular && npm install && npm run typecheck). Run it in your own Angular app to test it end to end.
23.6 Other frameworks#
Any framework works with either approach:
// Vue 3
onMounted(async () => { handle = await mountPixiForm(host.value, config); });
onBeforeUnmount(() => handle?.destroy());
// Svelte
onMount(() => { let h; mountPixiForm(node, config).then((x) => (h = x)); return () => h?.destroy(); });
…or render <pixi-form> and set its config property (Vue: :config.prop="config"; Svelte: bind:this then assign).
23.7 Host page requirements#
- CSP:
script-src 'self'for the bundle is all it needs. No'unsafe-eval', no workers (worker-src 'none'is fine), noblob:URLs. - Secure context: HTTPS or localhost (Web Crypto, used by
sealSecret). - Width: the form takes its container's width; set it with your CSS. Heights are automatic in
autolayout. - Multiple forms per page are fine (there is no WebGL context limit to hit). Each has its own canvas, and keyboard focus moves only within its form.
- Sticky or scrolling containers: focused fields are scrolled into view inside whatever element scrolls, and the hidden keyboard proxy follows page scrolls (IME candidate windows stay aligned).