@embedpdf/plugin-form 3.0.0-next.15 → 3.0.0-next.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/package.json +15 -15
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["AnnotationHostToken","ActionsHostToken","widgetNumber","NO_FIELDS","valueOf","NOTHING_SHOWN","AnnotationHostToken","ActionsHostToken","RenderHostToken","FormToken"],"sources":["../src/tools/definitions.ts","../src/tools/handlers.ts","../src/connect.ts","../src/model.ts","../src/read/fields.ts","../src/read/settings.ts","../src/read/fill-items.ts","../src/read/widgets.ts","../src/sync/predict.ts","../src/sync/fields.ts","../src/services/design.ts","../src/services/events.ts","../src/services/fill-rights.ts","../src/services/formatted.ts","../src/services/looks.ts","../src/services/pictures.ts","../src/services/scripting.ts","../src/services/siblings.ts","../src/services/index.ts","../src/write/activation.ts","../src/services/object-numbers.ts","../src/write/next-in-line.ts","../src/write/fields.ts","../src/write/fill.ts","../src/write/interchange.ts","../src/write/lending.ts","../src/field-selection.ts","../src/write/reset.ts","../src/write/script-effects.ts","../src/write/typing.ts","../src/write/values.ts","../src/controller.ts","../src/form.plugin.ts","../src/state.ts"],"sourcesContent":["/**\n * The form-tool table — the single source of truth for the palette. Every\n * derivation reads this one list: interaction registration (annotation-less),\n * annotation tool/style registration (full viewer), active-tool → field\n * family lookup, click placement, and default appearance. With the\n * annotation plugin each tool shows a ghost: the field a click places, drawn\n * with the tool's defaults where it will land.\n *\n * \"One tool system, two commit planes\": the tools live in the annotation\n * registry when that plugin is present (defaults, style panel, click-create —\n * the shared authoring infrastructure), but the commit always goes\n * through `form.create()` from the form place handler. The tags make\n * that structural: these tools enable `form-place`, never `annotation-draw`,\n * so the annotation draw handler can't wake up for them.\n */\nimport type { FormFieldFamily, WidgetAppearance } from '@embedpdf/engine-core/runtime';\nimport type { ClickCreate } from '@embedpdf/plugin-annotation/contract';\n\n/** The families the palette places. */\nexport type AuthorableFormFamily = Exclude<FormFieldFamily, 'unknown'>;\n\nexport interface FormToolDef {\n id: string;\n /** The field family the tool places (the form plane's vocabulary). */\n family: AuthorableFormFamily;\n /** The client kind the annotation registry routes on (props panel).\n * Not a PDF subtype — every widget is PDF `widget`; this is the view. */\n visualKind:\n | 'widget-text'\n | 'widget-choice'\n | 'widget-button'\n | 'widget-toggle'\n | 'widget-radio'\n | 'widget-box';\n /** What a bare click places (box policies only — fields are boxes). */\n clickCreate: Extract<ClickCreate, { width: number }>;\n /** Seed drawing defaults, the widget's appearance fields: a placed field is\n * visible (white box, gray border) and restylable per tool through the\n * shared style panel. */\n defaults: WidgetAppearance;\n cursor: string;\n}\n\n/** Palette tools keep widgets editable right after placement. */\nexport const PLACE_TAGS = ['form-place', 'annotation-edit'] as const;\n\nconst FIELD_CHROME: WidgetAppearance = {\n interiorColor: '#ffffff',\n color: '#6b7280',\n strokeWidth: 1,\n};\n\nexport const FORM_TOOLS: readonly FormToolDef[] = [\n {\n id: 'form-text',\n family: 'text',\n visualKind: 'widget-text',\n clickCreate: { width: 160, height: 24 },\n defaults: { ...FIELD_CHROME, fontSize: 12 },\n cursor: 'crosshair',\n },\n {\n id: 'form-checkbox',\n family: 'checkbox',\n visualKind: 'widget-toggle',\n clickCreate: { width: 18, height: 18 },\n defaults: FIELD_CHROME,\n cursor: 'crosshair',\n },\n {\n id: 'form-radio',\n family: 'radio',\n // Round, as the engine draws a radio button: its ghost and its placement too.\n visualKind: 'widget-radio',\n clickCreate: { width: 18, height: 18 },\n defaults: FIELD_CHROME,\n cursor: 'crosshair',\n },\n {\n id: 'form-combobox',\n family: 'combobox',\n visualKind: 'widget-choice',\n clickCreate: { width: 140, height: 24 },\n defaults: { ...FIELD_CHROME, fontSize: 12 },\n cursor: 'crosshair',\n },\n {\n id: 'form-listbox',\n family: 'listbox',\n visualKind: 'widget-choice',\n clickCreate: { width: 140, height: 72 },\n defaults: { ...FIELD_CHROME, fontSize: 12 },\n cursor: 'crosshair',\n },\n // A push button: its caption is its text; what it does is its actions.\n {\n id: 'form-button',\n family: 'pushbutton',\n visualKind: 'widget-button',\n clickCreate: { width: 100, height: 28 },\n defaults: { ...FIELD_CHROME, interiorColor: '#e5e7eb', fontSize: 12 },\n cursor: 'crosshair',\n },\n // A signature field: the bare widget box every non-text family ingests\n // as (`widget-box`). It has no value of its own to style — the signing\n // act (the signature plugin) draws the mark into it later.\n {\n id: 'form-signature',\n family: 'signature',\n visualKind: 'widget-box',\n clickCreate: { width: 160, height: 48 },\n defaults: FIELD_CHROME,\n cursor: 'crosshair',\n },\n];\n\nexport const FORM_TOOL_BY_ID: ReadonlyMap<string, FormToolDef> = new Map(\n FORM_TOOLS.map((tool) => [tool.id, tool]),\n);\n","import { gesturePlacement, widgetAppearanceOf } from '@embedpdf/core-annotation';\nimport type { FormFieldDraft, PageRef, WidgetPlacement } from '@embedpdf/engine-core/runtime';\nimport type { AnnotationHostCapability } from '@embedpdf/plugin-annotation/contract/host';\nimport {\n samplePointOn,\n type InteractionHandler,\n type InteractionHostCapability,\n} from '@embedpdf/plugin-interaction/contract/host';\n\nimport type { FormHostCapability } from '../host-contract';\nimport type { Box } from '../model';\nimport { FORM_TOOL_BY_ID, type FormToolDef } from './definitions';\n\ntype Vec = { x: number; y: number };\n\n/** A name for a field placed with a tool: `text_1`, `text_2`, …, the first one the form doesn't have. */\nexport function nextFieldName(family: string, taken: ReadonlySet<string>): string {\n let count = 1;\n while (taken.has(`${family}_${count}`)) count++;\n return `${family}_${count}`;\n}\n\n/** The part of a box on the page; `null` when too little of it is. */\nexport function clampToPage(box: Box, page: Box): Box | null {\n const x = Math.max(page.x, Math.min(box.x, page.width));\n const y = Math.max(page.y, Math.min(box.y, page.height));\n const clamped = {\n x,\n y,\n width: Math.max(0, Math.min(box.x + box.width, page.width) - x),\n height: Math.max(0, Math.min(box.y + box.height, page.height) - y),\n };\n return clamped.width < 1 || clamped.height < 1 ? null : clamped;\n}\n\n/**\n * The field a palette tool places: one widget at `widget`, named like\n * `text_1`. A radio button stands for `'Choice1'` and a dropdown or a list\n * starts with two options, as in Acrobat; rename and change them in a\n * settings panel.\n */\nexport function toolDraft(\n tool: FormToolDef,\n name: string,\n widget: WidgetPlacement,\n): FormFieldDraft {\n switch (tool.family) {\n case 'radio':\n return { family: 'radio', name, widgets: [{ ...widget, exportValue: 'Choice1' }] };\n case 'combobox':\n case 'listbox':\n return {\n family: tool.family,\n name,\n widgets: [widget],\n options: [\n { label: 'Option 1', value: 'Option 1' },\n { label: 'Option 2', value: 'Option 2' },\n ],\n };\n case 'pushbutton':\n return { family: 'pushbutton', name, widgets: [{ ...widget, caption: 'Button' }] };\n default:\n return { family: tool.family, name, widgets: [widget] };\n }\n}\n\n/**\n * Draw-to-place: drag a box or just click. The commit creates the field and\n * its widget through `form.create()`, styled from the tool's live defaults.\n * Where the field goes is `gesturePlacement`, the call the annotation core\n * makes for its own drawings: the dragged box once the gesture is a drag\n * (the shared click ↔ drag threshold), else the tool's `clickCreate` box.\n * What follows is the annotation plugin's `afterCreate` setting, as for\n * every tool: select the new widget, and keep the tool or go back to the\n * default one.\n *\n * With the annotation plugin, the tool's ghost shows the field a click\n * places: this handler's hover puts it where the click would reach it (no\n * widget or annotation under the pointer claims it) and the user may design\n * forms. The gesture reports itself (`previewPlacement`), so once it drags\n * the page paints the field the release places, a radio button round.\n *\n * Gesture rules match the annotation handlers: page-anchored via the sample\n * projection (the box keeps sizing along the edge when the cursor overshoots\n * or crosses a gap), and the up sample is the final point.\n */\nexport function createPlaceHandler(\n form: FormHostCapability,\n interaction: InteractionHostCapability,\n annotation: AnnotationHostCapability | null,\n): InteractionHandler {\n let origin: { page: PageRef; start: Vec; last: Vec } | null = null;\n /** Drop the gesture and what it painted: its placement and the tool's ghost. */\n const endGesture = (): void => {\n origin = null;\n annotation?.clearPlacementPreview();\n annotation?.clearGhost();\n };\n\n const place = async (tool: FormToolDef, page: PageRef, box: Box): Promise<void> => {\n const pageBox = form.getPageBox(page);\n const rect = pageBox ? clampToPage(box, pageBox) : null;\n if (!rect) return;\n // Style from the tool's live defaults when the annotation plugin holds\n // them (the user may have restyled the tool); without it, use the tool\n // table's defaults, so a field is never invisible.\n const look = widgetAppearanceOf(\n annotation ? annotation.tools.getDefaults(tool.id) : tool.defaults,\n );\n const name = nextFieldName(tool.family, new Set(form.list().map((field) => field.name)));\n // The new field shows at once, when the document holds the numbers it\n // takes: then it is selected in the same frame. Otherwise once it shows.\n const created = form.create(toolDraft(tool, name, { page, rect, ...look }));\n const field = form.get({ kind: 'fqn', name }) ?? (await created).field;\n // Skip the follow-up when the tool changed meanwhile.\n if (!annotation || interaction.getActiveToolId() !== tool.id) return;\n const policy = annotation.getSettings().afterCreate;\n const widget = field.widgets.find(\n (candidate) => candidate.page?.objectNumber === page.objectNumber,\n );\n if (policy.select && widget?.ref) annotation.selection.set([widget.ref]);\n // Back to design's resting tool, not the default pointer: that one fills, which would end\n // design and drop the new field's selection.\n if (policy.tool === 'default') interaction.activateTool('form-edit');\n await created;\n };\n\n return {\n id: 'form-place',\n // Above the annotation edit handler (100): while a palette tool is\n // active, a drag on empty page means \"place a field\", not \"marquee\".\n priority: 95,\n enabledFor: (tool) => tool.enables.has('form-place'),\n onHover: (sample) => {\n if (!annotation) return;\n const toolId = interaction.getActiveToolId();\n if (\n sample.page &&\n FORM_TOOL_BY_ID.has(toolId) &&\n form.canDesign() &&\n !interaction.hasCursorClaim()\n ) {\n annotation.hoverGhostAt(\n toolId,\n sample.page.ref,\n sample.page.point,\n sample.page.rotation,\n sample.page.zoom,\n );\n } else {\n annotation.clearGhost();\n }\n },\n onDown: (sample) => {\n // No capture without a page, a known palette tool, or design permission:\n // declining lets editing, panning or text selection take the gesture.\n if (!sample.page || !FORM_TOOL_BY_ID.has(interaction.getActiveToolId())) return false;\n if (!form.canDesign()) return false;\n origin = { page: sample.page.ref, start: sample.page.point, last: sample.page.point };\n return true;\n },\n onMove: (sample) => {\n if (!origin) return;\n const point = samplePointOn(sample, origin.page);\n if (!point) return;\n origin.last = point;\n annotation?.previewPlacement(interaction.getActiveToolId(), origin.page, origin.start, point);\n },\n onUp: (sample) => {\n if (!origin) return;\n const gesture = origin;\n endGesture();\n const tool = FORM_TOOL_BY_ID.get(interaction.getActiveToolId());\n if (!tool) return;\n // The up sample is the final point (projection first, like every\n // page-anchored gesture); a release over the gap falls back to the\n // last resolved point.\n const end = samplePointOn(sample, gesture.page) ?? gesture.last;\n const placement = gesturePlacement('box', gesture.start, end, tool.clickCreate, {\n pageBox: form.getPageBox(gesture.page) ?? undefined,\n });\n if (placement?.kind !== 'box') return;\n place(tool, gesture.page, placement.rect).catch((error) => {\n globalThis.console?.error('[form] placing the field failed:', error);\n });\n },\n // Aborted (a second finger, a system cancel): nothing is placed.\n onCancel: endGesture,\n };\n}\n","/**\n * The form plugin's wiring to its siblings, run once every capability exists:\n * its tools and place handler on the interaction hub, its widgets lent to the\n * annotation plugin for design, and the reset executor, commit sink, form\n * reader and submit resolver on the actions plugin. Every registration is released with\n * the document.\n */\nimport { ActionsToken as ActionsHostToken } from '@embedpdf/plugin-actions/contract/host';\nimport {\n AnnotationToken as AnnotationHostToken,\n type AnnotationLender,\n} from '@embedpdf/plugin-annotation/contract/host';\nimport { InteractionToken } from '@embedpdf/plugin-interaction/contract/host';\n\nimport type { FormHostCapability } from './host-contract';\nimport type { FormContext } from './services';\nimport { FORM_TOOLS, PLACE_TAGS } from './tools/definitions';\nimport { createPlaceHandler } from './tools/handlers';\n\nexport function connectForm(\n ctx: FormContext,\n form: FormHostCapability,\n lender: AnnotationLender,\n): void {\n const interaction = ctx.get(InteractionToken);\n const annotation = ctx.tryGet(AnnotationHostToken);\n\n // Fill-only mode: forms are fillable and annotations are not editable. The\n // default fill experience does not need this tool, because the built-in\n // pointer and pan tools carry the 'form-fill' tag themselves. 'link-nav'\n // keeps links navigable while filling, as in Acrobat.\n ctx.cleanup(\n interaction.registerTool({\n id: 'form-fill',\n cursor: 'default',\n enables: new Set(['form-fill', 'link-nav']),\n }),\n );\n // Design mode's resting tool: without 'form-fill' the widget behavior\n // disengages, and widgets select, move and resize like any annotation.\n // Palette tools add drag-to-place on top of it.\n ctx.cleanup(\n interaction.registerTool({\n id: 'form-edit',\n cursor: 'default',\n enables: new Set(['annotation-edit', 'annotation-marquee']),\n }),\n );\n\n // The field palette is one tool table with two registration paths. With the\n // annotation plugin, the tools join its registry and gain live defaults,\n // the style panel and click-to-create. Without it they are plain hub tools:\n // placement still works; only interactive styling needs the annotation\n // plugin, and so does the ghost. Either way the form place handler commits\n // them: these tools enable 'form-place', never 'annotation-draw'.\n for (const tool of FORM_TOOLS) {\n ctx.cleanup(\n annotation\n ? annotation.tools.register({\n id: tool.id,\n subtype: tool.visualKind,\n cursor: tool.cursor,\n enables: [...PLACE_TAGS],\n clickCreate: tool.clickCreate,\n defaults: tool.defaults,\n // Click-first: the field a click places follows the pointer.\n ghost: true,\n })\n : interaction.registerTool({\n id: tool.id,\n cursor: tool.cursor,\n enables: new Set(PLACE_TAGS),\n }),\n );\n }\n ctx.cleanup(interaction.registerHandler(createPlaceHandler(form, interaction, annotation)));\n\n // Design mode: the widgets are lent to the annotation plugin, which selects,\n // moves, restyles and deletes them with its own tools (write/lending.ts).\n if (annotation && ctx.allows('doc.forms.modify')) {\n ctx.cleanup(annotation.lend(lender));\n }\n\n const actions = ctx.tryGet(ActionsHostToken);\n if (!actions) return;\n // Script form effects are written through this plugin, which owns the fields, and scripts\n // read the form as the user sees it, with the fills still on their way.\n ctx.cleanup(actions.registerFormCommitSink((effects) => form.commitScriptFormEffects(effects)));\n ctx.cleanup(actions.registerFormReader(() => form.getSnapshot()));\n ctx.cleanup(\n actions.registerSubmitResolver((intent, actionContext, diagnose) =>\n form.resolveSubmitDataset(intent, actionContext, diagnose),\n ),\n );\n // The executor passes its action context through, so a ResetForm run by a\n // page or document trigger reports its recalculation with that origin.\n ctx.cleanup(\n actions.registerExecutor('reset-form', async (node, actionContext) => {\n if (node.type !== 'reset-form') return { status: 'inert', reason: 'not a reset-form node' };\n const result = await form.resetFormAction(node.fields, node.exclude, actionContext.origin);\n if (result.status === 'failed') {\n return { status: 'failed', error: result.error?.message ?? 'reset failed' };\n }\n if (result.status === 'unchanged') {\n return {\n status: 'inert',\n reason: result.diagnostics[0]?.message ?? 'reset-form resolved no fields',\n };\n }\n return { status: 'executed' };\n }),\n );\n}\n","/**\n * The form plugin's data, all pure:\n *\n * - `FieldIndex` is the form as the engine confirmed it: the field tree and\n * every widget row, indexed by field key and by widget. It is the value of\n * the plugin's `fields` mirror and changes only through `foldFormEvent` and\n * loads; `predictFormOp` (sync/predict.ts) shows this session's changes on\n * top of it.\n * - `PageWidgets` is one page's widgets, where each is and how it looks,\n * derived from the index's widget rows (`pageWidgetsOf`).\n *\n * The text being typed in a field is not here: it waits in `write/typing.ts`\n * until it is committed.\n */\nimport { reload, type MirrorReload } from '@embedpdf/core';\nimport {\n annotationKey,\n reorderPart,\n type AnnotationRef,\n type DocumentEvent,\n type FormFieldDTO,\n type FormFieldRef,\n type FormSnapshot,\n type FormWidget,\n type PageRef,\n type WidgetAnnotation,\n} from '@embedpdf/engine-core/runtime';\n\n/** A page-space box (top-left origin, y-down, PDF points). */\nexport interface Box {\n readonly x: number;\n readonly y: number;\n readonly width: number;\n readonly height: number;\n}\n\n/** Stable client key for a field: its object number when durable, else its fully qualified name. */\nexport type FieldKey = string;\n\nexport const fieldKeyOfRef = (ref: FormFieldRef): FieldKey =>\n ref.kind === 'objectNumber' ? `obj:${ref.objectNumber}` : `fqn:${ref.name}`;\n\n/** A field's ref is its object number, or its name when it has none. */\nexport const fieldKeyOf = (field: { ref: FormFieldRef }): FieldKey => fieldKeyOfRef(field.ref);\n\n// ── the field index (the `fields` mirror) ────────────────────────────────────\n\nexport interface FieldIndex {\n readonly snapshot: FormSnapshot | null;\n /** Field key → index into `snapshot.fields`. */\n readonly byKey: Readonly<Record<FieldKey, number>>;\n /** Full name → index into `snapshot.fields`, for a ref made with `toFieldRef(name)`. */\n readonly byName: Readonly<Record<string, number>>;\n /** Widget annotation object number → index into `snapshot.fields`. */\n readonly byWidget: Readonly<Record<number, number>>;\n /** Widget annotation object number → index into `snapshot.widgets`, its row. */\n readonly rowByWidget: Readonly<Record<number, number>>;\n /**\n * Widget annotation object number → the version of its picture. It moves\n * when the engine draws the widget again, and only then: its pictures are\n * fetched again exactly when it moves. A widget that went keeps its entry,\n * so one made again with its number never takes an older picture.\n */\n readonly pictureVersions: Readonly<Record<number, number>>;\n}\n\nexport const emptyFieldIndex = (): FieldIndex => ({\n snapshot: null,\n byKey: {},\n byName: {},\n byWidget: {},\n rowByWidget: {},\n pictureVersions: {},\n});\n\nexport function indexFields(\n snapshot: FormSnapshot,\n pictureVersions: FieldIndex['pictureVersions'] = {},\n): FieldIndex {\n const byKey: Record<FieldKey, number> = {};\n const byName: Record<string, number> = {};\n const byWidget: Record<number, number> = {};\n const rowByWidget: Record<number, number> = {};\n snapshot.fields.forEach((field, position) => {\n byKey[fieldKeyOf(field)] = position;\n byName[field.name] ??= position;\n for (const widget of field.widgets) {\n if (widget.objectNumber > 0) byWidget[widget.objectNumber] = position;\n }\n });\n snapshot.widgets.forEach((row, position) => {\n if (row.ref.kind === 'objectNumber') rowByWidget[row.ref.objectNumber] = position;\n });\n return { snapshot, byKey, byName, byWidget, rowByWidget, pictureVersions };\n}\n\n/** The index of `snapshot`, keeping `index`'s picture versions. */\nconst reindex = (index: FieldIndex, snapshot: FormSnapshot): FieldIndex =>\n indexFields(snapshot, index.pictureVersions);\n\n/**\n * A fresh read of the whole form: every widget's picture version moves past\n * the one it had, so a reload re-fetches every picture (the pictures may\n * have changed while the event stream wasn't trusted). A new widget starts at 0.\n */\nexport function indexLoadedFields(previous: FieldIndex, snapshot: FormSnapshot): FieldIndex {\n const pictureVersions: Record<number, number> = {};\n for (const [number, version] of Object.entries(previous.pictureVersions)) {\n pictureVersions[Number(number)] = version + 1;\n }\n for (const row of snapshot.widgets) {\n const number = widgetNumber(row);\n if (number > 0) pictureVersions[number] ??= 0;\n }\n return indexFields(snapshot, pictureVersions);\n}\n\n/** The picture version of a widget; 0 for one the index has never seen. */\nexport const pictureVersionOf = (index: FieldIndex, annotObjectNumber: number): number =>\n index.pictureVersions[annotObjectNumber] ?? 0;\n\n/** Replace a field by key, or append it when it is new. */\nexport function upsertFields(index: FieldIndex, fields: readonly FormFieldDTO[]): FieldIndex {\n if (!index.snapshot || fields.length === 0) return index;\n const next = index.snapshot.fields.slice();\n for (const field of fields) {\n const position = index.byKey[fieldKeyOf(field)];\n if (position === undefined) next.push(field);\n else next[position] = field;\n }\n return reindex(index, { ...index.snapshot, fields: next });\n}\n\nconst widgetNumber = (widget: WidgetAnnotation): number =>\n widget.ref.kind === 'objectNumber' ? widget.ref.objectNumber : 0;\n\n/** Replace widget rows by object number, or append the ones that are new. */\nexport function upsertWidgets(index: FieldIndex, rows: readonly WidgetAnnotation[]): FieldIndex {\n if (!index.snapshot || rows.length === 0) return index;\n const incoming = new Map(rows.map((row) => [widgetNumber(row), row]));\n const next = index.snapshot.widgets.map((row) => {\n const replaced = incoming.get(widgetNumber(row));\n if (replaced) incoming.delete(widgetNumber(row));\n return replaced ?? row;\n });\n return reindex(index, { ...index.snapshot, widgets: [...next, ...incoming.values()] });\n}\n\n/** The page's widget rows in `order` (bottom to top), in their slots: other pages' keep theirs. */\nexport function reorderWidgetRows(\n index: FieldIndex,\n page: PageRef,\n order: readonly AnnotationRef[],\n): FieldIndex {\n if (!index.snapshot) return index;\n const widgets = reorderPart(\n index.snapshot.widgets,\n (row) => row.page.objectNumber === page.objectNumber,\n order.map(annotationKey),\n (row) => annotationKey(row.ref),\n );\n return reindex(index, { ...index.snapshot, widgets });\n}\n\n/** Drop the rows of widgets that went (with their field, or with their page). */\nexport function removeWidgets(index: FieldIndex, gone: readonly FormWidget[]): FieldIndex {\n if (!index.snapshot || gone.length === 0) return index;\n const numbers = new Set(gone.map((widget) => widget.objectNumber));\n const widgets = index.snapshot.widgets.filter((row) => !numbers.has(widgetNumber(row)));\n if (widgets.length === index.snapshot.widgets.length) return index;\n return reindex(index, { ...index.snapshot, widgets });\n}\n\nexport function removeField(index: FieldIndex, ref: FormFieldRef): FieldIndex {\n if (!index.snapshot) return index;\n const fields = index.snapshot.fields.filter((field) =>\n ref.kind === 'objectNumber'\n ? !(field.ref.kind === 'objectNumber' && field.ref.objectNumber === ref.objectNumber)\n : field.name !== ref.name,\n );\n if (fields.length === index.snapshot.fields.length) return index;\n return reindex(index, { ...index.snapshot, fields });\n}\n\n/**\n * Apply one confirmed document event to the field index. Every form event\n * carries the fields and the widget rows it touched as the engine read them\n * back, so the index never needs a re-read except for a repair, whose result\n * reports only counts, and for writes that remove widgets with their pages.\n * The widgets the engine drew again take a new picture version.\n */\nexport function foldFormEvent(index: FieldIndex, event: DocumentEvent): FieldIndex | MirrorReload {\n return foldFormFacts(withRedrawnPictures(index, redrawnWidgetsOf(event)), event);\n}\n\n/** A widget an event says it drew: its page, and its number when the event names it. */\ntype PlacedWidget = { readonly page: PageRef | null; readonly objectNumber?: number };\n\n/**\n * The widgets a confirmed fact drew again: the ones the engine says it\n * redrew (`meta.redrawnWidgets`: a checkbox that only switched its state isn't\n * one), else the ones it changed; the signed widget of a signing.\n */\nfunction redrawnWidgetsOf(event: DocumentEvent): readonly PlacedWidget[] {\n if (event.type === 'signatures.completed') {\n return event.signature.widget ? [event.signature.widget] : [];\n }\n if (!event.type.startsWith('forms.') || !('meta' in event)) return [];\n const meta = event.meta as {\n readonly changedWidgets?: readonly PlacedWidget[];\n readonly redrawnWidgets?: readonly PlacedWidget[];\n };\n return meta.redrawnWidgets ?? meta.changedWidgets ?? [];\n}\n\n/** Each widget drawn again takes a new picture version; one named by its page only, all of that page's. */\nfunction withRedrawnPictures(index: FieldIndex, redrawn: readonly PlacedWidget[]): FieldIndex {\n if (redrawn.length === 0) return index;\n const numbers = new Set<number>();\n for (const widget of redrawn) {\n if (widget.objectNumber) numbers.add(widget.objectNumber);\n else if (widget.page) {\n for (const row of index.snapshot?.widgets ?? []) {\n if (row.page.objectNumber === widget.page.objectNumber) numbers.add(widgetNumber(row));\n }\n }\n }\n if (numbers.size === 0) return index;\n const pictureVersions = { ...index.pictureVersions };\n for (const number of numbers) pictureVersions[number] = (pictureVersions[number] ?? 0) + 1;\n return { ...index, pictureVersions };\n}\n\n/**\n * A merged field split as it took a second widget: its widget half moved to a new number (one\n * of the event's widgets), and the row at the field's own number is gone with it.\n */\nfunction withoutSplitRow(index: FieldIndex, field: FormFieldDTO): FieldIndex {\n if (field.ref.kind !== 'objectNumber') return index;\n const own = field.ref.objectNumber;\n if (field.widgets.some((widget) => widget.objectNumber === own)) return index;\n const row = widgetRowOf(index, own);\n return row ? removeWidgets(index, [{ ref: row.ref, objectNumber: own, page: row.page }]) : index;\n}\n\nfunction foldFormFacts(index: FieldIndex, event: DocumentEvent): FieldIndex | MirrorReload {\n switch (event.type) {\n case 'forms.widgetAdded':\n return withoutSplitRow(\n upsertWidgets(upsertFields(index, [event.field]), event.widgets),\n event.field,\n );\n case 'forms.valueSet':\n case 'forms.widgetRemoved':\n case 'forms.restored':\n return upsertWidgets(upsertFields(index, [event.field]), event.widgets);\n case 'forms.updated':\n return withCalculationOrder(\n upsertWidgets(upsertFields(index, [event.field]), event.widgets),\n event.calculationOrder,\n );\n case 'forms.created': {\n // The first field of a document without a form creates its /AcroForm.\n const created = upsertWidgets(upsertFields(index, [event.field]), event.widgets);\n return withCalculationOrder(\n created.snapshot?.formKind === 'none'\n ? reindex(created, { ...created.snapshot, formKind: 'acroform' })\n : created,\n event.calculationOrder,\n );\n }\n case 'forms.calculationsReordered':\n return withCalculationOrder(index, event.calculationOrder);\n case 'forms.widgetDeleted': {\n const gone = removeWidgets(index, event.meta.changedWidgets);\n return event.field ? upsertFields(gone, [event.field]) : gone;\n }\n case 'forms.widgetRestored':\n return upsertWidgets(event.field ? upsertFields(index, [event.field]) : index, event.widgets);\n case 'forms.widgetUpdated':\n return upsertWidgets(index, [event.widget]);\n case 'forms.widgetsReordered':\n return reorderWidgetRows(index, event.page, event.order);\n case 'forms.deleted':\n return event.deleted\n ? withCalculationOrder(\n removeWidgets(removeField(index, event.deleted), event.meta.changedWidgets),\n event.calculationOrder,\n )\n : reload();\n // A repair reports only counts; the others remove pages, or paint their\n // widgets into the content.\n case 'forms.repaired':\n case 'pages.deleted':\n case 'pages.inserted':\n case 'pages.flattened':\n case 'annotations.flattened':\n case 'redaction.applied':\n return reload();\n default:\n return index;\n }\n}\n\n/** Whether any field has a keystroke, validate, calculate or format script. */\nexport function formHasScripts(index: FieldIndex): boolean {\n return (index.snapshot?.fields ?? []).some(\n ({ actions }) =>\n !!(actions?.keystroke || actions?.validate || actions?.calculate || actions?.format),\n );\n}\n\n/** The index with the calculation order a write answered, when the write changed it. */\nexport function withCalculationOrder(\n index: FieldIndex,\n order: readonly (FormFieldRef | null)[] | undefined,\n): FieldIndex {\n if (!order || !index.snapshot) return index;\n return reindex(index, { ...index.snapshot, calculationOrder: [...order] });\n}\n\nexport const fieldByKey = (index: FieldIndex, key: FieldKey): FormFieldDTO | null => {\n const position = index.byKey[key];\n return position === undefined ? null : (index.snapshot?.fields[position] ?? null);\n};\n\n/** The field a ref names: by object number, or by full name for `toFieldRef(name)`. */\nexport function fieldByRef(index: FieldIndex, ref: FormFieldRef): FormFieldDTO | null {\n const position = ref.kind === 'fqn' ? index.byName[ref.name] : index.byKey[fieldKeyOfRef(ref)];\n return position === undefined ? null : (index.snapshot?.fields[position] ?? null);\n}\n\n/** The key a field is known by, whichever ref names it: a name ref resolves to its field's key. */\nexport const canonicalKey = (index: FieldIndex, ref: FormFieldRef): FieldKey => {\n const field = fieldByRef(index, ref);\n return field ? fieldKeyOf(field) : fieldKeyOfRef(ref);\n};\n\nexport const fieldForWidget = (\n index: FieldIndex,\n annotObjectNumber: number,\n): FormFieldDTO | null => {\n const position = index.byWidget[annotObjectNumber];\n return position === undefined ? null : (index.snapshot?.fields[position] ?? null);\n};\n\n/** The fields whose value entry differs between two indexes (new fields included). */\nexport function fieldsWithChangedValues(previous: FieldIndex, next: FieldIndex): FormFieldDTO[] {\n return (next.snapshot?.fields ?? []).filter((field) => {\n const before = fieldByKey(previous, fieldKeyOf(field));\n return !before || JSON.stringify(valueEntryOf(before)) !== JSON.stringify(valueEntryOf(field));\n });\n}\n\nconst valueEntryOf = (field: FormFieldDTO): unknown =>\n 'valueEntry' in field ? field.valueEntry : null;\n\n// ── widgets (each page's, from the index's widget rows) ──────────────────────\n\n/**\n * How a widget looks in the PDF, as its own appearance settings say: `null`\n * where it has none of its own. A viewer that draws controls over the field\n * uses these, and its own settings where the field has nothing.\n */\nexport interface FormWidgetLook {\n /** The border color (`/MK /BC`), or `null` for a widget without a border. */\n readonly border: string | null;\n /** The border width in points. */\n readonly borderWidth: number;\n readonly borderStyle: 'solid' | 'dashed' | 'beveled' | 'inset' | 'underline';\n /** The background color (`/MK /BG`), or `null` for a see-through widget. */\n readonly background: string | null;\n /** The text color (`/DA`), or `null` when the field names none. */\n readonly color: string | null;\n /** One of the 14 standard PDF fonts, such as `'helvetica'`, or `null` when the field names none. */\n readonly fontFamily: string | null;\n /** The font size in points; `0` or `null` sizes the text to the box. */\n readonly fontSize: number | null;\n readonly textAlign: 'left' | 'center' | 'right';\n}\n\n/** One widget on its page: its page-space box and its look. */\nexport interface PageWidget {\n readonly box: Box;\n readonly look: FormWidgetLook;\n}\n\n/** One page's widgets: widget annotation object number → where it is and how it looks. */\nexport type PageWidgets = Readonly<Record<number, PageWidget>>;\n\n/** Whether a widget shows on screen: its `hidden` and `noView` flags hide it. */\nexport const shownOnScreen = (row: WidgetAnnotation): boolean => !row.hidden && !row.noView;\n\n/** The widgets one page shows, from the form's widget rows. */\nexport function pageWidgetsOf(index: FieldIndex, pageObjectNumber: number): PageWidgets {\n const widgets: Record<number, PageWidget> = {};\n for (const row of index.snapshot?.widgets ?? []) {\n if (row.page.objectNumber !== pageObjectNumber || row.ref.kind !== 'objectNumber') continue;\n if (!shownOnScreen(row)) continue;\n widgets[row.ref.objectNumber] = {\n box: row.rect,\n look: {\n border: row.color ?? null,\n borderWidth: row.strokeWidth ?? 1,\n borderStyle: row.borderStyle ?? 'solid',\n background: row.interiorColor ?? null,\n color: row.fontColor ?? null,\n fontFamily: row.fontFamily ?? null,\n fontSize: row.fontSize ?? null,\n textAlign: row.textAlign ?? 'left',\n },\n };\n }\n return widgets;\n}\n\n/** A widget a page shows: its address, the appearance state it shows, and how new its look is. */\nexport interface ShownWidget {\n readonly ref: AnnotationRef;\n /** Where it stands on its page, in page space: its picture's box, and the painter's. */\n readonly rect: Box;\n /** The state it shows (`/AS`), or `null` for a widget without states. */\n readonly appearanceState: string | null;\n /**\n * Its look in the view isn't its confirmed look yet (a value, a restyle, a\n * new field): its picture shows something older, so the painter draws it.\n */\n readonly pending: boolean;\n /** Its confirmed picture version: a picture drawn at another one shows another look. */\n readonly pictureVersion: number;\n}\n\n/** How new a shown widget's look is: whether it's pending, and its confirmed picture version. */\nexport type WidgetLookOf = (\n row: WidgetAnnotation,\n) => Pick<ShownWidget, 'pending' | 'pictureVersion'>;\n\nconst AT_REST: ReturnType<WidgetLookOf> = { pending: false, pictureVersion: 0 };\n\n/** The widgets one page shows, in the order the page draws them. */\nexport function shownWidgetsOf(\n index: FieldIndex,\n pageObjectNumber: number,\n lookOf: WidgetLookOf = () => AT_REST,\n): ShownWidget[] {\n const shown: ShownWidget[] = [];\n for (const row of index.snapshot?.widgets ?? []) {\n if (row.page.objectNumber !== pageObjectNumber || !shownOnScreen(row)) continue;\n shown.push({\n ref: row.ref,\n rect: row.rect,\n appearanceState: row.appearanceState,\n ...lookOf(row),\n });\n }\n return shown;\n}\n\nexport function widgetRowOf(index: FieldIndex, annotObjectNumber: number): WidgetAnnotation | null {\n const position = index.rowByWidget[annotObjectNumber];\n return position === undefined ? null : (index.snapshot?.widgets[position] ?? null);\n}\n\n/** A widget hit: the annotation under the point and the field it belongs to. */\nexport interface WidgetHit {\n readonly annotObjectNumber: number;\n readonly field: FormFieldDTO;\n /** The widget's page-space box. */\n readonly box: Box;\n}\n\nexport const boxContains = (box: Box, point: { x: number; y: number }): boolean =>\n point.x >= box.x &&\n point.x <= box.x + box.width &&\n point.y >= box.y &&\n point.y <= box.y + box.height;\n\n/** The widget under a page-space point; nested widgets resolve to the smallest box. */\nexport function widgetAt(\n index: FieldIndex,\n widgets: PageWidgets | undefined,\n point: { x: number; y: number },\n): WidgetHit | null {\n if (!widgets) return null;\n let best: WidgetHit | null = null;\n for (const [key, { box }] of Object.entries(widgets)) {\n if (!boxContains(box, point)) continue;\n const annotObjectNumber = Number(key);\n const field = fieldForWidget(index, annotObjectNumber);\n if (!field) continue;\n if (!best || box.width * box.height < best.box.width * best.box.height) {\n best = { annotObjectNumber, field, box };\n }\n }\n return best;\n}\n\n// ── session state ────────────────────────────────────────────────────────────\n\n/** The plugin's session state: nothing yet; a write in flight shows in the mirror's view. */\nexport type FormState = Readonly<Record<string, never>>;\n\nexport const initialFormState = (): FormState => ({});\n","/**\n * Reads over the mirrored field tree: fields, values, the joins between a\n * field and its widgets' rows, the field of the selected widget, and the\n * required-field check.\n */\nimport { memo, memoByKey } from '@embedpdf/core';\nimport {\n pageRefsEqual,\n type FormFieldDTO,\n type FormFieldValue,\n type FormKind,\n type WidgetAnnotation,\n} from '@embedpdf/engine-core/runtime';\n\nimport type {\n FormCapability,\n FormFilter,\n FormPlainValue,\n FormValidation,\n WidgetAddress,\n} from '../contract';\nimport { canonicalKey, fieldByKey, fieldByRef, fieldForWidget, widgetRowOf } from '../model';\nimport type { FormContext, FormServices } from '../services';\n\nconst NO_FIELDS: readonly FormFieldDTO[] = Object.freeze([]);\nconst NOTHING_SELECTED: readonly { readonly subtype: string; readonly ref: WidgetAddress }[] =\n Object.freeze([]);\n\n/** A widget address as the annotation object number the field index is keyed by. */\nexport const widgetObjectOf = (widget: WidgetAddress): number =>\n 'kind' in widget\n ? widget.kind === 'objectNumber'\n ? widget.objectNumber\n : 0\n : widget.objectNumber;\n\n/** A field's value in the write vocabulary, or null for a valueless or unsupported entry. */\nexport function valueOf(field: FormFieldDTO): FormFieldValue | null {\n const entry = field.valueEntry;\n if (entry.kind === 'none' || entry.kind === 'unsupported') return null;\n switch (field.family) {\n case 'text':\n return { value: field.value };\n case 'checkbox':\n return { checked: field.checked };\n case 'radio':\n return { value: field.value === 'Off' ? null : field.value };\n case 'combobox':\n return { value: field.value === '' ? null : field.value };\n case 'listbox':\n return { selectedValues: [...field.selectedValues] };\n default:\n return null;\n }\n}\n\n/** A field's value as plain data: what `exportValues()` gives and `importValues()` takes. */\nexport function plainValueOf(field: FormFieldDTO): FormPlainValue | undefined {\n const value = valueOf(field);\n if (!value) return undefined;\n if ('checked' in value) return value.checked;\n if ('selectedValues' in value) return value.selectedValues;\n return value.value;\n}\n\n/**\n * The write a plain value makes for a field of this family, or null when the\n * family can't take it (a list given `true`, a value for a push button).\n */\nexport function writeOfPlainValue(\n field: FormFieldDTO,\n value: FormPlainValue,\n): FormFieldValue | null {\n switch (field.family) {\n case 'checkbox':\n if (typeof value === 'boolean') return { checked: value };\n return typeof value === 'string' || value === null ? { value } : null;\n case 'text':\n case 'radio':\n case 'combobox':\n return typeof value === 'string' || value === null ? { value } : null;\n case 'listbox':\n if (value === null) return { selectedValues: [] };\n if (typeof value === 'string') return { selectedValues: [value] };\n return Array.isArray(value) ? { selectedValues: [...value] } : null;\n default:\n return null;\n }\n}\n\n/** Whether a field holds nothing a required check would accept. */\nfunction isEmpty(field: FormFieldDTO): boolean {\n switch (field.family) {\n case 'text':\n case 'combobox':\n return field.value === '';\n case 'checkbox':\n return !field.checked;\n case 'radio':\n return field.value === 'Off' || field.value === '';\n case 'listbox':\n return field.selectedValues.length === 0;\n case 'signature':\n return field.valueEntry.kind === 'none';\n default:\n return false;\n }\n}\n\nexport function createFieldReads(\n ctx: FormContext,\n { fields, rights, siblings }: Pick<FormServices, 'fields' | 'rights' | 'siblings'>,\n) {\n const all = (): readonly FormFieldDTO[] => fields.view().snapshot?.fields ?? NO_FIELDS;\n\n const list = (filter?: FormFilter): readonly FormFieldDTO[] => {\n if (!filter) return all();\n const page = filter.page === undefined ? undefined : ctx.getPage(filter.page)?.ref;\n // A page that isn't in the document has no fields.\n if (filter.page !== undefined && !page) return NO_FIELDS;\n return all().filter(\n (field) =>\n (!filter.family || field.family === filter.family) &&\n (filter.name === undefined || field.name === filter.name) &&\n (!page || field.widgets.some((widget) => widget.page && pageRefsEqual(widget.page, page))),\n );\n };\n\n // One value object per field while its value stays the same, so a reader\n // that compares by reference re-renders only when this field's value\n // changes: a fill shows before the engine answers, and the answer brings the\n // same value in a new field.\n const valueByKey = memoByKey(\n (key: string) => {\n const field = fieldByKey(fields.view(), key);\n return [field ? JSON.stringify(valueOf(field)) : null];\n },\n (_key, value): FormFieldValue | null =>\n value === null ? null : (JSON.parse(value) as FormFieldValue | null),\n { maxEntries: 1024 },\n );\n\n // One array per field while its widgets' rows stay the same objects.\n const widgetsByKey = memoByKey(\n (key: string) => {\n const index = fields.view();\n const field = fieldByKey(index, key);\n return (field?.widgets ?? []).map((widget) => widgetRowOf(index, widget.objectNumber));\n },\n (_key, ...rows): readonly WidgetAnnotation[] =>\n Object.freeze(rows.filter((row): row is WidgetAnnotation => row !== null)),\n { maxEntries: 1024 },\n );\n\n const exportValues = memo(\n () => [fields.view()],\n (index): Readonly<Record<string, FormPlainValue>> => {\n const values: Record<string, FormPlainValue> = {};\n for (const field of index.snapshot?.fields ?? []) {\n const value = plainValueOf(field);\n if (value !== undefined) values[field.name] = value;\n }\n return values;\n },\n );\n\n /** Where a field first shows: its page's index, then top to bottom, then left to right. */\n const placeOf = (field: FormFieldDTO): readonly [number, number, number] => {\n const index = fields.view();\n const row = field.widgets\n .map((widget) => widgetRowOf(index, widget.objectNumber))\n .find((candidate) => candidate !== null);\n const page = row ? (ctx.getPage(row.page)?.index ?? Infinity) : Infinity;\n return [page, row?.rect.y ?? 0, row?.rect.x ?? 0];\n };\n\n // The page order is an input too: moving a page moves its fields in the list.\n // Only the fields the user may fill in count: another signer's empty field\n // isn't theirs to fill.\n const validate = memo(\n () => [fields.view(), ctx.document(), rights.key()],\n (index): FormValidation => {\n const missing = (index.snapshot?.fields ?? [])\n .filter((field) => field.required && isEmpty(field) && rights.mayFill(field))\n .map((field) => ({ field, place: placeOf(field) }))\n .sort(\n (left, right) =>\n left.place[0] - right.place[0] ||\n left.place[1] - right.place[1] ||\n left.place[2] - right.place[2],\n )\n .map(({ field }) => field);\n return { valid: missing.length === 0, missing };\n },\n );\n\n // The selection belongs to the annotation plugin: a widget is selected in\n // design mode, where widgets are boxes like any annotation.\n const getSelectedField = memo(\n () => [fields.view(), siblings.annotation()?.selection.list() ?? NOTHING_SELECTED],\n (index, selected): FormFieldDTO | null => {\n const [annotation] = selected;\n if (selected.length !== 1 || !annotation?.subtype.startsWith('widget')) return null;\n return fieldForWidget(index, widgetObjectOf(annotation.ref));\n },\n );\n\n return {\n api: {\n getSnapshot: () => fields.view().snapshot,\n getStatus: fields.getStatus,\n getFormKind: (): FormKind => fields.view().snapshot?.formKind ?? 'none',\n refresh: (options) => ctx.cancellable(options?.signal, fields.refresh()),\n get: (ref) => fieldByRef(fields.view(), ref),\n getFieldForWidget: (widget) => fieldForWidget(fields.view(), widgetObjectOf(widget)),\n getWidget: (widget) => widgetRowOf(fields.view(), widgetObjectOf(widget)),\n getWidgets: (ref) => widgetsByKey(canonicalKey(fields.view(), ref)),\n list,\n getValue: (ref) => valueByKey(canonicalKey(fields.view(), ref)),\n getSelectedField,\n validate,\n exportValues,\n } satisfies Partial<FormCapability>,\n };\n}\n","/**\n * A field's settings, described for a settings panel the way an annotation\n * kind describes its look: which settings the field's family has, how each is\n * edited, and its value. `update()` writes them.\n */\nimport { memoByKey } from '@embedpdf/core';\nimport type { FormFieldDTO, FormFieldRef } from '@embedpdf/engine-core/runtime';\n\nimport type { FormCapability, FormFieldSetting, FormFieldSettings } from '../contract';\nimport { canonicalKey, fieldByKey } from '../model';\nimport type { FormServices } from '../services';\n\n/** What every field has. */\nconst COMMON: readonly FormFieldSetting[] = [\n { key: 'name', control: 'text', label: 'Name', labelKey: 'form.settings.name' },\n { key: 'alternateName', control: 'text', label: 'Tooltip', labelKey: 'form.settings.tooltip' },\n { key: 'required', control: 'flag', label: 'Required', labelKey: 'form.settings.required' },\n { key: 'readOnly', control: 'flag', label: 'Read-only', labelKey: 'form.settings.readOnly' },\n { key: 'noExport', control: 'flag', label: \"Don't export\", labelKey: 'form.settings.noExport' },\n];\n\nconst DEFAULT_VALUE = { label: 'Default value', labelKey: 'form.settings.defaultValue' } as const;\nconst OPTIONS: FormFieldSetting = {\n key: 'options',\n control: 'options',\n label: 'Options',\n labelKey: 'form.settings.options',\n};\n\n/** What each family adds. */\nfunction familySettings(field: FormFieldDTO): readonly FormFieldSetting[] {\n switch (field.family) {\n case 'text':\n return [\n { key: 'defaultValue', control: 'text', ...DEFAULT_VALUE },\n {\n key: 'maxLength',\n control: 'number',\n label: 'Maximum length',\n labelKey: 'form.settings.maxLength',\n min: 1,\n },\n {\n key: 'multiline',\n control: 'flag',\n label: 'Several lines',\n labelKey: 'form.settings.multiline',\n },\n { key: 'password', control: 'flag', label: 'Password', labelKey: 'form.settings.password' },\n {\n key: 'comb',\n control: 'flag',\n label: 'One character per box',\n labelKey: 'form.settings.comb',\n },\n ];\n case 'radio':\n return [\n {\n key: 'radiosInUnison',\n control: 'flag',\n label: 'Buttons with one value turn on together',\n labelKey: 'form.settings.radiosInUnison',\n },\n {\n key: 'noToggleToOff',\n control: 'flag',\n label: 'Keep one on',\n labelKey: 'form.settings.keepOneOn',\n },\n ];\n case 'combobox':\n return [\n OPTIONS,\n {\n key: 'edit',\n control: 'flag',\n label: 'Allow typing',\n labelKey: 'form.settings.allowTyping',\n },\n {\n key: 'defaultValue',\n control: 'choice',\n ...DEFAULT_VALUE,\n options: field.options.map((option) => option.value),\n free: field.edit,\n },\n ];\n case 'listbox':\n return [\n OPTIONS,\n {\n key: 'multiSelect',\n control: 'flag',\n label: 'Several choices',\n labelKey: 'form.settings.multiSelect',\n },\n {\n key: 'defaultValue',\n control: 'choices',\n ...DEFAULT_VALUE,\n options: field.options.map((option) => option.value),\n },\n ];\n default:\n return [];\n }\n}\n\n/** Each setting's value, as the field holds it. */\nfunction valuesOf(\n field: FormFieldDTO,\n settings: readonly FormFieldSetting[],\n): Record<string, unknown> {\n const held = field as unknown as Record<string, unknown>;\n const values: Record<string, unknown> = {};\n for (const { key } of settings) {\n if (key === 'name') values.name = field.name.slice(field.name.lastIndexOf('.') + 1);\n else if (key === 'alternateName') values.alternateName = field.alternateName ?? '';\n else values[key] = held[key] ?? null;\n }\n return values;\n}\n\nexport function createFieldSettings({ fields }: Pick<FormServices, 'fields'>) {\n const settingsByKey = memoByKey(\n (key: string) => [fieldByKey(fields.view(), key)],\n (_key, field): FormFieldSettings | null => {\n if (!field) return null;\n const properties = [...COMMON, ...familySettings(field)];\n return { properties, values: valuesOf(field, properties) };\n },\n { maxEntries: 256 },\n );\n return {\n api: {\n getFieldSettings: (ref: FormFieldRef) => settingsByKey(canonicalKey(fields.view(), ref)),\n } satisfies Partial<FormCapability>,\n };\n}\n","/**\n * The widget projection: what a framework draws for one page's fields. Pure\n * data in page space (top-left origin, y-down PDF points), the same space\n * annotation render items use, so layers position with the page transform\n * and never re-derive scale.\n *\n * Where a widget is and how it looks come from the form's widget rows (`/Rect`\n * and `/MK`), identity, value and behavior from its field.\n */\nimport type {\n AnnotationRef,\n FormFieldDTO,\n FormFieldOption,\n FormFieldRef,\n} from '@embedpdf/engine-core/runtime';\n\nimport {\n fieldKeyOf,\n type Box,\n type FieldIndex,\n type FieldKey,\n type FormWidgetLook,\n type PageWidget,\n type PageWidgets,\n} from '../model';\n\nexport type { Box, FormWidgetLook } from '../model';\n\ninterface FormWidgetItemBase {\n key: FieldKey;\n /** The field this widget belongs to: what the write verbs take. */\n fieldRef: FormFieldRef;\n /** The widget's annotation object number. */\n annotObjectNumber: number;\n /** The widget's annotation address (null until the engine has placed it). */\n annotationRef: AnnotationRef | null;\n /** Where the widget is on its page. */\n box: Box;\n /** How the widget looks in the PDF. */\n look: FormWidgetLook;\n /** A read-only field, no permission to fill, filling it turned off (`fillable`), or a write on its way: draw it, don't take input. */\n disabled: boolean;\n /** Accessible name: the field's tooltip (`/TU`) when it has one, else its full name. */\n label: string;\n}\n\n/** One widget as a fill control draws it: where, how it looks, its control and its value. */\nexport type FormWidgetItem = FormWidgetItemBase &\n (\n | {\n control: 'text';\n value: string;\n multiline: boolean;\n password: boolean;\n maxLength: number | null;\n comb: boolean;\n }\n | {\n control: 'toggle';\n kind: 'checkbox' | 'radio';\n checked: boolean;\n /** The export value that checks this widget. */\n exportValue: string;\n }\n | {\n control: 'choice';\n kind: 'combo' | 'list';\n edit: boolean;\n multi: boolean;\n options: FormFieldOption[];\n selected: string[];\n }\n | { control: 'button' }\n /**\n * A signature field's widget. `signed`: it carries a `/V` (a signature\n * dictionary), so the field is final and its appearance sealed, and the\n * control shows what the signature says rather than signing. Unsigned, it\n * is \"sign here\": signing belongs to the signature plugin.\n */\n | { control: 'signature'; signed: boolean }\n );\n\n/**\n * Project one widget of a field into a fill control; `fillable`: the user may\n * fill the field in (a signature field: sign it). Null for families with no\n * fill control.\n */\nexport function projectWidget(\n field: FormFieldDTO,\n annotObjectNumber: number,\n widget: PageWidget,\n fillable: boolean,\n): FormWidgetItem | null {\n const key = fieldKeyOf(field);\n const base: FormWidgetItemBase = {\n key,\n fieldRef: field.ref,\n annotObjectNumber,\n annotationRef:\n field.widgets.find((candidate) => candidate.objectNumber === annotObjectNumber)?.ref ?? null,\n box: widget.box,\n look: widget.look,\n disabled: field.readOnly || !fillable,\n label: field.alternateName ?? field.name,\n };\n switch (field.family) {\n case 'text':\n return {\n ...base,\n control: 'text',\n value: field.value,\n multiline: field.multiline,\n password: field.password,\n maxLength: field.maxLength,\n comb: field.comb,\n };\n case 'checkbox': {\n const toggle = field.widgets.find(\n (candidate) => candidate.objectNumber === annotObjectNumber,\n );\n return {\n ...base,\n control: 'toggle',\n kind: 'checkbox',\n checked: field.checked,\n exportValue: toggle && 'exportValue' in toggle ? toggle.exportValue : field.exportValue,\n };\n }\n case 'radio': {\n const toggle = field.widgets.find(\n (candidate) => candidate.objectNumber === annotObjectNumber,\n );\n return {\n ...base,\n control: 'toggle',\n kind: 'radio',\n checked: toggle && 'checked' in toggle ? toggle.checked : false,\n exportValue: toggle && 'exportValue' in toggle ? toggle.exportValue : '',\n };\n }\n case 'combobox':\n return {\n ...base,\n control: 'choice',\n kind: 'combo',\n edit: field.edit,\n multi: false,\n options: field.options,\n selected: field.value === '' ? [] : [field.value],\n };\n case 'listbox':\n return {\n ...base,\n control: 'choice',\n kind: 'list',\n edit: false,\n multi: field.multiSelect,\n options: field.options,\n selected: field.selectedValues,\n };\n case 'pushbutton':\n return { ...base, control: 'button' };\n case 'signature':\n return { ...base, control: 'signature', signed: field.valueEntry.kind !== 'none' };\n default:\n return null;\n }\n}\n\n/**\n * Project one page's widgets into fill controls, each disabled when the user\n * may not fill its field in, or sign it (`mayFill`). Widgets whose page has not loaded (or\n * that are direct objects with no join key) are skipped; the projection runs\n * again when the page's widgets land.\n */\nexport function fillItems(\n index: FieldIndex,\n pageObjectNumber: number,\n widgets: PageWidgets | undefined,\n mayFill: (field: FormFieldDTO) => boolean,\n): FormWidgetItem[] {\n if (!index.snapshot || !widgets) return [];\n const items: FormWidgetItem[] = [];\n for (const field of index.snapshot.fields) {\n for (const widget of field.widgets) {\n if (widget.page?.objectNumber !== pageObjectNumber) continue;\n const placed = widgets[widget.objectNumber];\n if (!placed) continue;\n const item = projectWidget(field, widget.objectNumber, placed, mayFill(field));\n if (item) items.push(item);\n }\n }\n return items;\n}\n","/**\n * The widgets' reads: each page's widgets (from the form's widget rows), the\n * ones it shows for the form layer to paint (and the painter's scene of each,\n * `services/looks.ts`), the fill projection with the session's fill permission\n * folded in, and the widget hit test.\n */\nimport { memoByKey } from '@embedpdf/core';\nimport type { FormFieldDTO, FormFieldFamily, PageRef } from '@embedpdf/engine-core/runtime';\n\nimport type { FillableFields } from '../contract';\nimport type { FormHostCapability } from '../host-contract';\nimport { pageWidgetsOf, widgetAt, type Box, type ShownWidget, type WidgetHit } from '../model';\nimport type { FormContext, FormServices } from '../services';\nimport { fillItems, type FormWidgetItem } from './fill-items';\n\nconst NO_WIDGETS: readonly FormWidgetItem[] = Object.freeze([]);\n\n/** Whether the `fillable` setting lets people fill in a field of this family by hand. */\nconst isFillableByHand = (fillable: FillableFields, family: FormFieldFamily): boolean =>\n typeof fillable === 'boolean' ? fillable : fillable.includes(family);\nconst NOTHING_SHOWN: readonly ShownWidget[] = Object.freeze([]);\n\nexport function createWidgetReads(\n ctx: FormContext,\n {\n fields,\n rights,\n looks,\n pictures,\n }: Pick<FormServices, 'fields' | 'rights' | 'looks' | 'pictures'>,\n) {\n /** Every page's widgets come with the form: one read for the document. */\n const loadWidgets = (_page: PageRef): Promise<void> => fields.settled();\n\n const widgetsOn = memoByKey(\n (pageObjectNumber: number) => [fields.view()],\n (pageObjectNumber, index) => pageWidgetsOf(index, pageObjectNumber),\n );\n\n /** The widget under a page point. */\n const getWidgetAt = (\n pageArgument: PageRef | number,\n point: { x: number; y: number },\n ): WidgetHit | null => {\n const page = ctx.getPage(pageArgument)?.ref;\n if (!page) return null;\n return widgetAt(fields.view(), widgetsOn(page.objectNumber), point);\n };\n\n // A field the user may not fill in (a signature field: sign), or one the\n // `fillable` setting leaves out, has its widgets `disabled`, the same flag a\n // field's read-only flag sets, so the controls never offer a write the\n // engine would refuse, nor one the app turned off.\n const fillable = (): FillableFields => ctx.settings().get().fillable;\n const mayWrite = (field: FormFieldDTO): boolean =>\n isFillableByHand(fillable(), field.family) &&\n (field.family === 'signature' ? rights.maySign(field) : rights.mayFill(field));\n const widgetsOfPage = memoByKey(\n (pageObjectNumber: number) => [\n fields.view(),\n widgetsOn(pageObjectNumber),\n rights.key(),\n fillable(),\n ],\n (pageObjectNumber, index, widgets): readonly FormWidgetItem[] =>\n fillItems(index, pageObjectNumber, widgets, mayWrite),\n );\n\n /** The page's content box (`{0, 0, width, height}`), for page-bound placement. */\n const getPageBox = (page: PageRef): Box | null => {\n const size = ctx.getPage(page)?.size;\n return size ? { x: 0, y: 0, width: size.width, height: size.height } : null;\n };\n\n return {\n getPageBox,\n api: {\n listWidgets: (pageArgument) => {\n const page = ctx.getPage(pageArgument)?.ref;\n return page ? widgetsOfPage(page.objectNumber) : NO_WIDGETS;\n },\n listShownWidgets: (pageArgument) => {\n const page = ctx.getPage(pageArgument)?.ref;\n return page ? looks.listShownWidgets(page.objectNumber) : NOTHING_SHOWN;\n },\n getAppearanceEpoch: pictures.epoch,\n renderAppearances: pictures.render,\n getWidgetPainting: looks.getWidgetPainting,\n getTextEditorLayout: looks.getTextEditorLayout,\n ensureLoaded: loadWidgets,\n getWidgetAt,\n getPageBox,\n } satisfies Partial<FormHostCapability>,\n };\n}\n","/**\n * What this session asked for and the engine hasn't answered, on top of the\n * form: `predictFormOp`, the fields mirror's `predict` (the view replays it\n * op by op), and `undoLookOf`, what undoing a change looks like. Both follow\n * the engine's own rules (engine-core's form prediction helpers). Pure.\n */\nimport type { PredictedOp } from '@embedpdf/core';\nimport {\n annotationKey,\n fieldAfterReset,\n fieldAfterValue,\n formFieldAfter,\n formFieldOfDraft,\n reorderedList,\n widgetAfterPatch,\n widgetsAfterDisplay,\n type AnnotationRef,\n type FieldWithWidgets,\n type FormFieldDTO,\n type FormFieldRef,\n type FormWidget,\n type WidgetAnnotation,\n} from '@embedpdf/engine-core/runtime';\n\nimport {\n fieldByKey,\n fieldByRef,\n fieldForWidget,\n fieldKeyOf,\n fieldKeyOfRef,\n indexFields,\n removeField,\n removeWidgets,\n reorderWidgetRows,\n upsertFields,\n upsertWidgets,\n widgetRowOf,\n withCalculationOrder,\n type FieldIndex,\n type FieldKey,\n} from '../model';\n\nconst widgetNumber = (widget: WidgetAnnotation): number =>\n widget.ref.kind === 'objectNumber' ? widget.ref.objectNumber : 0;\n\n/** The rows of a field's widgets, in its widget order. */\nfunction rowsOfField(index: FieldIndex, field: FormFieldDTO): WidgetAnnotation[] {\n return field.widgets.flatMap((widget) => {\n const row = widgetRowOf(index, widget.objectNumber);\n return row ? [row] : [];\n });\n}\n\n/** A field and the rows of its widgets, as the index holds them. */\nconst withRows = (index: FieldIndex, field: FormFieldDTO): FieldWithWidgets => ({\n field,\n widgets: rowsOfField(index, field),\n});\n\n/** Fields and their widget rows put into the index, all at once. */\nfunction withFields(index: FieldIndex, parts: readonly FieldWithWidgets[]): FieldIndex {\n if (parts.length === 0) return index;\n return upsertWidgets(\n upsertFields(\n index,\n parts.map((part) => part.field),\n ),\n parts.flatMap((part) => part.widgets),\n );\n}\n\n/** The fields a reset of the whole form puts back: the ones that hold a value. */\nconst resetTargets = (index: FieldIndex): FormFieldDTO[] =>\n (index.snapshot?.fields ?? []).filter((field) => RESET_FAMILIES.has(field.family));\n\nconst RESET_FAMILIES = new Set(['text', 'checkbox', 'radio', 'combobox', 'listbox']);\n\n/**\n * One op of a change this session staged, shown before the engine answers,\n * by the engine's own rules (`fieldAfterValue`, `fieldAfterReset`,\n * `widgetsAfterDisplay`, `formFieldOfDraft`, `formFieldAfter`,\n * `widgetAfterPatch`): what the fields and their widgets hold after it. An op\n * those rules refuse shows nothing; one whose values only the engine's schemas\n * refuse shows until the engine's refusal takes the change away.\n * A create shows once it names its numbers; taking a widget out of its field\n * shows once the engine answers.\n *\n * The view replays every pending change each time any change is staged; the\n * same op over the same form gives the same form, so a field keeps its object\n * while nothing about it changed.\n */\nexport function predictFormOp(index: FieldIndex, op: PredictedOp): FieldIndex {\n let byOp = predictions.get(index);\n const known = byOp?.get(op);\n if (known) return known;\n const next = predictOnce(index, op);\n if (!byOp) predictions.set(index, (byOp = new WeakMap()));\n byOp.set(op, next);\n return next;\n}\n\nconst predictions = new WeakMap<FieldIndex, WeakMap<PredictedOp, FieldIndex>>();\n\nfunction predictOnce(index: FieldIndex, op: PredictedOp): FieldIndex {\n try {\n switch (op.type) {\n case 'forms.setValue': {\n const field = fieldByRef(index, op.field);\n return field\n ? withFields(index, [fieldAfterValue(withRows(index, field), op.value)])\n : index;\n }\n case 'forms.reset': {\n const targets = op.fields\n ? op.fields.flatMap((ref) => fieldByRef(index, ref) ?? [])\n : resetTargets(index);\n return withFields(\n index,\n targets.map((field) => fieldAfterReset(withRows(index, field))),\n );\n }\n case 'forms.setDisplay': {\n const field = fieldByRef(index, op.field);\n if (!field) return index;\n return upsertWidgets(index, widgetsAfterDisplay(rowsOfField(index, field), op.display));\n }\n case 'forms.restore':\n return withFields(index, [op]);\n case 'forms.restoreWidget': {\n const restored = upsertWidgets(index, [op.widget]);\n return op.field ? upsertFields(restored, [op.field]) : restored;\n }\n case 'forms.create':\n return createdField(index, op);\n case 'forms.update': {\n const field = fieldByRef(index, op.field);\n return field\n ? withFields(index, [formFieldAfter(withRows(index, field), op.patch)])\n : index;\n }\n case 'forms.delete': {\n const field = fieldByRef(index, op.field);\n if (!field || !index.snapshot) return index;\n const gone = removeWidgets(removeField(index, field.ref), field.widgets);\n return withCalculationOrder(\n gone,\n index.snapshot.calculationOrder.filter((ref) => !sameField(ref, field.ref)),\n );\n }\n case 'forms.updateWidget': {\n const row = rowOfRef(index, op.widget);\n return row ? upsertWidgets(index, [widgetAfterPatch(row, op.patch)]) : index;\n }\n case 'forms.deleteWidget': {\n const row = rowOfRef(index, op.widget);\n if (!row) return index;\n const number = widgetNumber(row);\n const field = fieldForWidget(index, number);\n const gone = removeWidgets(index, [{ objectNumber: number, page: row.page } as FormWidget]);\n if (!field) return gone;\n const widgets = field.widgets.filter((widget) => widget.objectNumber !== number);\n return upsertFields(gone, [{ ...field, widgets } as FormFieldDTO]);\n }\n case 'forms.reorderWidgets': {\n if (!index.snapshot) return index;\n const onPage = index.snapshot.widgets\n .filter((row) => row.page.objectNumber === op.page.objectNumber)\n .map((row) => row.ref);\n const order = reorderedList(onPage, op.widgets, op.position, annotationKey);\n return reorderWidgetRows(index, op.page, order);\n }\n case 'forms.reorderCalculations': {\n if (!index.snapshot) return index;\n const order = index.snapshot.calculationOrder.filter(\n (ref): ref is FormFieldRef => ref !== null,\n );\n return withCalculationOrder(\n index,\n reorderedList(order, op.fields, op.position, fieldKeyOfRef),\n );\n }\n default:\n return index;\n }\n } catch {\n return index;\n }\n}\n\n/** A widget's row, by its annotation ref. */\nconst rowOfRef = (index: FieldIndex, ref: AnnotationRef): WidgetAnnotation | null =>\n ref.kind === 'objectNumber' ? widgetRowOf(index, ref.objectNumber) : null;\n\nconst sameField = (left: FormFieldRef | null, right: FormFieldRef): boolean =>\n left !== null && fieldKeyOfRef(left) === fieldKeyOfRef(right);\n\n/**\n * `forms.create`, once it names the numbers it takes: the field and its\n * widgets as a read of them returns them, last in the form, and last in the\n * calculation order when it calculates.\n */\nfunction createdField(\n index: FieldIndex,\n op: Extract<PredictedOp, { type: 'forms.create' }>,\n): FieldIndex {\n const placements = op.draft.widgets ?? [];\n const numbers = op.widgetObjectNumbers ?? [];\n if (op.objectNumber === undefined || numbers.length !== placements.length) return index;\n const snapshot = index.snapshot;\n if (!snapshot || fieldByRef(index, { kind: 'objectNumber', objectNumber: op.objectNumber })) {\n return index;\n }\n const created = formFieldOfDraft(op.draft, {\n objectNumber: op.objectNumber,\n widgets: placements.map((placement, at) => ({\n kind: 'objectNumber' as const,\n page: placement.page,\n objectNumber: numbers[at]!,\n })),\n });\n // The first field of a document without a form creates its /AcroForm.\n const formed =\n snapshot.formKind === 'none'\n ? indexFields({ ...snapshot, formKind: 'acroform' }, index.pictureVersions)\n : index;\n const next = withFields(formed, [created]);\n return op.draft.actions?.calculate\n ? withCalculationOrder(next, [...snapshot.calculationOrder, created.field.ref])\n : next;\n}\n\n/** The fields a change's ops write a value or a look to, each once, in op order. */\nexport function fieldsNamedBy(index: FieldIndex, ops: readonly PredictedOp[]): FormFieldDTO[] {\n const named = new Map<FieldKey, FormFieldDTO>();\n const add = (field: FormFieldDTO | null): void => {\n if (field && !named.has(fieldKeyOf(field))) named.set(fieldKeyOf(field), field);\n };\n for (const op of ops) {\n switch (op.type) {\n case 'forms.setValue':\n case 'forms.setDisplay':\n case 'forms.setAppearanceText':\n add(fieldByRef(index, op.field));\n break;\n case 'forms.reset':\n for (const field of op.fields\n ? op.fields.map((ref) => fieldByRef(index, ref))\n : resetTargets(index)) {\n add(field);\n }\n break;\n default:\n break;\n }\n }\n return [...named.values()];\n}\n\n/** `index` with these fields, and their widget rows, as `source` holds them. */\nexport function withFieldsFrom(\n index: FieldIndex,\n source: FieldIndex,\n fields: readonly FormFieldDTO[],\n): FieldIndex {\n return withFields(\n index,\n fields.flatMap((field) => {\n const held = fieldByKey(source, fieldKeyOf(field));\n return held ? [withRows(source, held)] : [];\n }),\n );\n}\n\n/** A field and its widgets back as `index` holds them. */\nconst restoreOf = (index: FieldIndex, field: FormFieldDTO): PredictedOp => ({\n type: 'forms.restore',\n field,\n widgets: rowsOfField(index, field),\n});\n\n/** A widget's row back as `index` holds it, with its field as it is there. */\nconst restoreWidgetOf = (index: FieldIndex, row: WidgetAnnotation): PredictedOp => ({\n type: 'forms.restoreWidget',\n widget: row,\n field: fieldForWidget(index, widgetNumber(row)),\n});\n\n/** What undoing one op looks like, over the form it applies to. */\nfunction undoOfOp(index: FieldIndex, op: PredictedOp): PredictedOp[] {\n switch (op.type) {\n case 'forms.create':\n return op.objectNumber === undefined\n ? []\n : [\n {\n type: 'forms.delete',\n field: { kind: 'objectNumber', objectNumber: op.objectNumber },\n },\n ];\n case 'forms.update':\n case 'forms.delete': {\n const field = fieldByRef(index, op.field);\n return field ? [restoreOf(index, field)] : [];\n }\n case 'forms.updateWidget':\n case 'forms.deleteWidget': {\n const row = rowOfRef(index, op.widget);\n return row ? [restoreWidgetOf(index, row)] : [];\n }\n case 'forms.removeWidget': {\n const field = fieldByRef(index, op.field);\n const row = rowOfRef(index, op.widget);\n return [\n ...(row ? [restoreWidgetOf(index, row)] : []),\n ...(field ? [restoreOf(index, field)] : []),\n ];\n }\n case 'forms.reorderWidgets': {\n // The page's whole order as it was.\n const widgets = (index.snapshot?.widgets ?? [])\n .filter((row) => row.page.objectNumber === op.page.objectNumber)\n .map((row) => row.ref);\n return [{ type: 'forms.reorderWidgets', page: op.page, widgets, position: 'start' }];\n }\n case 'forms.reorderCalculations': {\n const fields = (index.snapshot?.calculationOrder ?? []).filter(\n (ref): ref is FormFieldRef => ref !== null,\n );\n return [{ type: 'forms.reorderCalculations', fields, position: 'start' }];\n }\n default:\n return fieldsNamedBy(index, [op]).map((field) => restoreOf(index, field));\n }\n}\n\n/**\n * What undoing `ops` looks like, read off the form they apply to, each over\n * what the ones before it left: the ops that bring the form back, the last\n * op's first. Drawing only: the engine undoes a change by its own record of\n * it.\n */\nexport function undoLookOf(before: FieldIndex, ops: readonly PredictedOp[]): PredictedOp[] {\n const undo: PredictedOp[][] = [];\n let current = before;\n for (const op of ops) {\n undo.push(undoOfOp(current, op));\n current = predictFormOp(current, op);\n }\n return undo.reverse().flat();\n}\n","/**\n * The field tree, mirrored from the engine. It changes only by loads and by\n * confirmed form events, whoever caused them: the plugin's own writes, the\n * document's scripts, or another session. Its view shows this session's\n * pending changes on top (`predictFormOp`). This is also the one place the\n * value and field events fire.\n */\nimport type { Mirror } from '@embedpdf/core';\n\nimport { emptyFieldIndex, foldFormEvent, indexLoadedFields, type FieldIndex } from '../model';\nimport { predictFormOp } from './predict';\nimport type { FormContext } from '../services/context';\nimport type { FormEvents } from '../services/events';\n\nexport function createFieldsMirror(ctx: FormContext, events: FormEvents): Mirror<FieldIndex> {\n const fields: Mirror<FieldIndex> = ctx.mirror<FieldIndex>({\n name: 'fields',\n initial: emptyFieldIndex,\n // A reviewer-shaped token without `doc.forms.read` is a common narrowed\n // scope: skip the doomed read and report `forbidden`.\n readable: () => ctx.allows('doc.forms.read'),\n load: async (doc) => ({ value: indexLoadedFields(fields.get(), await doc.forms.list()) }),\n fold: foldFormEvent,\n predict: predictFormOp,\n changed: ({ cause, event, next }) => {\n if (cause === 'load') {\n if (next.snapshot) events.resynced.emit({ snapshot: next.snapshot });\n return;\n }\n if (!event || !('origin' in event)) return;\n const { origin } = event;\n switch (event.type) {\n case 'forms.valueSet':\n events.valueChanged.emit({ field: event.field, origin });\n return;\n case 'forms.created':\n events.fieldCreated.emit({ field: event.field, origin });\n return;\n case 'forms.updated':\n case 'forms.widgetAdded':\n case 'forms.widgetRemoved':\n events.fieldUpdated.emit({ field: event.field, origin });\n return;\n case 'forms.widgetDeleted':\n case 'forms.widgetRestored':\n if (event.field) events.fieldUpdated.emit({ field: event.field, origin });\n return;\n case 'forms.deleted':\n if (event.deleted) events.fieldDeleted.emit({ ref: event.deleted, origin });\n return;\n default:\n return;\n }\n },\n });\n return fields;\n}\n","/**\n * Whether the form's widgets are lent to the annotation plugin now\n * (write/lending.ts): the session may design, the annotation plugin is there,\n * and the active tool doesn't fill. Then the annotation layer draws and edits\n * the widgets, and the form layer leaves them out.\n */\nimport { InteractionToken } from '@embedpdf/plugin-interaction/contract/host';\n\nimport type { FormContext } from './context';\nimport type { FormSiblings } from './siblings';\n\nexport interface FormDesign {\n lending(): boolean;\n}\n\nexport function createDesign(ctx: FormContext, siblings: FormSiblings): FormDesign {\n const interaction = ctx.tryGet(InteractionToken);\n return {\n lending: () =>\n siblings.annotation() !== null &&\n interaction !== null &&\n ctx.allows('doc.forms.modify') &&\n !(interaction.getActiveTool()?.enables.has('form-fill') ?? false),\n };\n}\n","/** The form plugin's events. Fact events fire from the fields mirror; see `sync/fields.ts`. */\nimport type {\n FormFieldCreatedEvent,\n FormFieldDeletedEvent,\n FormFieldUpdatedEvent,\n FormResyncedEvent,\n FormValidationRejectedEvent,\n FormValueChangedEvent,\n} from '../contract';\nimport type { FormContext } from './context';\n\nexport function createEvents(ctx: FormContext) {\n return {\n valueChanged: ctx.events.source<FormValueChangedEvent>(),\n fieldCreated: ctx.events.source<FormFieldCreatedEvent>(),\n fieldUpdated: ctx.events.source<FormFieldUpdatedEvent>(),\n fieldDeleted: ctx.events.source<FormFieldDeletedEvent>(),\n validationRejected: ctx.events.source<FormValidationRejectedEvent>(),\n resynced: ctx.events.source<FormResyncedEvent>(),\n };\n}\nexport type FormEvents = ReturnType<typeof createEvents>;\n","/**\n * Who may fill in, and sign, which field: the engine's own answer per field\n * (`ctx.allowsField`), so a control gated on it never disagrees with the\n * write. A field's group decides: a `fields:fill` (`fields:sign`) permission\n * for its group, or `doc.forms.fill` (`doc.sign`) for every field.\n */\nimport { memo, type Mirror } from '@embedpdf/core';\n\nimport type { FieldIndex } from '../model';\nimport type { FormContext } from './context';\n\n/** What decides who may fill a field in: its group. */\ninterface Grouped {\n readonly groupId: string | null;\n}\n\nexport interface FillRights {\n /** Whether the session may fill in this field. */\n mayFill(field: Grouped): boolean;\n /** Whether the session may sign this signature field. */\n maySign(field: Grouped): boolean;\n /** Refuse a write to this field when the session may not fill it in, naming what it takes. */\n assertMayFill(field: Grouped, operation: string): void;\n /** What the session may fill in and sign, as a key that changes when that does: for memos. */\n key(): string;\n}\n\nexport function createFillRights(ctx: FormContext, fields: Mirror<FieldIndex>): FillRights {\n const mayFill = (field: Grouped): boolean => ctx.allowsField('fill', field);\n const maySign = (field: Grouped): boolean => ctx.allowsField('sign', field);\n\n /** The form's groups, `null` (no group) among them. */\n const groups = memo(\n () => [fields.view()],\n (index) => [...new Set((index.snapshot?.fields ?? []).map((field) => field.groupId))],\n );\n\n return {\n mayFill,\n maySign,\n assertMayFill: (field, operation) => ctx.assertAllowedField('fill', field, operation),\n key: () =>\n groups()\n .map((groupId) => `${mayFill({ groupId }) ? 1 : 0}${maySign({ groupId }) ? 1 : 0}`)\n .join(''),\n };\n}\n","/**\n * The texts this session's format scripts wrote. The engine draws a field's\n * formatted text into its picture but doesn't say what it was (a\n * `forms.setAppearanceText` answers as `forms.updated`), so the painter takes\n * it from here: the text each change wrote, for the value the field had.\n * Looked up by the value the field has now, so a refused change, or another\n * session's fill, falls back to the value itself.\n */\nimport type { Mirror } from '@embedpdf/core';\nimport type { ChangeOp, FormFieldDTO } from '@embedpdf/engine-core/runtime';\n\nimport { fieldByRef, fieldKeyOf, type FieldIndex, type FieldKey } from '../model';\nimport type { FormContext } from './context';\n\n/** The values remembered per field: enough for an undo or two. */\nconst KEPT_PER_FIELD = 8;\n\nexport interface FormattedTexts {\n /** The text the field shows for its value, as this session formatted it; `null` when it didn't. */\n textOf(field: FormFieldDTO): string | null;\n /** Moves when a text is remembered. */\n version(): number;\n}\n\nconst valueOf = (field: FormFieldDTO): string | null =>\n field.family === 'text' || field.family === 'combobox' ? field.value : null;\n\nexport function createFormattedTexts(ctx: FormContext, fields: Mirror<FieldIndex>): FormattedTexts {\n const texts = new Map<FieldKey, Map<string, string>>();\n let version = 0;\n ctx.listen(ctx.changes.onStaged, (change) => {\n // Staged: the view shows the change, its fields at the values it wrote.\n const view = fields.view();\n for (const op of change.shows as readonly ChangeOp[]) {\n if (op.type !== 'forms.setAppearanceText') continue;\n const field = fieldByRef(view, op.field);\n const value = field ? valueOf(field) : null;\n if (!field || value === null) continue;\n const key = fieldKeyOf(field);\n const kept = texts.get(key) ?? new Map<string, string>();\n kept.delete(value);\n kept.set(value, op.text);\n while (kept.size > KEPT_PER_FIELD) kept.delete(kept.keys().next().value!);\n texts.set(key, kept);\n version += 1;\n }\n });\n return {\n textOf(field) {\n const value = valueOf(field);\n return value === null ? null : (texts.get(fieldKeyOf(field))?.get(value) ?? null);\n },\n version: () => version,\n };\n}\n","/**\n * What a shown widget looks like now: the engine's picture, or the painter's\n * drawing of it (`@embedpdf/core-form`).\n *\n * A widget's look is everything its picture depends on: its size and turn,\n * its style, and what it shows (the value, as this session formatted it). Its\n * place isn't (a move keeps the look), nor the state a toggle shows (its\n * picture of every state is held). A widget is `pending` while its look in\n * the view isn't its confirmed look: a value typed or calculated, a restyle,\n * a field just placed. The layer then draws the painter's scene, as it does\n * while the picture it holds is older than the widget's look.\n */\nimport { memoByKey, type Mirror } from '@embedpdf/core';\nimport type { SceneNode } from '@embedpdf/core-annotation';\nimport {\n paints,\n textEditorLayout,\n widgetDrawing,\n widgetScene,\n type TextEditorLayout,\n} from '@embedpdf/core-form';\nimport type { AnnotationRef, FormFieldDTO, WidgetAnnotation } from '@embedpdf/engine-core/runtime';\n\nimport {\n fieldForWidget,\n pictureVersionOf,\n shownWidgetsOf,\n widgetRowOf,\n type Box,\n type FieldIndex,\n type ShownWidget,\n} from '../model';\nimport type { FormDesign } from './design';\nimport type { FormattedTexts } from './formatted';\n\nconst NOTHING_SHOWN: readonly ShownWidget[] = Object.freeze([]);\n\n/** A widget as the painter draws it: its scene on the page (its text carries the faces it needs). */\nexport interface WidgetPainting {\n readonly scene: readonly SceneNode[];\n}\n\nconst numberOf = (ref: AnnotationRef): number =>\n ref.kind === 'objectNumber' ? ref.objectNumber : -1;\n\nexport type WidgetLooks = ReturnType<typeof createWidgetLooks>;\n\nexport function createWidgetLooks({\n fields,\n formatted,\n design,\n}: {\n readonly fields: Mirror<FieldIndex>;\n readonly formatted: FormattedTexts;\n readonly design: FormDesign;\n}) {\n /** What the widget's picture depends on, as one string. */\n const lookKeyOf = (row: WidgetAnnotation, field: FormFieldDTO | null): string => {\n const box = row.box ?? row.rect;\n const content = (() => {\n switch (field?.family) {\n case 'text':\n return [\n formatted.textOf(field) ?? field.value,\n field.multiline,\n field.password,\n field.comb,\n field.maxLength,\n ];\n case 'combobox':\n return [formatted.textOf(field) ?? field.value];\n case 'listbox':\n return [field.topIndex, field.options.map((option) => [option.label, option.selected])];\n default:\n return [field?.family ?? null];\n }\n })();\n return JSON.stringify([\n box.width,\n box.height,\n row.rotation ?? 0,\n row.color ?? null,\n row.interiorColor ?? null,\n row.strokeWidth ?? null,\n row.borderStyle ?? null,\n row.dashArray ?? null,\n row.fontFamily ?? null,\n row.fontSize ?? null,\n row.fontColor ?? null,\n row.textAlign ?? null,\n row.caption ?? null,\n row.checkStyle ?? null,\n content,\n ]);\n };\n\n const lookOf = (index: FieldIndex, number: number): string | null => {\n const row = widgetRowOf(index, number);\n return row ? lookKeyOf(row, fieldForWidget(index, number)) : null;\n };\n\n // In design mode the annotation layer draws the widgets it borrowed.\n const shownOn = memoByKey(\n (_pageObjectNumber: number) =>\n [fields.view(), fields.get(), formatted.version(), design.lending()] as const,\n (pageObjectNumber, view, truth, _formatted, lent): readonly ShownWidget[] =>\n lent\n ? NOTHING_SHOWN\n : shownWidgetsOf(view, pageObjectNumber, (row) => {\n const number = numberOf(row.ref);\n return {\n pending: lookOf(view, number) !== lookOf(truth, number),\n pictureVersion: pictureVersionOf(truth, number),\n };\n }),\n );\n\n /** The painter's drawing of `row` (in the view's field, as this session formatted it) at `box`, turned. */\n const paint = (\n row: WidgetAnnotation,\n box: Box,\n rotation: number | null | undefined,\n ): readonly SceneNode[] | null => {\n const view = fields.view();\n const field = fieldForWidget(view, numberOf(row.ref));\n if (!field) return null;\n const text = formatted.textOf(field);\n const drawing = widgetDrawing({ ...row, box }, field, text === null ? {} : { text });\n return drawing && widgetScene(drawing, { box, rotation });\n };\n\n /** The painter's drawing of a widget as the view has it; `null` for one it doesn't draw. */\n const sceneOf = memoByKey(\n (number: number) => {\n const view = fields.view();\n const row = widgetRowOf(view, number);\n const field = row ? fieldForWidget(view, number) : null;\n return [row, field, field ? formatted.textOf(field) : null] as const;\n },\n (_number, row): WidgetPainting | null => {\n const scene = row && paint(row, row.box ?? row.rect, row.rotation);\n return scene ? { scene } : null;\n },\n );\n\n return {\n listShownWidgets: (pageObjectNumber: number) => shownOn(pageObjectNumber),\n getWidgetPainting: (ref: AnnotationRef) => sceneOf(numberOf(ref)),\n /** The widget's look in the view isn't its confirmed look yet: it draws live until its picture is. */\n isPending: (ref: AnnotationRef): boolean => {\n const number = numberOf(ref);\n return lookOf(fields.view(), number) !== lookOf(fields.get(), number);\n },\n /**\n * How the painter draws a widget row live, upright in a box (where a gesture has it); `null`\n * for one whose field it doesn't draw (a signature).\n */\n painterOf: (row: WidgetAnnotation): ((box: Box) => readonly SceneNode[]) | null => {\n const field = fieldForWidget(fields.view(), numberOf(row.ref));\n return field && paints(field) ? (box) => paint(row, box, 0) ?? [] : null;\n },\n getTextEditorLayout: (ref: AnnotationRef, text: string): TextEditorLayout | null => {\n const view = fields.view();\n const number = numberOf(ref);\n const row = widgetRowOf(view, number);\n const field = row ? fieldForWidget(view, number) : null;\n return row && field ? textEditorLayout(row, field, text) : null;\n },\n };\n}\n","/**\n * The engine's pictures of each page's widgets, through the render plugin's\n * one door. The form layer draws them, and the annotation plugin draws the\n * widgets it borrows from the same ones (design mode), so switching modes\n * fetches nothing. A page's pictures depend on its widgets' picture versions\n * (the mirror's) and nothing else: a checkbox that only switches its state\n * fetches nothing.\n */\nimport { memoByKey, type Mirror } from '@embedpdf/core';\nimport type { AnnotationRef, PageRef } from '@embedpdf/engine-core/runtime';\nimport type { AppearanceItem, AppearancePicture } from '@embedpdf/plugin-render/contract/host';\n\nimport { pictureVersionOf, type FieldIndex } from '../model';\nimport type { FormSiblings } from './siblings';\n\nexport interface WidgetPictures {\n /** What the page's pictures depend on, `5@2|6@7`: a new value means new pictures. */\n epoch(page: PageRef): string;\n /** Every picture of the page's widgets, at rest, in every state, each with its widget's version. */\n render(page: PageRef, scale: number, signal?: AbortSignal): Promise<readonly AppearancePicture[]>;\n /** The widget's confirmed picture version. */\n versionOf(widget: AnnotationRef): number;\n}\n\nconst NO_PICTURES: readonly AppearancePicture[] = Object.freeze([]);\n\nexport function createWidgetPictures(\n fields: Mirror<FieldIndex>,\n { render }: Pick<FormSiblings, 'render'>,\n): WidgetPictures {\n /** The page's widgets, as the engine confirmed them, each at its picture version. */\n const itemsOn = memoByKey(\n (_pageObjectNumber: number) => [fields.get()] as const,\n (pageObjectNumber, index): readonly AppearanceItem[] =>\n (index.snapshot?.widgets ?? []).flatMap((row) =>\n row.page.objectNumber === pageObjectNumber && row.ref.kind === 'objectNumber'\n ? [{ ref: row.ref, version: pictureVersionOf(index, row.ref.objectNumber) }]\n : [],\n ),\n );\n const epochOn = memoByKey(\n (pageObjectNumber: number) => [itemsOn(pageObjectNumber)] as const,\n (_pageObjectNumber, items) =>\n items\n .map(\n ({ ref, version }) => `${ref.kind === 'objectNumber' ? ref.objectNumber : ''}@${version}`,\n )\n .sort()\n .join('|'),\n );\n return {\n epoch: (page) => epochOn(page.objectNumber),\n render: (page, scale, signal) => {\n const renderer = render();\n return renderer\n ? renderer.renderAppearances(page, {\n family: 'widgets',\n scale,\n items: itemsOn(page.objectNumber),\n ...(signal ? { signal } : {}),\n })\n : Promise.resolve(NO_PICTURES);\n },\n versionOf: (widget) =>\n widget.kind === 'objectNumber' ? pictureVersionOf(fields.get(), widget.objectNumber) : 0,\n };\n}\n","/**\n * The keystroke, validate, calculate and format script pipeline. Scripts run\n * in the actions plugin's per-document realm: when that realm offers a\n * transaction port, JavaScript is on (the switch is\n * `actionsPlugin({ javascript })`). The `validation` setting decides, at each\n * write, whether the pipeline runs; this plugin owns only the pipeline.\n */\nimport type { ActionOrigin } from '@embedpdf/plugin-actions/contract';\nimport type { ScriptCommitSurface } from '@embedpdf/plugin-actions/contract/host';\n\nimport { formHasScripts, type FieldIndex } from '../model';\nimport {\n createFormScriptingController,\n type FormScriptingController,\n} from '../scripting/controller';\nimport type { FormContext } from './context';\nimport type { FormSiblings } from './siblings';\n\nexport function createScriptingSeam(ctx: FormContext, siblings: FormSiblings) {\n // The pipeline over the actions plugin's realm, made the first time one is there.\n let pipeline: FormScriptingController | null = null;\n const pipelineOf = (): FormScriptingController | null => {\n if (pipeline) return pipeline;\n const realm = siblings.actions()?.scriptRealm ?? null;\n if (!realm) return null;\n const made = createFormScriptingController({\n document: () => ctx.document(),\n transaction: realm.transaction.bind(realm),\n budget: realm.budget,\n });\n ctx.cleanup(() => made.dispose());\n pipeline = made;\n return made;\n };\n const settings = ctx.settings();\n const controller = (): FormScriptingController | null =>\n settings.get().validation === 'scripts' ? pipelineOf() : null;\n\n // A one-shot developer hint: a form with scripts and no realm fills without them.\n let warnedNoRealm = false;\n const scriptsFor = (form: FieldIndex): FormScriptingController | null => {\n if (!formHasScripts(form)) return null;\n if (!pipelineOf() && !warnedNoRealm && settings.get().validation === 'scripts') {\n warnedNoRealm = true;\n console.warn(\n \"[form] this form has scripts, but they don't run: add the actions plugin with \" +\n 'JavaScript on (`actionsPlugin({ javascript: { enabled: true, sandboxFactory } })`), ' +\n \"or set the form's `validation` to 'none' to fill it in without them.\",\n );\n }\n return controller();\n };\n\n let warmed = false;\n return {\n /** The script pipeline when the document's scripts run, else `null`. */\n controller,\n /** The script pipeline for a write to this form: `null` too when no field has a script. */\n scriptsFor,\n /** Start the realm before the first write needs it, once, when the form has scripts. */\n warm(form: FieldIndex): void {\n if (warmed || !form.snapshot) return;\n const scripts = scriptsFor(form);\n if (!scripts) return;\n warmed = true;\n void scripts.warm(form.snapshot).catch(() => {\n /* the first write starts the realm, and reports why it can't */\n });\n },\n /** Script results (UI effects, diagnostics, errors) are surfaced through the\n * actions plugin, with the origin that caused them. */\n surface: (result: ScriptCommitSurface, origin: ActionOrigin): void => {\n siblings.actions()?.surfaceScriptCommit(result, { origin, realm: 'document' });\n },\n };\n}\nexport type FormScripting = ReturnType<typeof createScriptingSeam>;\n","/** The optional sibling planes, looked up each time they're used, not once\n * at construction: what a sibling is depends on no creation order. A\n * fill-only setup may have none; every area guards on null. */\nimport { ActionsToken as ActionsHostToken } from '@embedpdf/plugin-actions/contract/host';\nimport { AnnotationToken as AnnotationHostToken } from '@embedpdf/plugin-annotation/contract/host';\nimport { RenderToken as RenderHostToken } from '@embedpdf/plugin-render/contract/host';\n\nimport type { FormContext } from './context';\n\nexport function resolveSiblings(ctx: FormContext) {\n return {\n /** The annotation plugin: design mode's selection, tools, ghosts and placement previews. */\n annotation: () => ctx.tryGet(AnnotationHostToken),\n /** The script realm owner and the one surface port for script results. */\n actions: () => ctx.tryGet(ActionsHostToken),\n /** The page renderer: the widgets' pictures, shared by the form layer and design mode. */\n render: () => ctx.tryGet(RenderHostToken),\n };\n}\nexport type FormSiblings = ReturnType<typeof resolveSiblings>;\n","/**\n * Plugin-private services every area is built on: the form's mirror (the\n * field tree and every widget row), who may fill in which field, the events,\n * the sibling plugins, the scripting seam, and the one write queue. The rest\n * of the session's authority is the context's (`ctx.allows`,\n * `ctx.assertAllowed`).\n */\nimport type { Mirror, SerialQueue } from '@embedpdf/core';\nimport type { FormFieldRef } from '@embedpdf/engine-core/runtime';\n\nimport { canonicalKey, type FieldIndex, type FieldKey } from '../model';\nimport { createFieldsMirror } from '../sync/fields';\nimport type { FormContext } from './context';\nimport { createDesign, type FormDesign } from './design';\nimport { createEvents, type FormEvents } from './events';\nimport { createFillRights, type FillRights } from './fill-rights';\nimport { createFormattedTexts, type FormattedTexts } from './formatted';\nimport { createWidgetLooks, type WidgetLooks } from './looks';\nimport { createWidgetPictures, type WidgetPictures } from './pictures';\nimport { createScriptingSeam, type FormScripting } from './scripting';\nimport { resolveSiblings, type FormSiblings } from './siblings';\n\nexport type { FormContext } from './context';\n\nexport interface FormServices {\n readonly fields: Mirror<FieldIndex>;\n /** Who may fill in which field. */\n readonly rights: FillRights;\n readonly events: FormEvents;\n readonly siblings: FormSiblings;\n readonly scripting: FormScripting;\n /** Whether the widgets are lent to the annotation plugin now (design mode). */\n readonly design: FormDesign;\n /** The texts this session's format scripts wrote, for the painter. */\n readonly formatted: FormattedTexts;\n /** The engine's pictures of each page's widgets, at their picture versions. */\n readonly pictures: WidgetPictures;\n /** What each widget looks like now: pending or confirmed, and the painter's drawing of it. */\n readonly looks: WidgetLooks;\n /**\n * Fills take turns on one serial queue until they are sent (write/fill.ts),\n * and a repair until the engine answers.\n */\n readonly enqueue: SerialQueue;\n /** The key a field is known by, whichever ref names it (`toFieldRef(name)` too). */\n readonly keyOf: (ref: FormFieldRef) => FieldKey;\n}\n\nexport function createServices(ctx: FormContext): FormServices {\n const siblings = resolveSiblings(ctx);\n const events = createEvents(ctx);\n const fields = createFieldsMirror(ctx, events);\n const design = createDesign(ctx, siblings);\n const formatted = createFormattedTexts(ctx, fields);\n return {\n fields,\n rights: createFillRights(ctx, fields),\n events,\n siblings,\n scripting: createScriptingSeam(ctx, siblings),\n design,\n formatted,\n pictures: createWidgetPictures(fields, siblings),\n looks: createWidgetLooks({ fields, formatted, design }),\n enqueue: ctx.serialQueue('writes'),\n keyOf: (ref) => canonicalKey(fields.view(), ref),\n };\n}\n","/**\n * Widget activation and the widget DOM-event feed into the actions plane.\n * A click first offers the widget's `/A` tree to the dispatcher; only a\n * tree-less widget falls back to the form's own scripted activation.\n */\nimport { PluginError, type OperationOptions } from '@embedpdf/core';\nimport { type AnnotationRef, type FormFieldRef } from '@embedpdf/engine-core/runtime';\nimport { ActionsToken, createHoverPump } from '@embedpdf/plugin-actions/contract';\nimport type { ActionSource } from '@embedpdf/plugin-actions/contract';\n\nimport type { FormCommitResult, WidgetActivationResult } from '../contract';\nimport type { FormHostCapability } from '../host-contract';\nimport { fieldForWidget, widgetRowOf } from '../model';\nimport { widgetObjectOf } from '../read/fields';\nimport type { FormContext, FormServices } from '../services';\nimport type { Fills } from './fill';\n\nexport function createActivation(\n ctx: FormContext,\n services: Pick<FormServices, 'fields' | 'siblings' | 'scripting'>,\n { fill }: Fills,\n) {\n const { fields, scripting } = services;\n\n /** The widget's activation action, from its row in the form. */\n const annotationActivation = async (ref: AnnotationRef) => {\n await fields.settled();\n const row = ref.kind === 'objectNumber' ? widgetRowOf(fields.view(), ref.objectNumber) : null;\n return row?.actions?.activate ?? null;\n };\n\n /** The widget's activation through the form's own scripts: what they change is one fill. */\n const activateThroughScripts = async (\n ref: FormFieldRef,\n annotationRef: AnnotationRef,\n options?: OperationOptions,\n ): Promise<FormCommitResult> => {\n const pipeline = scripting.controller();\n if (!pipeline) {\n return {\n status: 'unchanged',\n scripted: false,\n uiEffects: [],\n diagnostics: [],\n };\n }\n const action = await annotationActivation(annotationRef);\n if (!action) {\n return {\n status: 'unchanged',\n scripted: true,\n uiEffects: [],\n diagnostics: [],\n };\n }\n const { result } = await fill(\n { ops: [], scripts: { kind: 'activate', field: ref, action }, origin: 'user' },\n options,\n );\n return result;\n };\n\n // ── widget DOM-event feed helpers ───────────────────────────────────────\n const widgetSource = (field: FormFieldRef, annotationRef: AnnotationRef): ActionSource => ({\n kind: 'widget',\n field,\n annotation: annotationRef,\n page: annotationRef.page,\n });\n\n /**\n * One shared hover pump (an exit and the next enter delivered as one\n * ordered pair; intermediate hovers skipped), created on first use.\n */\n let widgetPump: ReturnType<typeof createHoverPump> | null = null;\n const widgetHoverPump = (actions: {\n dispatch: Parameters<typeof createHoverPump>[0];\n }): ReturnType<typeof createHoverPump> => {\n widgetPump ??= createHoverPump(actions.dispatch);\n return widgetPump;\n };\n\n const widgetHoverFlags = (\n annotationRef: AnnotationRef,\n ): { enter: boolean; exit: boolean } | null => {\n const row =\n annotationRef.kind === 'objectNumber'\n ? widgetRowOf(fields.view(), annotationRef.objectNumber)\n : null;\n if (!row) return null;\n return {\n enter: Boolean(row.actions?.cursorEnter?.root),\n exit: Boolean(row.actions?.cursorExit?.root),\n };\n };\n\n return {\n api: {\n activateWidget: async (annotationRef, options): Promise<WidgetActivationResult> => {\n const field = fieldForWidget(fields.view(), widgetObjectOf(annotationRef));\n if (!field) throw new PluginError('not-found', 'form', 'no form field owns this widget');\n const actions = ctx.tryGet(ActionsToken);\n if (actions) {\n const result = await ctx.cancellable(\n options?.signal,\n actions.dispatch({\n scope: 'activate',\n ref: annotationRef,\n page: annotationRef.page,\n source: widgetSource(field.ref, annotationRef),\n }),\n );\n const noTree =\n result.status === 'inert' &&\n result.steps.length === 0 &&\n result.diagnostics.length === 0;\n if (!noTree) return { kind: 'dispatched', result };\n }\n return {\n kind: 'form',\n result: await activateThroughScripts(field.ref, annotationRef, options),\n };\n },\n notifyWidgetEvent: (fieldRef, annotationRef, event) => {\n const actions = ctx.tryGet(ActionsToken);\n if (!actions) return;\n const source = widgetSource(fieldRef, annotationRef);\n if (event === 'cursorEnter' || event === 'cursorExit') {\n if (event === 'cursorExit') {\n widgetHoverPump(actions).hover(null);\n return;\n }\n // Check for an enter/exit action tree through the annotation plugin\n // when it is present, so a widget without one costs no dispatch.\n // Without the annotation plugin the flags stay unknown and the\n // dispatcher resolves them in its queue.\n const flags = widgetHoverFlags(annotationRef);\n if (flags && !flags.enter && !flags.exit) return;\n widgetHoverPump(actions).hover({\n ref: annotationRef,\n page: annotationRef.page,\n source,\n ...(flags ? { events: flags } : {}),\n });\n return;\n }\n // The first field to take focus starts the realm, so the first commit doesn't wait.\n if (event === 'focus') scripting.warm(fields.view());\n // Down, up, focus and blur are fire-and-forget: dispatch never\n // rejects, the dispatcher's queue orders them, and results surface\n // through the actions events. The dispatcher also applies the rule\n // that /A shadows the up event (ISO 32000-2 Table 197).\n void actions.dispatch({\n scope: 'annotation',\n event,\n ref: annotationRef,\n page: annotationRef.page,\n source,\n });\n },\n } satisfies Partial<FormHostCapability>,\n };\n}\n","/**\n * The object numbers a new field and its widgets take: final names from the\n * document's pool (`ctx.changes`), so a field shows under the ref it keeps\n * from its first frame. A few taken and not used yet wait here for the next\n * create; one the engine reclaims leaves.\n */\nimport type { FormContext } from './context';\n\nexport interface ObjectNumbers {\n /** `count` numbers now, or `null` when the pool has too few (it refills as it goes). */\n takeNow(count: number): number[] | null;\n /** `count` numbers, once the pool has them. */\n take(count: number): Promise<number[]>;\n}\n\nexport function createObjectNumbers(ctx: Pick<FormContext, 'changes' | 'doc'>): ObjectNumbers {\n const held: number[] = [];\n let watching = false;\n const watchLost = (): void => {\n if (watching || !ctx.doc) return;\n watching = true;\n ctx.doc.objectNumbers.onLost(({ numbers }) => {\n const lost = new Set(numbers);\n held.splice(0, held.length, ...held.filter((number) => !lost.has(number)));\n });\n };\n\n const takeNow = (count: number): number[] | null => {\n watchLost();\n while (held.length < count) {\n const number = ctx.changes.takeObjectNumber();\n if (number === null) return null;\n held.push(number);\n }\n return held.splice(0, count);\n };\n\n return {\n takeNow,\n async take(count) {\n for (;;) {\n const taken = takeNow(count);\n if (taken) return taken;\n await ctx.changes.reserveObjectNumbers(count - held.length);\n }\n },\n };\n}\n","/**\n * Where a field's new widget goes when `addWidget()` gets no place for it: next in line after\n * the field's widgets on the page. A column of buttons grows downward and a row grows sideways,\n * each step the same as the one between the last two buttons; one button gets the next below\n * it, half its height away. Where the next step leaves the page, the line starts again beside\n * the group (a column) or under it (a row). Page space: top-left origin, y down.\n */\nimport type { Box } from '../model';\n\n/** The page's size, as the widgets' boxes are measured on it. */\ninterface PageSize {\n readonly width: number;\n readonly height: number;\n}\n\nconst fits = (box: Box, page: PageSize): boolean =>\n box.x >= 0 && box.y >= 0 && box.x + box.width <= page.width && box.y + box.height <= page.height;\n\n/** The box after `boxes`, the field's widgets on one page in the field's order. */\nexport function nextInLine(boxes: readonly Box[], page: PageSize): Box {\n const last = boxes.at(-1);\n if (!last) return { x: 0, y: 0, width: 0, height: 0 };\n const { width, height } = last;\n const previous = boxes.at(-2);\n // The step between the last two, or half a button's height below the only one.\n const step =\n previous && (previous.x !== last.x || previous.y !== last.y)\n ? { x: last.x - previous.x, y: last.y - previous.y }\n : { x: 0, y: height * 1.5 };\n const next = { x: last.x + step.x, y: last.y + step.y, width, height };\n if (fits(next, page)) return next;\n\n const column = Math.abs(step.y) >= Math.abs(step.x);\n const left = Math.min(...boxes.map((box) => box.x));\n const top = Math.min(...boxes.map((box) => box.y));\n const right = Math.max(...boxes.map((box) => box.x + box.width));\n const bottom = Math.max(...boxes.map((box) => box.y + box.height));\n // The gap between two buttons along the line: the new line keeps the same one.\n const gap = Math.max(column ? Math.abs(step.y) - height : Math.abs(step.x) - width, 0);\n const restart = column\n ? { x: right + (gap || width / 2), y: top, width, height }\n : { x: left, y: bottom + (gap || height / 2), width, height };\n if (fits(restart, page)) return restart;\n // No room beside the group either: on the page, at the last button's place shifted in.\n return {\n x: Math.min(Math.max(next.x, 0), Math.max(page.width - width, 0)),\n y: Math.min(Math.max(next.y, 0), Math.max(page.height - height, 0)),\n width,\n height,\n };\n}\n","/**\n * Building the form: every design verb is one change on the document's queue\n * (`ctx.changes`). It shows at once (the fields mirror predicts it), it is a\n * step of the history, and it resolves with the engine's answer. A create\n * takes its field's and widgets' object numbers first, so their refs are final\n * from the first frame and the new widget can be selected straight away.\n */\nimport {\n PluginError,\n toPluginError,\n type ChangeLabel,\n type OperationOptions,\n type PendingChange,\n} from '@embedpdf/core';\nimport {\n draftWritesScripts,\n writesScripts,\n type ChangeItem,\n type ChangeOp,\n type FormFieldDTO,\n type WidgetAnnotation,\n type WidgetPlacement,\n} from '@embedpdf/engine-core/runtime';\n\nimport type { FormCapability, FormFieldResult } from '../contract';\nimport { fieldByRef, widgetRowOf } from '../model';\nimport type { FormContext, FormServices } from '../services';\nimport { createObjectNumbers } from '../services/object-numbers';\nimport { undoLookOf } from '../sync/predict';\nimport { nextInLine } from './next-in-line';\n\n/**\n * A widget's look, as `addWidget()` copies it from the field's last widget onto the new one:\n * the engine's widget style fields (`WIDGET_STYLE_NAMES`), and its turn.\n */\nconst LOOK = [\n 'color',\n 'interiorColor',\n 'strokeWidth',\n 'borderStyle',\n 'dashArray',\n 'fontFamily',\n 'fontSize',\n 'fontColor',\n 'textAlign',\n 'caption',\n 'checkStyle',\n 'rotation',\n] as const;\n\nconst lookOf = (widget: WidgetAnnotation | undefined): Partial<WidgetPlacement> => {\n if (!widget) return {};\n const held = widget as unknown as Record<string, unknown>;\n const look: Record<string, unknown> = {};\n for (const name of LOOK)\n if (held[name] !== undefined && held[name] !== null) look[name] = held[name];\n return look as Partial<WidgetPlacement>;\n};\n\n/**\n * The export value a field's new widget gets when none is given: a radio group's next free\n * `Choice<n>` (the radio tool names its first button `Choice1`), a checkbox's own value, so\n * the boxes check together. Other families take none.\n */\nfunction exportValueFor(field: FormFieldDTO): string | undefined {\n if (field.family === 'checkbox') return field.exportValue;\n if (field.family !== 'radio') return undefined;\n const taken = new Set(field.widgets.map((widget) => widget.exportValue));\n let n = field.widgets.length + 1;\n while (taken.has(`Choice${n}`)) n += 1;\n return `Choice${n}`;\n}\n\n/** Whether the field's dictionary is its only widget's too, which adding a widget splits. */\nconst isMerged = (field: FormFieldDTO): boolean =>\n field.ref.kind === 'objectNumber' &&\n field.widgets.some(\n (widget) => widget.objectNumber === (field.ref as { objectNumber: number }).objectNumber,\n );\n\nconst MODIFY = 'doc.forms.modify';\nconst SCRIPT = 'doc.forms.script';\n\n/** The answer's item for the change's only op, of the type it names. */\ntype ItemOf<T extends ChangeItem['type']> = Extract<ChangeItem, { type: T }>;\n\nexport function createFieldWrites(\n ctx: FormContext,\n { fields, enqueue }: Pick<FormServices, 'fields' | 'enqueue'>,\n) {\n const numbers = createObjectNumbers(ctx);\n\n /** Refuse up front without `doc.forms.modify`, and without `doc.forms.script` when it writes scripts. */\n const allow = (operation: string, scripts = false): void => {\n ctx.assertAllowed(MODIFY, operation);\n if (scripts) ctx.assertAllowed(SCRIPT, operation);\n };\n\n /** Stage one design op as its own change: it shows at once, and undoing it shows the form as it was. */\n const stage = (verb: string, op: ChangeOp): PendingChange =>\n ctx.changes.stage({\n label: { key: `form.${verb}` } satisfies ChangeLabel,\n ops: [op],\n undo: undoLookOf(fields.view(), [op]),\n });\n\n /** The engine's answer to a staged design change: its one item. */\n const answer = async <T extends ChangeItem['type']>(\n change: PendingChange,\n options?: OperationOptions,\n ): Promise<ItemOf<T>> => {\n try {\n const result = await ctx.cancellable(options?.signal, change.result);\n return result.items[0] as ItemOf<T>;\n } catch (error) {\n throw toPluginError('form', error);\n }\n };\n\n const create: FormCapability['create'] = async (draft, options) => {\n allow('form.create', draftWritesScripts(draft));\n // The field, then each widget, in the draft's order.\n const count = 1 + (draft.widgets?.length ?? 0);\n const [objectNumber, ...widgetObjectNumbers] =\n numbers.takeNow(count) ?? (await numbers.take(count));\n const change = stage('create', {\n type: 'forms.create',\n draft,\n objectNumber,\n widgetObjectNumbers,\n });\n const item = await answer<'forms.create'>(change, options);\n return { field: item.field } satisfies FormFieldResult;\n };\n\n const addWidget: FormCapability['addWidget'] = async (ref, placement = {}, options) => {\n allow('form.addWidget', writesScripts(placement.actions));\n const index = fields.view();\n const field = fieldByRef(index, ref);\n if (!field) throw new PluginError('not-found', 'form', 'no form field has this ref');\n const rows = field.widgets\n .map((widget) => widgetRowOf(index, widget.objectNumber))\n .filter((row): row is WidgetAnnotation => row !== null);\n const last = rows.at(-1);\n const page = placement.page ?? last?.page;\n if (!page) {\n throw new PluginError(\n 'invalid-input',\n 'form',\n 'the field shows on no page: give `page` and `rect`',\n );\n }\n const size = ctx.getPage(page)?.size;\n const onPage = rows.filter((row) => row.page.objectNumber === page.objectNumber);\n const rect =\n placement.rect ??\n placement.box ??\n (size && onPage.length > 0\n ? nextInLine(\n onPage.map((row) => row.box),\n size,\n )\n : undefined);\n if (!rect) {\n throw new PluginError(\n 'invalid-input',\n 'form',\n 'no widget of the field on that page: give `rect`',\n );\n }\n const exportValue = placement.exportValue ?? exportValueFor(field);\n const split = isMerged(field);\n const [objectNumber, splitObjectNumber] =\n numbers.takeNow(split ? 2 : 1) ?? (await numbers.take(split ? 2 : 1));\n const change = stage('addWidget', {\n type: 'forms.addWidget',\n field: field.ref,\n placement: {\n ...lookOf(last),\n ...placement,\n page,\n ...(placement.box ? {} : { rect }),\n ...(exportValue === undefined ? {} : { exportValue }),\n },\n objectNumber,\n ...(split ? { splitObjectNumber } : {}),\n });\n const item = await answer<'forms.addWidget'>(change, options);\n const widget =\n item.widgets.find(\n (row) => row.ref.kind === 'objectNumber' && row.ref.objectNumber === objectNumber,\n ) ?? item.widgets.at(-1)!;\n return { field: item.field, widget };\n };\n\n return {\n api: {\n create,\n addWidget,\n update: async (ref, patch, options) => {\n allow('form.update', writesScripts(patch.actions));\n const change = stage('update', { type: 'forms.update', field: ref, patch });\n return { field: (await answer<'forms.update'>(change, options)).field };\n },\n reorderCalculations: async (fields, position, options) => {\n allow('form.reorderCalculations');\n const change = stage('reorderCalculations', {\n type: 'forms.reorderCalculations',\n fields,\n position,\n });\n const item = await answer<'forms.reorderCalculations'>(change, options);\n return { calculationOrder: item.calculationOrder };\n },\n delete: async (ref, options) => {\n allow('form.delete');\n await answer(stage('delete', { type: 'forms.delete', field: ref }), options);\n },\n removeWidget: async (ref, widget, options) => {\n allow('form.removeWidget');\n const change = stage('removeWidget', { type: 'forms.removeWidget', field: ref, widget });\n return { field: (await answer<'forms.removeWidget'>(change, options)).field };\n },\n updateWidget: async (widget, patch, options) => {\n allow('form.updateWidget');\n const change = stage('updateWidget', { type: 'forms.updateWidget', widget, patch });\n return { widget: (await answer<'forms.updateWidget'>(change, options)).widget };\n },\n deleteWidget: async (widget, options) => {\n allow('form.deleteWidget');\n const change = stage('deleteWidget', { type: 'forms.deleteWidget', widget });\n return { field: (await answer<'forms.deleteWidget'>(change, options)).field };\n },\n // A repair reads the whole form and fixes it where it stands: not a change of ops.\n repair: async (options) => {\n allow('form.repair');\n const { signal, ...repair } = options ?? {};\n const run = () => (options ? ctx.doc.forms.repair(repair) : ctx.doc.forms.repair());\n return enqueue(() => ctx.cancellable(signal, run()), options);\n },\n } satisfies Partial<FormCapability>,\n };\n}\n","/**\n * Filling the form in. Every fill is one change, whatever started it: a value, a batch of\n * values, a reset, a widget's activation, a script's or an action's effects.\n *\n * 1. What the user did shows at once: the change is held with the user's own ops.\n * 2. When its turn comes, the form's scripts run against the view, in one realm transaction.\n * 3. Inside that transaction the change gets every op the scripts asked for, and is sent.\n *\n * Fills take turns up to their send, not their answer: the next fill's scripts read this one in\n * the view while the engine answers it. A validation refusal cancels the change. A change the\n * engine refuses leaves the view, and the calculations run again against what is left, outside\n * the history: the fills after it were calculated with its values.\n */\nimport {\n PluginError,\n toPluginError,\n type ChangeLabel,\n type HeldChange,\n type OperationOptions,\n type PendingChange,\n} from '@embedpdf/core';\nimport {\n fieldValueOf,\n formEffectOps,\n type ChangeOp,\n type FormFieldDTO,\n type FormFieldRef,\n type FormFieldValue,\n type PdfActionTree,\n} from '@embedpdf/engine-core/runtime';\nimport type { ActionOrigin } from '@embedpdf/plugin-actions/contract';\n\nimport type { FormCommitResult } from '../contract';\nimport { fieldByKey, fieldKeyOf, type FieldIndex } from '../model';\nimport type { FormScriptResult, FormScripts } from '../scripting/controller';\nimport { scriptError } from '../scripting/results';\nimport type { FormContext, FormServices } from '../services';\nimport { fieldsNamedBy, predictFormOp, undoLookOf, withFieldsFrom } from '../sync/predict';\n\n/** The scripts a fill runs before it is sent, when the document's scripts run. */\nexport type FillScripts =\n /** A field's new value through its own scripts, then the calculations: they make the change. */\n | { readonly kind: 'commit'; readonly field: FormFieldRef; readonly value: FormFieldValue }\n /** A widget's activation action: what it changes is the change. */\n | {\n readonly kind: 'activate';\n readonly field: FormFieldRef;\n readonly action: PdfActionTree<unknown>;\n }\n /** The calculations the user's ops cause: what they change follows the user's ops. */\n | { readonly kind: 'recalculate' };\n\nexport interface FillRequest {\n /** What the change is called; a fill of the fields its ops name when left out. */\n readonly label?: ChangeLabel;\n /** What the user did: shown at once. */\n readonly ops: readonly ChangeOp[];\n readonly scripts: FillScripts | null;\n /** Who started it, for the alerts its scripts raise. */\n readonly origin: ActionOrigin;\n}\n\n/** How a fill ended, once the engine answered. */\nexport interface FillOutcome {\n readonly result: FormCommitResult;\n /** The form before the fill, as the view showed it. */\n readonly before: FieldIndex;\n /** The form once the fill had all its ops, as the view showed it. */\n readonly after: FieldIndex;\n}\n\n/** A fill shown, waiting for its turn. */\ninterface Begun {\n readonly request: FillRequest;\n /** The form before the user's ops showed. */\n readonly before: FieldIndex;\n /** The form as the user's ops showed it. */\n readonly shown: FieldIndex;\n readonly hold: HeldChange | null;\n}\n\n/** A fill sent, waiting for the engine. */\ninterface Sent {\n readonly script: FormScriptResult | null;\n /** The changes it was sent as: one, or two when the hold went before the scripts finished. */\n readonly changes: readonly PendingChange[];\n readonly after: FieldIndex;\n}\n\n/** A refused value writes only what the document's open scripts did, outside the history. */\nconst SCRIPTS_LABEL: ChangeLabel = { key: 'form.scripts' };\n/** The calculations again, outside the history: after a refused fill, or a stale one. */\nconst RECALCULATE_LABEL: ChangeLabel = { key: 'form.recalculate' };\n/** The changes that, refused, leave calculations made with their values. */\nconst FILLS = new Set(['form.fill', 'form.reset']);\n\nconst sameOp = (left: ChangeOp, right: ChangeOp): boolean =>\n JSON.stringify(left) === JSON.stringify(right);\n\nconst sameValue = (left: FormFieldDTO | null, right: FormFieldDTO | null): boolean =>\n JSON.stringify(left?.valueEntry ?? null) === JSON.stringify(right?.valueEntry ?? null);\n\nexport function createFill(\n ctx: FormContext,\n { fields, scripting, enqueue }: Pick<FormServices, 'fields' | 'scripting' | 'enqueue'>,\n) {\n const labelOf = (request: FillRequest, index: FieldIndex, ops: readonly ChangeOp[]) =>\n request.label ?? { key: 'form.fill', count: fieldsNamedBy(index, ops).length };\n\n /** Step 1: what the user did shows at once. */\n const begin = (request: FillRequest): Begun => {\n const before = fields.view();\n const shown = request.ops.reduce(predictFormOp, before);\n if (request.ops.length === 0) return { request, before, shown, hold: null };\n const hold = ctx.changes.hold(labelOf(request, before, request.ops));\n hold.set(request.ops, undoLookOf(before, request.ops));\n return { request, before, shown, hold };\n };\n\n /**\n * The form the change is undone to: as it is now, with the user's own fields as they were\n * before the user's ops showed.\n */\n const baseOf = ({ request, before }: Begun): FieldIndex =>\n withFieldsFrom(fields.view(), before, fieldsNamedBy(before, request.ops));\n\n /** Whether the hold went with the user's ops before the scripts finished. */\n const sentEarly = ({ hold }: Begun): boolean => hold !== null && !hold.open && !!hold.change;\n\n /** Whether the form still shows the values the user's ops wrote: the scripts ran for those. */\n const stillShown = ({ request, shown }: Begun): boolean => {\n const now = fields.view();\n return fieldsNamedBy(shown, request.ops).every((field) =>\n sameValue(fieldByKey(now, fieldKeyOf(field)), field),\n );\n };\n\n /** Step 3: the change with all its ops, sent. */\n const send = (begun: Begun, ops: readonly ChangeOp[], script: FormScriptResult | null): Sent => {\n const { request, hold } = begun;\n if (ops.length === 0) {\n hold?.cancel();\n return { script, changes: [], after: fields.view() };\n }\n if (!hold) {\n const label = labelOf(request, fields.view(), ops);\n const change = ctx.changes.stage({ label, ops, undo: undoLookOf(baseOf(begun), ops) });\n return { script, changes: [change], after: fields.view() };\n }\n if (hold.open) {\n hold.set(ops, undoLookOf(baseOf(begun), ops));\n const change = hold.send();\n return { script, changes: change ? [change] : [], after: fields.view() };\n }\n // Something sent the hold with the user's ops while the scripts ran (another plugin's\n // change, a download): the rest is a change of its own.\n const sent = hold.change;\n const rest = ops.filter((op) => !sent?.shows.some((shown) => sameOp(shown as ChangeOp, op)));\n const changes = sent ? [sent] : [];\n if (rest.length > 0) {\n const label = labelOf(request, fields.view(), rest);\n changes.push(ctx.changes.stage({ label, ops: rest, undo: undoLookOf(fields.view(), rest) }));\n }\n return { script, changes, after: fields.view() };\n };\n\n /** The user's ops went on their own and the scripts refused them: their fields are written back. */\n const takeBack = ({ request, before }: Begun): void => {\n const ops = fieldsNamedBy(before, request.ops).flatMap((field): ChangeOp[] => {\n const value = fieldValueOf(field);\n return value ? [{ type: 'forms.setValue', field: field.ref, value }] : [];\n });\n if (ops.length === 0) return;\n ctx.changes.stage({ label: labelOf(request, before, ops), ops, history: false });\n };\n\n /** The calculations again, against what the form shows now: one change, outside the history. */\n const recalculateNow = async (scripts: FormScripts, origin: ActionOrigin): Promise<void> => {\n const shown = fields.view().snapshot;\n if (!shown) return;\n const script = await scripts.recalculate(shown);\n scripting.surface(script, origin);\n if (script.status !== 'accepted' || script.effects.length === 0) return;\n ctx.changes.stage({\n label: RECALCULATE_LABEL,\n ops: formEffectOps(script.effects),\n history: false,\n });\n };\n\n /** Step 2: the scripts, against the view. */\n const runScripts = (\n scripts: FormScripts,\n begun: Begun,\n plan: FillScripts,\n ): Promise<FormScriptResult> | null => {\n const shown = fields.view().snapshot;\n if (!shown) return null;\n switch (plan.kind) {\n case 'commit': {\n // The value's own scripts read the form without it.\n const form = baseOf(begun).snapshot ?? shown;\n return scripts.commit(form, plan.field, plan.value);\n }\n case 'activate':\n return scripts.activate(shown, plan.field, plan.action);\n case 'recalculate':\n return scripts.recalculate(shown);\n }\n };\n\n /** Steps 2 and 3, when the fill's turn comes. */\n const finish = async (begun: Begun): Promise<Sent> => {\n const { request, hold } = begun;\n const plan = request.scripts;\n // A widget's action runs its own script; a value's scripts are the form's fields'.\n const pipeline = !plan\n ? null\n : plan.kind === 'activate'\n ? scripting.controller()\n : scripting.scriptsFor(fields.view());\n if (!plan || !pipeline) return send(begun, request.ops, null);\n if (!fields.view().snapshot) await fields.settled();\n try {\n // The ops are set inside the realm transaction: the next one reads the form with them.\n return await pipeline.transaction(async (scripts) => {\n const running = runScripts(scripts, begun, plan);\n if (!running) return send(begun, request.ops, null);\n const script = await running;\n scripting.surface(script, request.origin);\n const early = sentEarly(begun);\n if (script.status !== 'accepted') {\n hold?.cancel();\n if (early) takeBack(begun);\n if (script.status === 'rejected' && script.bootEffects.length > 0) {\n ctx.changes.stage({\n label: SCRIPTS_LABEL,\n ops: formEffectOps(script.bootEffects),\n history: false,\n });\n }\n return { script, changes: [], after: fields.view() };\n }\n if (early && !stillShown(begun)) {\n // The form shows other values for the user's fields now (an undo, a later fill): what\n // the scripts made of the user's values is stale, and the calculations run again.\n await recalculateNow(scripts, request.origin);\n return { script, changes: [hold!.change!], after: fields.view() };\n }\n const effects = formEffectOps(script.effects);\n return send(\n begun,\n plan.kind === 'recalculate' ? [...request.ops, ...effects] : effects,\n script,\n );\n });\n } catch (error) {\n hold?.cancel();\n throw error;\n }\n };\n\n /** What a sent fill did, once the engine answered. */\n const answered = async (begun: Begun, sent: Sent): Promise<FillOutcome> => {\n const { script } = sent;\n const scripted = script !== null;\n const reported = {\n scripted,\n uiEffects: script?.uiEffects ?? [],\n diagnostics: script?.diagnostics ?? [],\n ...(script?.error ? { error: script.error } : {}),\n };\n const outcome = (status: FormCommitResult['status']): FillOutcome => ({\n result: { status, ...reported },\n before: begun.before,\n after: sent.after,\n });\n if (script?.status === 'failed') return outcome('failed');\n if (script?.status === 'rejected') return outcome('rejected');\n let undoable = false;\n for (const change of sent.changes) {\n try {\n undoable = (await change.result).meta.undoable || undoable;\n } catch (error) {\n throw toPluginError('form', error);\n }\n }\n return outcome(undoable ? 'applied' : 'unchanged');\n };\n\n /**\n * Fill the form in: shown at once, sent when its turn comes; resolves once the engine\n * answered. A change the engine refuses rejects.\n */\n const fill = async (request: FillRequest, options?: OperationOptions): Promise<FillOutcome> => {\n const begun = begin(request);\n let sent: Sent;\n try {\n sent = await enqueue(() => finish(begun), options);\n } catch (error) {\n begun.hold?.cancel();\n throw toPluginError('form', error);\n }\n return ctx.cancellable(options?.signal, answered(begun, sent));\n };\n\n /**\n * Fill the form in without waiting: what a script's effects need, written while its own\n * transaction still runs. A failure is reported as the scripts' error.\n */\n const fillSoon = (request: FillRequest): void => {\n const begun = begin(request);\n void enqueue(() => finish(begun)).catch((error: unknown) => {\n begun.hold?.cancel();\n const message = toPluginError('form', error).message;\n scripting.surface(\n { uiEffects: [], diagnostics: [], error: scriptError(message) },\n request.origin,\n );\n });\n };\n\n // A fill the engine refused leaves the view, and the fills after it were calculated with its\n // values: the calculations run again against what is left.\n let recalculating = false;\n const recalculate = (): Promise<void> =>\n enqueue(async () => {\n recalculating = false;\n const pipeline = scripting.controller();\n if (pipeline) await pipeline.transaction((scripts) => recalculateNow(scripts, 'user'));\n });\n ctx.changes.onSettled((settled) => {\n if (settled.status !== 'refused' || settled.change.undoOf !== null) return;\n if (!FILLS.has(settled.change.label.key) || recalculating) return;\n const order = fields.view().snapshot?.calculationOrder ?? [];\n if (!scripting.controller() || !order.some((ref) => ref !== null)) return;\n recalculating = true;\n void recalculate().catch(() => {\n /* the scripts' failure is surfaced; a refused recalculation is reported by the queue */\n });\n });\n\n // A download waits for the fills on their way, and for the engine's answers to them.\n ctx.onSettle(async () => {\n await enqueue.idle();\n await ctx.changes.whenSettled();\n });\n\n return { fill, fillSoon };\n}\n\nexport type Fills = ReturnType<typeof createFill>;\n\n/** A fill that failed in the form's own scripts, as the verbs report it. */\nexport function failedFill(result: FormCommitResult): PluginError {\n return new PluginError(\n 'operation-failed',\n 'form',\n result.error?.message ?? result.diagnostics[0]?.message ?? 'the write failed',\n );\n}\n","/**\n * Fields in and out as bundles: whole fields with their widgets, values and\n * scripts, taken out of one document and copied into another, or the same.\n */\nimport type { FormCapability } from '../contract';\nimport type { FormContext, FormServices } from '../services';\n\nexport function createInterchange(\n ctx: FormContext,\n services: Pick<FormServices, 'siblings' | 'enqueue'>,\n) {\n const { enqueue, siblings } = services;\n\n const exportBundle: FormCapability['export'] = async (selection = {}, options) => {\n ctx.assertAllowed('doc.forms.read', 'form.export');\n ctx.assertAllowed('doc.download', 'form.export');\n const pages = selection.pages?.map((page) => ctx.pageOf(page).ref);\n // What the user sees is what the bundle carries: pending writes land first.\n return enqueue(\n () =>\n ctx.cancellable(\n options?.signal,\n ctx.doc.forms.export({\n ...(selection.fields ? { fields: selection.fields } : {}),\n ...(pages ? { pages } : {}),\n }),\n ),\n options,\n );\n };\n\n const importBundle: FormCapability['import'] = async (bundle, options = {}) => {\n const { signal, ...importOptions } = options;\n ctx.assertAllowed('doc.forms.modify', 'form.import');\n if ((importOptions.attribution ?? 'restore') === 'restore') {\n ctx.assertAllowed('doc.forms.import', 'form.import');\n }\n return enqueue(async () => {\n const result = await ctx.cancellable(signal, ctx.doc.forms.import(bundle, importOptions));\n // Wait for the annotation plugin to read the new widgets, as `create()` does.\n const annotationHost = siblings.annotation();\n if (annotationHost) await annotationHost.whenSynced();\n return { fields: result.fields, refMap: result.refMap, dropped: result.dropped };\n }, options);\n };\n\n return {\n api: { export: exportBundle, import: importBundle } satisfies Partial<FormCapability>,\n };\n}\n","/**\n * Design mode: the form's widgets, lent to the annotation plugin\n * (`AnnotationLender`, its host contract). While the session may design and\n * the active tool doesn't fill, the annotation plugin shows the widgets among\n * its records and edits them with its tools: select, move, resize, restyle,\n * reorder, delete. Each edit comes back here as the form's ops, in the same\n * change as the rest of it. While the tool fills, nothing is lent, and the\n * form layer draws and fills every widget.\n */\nimport { memo } from '@embedpdf/core';\nimport { refOf, type Effect, type Model } from '@embedpdf/core-annotation';\nimport {\n type AnnotationRef,\n type ChangeOp,\n type FormFieldDTO,\n type PageRef,\n type WidgetAnnotation,\n type WidgetPatch,\n} from '@embedpdf/engine-core/runtime';\nimport type { AnnotationLender } from '@embedpdf/plugin-annotation/contract/host';\n\nimport { fieldForWidget, fieldKeyOf } from '../model';\nimport type { FormContext, FormServices } from '../services';\nimport { undoLookOf } from '../sync/predict';\n\nconst objectNumberOf = (ref: AnnotationRef): number =>\n ref.kind === 'objectNumber' ? ref.objectNumber : -1;\n\nexport function createWidgetLender(\n ctx: FormContext,\n {\n fields,\n design,\n pictures,\n looks,\n }: Pick<FormServices, 'fields' | 'design' | 'pictures' | 'looks'>,\n): AnnotationLender {\n const records = memo(\n () => [design.lending(), fields.get().snapshot, fields.view().snapshot] as const,\n (lending, confirmed, shown) =>\n lending && confirmed && shown ? { confirmed: confirmed.widgets, shown: shown.widgets } : null,\n );\n\n /**\n * Deleted widgets, as the form's ops: a widget leaves its field\n * (`deleteWidget`), and a field whose every widget goes is deleted whole\n * (a merged field and widget among them).\n */\n const deleteOps = (deleted: readonly WidgetAnnotation[]): ChangeOp[] => {\n const index = fields.view();\n const ops: ChangeOp[] = [];\n const byField = new Map<string, { field: FormFieldDTO; widgets: WidgetAnnotation[] }>();\n for (const row of deleted) {\n const field = fieldForWidget(index, objectNumberOf(row.ref));\n if (!field) {\n ops.push({ type: 'forms.deleteWidget', widget: row.ref });\n continue;\n }\n const entry = byField.get(fieldKeyOf(field)) ?? { field, widgets: [] };\n entry.widgets.push(row);\n byField.set(fieldKeyOf(field), entry);\n }\n for (const { field, widgets } of byField.values()) {\n const going = new Set(widgets.map((row) => objectNumberOf(row.ref)));\n if (field.widgets.every((widget) => going.has(widget.objectNumber))) {\n ops.push({ type: 'forms.delete', field: field.ref });\n } else {\n ops.push(\n ...widgets.map((row): ChangeOp => ({ type: 'forms.deleteWidget', widget: row.ref })),\n );\n }\n }\n return ops;\n };\n\n return {\n owner: 'form',\n records,\n opsOf(effects: readonly Effect[], model: Model, before: Model) {\n const ops: ChangeOp[] = [];\n const deleted: WidgetAnnotation[] = [];\n for (const effect of effects) {\n if (effect.type === 'patch') {\n const ref = refOf(model.byId[effect.id]);\n if (!ref) continue;\n const { subtype: _subtype, ...patch } = effect.patch as WidgetPatch & {\n subtype?: string;\n };\n ops.push({ type: 'forms.updateWidget', widget: ref, patch: patch as WidgetPatch });\n } else if (effect.type === 'delete') {\n const record = before.byId[effect.id];\n if (record) deleted.push(record.annotation as WidgetAnnotation);\n }\n }\n return [...ops, ...deleteOps(deleted)];\n },\n undoOf: (ops) => undoLookOf(fields.view(), ops),\n reorderOps: (page: PageRef, refs, position) => [\n { type: 'forms.reorderWidgets', page, widgets: [...refs], position },\n ],\n authority: () => {\n const may = ctx.allows('doc.forms.modify');\n return { update: may, delete: may };\n },\n // The pictures the form layer draws too, from one store: switching modes\n // fetches nothing, and a page's pictures change only with its widgets.\n pictureEpoch: pictures.epoch,\n pictureVersion: pictures.versionOf,\n renderAppearances: pictures.render,\n // A widget draws live, by the painter, while a gesture reshapes it, while its look isn't\n // confirmed (a restyle, a resize, a field just placed), and until its new picture is there.\n pending: looks.isPending,\n painter: (record) =>\n record.subtype === 'widget' ? looks.painterOf(record as WidgetAnnotation) : null,\n };\n}\n","import type {\n FormFieldDTO,\n FormFieldRef,\n FormSubmissionEntry,\n PdfActionTargetRef,\n} from '@embedpdf/engine-core/runtime';\nimport type { ActionDiagnostic, SubmitIntent } from '@embedpdf/plugin-actions/contract';\n\n/**\n * ISO field selection, written once for ResetForm (Tables 241/242) and\n * SubmitForm (Tables 239/240): a name target selects the field and its\n * descendants (FQN dot-prefix — `parent` selects `parent.c1`, the rule the\n * old exact-match resolution violated); an objectNumber target selects that\n * field dictionary. Include mode keeps the selection; exclude mode keeps\n * the complement (a name excludes its subtree the same way it includes\n * it). `targets === null` (the key absent) selects everything and the flag\n * is ignored; `[]` + include selects nothing while `[]` + exclude selects\n * everything — presence and emptiness are different states.\n *\n * `listed` reports whether a field was addressed by the target list\n * (directly or through its subtree) — the \"explicitly listed\" predicate the\n * submit honesty diagnostics key on.\n */\nexport const resolveFieldSelection = <F extends { name: string; ref: FormFieldRef }>(\n all: readonly F[],\n targets: PdfActionTargetRef[] | null,\n exclude: boolean,\n): { selected: F[]; listed: (field: F) => boolean } => {\n if (targets === null) return { selected: [...all], listed: () => false };\n const names = targets.filter((target) => target.kind === 'name').map((target) => target.name);\n const objectNumbers = new Set(\n targets.filter((target) => target.kind === 'objectNumber').map((target) => target.objectNumber),\n );\n const listed = (field: F): boolean =>\n (field.ref.kind === 'objectNumber' && objectNumbers.has(field.ref.objectNumber)) ||\n names.some((name) => field.name === name || field.name.startsWith(`${name}.`));\n const selected = exclude ? all.filter((field) => !listed(field)) : all.filter(listed);\n return { selected, listed };\n};\n\n/**\n * Build the resolved submission dataset from a live field list (Tables\n * 239/240 semantics; pure — the capability supplies a fresh engine read so\n * no model-lag class exists):\n *\n * - the unconditional **NoExport veto** — even an explicit include cannot\n * override it (diagnosed when explicitly listed, so the veto is\n * observable, silent when swept in implicitly);\n * - **push-buttons and signatures** never contribute entries in v1 —\n * ISO's explicit-pushbutton-`/AP`-in-FDF rule is unrepresentable in the\n * current DTO, so an explicitly listed one is diagnosed\n * (`submit-entry-unsupported`), never silently dropped;\n * - an **unsupported `/V` shape** is always diagnosed (silent omission\n * would be data loss);\n * - a valueless field becomes a name-only entry (`value: null`) only under\n * IncludeNoValueFields, else it is skipped (the ISO default);\n * - values are entry-faithful: scalar → string, array (multi-select list\n * box) → string[]; the submitted name is the fully qualified name.\n */\nexport const buildSubmitEntries = (\n fields: readonly FormFieldDTO[],\n intent: SubmitIntent,\n diagnose: (diagnostic: ActionDiagnostic) => void,\n): FormSubmissionEntry[] => {\n const { selected, listed } = resolveFieldSelection(fields, intent.fields, intent.exclude);\n const explicitInclude = intent.fields !== null && !intent.exclude;\n const entries: FormSubmissionEntry[] = [];\n for (const field of selected) {\n const explicit = explicitInclude && listed(field);\n if (field.family === 'pushbutton' || field.family === 'signature') {\n if (explicit) {\n diagnose({\n code: 'submit-entry-unsupported',\n message: `submit: '${field.name}' (${field.family}) has no representable submission value in v1 — skipped`,\n });\n }\n continue;\n }\n if (field.noExport) {\n if (explicit) {\n diagnose({\n code: 'submit-entry-unsupported',\n message: `submit: '${field.name}' carries the NoExport flag — the veto is unconditional (ISO 12.7.6.2), skipped`,\n });\n }\n continue;\n }\n const entry = field.valueEntry;\n if (entry.kind === 'scalar') {\n entries.push({ name: field.name, value: entry.value });\n } else if (entry.kind === 'array') {\n entries.push({ name: field.name, value: entry.values });\n } else if (entry.kind === 'none') {\n if (intent.includeNoValueFields) entries.push({ name: field.name, value: null });\n } else {\n diagnose({\n code: 'submit-entry-unsupported',\n message: `submit: '${field.name}' has an unsupported /V shape — skipped (would otherwise be silent data loss)`,\n });\n }\n }\n return entries;\n};\n","/**\n * Resets: one shared core (one fill: the reset, then the recalculation when the document's\n * scripts run) used by both the ResetForm action executor and the public `reset`, so the two\n * cannot diverge. A reset resets the fields it selects that the user may fill in: another\n * signer's fields stay as they are.\n */\nimport type { OperationOptions } from '@embedpdf/core';\nimport type { FormFieldDTO, FormFieldRef, PdfActionTargetRef } from '@embedpdf/engine-core/runtime';\nimport type { ActionOrigin } from '@embedpdf/plugin-actions/contract';\n\nimport type { FormCommitResult } from '../contract';\nimport { resolveFieldSelection } from '../field-selection';\nimport type { FormHostCapability } from '../host-contract';\nimport { fieldByRef, fieldsWithChangedValues } from '../model';\nimport type { FormContext, FormServices } from '../services';\nimport type { FillOutcome, Fills } from './fill';\n\n/** A reset of no fields: what the executor reports as inert. */\nconst NOTHING_RESET: FormCommitResult = {\n status: 'unchanged',\n scripted: false,\n uiEffects: [],\n diagnostics: [],\n};\n\n/** A field ref as an action's target: by object number, or by full name. */\nconst targetOf = (ref: FormFieldRef): PdfActionTargetRef =>\n ref.kind === 'objectNumber'\n ? { kind: 'objectNumber', objectNumber: ref.objectNumber }\n : { kind: 'name', name: ref.name };\n\nexport function createResetWrites(\n _ctx: FormContext,\n services: Pick<FormServices, 'fields' | 'rights'>,\n { fill }: Fills,\n) {\n const { fields, rights } = services;\n\n /**\n * Whether a reset puts this field back: the engine refuses push button and\n * signature refs, and another signer's fields are theirs.\n */\n const resettable = (field: FormFieldDTO): boolean =>\n field.family !== 'pushbutton' && field.family !== 'signature' && rights.mayFill(field);\n\n /**\n * Reset the selected fields, then recalculate, as one change. `origin` is carried through to\n * the surfaced recalculation results, so a ResetForm run by a page or hover trigger never\n * reports its alerts as a user action. `null` when it selects nothing; a refused reset throws:\n * none of it was written.\n */\n const resetSelection = async (\n targets: PdfActionTargetRef[] | null,\n exclude: boolean,\n origin: ActionOrigin,\n options?: OperationOptions,\n ): Promise<FillOutcome | null> => {\n if (!fields.view().snapshot) await fields.settled();\n // ISO 32000-2 Tables 241/242: a parent name resets its descendants too.\n const { selected } = resolveFieldSelection(\n fields.view().snapshot?.fields ?? [],\n targets,\n exclude,\n );\n // An exclude-mode complement always includes the form's buttons. Zero refs must not reach\n // the engine (it refuses an empty reset); an include list of `[]` resets nothing.\n const refs = selected.filter(resettable).map((field) => field.ref);\n if (refs.length === 0) return null;\n return fill(\n {\n label: { key: 'form.reset', count: refs.length },\n ops: [{ type: 'forms.reset', fields: refs }],\n scripts: { kind: 'recalculate' },\n origin,\n },\n options,\n );\n };\n\n const reset: FormHostCapability['reset'] = async (refs, options) => {\n // A field you name is one you mean: one you may not fill in refuses the reset.\n for (const ref of refs ?? []) {\n const field = fieldByRef(fields.view(), ref);\n if (field) rights.assertMayFill(field, 'form.reset');\n }\n if (refs && refs.length === 0) return { fields: [] };\n const outcome = await resetSelection(refs ? refs.map(targetOf) : null, false, 'user', options);\n // What changed is what holds another value after the reset and its recalculation.\n return { fields: outcome ? fieldsWithChangedValues(outcome.before, outcome.after) : [] };\n };\n\n return {\n api: {\n reset,\n resetFormAction: async (targets, exclude, origin = 'user') => {\n const outcome = await resetSelection(targets, exclude, origin);\n if (!outcome) return NOTHING_RESET;\n // The action ran, even on fields already at their defaults.\n const { result } = outcome;\n return result.status === 'unchanged' ? { ...result, status: 'applied' } : result;\n },\n } satisfies Partial<FormHostCapability>,\n };\n}\n","/**\n * The actions plugin's seams into the form plugin: the form-effects commit\n * sink (script `setValue`, `setDisplay` and reset effects are written through\n * the plugin that owns the fields, as one fill with the calculations they\n * cause) and the submit dataset resolver.\n */\nimport {\n formEffectOps,\n serializeError,\n type FormEffect,\n type FormFieldRef,\n} from '@embedpdf/engine-core/runtime';\nimport type {\n ActionContext,\n ActionDiagnostic,\n ActionSubmitRequest,\n SubmitIntent,\n} from '@embedpdf/plugin-actions/contract';\n\nimport { buildSubmitEntries } from '../field-selection';\nimport type { FormHostCapability } from '../host-contract';\nimport { fieldByRef } from '../model';\nimport type { FormContext, FormServices } from '../services';\nimport type { Fills } from './fill';\n\n/** The fields a script's effects write to. */\nconst refsOf = (effects: readonly FormEffect[]): FormFieldRef[] =>\n effects.flatMap((effect) => (effect.kind === 'reset' ? effect.refs : [effect.ref]));\n\nexport function createScriptEffects(\n ctx: FormContext,\n { fields, rights, enqueue }: Pick<FormServices, 'fields' | 'rights' | 'enqueue'>,\n { fillSoon }: Fills,\n) {\n /**\n * The submit dataset: the fields as the user sees them once every fill on its way is\n * answered, then the pure ISO builder. Selection, veto and value semantics live in\n * `field-selection.ts`; this only supplies the fields and assembles the request.\n */\n const resolveSubmitDataset = async (\n intent: SubmitIntent,\n actionContext: ActionContext,\n diagnose: (diagnostic: ActionDiagnostic) => void,\n ): Promise<ActionSubmitRequest> => {\n await enqueue.idle();\n await ctx.changes.whenSettled();\n if (!fields.view().snapshot) await fields.settled();\n return {\n url: intent.url,\n method: intent.method,\n format: intent.format,\n flagsRaw: intent.flagsRaw,\n ...(intent.charSet === undefined ? {} : { charSet: intent.charSet }),\n entries: buildSubmitEntries(fields.view().snapshot?.fields ?? [], intent, diagnose),\n origin: actionContext.origin,\n event: actionContext.event,\n };\n };\n\n return {\n api: {\n resolveSubmitDataset,\n commitScriptFormEffects: async (effects) => {\n try {\n // A field the session may not fill in is refused here, at once: the script learns\n // its write failed, as it would from the engine.\n for (const ref of refsOf(effects)) {\n const field = fieldByRef(fields.view(), ref);\n if (field) rights.assertMayFill(field, 'form.fill');\n }\n // The script's realm transaction is still running: the effects show at once, and\n // the calculations a value causes run once it ends, in the same change.\n const recalculates = effects.some(\n (effect) => effect.kind === 'setValue' || effect.kind === 'reset',\n );\n fillSoon({\n ops: formEffectOps(effects),\n scripts: recalculates ? { kind: 'recalculate' } : null,\n origin: 'user',\n });\n return { status: 'applied' };\n } catch (error) {\n // The sink never throws: a change it can't stage reports why.\n return { status: 'failed', error: serializeError(error).message };\n }\n },\n } satisfies Partial<FormHostCapability>,\n };\n}\n","/**\n * The text someone is typing in a field, before it's written. A text field commits on blur or\n * Enter, when its scripts run (as in Acrobat), so what is typed waits here, one draft per field.\n * A download writes the drafts first (`ctx.onSettle`), the way Acrobat commits the field being\n * edited before it saves.\n */\nimport type { FormFieldRef } from '@embedpdf/engine-core/runtime';\n\nimport type { FormSetValueResult } from '../contract';\nimport type { FormContext, FormServices } from '../services';\n\nexport function createTyping(\n ctx: Pick<FormContext, 'onSettle'>,\n { keyOf }: Pick<FormServices, 'keyOf'>,\n setText: (field: FormFieldRef, text: string) => Promise<FormSetValueResult>,\n) {\n /** The text typed in each field and not written yet, by field key. */\n const drafts = new Map<string, { readonly field: FormFieldRef; readonly text: string }>();\n\n /** Write the field's draft, if it has one; `null` when there is nothing to write. */\n const commitDraftText = async (field: FormFieldRef): Promise<FormSetValueResult | null> => {\n const key = keyOf(field);\n const draft = drafts.get(key);\n if (!draft) return null;\n drafts.delete(key);\n return setText(draft.field, draft.text);\n };\n\n ctx.onSettle(async () => {\n await Promise.all([...drafts.values()].map((draft) => commitDraftText(draft.field)));\n });\n\n return {\n api: {\n draftText: (field: FormFieldRef, text: string): void => {\n drafts.set(keyOf(field), { field, text });\n },\n commitDraftText,\n discardDraftText: (field: FormFieldRef): void => {\n drafts.delete(keyOf(field));\n },\n },\n };\n}\n","/**\n * Value writes, each one fill (write/fill.ts): one field through the form's scripts (when the\n * `validation` setting runs them), and the batch verbs, whose plain values go as one change\n * with one recalculation, as a script's `field.value` assignments do in Acrobat.\n */\nimport {\n PluginError,\n toPluginError,\n toPluginErrorInfo,\n type BatchResult,\n type OperationOptions,\n type PluginErrorInfo,\n} from '@embedpdf/core';\nimport {\n fieldValueWriteOf,\n type ChangeOp,\n type FormFieldRef,\n type FormFieldValue,\n} from '@embedpdf/engine-core/runtime';\n\nimport type { FormCapability, FormSetValueResult } from '../contract';\nimport { fieldByRef } from '../model';\nimport { writeOfPlainValue } from '../read/fields';\nimport type { FormContext, FormServices } from '../services';\nimport { failedFill, type Fills } from './fill';\n\n/** A batch that stops when its caller cancels it. */\nfunction throwIfCancelled(options?: OperationOptions): void {\n if (options?.signal?.aborted) {\n throw new PluginError('operation-cancelled', 'form', 'operation cancelled', {\n cause: options.signal.reason,\n });\n }\n}\n\nconst setValueOp = (field: FormFieldRef, value: FormFieldValue): ChangeOp => ({\n type: 'forms.setValue',\n field,\n value,\n});\n\nexport function createValueWrites(\n _ctx: FormContext,\n services: Pick<FormServices, 'events' | 'fields' | 'rights'>,\n { fill }: Fills,\n) {\n const { validationRejected } = services.events;\n const { fields, rights } = services;\n\n /** One field's value through its scripts: shown at once, written as one change. */\n const commit = async (\n ref: FormFieldRef,\n value: FormFieldValue,\n operation: string,\n options?: OperationOptions,\n ): Promise<FormSetValueResult> => {\n const known = fieldByRef(fields.view(), ref);\n // A field the form doesn't show yet is the engine's to answer (`not-found`).\n if (known) rights.assertMayFill(known, operation);\n const { result } = await fill(\n {\n ops: [setValueOp(ref, value)],\n scripts: { kind: 'commit', field: ref, value },\n origin: 'user',\n },\n options,\n );\n if (result.status === 'failed') throw failedFill(result);\n const field = fieldByRef(fields.get(), ref);\n if (!field) throw new PluginError('not-found', 'form', 'no form field has this ref');\n if (result.status === 'rejected') {\n validationRejected.emit({ field, issues: result.diagnostics });\n return { field, status: 'rejected' };\n }\n return { field, status: result.status };\n };\n\n /**\n * Plain values for several fields, as one change with one recalculation. A value its field\n * can't take, or a field the session may not fill in, fails on its own; the rest go together,\n * and fail together when the engine refuses them.\n */\n const fillPlain = async (\n entries: readonly { readonly ref: FormFieldRef; readonly value: FormFieldValue }[],\n options?: OperationOptions,\n ): Promise<{\n applied: FormFieldRef[];\n failed: { ref: FormFieldRef; error: PluginErrorInfo }[];\n }> => {\n if (!fields.view().snapshot) await fields.settled();\n const index = fields.view();\n const accepted: { ref: FormFieldRef; value: FormFieldValue }[] = [];\n const failed: { ref: FormFieldRef; error: PluginErrorInfo }[] = [];\n for (const entry of entries) {\n try {\n const field = fieldByRef(index, entry.ref);\n if (!field) throw new PluginError('not-found', 'form', 'no form field has this ref');\n rights.assertMayFill(field, 'form.setValues');\n fieldValueWriteOf(field, entry.value);\n accepted.push({ ref: field.ref, value: entry.value });\n } catch (error) {\n failed.push({ ref: entry.ref, error: toPluginErrorInfo(toPluginError('form', error)) });\n }\n }\n if (accepted.length === 0) return { applied: [], failed };\n throwIfCancelled(options);\n try {\n const { result } = await fill(\n {\n ops: accepted.map((entry) => setValueOp(entry.ref, entry.value)),\n scripts: { kind: 'recalculate' },\n origin: 'user',\n },\n options,\n );\n if (result.status === 'failed') throw failedFill(result);\n return { applied: accepted.map((entry) => entry.ref), failed };\n } catch (error) {\n const info = toPluginErrorInfo(toPluginError('form', error));\n return {\n applied: [],\n failed: [...failed, ...accepted.map(({ ref }) => ({ ref, error: info }))],\n };\n }\n };\n\n const setValues: FormCapability['setValues'] = async (entries, options) => {\n throwIfCancelled(options);\n const { applied, failed } = await fillPlain(entries, options);\n return { applied, skipped: [], failed };\n };\n\n const importValues: FormCapability['importValues'] = async (values, options) => {\n throwIfCancelled(options);\n if (!fields.view().snapshot) await fields.settled();\n const index = fields.view();\n const skipped: { ref: string; reason: string }[] = [];\n const entries: { ref: FormFieldRef; value: FormFieldValue }[] = [];\n const names = new Map<string, string>();\n for (const [name, plain] of Object.entries(values)) {\n const field = fieldByRef(index, { kind: 'fqn', name });\n if (!field) {\n skipped.push({ ref: name, reason: 'the form has no field with this name' });\n continue;\n }\n if (!rights.mayFill(field)) {\n skipped.push({ ref: name, reason: 'you may not fill in this field' });\n continue;\n }\n const value = writeOfPlainValue(field, plain);\n if (!value) {\n skipped.push({ ref: name, reason: `a ${field.family} field can't take this value` });\n continue;\n }\n entries.push({ ref: field.ref, value });\n names.set(JSON.stringify(field.ref), name);\n }\n const { applied, failed } = await fillPlain(entries, options);\n return {\n applied,\n skipped,\n failed: failed.map(({ ref, error }) => ({\n ref: names.get(JSON.stringify(ref)) ?? '',\n error,\n })),\n } satisfies BatchResult<FormFieldRef, string>;\n };\n\n return {\n /** A text field's write, for the text being typed (write/typing.ts). */\n setText: (ref: FormFieldRef, text: string): Promise<FormSetValueResult> =>\n commit(ref, { value: text }, 'form.setValue'),\n api: {\n setValue: (ref, value, options) => commit(ref, value, 'form.setValue', options),\n setValues,\n importValues,\n } satisfies Partial<FormCapability>,\n };\n}\n","/**\n * The form controller: the composition root. It builds the plugin's services\n * once, wires each area with the services it declares, and assembles the\n * host capability from the areas' API slices. No behavior lives here: every\n * verb and read has a home in `read/`, `write/` or `sync/`.\n */\nimport { composeApi } from '@embedpdf/core';\nimport type { FormFieldRef } from '@embedpdf/engine-core/runtime';\n\nimport { connectForm } from './connect';\nimport type { FormHostCapability } from './host-contract';\nimport { fieldByRef } from './model';\nimport { createFieldReads } from './read/fields';\nimport { createFieldSettings } from './read/settings';\nimport { createWidgetReads } from './read/widgets';\nimport { createServices, type FormContext } from './services';\nimport { createActivation } from './write/activation';\nimport { createFieldWrites } from './write/fields';\nimport { createFill } from './write/fill';\nimport { createInterchange } from './write/interchange';\nimport { createWidgetLender } from './write/lending';\nimport { createResetWrites } from './write/reset';\nimport { createScriptEffects } from './write/script-effects';\nimport { createTyping } from './write/typing';\nimport { createValueWrites } from './write/values';\n\nexport function createFormController(ctx: FormContext) {\n const services = createServices(ctx);\n const { events, rights } = services;\n const settings = ctx.settings();\n\n const fields = createFieldReads(ctx, services);\n const widgets = createWidgetReads(ctx, services);\n const settingsReads = createFieldSettings(services);\n\n const fills = createFill(ctx, services);\n const values = createValueWrites(ctx, services, fills);\n const typing = createTyping(ctx, services, values.setText);\n const resets = createResetWrites(ctx, services, fills);\n const design = createFieldWrites(ctx, services);\n const interchange = createInterchange(ctx, services);\n const activation = createActivation(ctx, services, fills);\n const scripts = createScriptEffects(ctx, services, fills);\n\n const api: FormHostCapability = composeApi('form', [\n settings.api,\n fields.api,\n widgets.api,\n settingsReads.api,\n values.api,\n typing.api,\n resets.api,\n design.api,\n interchange.api,\n activation.api,\n scripts.api,\n {\n canRead: () => ctx.allows('doc.forms.read'),\n canFill: (ref: FormFieldRef) => {\n const field = fieldByRef(services.fields.view(), ref);\n return field !== null && rights.mayFill(field);\n },\n canDesign: () => ctx.allows('doc.forms.modify'),\n canRestoreAttribution: () => ctx.allows('doc.forms.import'),\n canWriteScripts: () => ctx.allows('doc.forms.script'),\n onValueChanged: events.valueChanged.on,\n onFieldCreated: events.fieldCreated.on,\n onFieldUpdated: events.fieldUpdated.on,\n onFieldDeleted: events.fieldDeleted.on,\n onValidationRejected: events.validationRejected.on,\n onResynced: events.resynced.on,\n },\n ]);\n\n return {\n api,\n connect: () => connectForm(ctx, api, createWidgetLender(ctx, services)),\n };\n}\n","import { definePlugin } from '@embedpdf/core';\nimport { ActionsToken } from '@embedpdf/plugin-actions/contract';\nimport { AnnotationToken } from '@embedpdf/plugin-annotation/contract';\nimport { InteractionToken } from '@embedpdf/plugin-interaction/contract/host';\nimport { RenderToken } from '@embedpdf/plugin-render/contract';\n\nimport { FORM_DEFAULTS, type FormConfig } from './contract';\nimport { createFormController } from './controller';\nimport { FormToken } from './host-contract';\nimport { initialFormState } from './model';\n\n/**\n * The form plugin: the field plane. Document-scoped; requires the\n * interaction hub. Filling works without the annotation plugin, because\n * widget geometry is read from the engine's widget records. The active tool\n * is the mode switch: while it carries 'form-fill' (the built-in pointer and\n * pan tools do, so filling is the resting state), the form layer draws and\n * fills every widget. Design mode is the 'form-edit' and palette tools: with\n * the annotation plugin present, the form lends it the widgets, which its\n * tools then select, move, restyle and delete. The render plugin draws the\n * widgets' pictures in both modes. `config` is the settings the app\n * registers, over {@link FORM_DEFAULTS}.\n */\nexport const formPlugin = (config?: FormConfig) =>\n definePlugin({\n id: 'form',\n token: FormToken,\n scope: 'document',\n requires: [InteractionToken],\n optional: [AnnotationToken, ActionsToken, RenderToken],\n state: initialFormState,\n settings: { defaults: FORM_DEFAULTS, registered: config },\n create: createFormController,\n });\n","/**\n * The form page's State table as code: what `useFormState()` returns, and the\n * same fields in every other framework. One field's value has its own hook\n * (`useFormValue(ref)`), so a total in your own UI re-renders only when that\n * field changes.\n */\nimport { defineState } from '@embedpdf/core';\nimport type { FormFieldDTO } from '@embedpdf/engine-core/runtime';\n\nimport { FormToken } from './contract';\n\nconst NO_FIELDS: readonly FormFieldDTO[] = Object.freeze([]);\n\nexport const formState = defineState(FormToken, {\n read: (form) => ({\n fields: form.list(),\n status: form.getStatus(),\n formKind: form.getFormKind(),\n selectedField: form.getSelectedField(),\n }),\n empty: {\n fields: NO_FIELDS,\n status: 'idle',\n formKind: 'none',\n selectedField: null,\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;AA4CA,MAAa,aAAa,CAAC,cAAc,iBAAiB;AAE1D,MAAM,eAAiC;CACrC,eAAe;CACf,OAAO;CACP,aAAa;AACf;AAEA,MAAa,aAAqC;CAChD;EACE,IAAI;EACJ,QAAQ;EACR,YAAY;EACZ,aAAa;GAAE,OAAO;GAAK,QAAQ;EAAG;EACtC,UAAU;GAAE,GAAG;GAAc,UAAU;EAAG;EAC1C,QAAQ;CACV;CACA;EACE,IAAI;EACJ,QAAQ;EACR,YAAY;EACZ,aAAa;GAAE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,QAAQ;EACR,cAAc;EACd,OAAO;EACP,OAAO;EACP,OAAO;EACP,OAAO;EACP,YAAY;EACZ,WAAW;EACX,QAAQ;EACR;GACE,eAAe,IAAI,OAAO,gBAAgB;GAC1C,UAAU,QAAsB;IAC9B,MAAM,QAAQ,WAAW,SAAS,OAAO,KAAK,GAAG,GAAG;IACpD,OAAO,UAAU,QAAQ,OAAO,QAAQ,KAAK;GAC/C;GACA,iBAAiB,IAAI,OAAO,kBAAkB;GAC9C,6BAA6B,IAAI,OAAO,kBAAkB;GAC1D,uBAAuB,IAAI,OAAO,kBAAkB;GACpD,gBAAgB,OAAO,aAAa;GACpC,gBAAgB,OAAO,aAAa;GACpC,gBAAgB,OAAO,aAAa;GACpC,gBAAgB,OAAO,aAAa;GACpC,sBAAsB,OAAO,mBAAmB;GAChD,YAAY,OAAO,SAAS;EAC9B;CACF,CAAC;CAED,OAAO;EACL;EACA,eAAe,YAAY,KAAK,KAAK,mBAAmB,KAAK,QAAQ,CAAC;CACxE;AACF;;;;;;;;;;;;;;;ACvDA,MAAa,cAAc,WACzB,aAAa;CACX,IAAI;CACJ,OAAOC;CACP,OAAO;CACP,UAAU,CAAC,gBAAgB;CAC3B,UAAU;EAAC;EAAiB;EAAc;CAAW;CACrD,OAAO;CACP,UAAU;EAAE,UAAU;EAAe,YAAY;CAAO;CACxD,QAAQ;AACV,CAAC;ACpBH,MAAa,YAAY,YAAY,WAAW;CAC9C,OAAO,UAAU;EACf,QAAQ,KAAK,KAAK;EAClB,QAAQ,KAAK,UAAU;EACvB,UAAU,KAAK,YAAY;EAC3B,eAAe,KAAK,iBAAiB;CACvC;CACA,OAAO;EACL,QAVuC,OAAO,OAAO,CAAC,CAU9C;EACR,QAAQ;EACR,UAAU;EACV,eAAe;CACjB;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["AnnotationHostToken","ActionsHostToken","widgetNumber","NO_FIELDS","valueOf","NOTHING_SHOWN","AnnotationHostToken","ActionsHostToken","RenderHostToken","FormToken"],"sources":["../src/tools/definitions.ts","../src/tools/handlers.ts","../src/connect.ts","../src/model.ts","../src/read/fields.ts","../src/read/settings.ts","../src/read/fill-items.ts","../src/read/widgets.ts","../src/sync/predict.ts","../src/sync/fields.ts","../src/services/design.ts","../src/services/events.ts","../src/services/fill-rights.ts","../src/services/formatted.ts","../src/services/looks.ts","../src/services/pictures.ts","../src/services/scripting.ts","../src/services/siblings.ts","../src/services/index.ts","../src/write/activation.ts","../src/services/object-numbers.ts","../src/write/next-in-line.ts","../src/write/fields.ts","../src/write/fill.ts","../src/write/interchange.ts","../src/write/lending.ts","../src/field-selection.ts","../src/write/reset.ts","../src/write/script-effects.ts","../src/write/typing.ts","../src/write/values.ts","../src/controller.ts","../src/form.plugin.ts","../src/state.ts"],"sourcesContent":["/**\n * The form-tool table — the single source of truth for the palette. Every\n * derivation reads this one list: interaction registration (annotation-less),\n * annotation tool/style registration (full viewer), active-tool → field\n * family lookup, click placement, and default appearance. With the\n * annotation plugin each tool shows a ghost: the field a click places, drawn\n * with the tool's defaults where it will land.\n *\n * \"One tool system, two commit planes\": the tools live in the annotation\n * registry when that plugin is present (defaults, style panel, click-create —\n * the shared authoring infrastructure), but the commit always goes\n * through `form.create()` from the form place handler. The tags make\n * that structural: these tools enable `form-place`, never `annotation-draw`,\n * so the annotation draw handler can't wake up for them.\n */\nimport type { FormFieldFamily, WidgetAppearance } from '@embedpdf/engine-core/runtime';\nimport type { ClickCreate } from '@embedpdf/plugin-annotation/contract';\n\n/** The families the palette places. */\nexport type AuthorableFormFamily = Exclude<FormFieldFamily, 'unknown'>;\n\nexport interface FormToolDef {\n id: string;\n /** The field family the tool places (the form plane's vocabulary). */\n family: AuthorableFormFamily;\n /** The client kind the annotation registry routes on (props panel).\n * Not a PDF subtype — every widget is PDF `widget`; this is the view. */\n visualKind:\n | 'widget-text'\n | 'widget-choice'\n | 'widget-button'\n | 'widget-toggle'\n | 'widget-radio'\n | 'widget-box';\n /** What a bare click places (box policies only — fields are boxes). */\n clickCreate: Extract<ClickCreate, { width: number }>;\n /** Seed drawing defaults, the widget's appearance fields: a placed field is\n * visible (white box, gray border) and restylable per tool through the\n * shared style panel. */\n defaults: WidgetAppearance;\n cursor: string;\n}\n\n/** Palette tools keep widgets editable right after placement. */\nexport const PLACE_TAGS = ['form-place', 'annotation-edit'] as const;\n\nconst FIELD_CHROME: WidgetAppearance = {\n interiorColor: '#ffffff',\n color: '#6b7280',\n strokeWidth: 1,\n};\n\nexport const FORM_TOOLS: readonly FormToolDef[] = [\n {\n id: 'form-text',\n family: 'text',\n visualKind: 'widget-text',\n clickCreate: { width: 160, height: 24 },\n defaults: { ...FIELD_CHROME, fontSize: 12 },\n cursor: 'crosshair',\n },\n {\n id: 'form-checkbox',\n family: 'checkbox',\n visualKind: 'widget-toggle',\n clickCreate: { width: 18, height: 18 },\n defaults: FIELD_CHROME,\n cursor: 'crosshair',\n },\n {\n id: 'form-radio',\n family: 'radio',\n // Round, as the engine draws a radio button: its ghost and its placement too.\n visualKind: 'widget-radio',\n clickCreate: { width: 18, height: 18 },\n defaults: FIELD_CHROME,\n cursor: 'crosshair',\n },\n {\n id: 'form-combobox',\n family: 'combobox',\n visualKind: 'widget-choice',\n clickCreate: { width: 140, height: 24 },\n defaults: { ...FIELD_CHROME, fontSize: 12 },\n cursor: 'crosshair',\n },\n {\n id: 'form-listbox',\n family: 'listbox',\n visualKind: 'widget-choice',\n clickCreate: { width: 140, height: 72 },\n defaults: { ...FIELD_CHROME, fontSize: 12 },\n cursor: 'crosshair',\n },\n // A push button: its caption is its text; what it does is its actions.\n {\n id: 'form-button',\n family: 'pushbutton',\n visualKind: 'widget-button',\n clickCreate: { width: 100, height: 28 },\n defaults: { ...FIELD_CHROME, interiorColor: '#e5e7eb', fontSize: 12 },\n cursor: 'crosshair',\n },\n // A signature field: the bare widget box every non-text family ingests\n // as (`widget-box`). It has no value of its own to style — the signing\n // act (the signature plugin) draws the mark into it later.\n {\n id: 'form-signature',\n family: 'signature',\n visualKind: 'widget-box',\n clickCreate: { width: 160, height: 48 },\n defaults: FIELD_CHROME,\n cursor: 'crosshair',\n },\n];\n\nexport const FORM_TOOL_BY_ID: ReadonlyMap<string, FormToolDef> = new Map(\n FORM_TOOLS.map((tool) => [tool.id, tool]),\n);\n","import { gesturePlacement, widgetAppearanceOf } from '@embedpdf/core-annotation';\nimport type { FormFieldDraft, PageRef, WidgetPlacement } from '@embedpdf/engine-core/runtime';\nimport type { AnnotationHostCapability } from '@embedpdf/plugin-annotation/contract/host';\nimport {\n samplePointOn,\n type InteractionHandler,\n type InteractionHostCapability,\n} from '@embedpdf/plugin-interaction/contract/host';\n\nimport type { FormHostCapability } from '../host-contract';\nimport type { Box } from '../model';\nimport { FORM_TOOL_BY_ID, type FormToolDef } from './definitions';\n\ntype Vec = { x: number; y: number };\n\n/** A name for a field placed with a tool: `text_1`, `text_2`, …, the first one the form doesn't have. */\nexport function nextFieldName(family: string, taken: ReadonlySet<string>): string {\n let count = 1;\n while (taken.has(`${family}_${count}`)) count++;\n return `${family}_${count}`;\n}\n\n/** The part of a box on the page; `null` when too little of it is. */\nexport function clampToPage(box: Box, page: Box): Box | null {\n const x = Math.max(page.x, Math.min(box.x, page.width));\n const y = Math.max(page.y, Math.min(box.y, page.height));\n const clamped = {\n x,\n y,\n width: Math.max(0, Math.min(box.x + box.width, page.width) - x),\n height: Math.max(0, Math.min(box.y + box.height, page.height) - y),\n };\n return clamped.width < 1 || clamped.height < 1 ? null : clamped;\n}\n\n/**\n * The field a palette tool places: one widget at `widget`, named like\n * `text_1`. A radio button stands for `'Choice1'` and a dropdown or a list\n * starts with two options, as in Acrobat; rename and change them in a\n * settings panel.\n */\nexport function toolDraft(\n tool: FormToolDef,\n name: string,\n widget: WidgetPlacement,\n): FormFieldDraft {\n switch (tool.family) {\n case 'radio':\n return { family: 'radio', name, widgets: [{ ...widget, exportValue: 'Choice1' }] };\n case 'combobox':\n case 'listbox':\n return {\n family: tool.family,\n name,\n widgets: [widget],\n options: [\n { label: 'Option 1', value: 'Option 1' },\n { label: 'Option 2', value: 'Option 2' },\n ],\n };\n case 'pushbutton':\n return { family: 'pushbutton', name, widgets: [{ ...widget, caption: 'Button' }] };\n default:\n return { family: tool.family, name, widgets: [widget] };\n }\n}\n\n/**\n * Draw-to-place: drag a box or just click. The commit creates the field and\n * its widget through `form.create()`, styled from the tool's live defaults.\n * Where the field goes is `gesturePlacement`, the call the annotation core\n * makes for its own drawings: the dragged box once the gesture is a drag\n * (the shared click ↔ drag threshold), else the tool's `clickCreate` box.\n * What follows is the annotation plugin's `afterCreate` setting, as for\n * every tool: select the new widget, and keep the tool or go back to the\n * default one.\n *\n * With the annotation plugin, the tool's ghost shows the field a click\n * places: this handler's hover puts it where the click would reach it (no\n * widget or annotation under the pointer claims it) and the user may design\n * forms. The gesture reports itself (`previewPlacement`), so once it drags\n * the page paints the field the release places, a radio button round.\n *\n * Gesture rules match the annotation handlers: page-anchored via the sample\n * projection (the box keeps sizing along the edge when the cursor overshoots\n * or crosses a gap), and the up sample is the final point.\n */\nexport function createPlaceHandler(\n form: FormHostCapability,\n interaction: InteractionHostCapability,\n annotation: AnnotationHostCapability | null,\n): InteractionHandler {\n let origin: { page: PageRef; start: Vec; last: Vec } | null = null;\n /** Drop the gesture and what it painted: its placement and the tool's ghost. */\n const endGesture = (): void => {\n origin = null;\n annotation?.clearPlacementPreview();\n annotation?.clearGhost();\n };\n\n const place = async (tool: FormToolDef, page: PageRef, box: Box): Promise<void> => {\n const pageBox = form.getPageBox(page);\n const rect = pageBox ? clampToPage(box, pageBox) : null;\n if (!rect) return;\n // Style from the tool's live defaults when the annotation plugin holds\n // them (the user may have restyled the tool); without it, use the tool\n // table's defaults, so a field is never invisible.\n const look = widgetAppearanceOf(\n annotation ? annotation.tools.getDefaults(tool.id) : tool.defaults,\n );\n const name = nextFieldName(tool.family, new Set(form.list().map((field) => field.name)));\n // The new field shows at once, when the document holds the numbers it\n // takes: then it is selected in the same frame. Otherwise once it shows.\n const created = form.create(toolDraft(tool, name, { page, rect, ...look }));\n const field = form.get({ kind: 'fqn', name }) ?? (await created).field;\n // Skip the follow-up when the tool changed meanwhile.\n if (!annotation || interaction.getActiveToolId() !== tool.id) return;\n const policy = annotation.getSettings().afterCreate;\n const widget = field.widgets.find(\n (candidate) => candidate.page?.objectNumber === page.objectNumber,\n );\n if (policy.select && widget?.ref) annotation.selection.set([widget.ref]);\n // Back to design's resting tool, not the default pointer: that one fills, which would end\n // design and drop the new field's selection.\n if (policy.tool === 'default') interaction.activateTool('form-edit');\n await created;\n };\n\n return {\n id: 'form-place',\n // Above the annotation edit handler (100): while a palette tool is\n // active, a drag on empty page means \"place a field\", not \"marquee\".\n priority: 95,\n enabledFor: (tool) => tool.enables.has('form-place'),\n onHover: (sample) => {\n if (!annotation) return;\n const toolId = interaction.getActiveToolId();\n if (\n sample.page &&\n FORM_TOOL_BY_ID.has(toolId) &&\n form.canDesign() &&\n !interaction.hasCursorClaim()\n ) {\n annotation.hoverGhostAt(\n toolId,\n sample.page.ref,\n sample.page.point,\n sample.page.rotation,\n sample.page.zoom,\n );\n } else {\n annotation.clearGhost();\n }\n },\n onDown: (sample) => {\n // No capture without a page, a known palette tool, or design permission:\n // declining lets editing, panning or text selection take the gesture.\n if (!sample.page || !FORM_TOOL_BY_ID.has(interaction.getActiveToolId())) return false;\n if (!form.canDesign()) return false;\n origin = { page: sample.page.ref, start: sample.page.point, last: sample.page.point };\n return true;\n },\n onMove: (sample) => {\n if (!origin) return;\n const point = samplePointOn(sample, origin.page);\n if (!point) return;\n origin.last = point;\n annotation?.previewPlacement(interaction.getActiveToolId(), origin.page, origin.start, point);\n },\n onUp: (sample) => {\n if (!origin) return;\n const gesture = origin;\n endGesture();\n const tool = FORM_TOOL_BY_ID.get(interaction.getActiveToolId());\n if (!tool) return;\n // The up sample is the final point (projection first, like every\n // page-anchored gesture); a release over the gap falls back to the\n // last resolved point.\n const end = samplePointOn(sample, gesture.page) ?? gesture.last;\n const placement = gesturePlacement('box', gesture.start, end, tool.clickCreate, {\n pageBox: form.getPageBox(gesture.page) ?? undefined,\n });\n if (placement?.kind !== 'box') return;\n place(tool, gesture.page, placement.rect).catch((error) => {\n globalThis.console?.error('[form] placing the field failed:', error);\n });\n },\n // Aborted (a second finger, a system cancel): nothing is placed.\n onCancel: endGesture,\n };\n}\n","/**\n * The form plugin's wiring to its siblings, run once every capability exists:\n * its tools and place handler on the interaction hub, its widgets lent to the\n * annotation plugin for design, and the reset executor, commit sink, form\n * reader and submit resolver on the actions plugin. Every registration is released with\n * the document.\n */\nimport { ActionsToken as ActionsHostToken } from '@embedpdf/plugin-actions/contract/host';\nimport {\n AnnotationToken as AnnotationHostToken,\n type AnnotationLender,\n} from '@embedpdf/plugin-annotation/contract/host';\nimport { InteractionToken } from '@embedpdf/plugin-interaction/contract/host';\n\nimport type { FormHostCapability } from './host-contract';\nimport type { FormContext } from './services';\nimport { FORM_TOOLS, PLACE_TAGS } from './tools/definitions';\nimport { createPlaceHandler } from './tools/handlers';\n\nexport function connectForm(\n ctx: FormContext,\n form: FormHostCapability,\n lender: AnnotationLender,\n): void {\n const interaction = ctx.get(InteractionToken);\n const annotation = ctx.tryGet(AnnotationHostToken);\n\n // Fill-only mode: forms are fillable and annotations are not editable. The\n // default fill experience does not need this tool, because the built-in\n // pointer and pan tools carry the 'form-fill' tag themselves. 'link-nav'\n // keeps links navigable while filling, as in Acrobat.\n ctx.cleanup(\n interaction.registerTool({\n id: 'form-fill',\n cursor: 'default',\n enables: new Set(['form-fill', 'link-nav']),\n }),\n );\n // Design mode's resting tool: without 'form-fill' the widget behavior\n // disengages, and widgets select, move and resize like any annotation.\n // Palette tools add drag-to-place on top of it.\n ctx.cleanup(\n interaction.registerTool({\n id: 'form-edit',\n cursor: 'default',\n enables: new Set(['annotation-edit', 'annotation-marquee']),\n }),\n );\n\n // The field palette is one tool table with two registration paths. With the\n // annotation plugin, the tools join its registry and gain live defaults,\n // the style panel and click-to-create. Without it they are plain hub tools:\n // placement still works; only interactive styling needs the annotation\n // plugin, and so does the ghost. Either way the form place handler commits\n // them: these tools enable 'form-place', never 'annotation-draw'.\n for (const tool of FORM_TOOLS) {\n ctx.cleanup(\n annotation\n ? annotation.tools.register({\n id: tool.id,\n subtype: tool.visualKind,\n cursor: tool.cursor,\n enables: [...PLACE_TAGS],\n clickCreate: tool.clickCreate,\n defaults: tool.defaults,\n // Click-first: the field a click places follows the pointer.\n ghost: true,\n })\n : interaction.registerTool({\n id: tool.id,\n cursor: tool.cursor,\n enables: new Set(PLACE_TAGS),\n }),\n );\n }\n ctx.cleanup(interaction.registerHandler(createPlaceHandler(form, interaction, annotation)));\n\n // Design mode: the widgets are lent to the annotation plugin, which selects,\n // moves, restyles and deletes them with its own tools (write/lending.ts).\n if (annotation && ctx.allows('doc.forms.modify')) {\n ctx.cleanup(annotation.lend(lender));\n }\n\n const actions = ctx.tryGet(ActionsHostToken);\n if (!actions) return;\n // Script form effects are written through this plugin, which owns the fields, and scripts\n // read the form as the user sees it, with the fills still on their way.\n ctx.cleanup(actions.registerFormCommitSink((effects) => form.commitScriptFormEffects(effects)));\n ctx.cleanup(actions.registerFormReader(() => form.getSnapshot()));\n ctx.cleanup(\n actions.registerSubmitResolver((intent, actionContext, diagnose) =>\n form.resolveSubmitDataset(intent, actionContext, diagnose),\n ),\n );\n // The executor passes its action context through, so a ResetForm run by a\n // page or document trigger reports its recalculation with that origin.\n ctx.cleanup(\n actions.registerExecutor('reset-form', async (node, actionContext) => {\n if (node.type !== 'reset-form') return { status: 'inert', reason: 'not a reset-form node' };\n const result = await form.resetFormAction(node.fields, node.exclude, actionContext.origin);\n if (result.status === 'failed') {\n return { status: 'failed', error: result.error?.message ?? 'reset failed' };\n }\n if (result.status === 'unchanged') {\n return {\n status: 'inert',\n reason: result.diagnostics[0]?.message ?? 'reset-form resolved no fields',\n };\n }\n return { status: 'executed' };\n }),\n );\n}\n","/**\n * The form plugin's data, all pure:\n *\n * - `FieldIndex` is the form as the engine confirmed it: the field tree and\n * every widget row, indexed by field key and by widget. It is the value of\n * the plugin's `fields` mirror and changes only through `foldFormEvent` and\n * loads; `predictFormOp` (sync/predict.ts) shows this session's changes on\n * top of it.\n * - `PageWidgets` is one page's widgets, where each is and how it looks,\n * derived from the index's widget rows (`pageWidgetsOf`).\n *\n * The text being typed in a field is not here: it waits in `write/typing.ts`\n * until it is committed.\n */\nimport { reload, type MirrorReload } from '@embedpdf/core';\nimport {\n annotationKey,\n reorderPart,\n type AnnotationRef,\n type DocumentEvent,\n type FormFieldDTO,\n type FormFieldRef,\n type FormSnapshot,\n type FormWidget,\n type PageRef,\n type WidgetAnnotation,\n} from '@embedpdf/engine-core/runtime';\n\n/** A page-space box (top-left origin, y-down, PDF points). */\nexport interface Box {\n readonly x: number;\n readonly y: number;\n readonly width: number;\n readonly height: number;\n}\n\n/** Stable client key for a field: its object number when durable, else its fully qualified name. */\nexport type FieldKey = string;\n\nexport const fieldKeyOfRef = (ref: FormFieldRef): FieldKey =>\n ref.kind === 'objectNumber' ? `obj:${ref.objectNumber}` : `fqn:${ref.name}`;\n\n/** A field's ref is its object number, or its name when it has none. */\nexport const fieldKeyOf = (field: { ref: FormFieldRef }): FieldKey => fieldKeyOfRef(field.ref);\n\n// ── the field index (the `fields` mirror) ────────────────────────────────────\n\nexport interface FieldIndex {\n readonly snapshot: FormSnapshot | null;\n /** Field key → index into `snapshot.fields`. */\n readonly byKey: Readonly<Record<FieldKey, number>>;\n /** Full name → index into `snapshot.fields`, for a ref made with `toFieldRef(name)`. */\n readonly byName: Readonly<Record<string, number>>;\n /** Widget annotation object number → index into `snapshot.fields`. */\n readonly byWidget: Readonly<Record<number, number>>;\n /** Widget annotation object number → index into `snapshot.widgets`, its row. */\n readonly rowByWidget: Readonly<Record<number, number>>;\n /**\n * Widget annotation object number → the version of its picture. It moves\n * when the engine draws the widget again, and only then: its pictures are\n * fetched again exactly when it moves. A widget that went keeps its entry,\n * so one made again with its number never takes an older picture.\n */\n readonly pictureVersions: Readonly<Record<number, number>>;\n}\n\nexport const emptyFieldIndex = (): FieldIndex => ({\n snapshot: null,\n byKey: {},\n byName: {},\n byWidget: {},\n rowByWidget: {},\n pictureVersions: {},\n});\n\nexport function indexFields(\n snapshot: FormSnapshot,\n pictureVersions: FieldIndex['pictureVersions'] = {},\n): FieldIndex {\n const byKey: Record<FieldKey, number> = {};\n const byName: Record<string, number> = {};\n const byWidget: Record<number, number> = {};\n const rowByWidget: Record<number, number> = {};\n snapshot.fields.forEach((field, position) => {\n byKey[fieldKeyOf(field)] = position;\n byName[field.name] ??= position;\n for (const widget of field.widgets) {\n if (widget.objectNumber > 0) byWidget[widget.objectNumber] = position;\n }\n });\n snapshot.widgets.forEach((row, position) => {\n if (row.ref.kind === 'objectNumber') rowByWidget[row.ref.objectNumber] = position;\n });\n return { snapshot, byKey, byName, byWidget, rowByWidget, pictureVersions };\n}\n\n/** The index of `snapshot`, keeping `index`'s picture versions. */\nconst reindex = (index: FieldIndex, snapshot: FormSnapshot): FieldIndex =>\n indexFields(snapshot, index.pictureVersions);\n\n/**\n * A fresh read of the whole form: every widget's picture version moves past\n * the one it had, so a reload re-fetches every picture (the pictures may\n * have changed while the event stream wasn't trusted). A new widget starts at 0.\n */\nexport function indexLoadedFields(previous: FieldIndex, snapshot: FormSnapshot): FieldIndex {\n const pictureVersions: Record<number, number> = {};\n for (const [number, version] of Object.entries(previous.pictureVersions)) {\n pictureVersions[Number(number)] = version + 1;\n }\n for (const row of snapshot.widgets) {\n const number = widgetNumber(row);\n if (number > 0) pictureVersions[number] ??= 0;\n }\n return indexFields(snapshot, pictureVersions);\n}\n\n/** The picture version of a widget; 0 for one the index has never seen. */\nexport const pictureVersionOf = (index: FieldIndex, annotObjectNumber: number): number =>\n index.pictureVersions[annotObjectNumber] ?? 0;\n\n/** Replace a field by key, or append it when it is new. */\nexport function upsertFields(index: FieldIndex, fields: readonly FormFieldDTO[]): FieldIndex {\n if (!index.snapshot || fields.length === 0) return index;\n const next = index.snapshot.fields.slice();\n for (const field of fields) {\n const position = index.byKey[fieldKeyOf(field)];\n if (position === undefined) next.push(field);\n else next[position] = field;\n }\n return reindex(index, { ...index.snapshot, fields: next });\n}\n\nconst widgetNumber = (widget: WidgetAnnotation): number =>\n widget.ref.kind === 'objectNumber' ? widget.ref.objectNumber : 0;\n\n/** Replace widget rows by object number, or append the ones that are new. */\nexport function upsertWidgets(index: FieldIndex, rows: readonly WidgetAnnotation[]): FieldIndex {\n if (!index.snapshot || rows.length === 0) return index;\n const incoming = new Map(rows.map((row) => [widgetNumber(row), row]));\n const next = index.snapshot.widgets.map((row) => {\n const replaced = incoming.get(widgetNumber(row));\n if (replaced) incoming.delete(widgetNumber(row));\n return replaced ?? row;\n });\n return reindex(index, { ...index.snapshot, widgets: [...next, ...incoming.values()] });\n}\n\n/** The page's widget rows in `order` (bottom to top), in their slots: other pages' keep theirs. */\nexport function reorderWidgetRows(\n index: FieldIndex,\n page: PageRef,\n order: readonly AnnotationRef[],\n): FieldIndex {\n if (!index.snapshot) return index;\n const widgets = reorderPart(\n index.snapshot.widgets,\n (row) => row.page.objectNumber === page.objectNumber,\n order.map(annotationKey),\n (row) => annotationKey(row.ref),\n );\n return reindex(index, { ...index.snapshot, widgets });\n}\n\n/** Drop the rows of widgets that went (with their field, or with their page). */\nexport function removeWidgets(index: FieldIndex, gone: readonly FormWidget[]): FieldIndex {\n if (!index.snapshot || gone.length === 0) return index;\n const numbers = new Set(gone.map((widget) => widget.objectNumber));\n const widgets = index.snapshot.widgets.filter((row) => !numbers.has(widgetNumber(row)));\n if (widgets.length === index.snapshot.widgets.length) return index;\n return reindex(index, { ...index.snapshot, widgets });\n}\n\nexport function removeField(index: FieldIndex, ref: FormFieldRef): FieldIndex {\n if (!index.snapshot) return index;\n const fields = index.snapshot.fields.filter((field) =>\n ref.kind === 'objectNumber'\n ? !(field.ref.kind === 'objectNumber' && field.ref.objectNumber === ref.objectNumber)\n : field.name !== ref.name,\n );\n if (fields.length === index.snapshot.fields.length) return index;\n return reindex(index, { ...index.snapshot, fields });\n}\n\n/**\n * Apply one confirmed document event to the field index. Every form event\n * carries the fields and the widget rows it touched as the engine read them\n * back, so the index never needs a re-read except for a repair, whose result\n * reports only counts, and for writes that remove widgets with their pages.\n * The widgets the engine drew again take a new picture version.\n */\nexport function foldFormEvent(index: FieldIndex, event: DocumentEvent): FieldIndex | MirrorReload {\n return foldFormFacts(withRedrawnPictures(index, redrawnWidgetsOf(event)), event);\n}\n\n/** A widget an event says it drew: its page, and its number when the event names it. */\ntype PlacedWidget = { readonly page: PageRef | null; readonly objectNumber?: number };\n\n/**\n * The widgets a confirmed fact drew again: the ones the engine says it\n * redrew (`meta.redrawnWidgets`: a checkbox that only switched its state isn't\n * one), else the ones it changed; the signed widget of a signing.\n */\nfunction redrawnWidgetsOf(event: DocumentEvent): readonly PlacedWidget[] {\n if (event.type === 'signatures.completed') {\n return event.signature.widget ? [event.signature.widget] : [];\n }\n if (!event.type.startsWith('forms.') || !('meta' in event)) return [];\n const meta = event.meta as {\n readonly changedWidgets?: readonly PlacedWidget[];\n readonly redrawnWidgets?: readonly PlacedWidget[];\n };\n return meta.redrawnWidgets ?? meta.changedWidgets ?? [];\n}\n\n/** Each widget drawn again takes a new picture version; one named by its page only, all of that page's. */\nfunction withRedrawnPictures(index: FieldIndex, redrawn: readonly PlacedWidget[]): FieldIndex {\n if (redrawn.length === 0) return index;\n const numbers = new Set<number>();\n for (const widget of redrawn) {\n if (widget.objectNumber) numbers.add(widget.objectNumber);\n else if (widget.page) {\n for (const row of index.snapshot?.widgets ?? []) {\n if (row.page.objectNumber === widget.page.objectNumber) numbers.add(widgetNumber(row));\n }\n }\n }\n if (numbers.size === 0) return index;\n const pictureVersions = { ...index.pictureVersions };\n for (const number of numbers) pictureVersions[number] = (pictureVersions[number] ?? 0) + 1;\n return { ...index, pictureVersions };\n}\n\n/**\n * A merged field split as it took a second widget: its widget half moved to a new number (one\n * of the event's widgets), and the row at the field's own number is gone with it.\n */\nfunction withoutSplitRow(index: FieldIndex, field: FormFieldDTO): FieldIndex {\n if (field.ref.kind !== 'objectNumber') return index;\n const own = field.ref.objectNumber;\n if (field.widgets.some((widget) => widget.objectNumber === own)) return index;\n const row = widgetRowOf(index, own);\n return row ? removeWidgets(index, [{ ref: row.ref, objectNumber: own, page: row.page }]) : index;\n}\n\nfunction foldFormFacts(index: FieldIndex, event: DocumentEvent): FieldIndex | MirrorReload {\n switch (event.type) {\n case 'forms.widgetAdded':\n return withoutSplitRow(\n upsertWidgets(upsertFields(index, [event.field]), event.widgets),\n event.field,\n );\n case 'forms.valueSet':\n case 'forms.widgetRemoved':\n case 'forms.restored':\n return upsertWidgets(upsertFields(index, [event.field]), event.widgets);\n case 'forms.updated':\n return withCalculationOrder(\n upsertWidgets(upsertFields(index, [event.field]), event.widgets),\n event.calculationOrder,\n );\n case 'forms.created': {\n // The first field of a document without a form creates its /AcroForm.\n const created = upsertWidgets(upsertFields(index, [event.field]), event.widgets);\n return withCalculationOrder(\n created.snapshot?.formKind === 'none'\n ? reindex(created, { ...created.snapshot, formKind: 'acroform' })\n : created,\n event.calculationOrder,\n );\n }\n case 'forms.calculationsReordered':\n return withCalculationOrder(index, event.calculationOrder);\n case 'forms.widgetDeleted': {\n const gone = removeWidgets(index, event.meta.changedWidgets);\n return event.field ? upsertFields(gone, [event.field]) : gone;\n }\n case 'forms.widgetRestored':\n return upsertWidgets(event.field ? upsertFields(index, [event.field]) : index, event.widgets);\n case 'forms.widgetUpdated':\n return upsertWidgets(index, [event.widget]);\n case 'forms.widgetsReordered':\n return reorderWidgetRows(index, event.page, event.order);\n case 'forms.deleted':\n return event.deleted\n ? withCalculationOrder(\n removeWidgets(removeField(index, event.deleted), event.meta.changedWidgets),\n event.calculationOrder,\n )\n : reload();\n // A repair reports only counts; the others add or remove pages, or paint their\n // widgets into the content.\n case 'forms.repaired':\n case 'pages.deleted':\n case 'pages.inserted':\n case 'pages.restored':\n case 'pages.flattened':\n case 'annotations.flattened':\n case 'redaction.applied':\n return reload();\n default:\n return index;\n }\n}\n\n/** Whether any field has a keystroke, validate, calculate or format script. */\nexport function formHasScripts(index: FieldIndex): boolean {\n return (index.snapshot?.fields ?? []).some(\n ({ actions }) =>\n !!(actions?.keystroke || actions?.validate || actions?.calculate || actions?.format),\n );\n}\n\n/** The index with the calculation order a write answered, when the write changed it. */\nexport function withCalculationOrder(\n index: FieldIndex,\n order: readonly (FormFieldRef | null)[] | undefined,\n): FieldIndex {\n if (!order || !index.snapshot) return index;\n return reindex(index, { ...index.snapshot, calculationOrder: [...order] });\n}\n\nexport const fieldByKey = (index: FieldIndex, key: FieldKey): FormFieldDTO | null => {\n const position = index.byKey[key];\n return position === undefined ? null : (index.snapshot?.fields[position] ?? null);\n};\n\n/** The field a ref names: by object number, or by full name for `toFieldRef(name)`. */\nexport function fieldByRef(index: FieldIndex, ref: FormFieldRef): FormFieldDTO | null {\n const position = ref.kind === 'fqn' ? index.byName[ref.name] : index.byKey[fieldKeyOfRef(ref)];\n return position === undefined ? null : (index.snapshot?.fields[position] ?? null);\n}\n\n/** The key a field is known by, whichever ref names it: a name ref resolves to its field's key. */\nexport const canonicalKey = (index: FieldIndex, ref: FormFieldRef): FieldKey => {\n const field = fieldByRef(index, ref);\n return field ? fieldKeyOf(field) : fieldKeyOfRef(ref);\n};\n\nexport const fieldForWidget = (\n index: FieldIndex,\n annotObjectNumber: number,\n): FormFieldDTO | null => {\n const position = index.byWidget[annotObjectNumber];\n return position === undefined ? null : (index.snapshot?.fields[position] ?? null);\n};\n\n/** The fields whose value entry differs between two indexes (new fields included). */\nexport function fieldsWithChangedValues(previous: FieldIndex, next: FieldIndex): FormFieldDTO[] {\n return (next.snapshot?.fields ?? []).filter((field) => {\n const before = fieldByKey(previous, fieldKeyOf(field));\n return !before || JSON.stringify(valueEntryOf(before)) !== JSON.stringify(valueEntryOf(field));\n });\n}\n\nconst valueEntryOf = (field: FormFieldDTO): unknown =>\n 'valueEntry' in field ? field.valueEntry : null;\n\n// ── widgets (each page's, from the index's widget rows) ──────────────────────\n\n/**\n * How a widget looks in the PDF, as its own appearance settings say: `null`\n * where it has none of its own. A viewer that draws controls over the field\n * uses these, and its own settings where the field has nothing.\n */\nexport interface FormWidgetLook {\n /** The border color (`/MK /BC`), or `null` for a widget without a border. */\n readonly border: string | null;\n /** The border width in points. */\n readonly borderWidth: number;\n readonly borderStyle: 'solid' | 'dashed' | 'beveled' | 'inset' | 'underline';\n /** The background color (`/MK /BG`), or `null` for a see-through widget. */\n readonly background: string | null;\n /** The text color (`/DA`), or `null` when the field names none. */\n readonly color: string | null;\n /** One of the 14 standard PDF fonts, such as `'helvetica'`, or `null` when the field names none. */\n readonly fontFamily: string | null;\n /** The font size in points; `0` or `null` sizes the text to the box. */\n readonly fontSize: number | null;\n readonly textAlign: 'left' | 'center' | 'right';\n}\n\n/** One widget on its page: its page-space box and its look. */\nexport interface PageWidget {\n readonly box: Box;\n readonly look: FormWidgetLook;\n}\n\n/** One page's widgets: widget annotation object number → where it is and how it looks. */\nexport type PageWidgets = Readonly<Record<number, PageWidget>>;\n\n/** Whether a widget shows on screen: its `hidden` and `noView` flags hide it. */\nexport const shownOnScreen = (row: WidgetAnnotation): boolean => !row.hidden && !row.noView;\n\n/** The widgets one page shows, from the form's widget rows. */\nexport function pageWidgetsOf(index: FieldIndex, pageObjectNumber: number): PageWidgets {\n const widgets: Record<number, PageWidget> = {};\n for (const row of index.snapshot?.widgets ?? []) {\n if (row.page.objectNumber !== pageObjectNumber || row.ref.kind !== 'objectNumber') continue;\n if (!shownOnScreen(row)) continue;\n widgets[row.ref.objectNumber] = {\n box: row.rect,\n look: {\n border: row.color ?? null,\n borderWidth: row.strokeWidth ?? 1,\n borderStyle: row.borderStyle ?? 'solid',\n background: row.interiorColor ?? null,\n color: row.fontColor ?? null,\n fontFamily: row.fontFamily ?? null,\n fontSize: row.fontSize ?? null,\n textAlign: row.textAlign ?? 'left',\n },\n };\n }\n return widgets;\n}\n\n/** A widget a page shows: its address, the appearance state it shows, and how new its look is. */\nexport interface ShownWidget {\n readonly ref: AnnotationRef;\n /** Where it stands on its page, in page space: its picture's box, and the painter's. */\n readonly rect: Box;\n /** The state it shows (`/AS`), or `null` for a widget without states. */\n readonly appearanceState: string | null;\n /**\n * Its look in the view isn't its confirmed look yet (a value, a restyle, a\n * new field): its picture shows something older, so the painter draws it.\n */\n readonly pending: boolean;\n /** Its confirmed picture version: a picture drawn at another one shows another look. */\n readonly pictureVersion: number;\n}\n\n/** How new a shown widget's look is: whether it's pending, and its confirmed picture version. */\nexport type WidgetLookOf = (\n row: WidgetAnnotation,\n) => Pick<ShownWidget, 'pending' | 'pictureVersion'>;\n\nconst AT_REST: ReturnType<WidgetLookOf> = { pending: false, pictureVersion: 0 };\n\n/** The widgets one page shows, in the order the page draws them. */\nexport function shownWidgetsOf(\n index: FieldIndex,\n pageObjectNumber: number,\n lookOf: WidgetLookOf = () => AT_REST,\n): ShownWidget[] {\n const shown: ShownWidget[] = [];\n for (const row of index.snapshot?.widgets ?? []) {\n if (row.page.objectNumber !== pageObjectNumber || !shownOnScreen(row)) continue;\n shown.push({\n ref: row.ref,\n rect: row.rect,\n appearanceState: row.appearanceState,\n ...lookOf(row),\n });\n }\n return shown;\n}\n\nexport function widgetRowOf(index: FieldIndex, annotObjectNumber: number): WidgetAnnotation | null {\n const position = index.rowByWidget[annotObjectNumber];\n return position === undefined ? null : (index.snapshot?.widgets[position] ?? null);\n}\n\n/** A widget hit: the annotation under the point and the field it belongs to. */\nexport interface WidgetHit {\n readonly annotObjectNumber: number;\n readonly field: FormFieldDTO;\n /** The widget's page-space box. */\n readonly box: Box;\n}\n\nexport const boxContains = (box: Box, point: { x: number; y: number }): boolean =>\n point.x >= box.x &&\n point.x <= box.x + box.width &&\n point.y >= box.y &&\n point.y <= box.y + box.height;\n\n/** The widget under a page-space point; nested widgets resolve to the smallest box. */\nexport function widgetAt(\n index: FieldIndex,\n widgets: PageWidgets | undefined,\n point: { x: number; y: number },\n): WidgetHit | null {\n if (!widgets) return null;\n let best: WidgetHit | null = null;\n for (const [key, { box }] of Object.entries(widgets)) {\n if (!boxContains(box, point)) continue;\n const annotObjectNumber = Number(key);\n const field = fieldForWidget(index, annotObjectNumber);\n if (!field) continue;\n if (!best || box.width * box.height < best.box.width * best.box.height) {\n best = { annotObjectNumber, field, box };\n }\n }\n return best;\n}\n\n// ── session state ────────────────────────────────────────────────────────────\n\n/** The plugin's session state: nothing yet; a write in flight shows in the mirror's view. */\nexport type FormState = Readonly<Record<string, never>>;\n\nexport const initialFormState = (): FormState => ({});\n","/**\n * Reads over the mirrored field tree: fields, values, the joins between a\n * field and its widgets' rows, the field of the selected widget, and the\n * required-field check.\n */\nimport { memo, memoByKey } from '@embedpdf/core';\nimport {\n pageRefsEqual,\n type FormFieldDTO,\n type FormFieldValue,\n type FormKind,\n type WidgetAnnotation,\n} from '@embedpdf/engine-core/runtime';\n\nimport type {\n FormCapability,\n FormFilter,\n FormPlainValue,\n FormValidation,\n WidgetAddress,\n} from '../contract';\nimport { canonicalKey, fieldByKey, fieldByRef, fieldForWidget, widgetRowOf } from '../model';\nimport type { FormContext, FormServices } from '../services';\n\nconst NO_FIELDS: readonly FormFieldDTO[] = Object.freeze([]);\nconst NOTHING_SELECTED: readonly { readonly subtype: string; readonly ref: WidgetAddress }[] =\n Object.freeze([]);\n\n/** A widget address as the annotation object number the field index is keyed by. */\nexport const widgetObjectOf = (widget: WidgetAddress): number =>\n 'kind' in widget\n ? widget.kind === 'objectNumber'\n ? widget.objectNumber\n : 0\n : widget.objectNumber;\n\n/** A field's value in the write vocabulary, or null for a valueless or unsupported entry. */\nexport function valueOf(field: FormFieldDTO): FormFieldValue | null {\n const entry = field.valueEntry;\n if (entry.kind === 'none' || entry.kind === 'unsupported') return null;\n switch (field.family) {\n case 'text':\n return { value: field.value };\n case 'checkbox':\n return { checked: field.checked };\n case 'radio':\n return { value: field.value === 'Off' ? null : field.value };\n case 'combobox':\n return { value: field.value === '' ? null : field.value };\n case 'listbox':\n return { selectedValues: [...field.selectedValues] };\n default:\n return null;\n }\n}\n\n/** A field's value as plain data: what `exportValues()` gives and `importValues()` takes. */\nexport function plainValueOf(field: FormFieldDTO): FormPlainValue | undefined {\n const value = valueOf(field);\n if (!value) return undefined;\n if ('checked' in value) return value.checked;\n if ('selectedValues' in value) return value.selectedValues;\n return value.value;\n}\n\n/**\n * The write a plain value makes for a field of this family, or null when the\n * family can't take it (a list given `true`, a value for a push button).\n */\nexport function writeOfPlainValue(\n field: FormFieldDTO,\n value: FormPlainValue,\n): FormFieldValue | null {\n switch (field.family) {\n case 'checkbox':\n if (typeof value === 'boolean') return { checked: value };\n return typeof value === 'string' || value === null ? { value } : null;\n case 'text':\n case 'radio':\n case 'combobox':\n return typeof value === 'string' || value === null ? { value } : null;\n case 'listbox':\n if (value === null) return { selectedValues: [] };\n if (typeof value === 'string') return { selectedValues: [value] };\n return Array.isArray(value) ? { selectedValues: [...value] } : null;\n default:\n return null;\n }\n}\n\n/** Whether a field holds nothing a required check would accept. */\nfunction isEmpty(field: FormFieldDTO): boolean {\n switch (field.family) {\n case 'text':\n case 'combobox':\n return field.value === '';\n case 'checkbox':\n return !field.checked;\n case 'radio':\n return field.value === 'Off' || field.value === '';\n case 'listbox':\n return field.selectedValues.length === 0;\n case 'signature':\n return field.valueEntry.kind === 'none';\n default:\n return false;\n }\n}\n\nexport function createFieldReads(\n ctx: FormContext,\n { fields, rights, siblings }: Pick<FormServices, 'fields' | 'rights' | 'siblings'>,\n) {\n const all = (): readonly FormFieldDTO[] => fields.view().snapshot?.fields ?? NO_FIELDS;\n\n const list = (filter?: FormFilter): readonly FormFieldDTO[] => {\n if (!filter) return all();\n const page = filter.page === undefined ? undefined : ctx.getPage(filter.page)?.ref;\n // A page that isn't in the document has no fields.\n if (filter.page !== undefined && !page) return NO_FIELDS;\n return all().filter(\n (field) =>\n (!filter.family || field.family === filter.family) &&\n (filter.name === undefined || field.name === filter.name) &&\n (!page || field.widgets.some((widget) => widget.page && pageRefsEqual(widget.page, page))),\n );\n };\n\n // One value object per field while its value stays the same, so a reader\n // that compares by reference re-renders only when this field's value\n // changes: a fill shows before the engine answers, and the answer brings the\n // same value in a new field.\n const valueByKey = memoByKey(\n (key: string) => {\n const field = fieldByKey(fields.view(), key);\n return [field ? JSON.stringify(valueOf(field)) : null];\n },\n (_key, value): FormFieldValue | null =>\n value === null ? null : (JSON.parse(value) as FormFieldValue | null),\n { maxEntries: 1024 },\n );\n\n // One array per field while its widgets' rows stay the same objects.\n const widgetsByKey = memoByKey(\n (key: string) => {\n const index = fields.view();\n const field = fieldByKey(index, key);\n return (field?.widgets ?? []).map((widget) => widgetRowOf(index, widget.objectNumber));\n },\n (_key, ...rows): readonly WidgetAnnotation[] =>\n Object.freeze(rows.filter((row): row is WidgetAnnotation => row !== null)),\n { maxEntries: 1024 },\n );\n\n const exportValues = memo(\n () => [fields.view()],\n (index): Readonly<Record<string, FormPlainValue>> => {\n const values: Record<string, FormPlainValue> = {};\n for (const field of index.snapshot?.fields ?? []) {\n const value = plainValueOf(field);\n if (value !== undefined) values[field.name] = value;\n }\n return values;\n },\n );\n\n /** Where a field first shows: its page's index, then top to bottom, then left to right. */\n const placeOf = (field: FormFieldDTO): readonly [number, number, number] => {\n const index = fields.view();\n const row = field.widgets\n .map((widget) => widgetRowOf(index, widget.objectNumber))\n .find((candidate) => candidate !== null);\n const page = row ? (ctx.getPage(row.page)?.index ?? Infinity) : Infinity;\n return [page, row?.rect.y ?? 0, row?.rect.x ?? 0];\n };\n\n // The page order is an input too: moving a page moves its fields in the list.\n // Only the fields the user may fill in count: another signer's empty field\n // isn't theirs to fill.\n const validate = memo(\n () => [fields.view(), ctx.document(), rights.key()],\n (index): FormValidation => {\n const missing = (index.snapshot?.fields ?? [])\n .filter((field) => field.required && isEmpty(field) && rights.mayFill(field))\n .map((field) => ({ field, place: placeOf(field) }))\n .sort(\n (left, right) =>\n left.place[0] - right.place[0] ||\n left.place[1] - right.place[1] ||\n left.place[2] - right.place[2],\n )\n .map(({ field }) => field);\n return { valid: missing.length === 0, missing };\n },\n );\n\n // The selection belongs to the annotation plugin: a widget is selected in\n // design mode, where widgets are boxes like any annotation.\n const getSelectedField = memo(\n () => [fields.view(), siblings.annotation()?.selection.list() ?? NOTHING_SELECTED],\n (index, selected): FormFieldDTO | null => {\n const [annotation] = selected;\n if (selected.length !== 1 || !annotation?.subtype.startsWith('widget')) return null;\n return fieldForWidget(index, widgetObjectOf(annotation.ref));\n },\n );\n\n return {\n api: {\n getSnapshot: () => fields.view().snapshot,\n getStatus: fields.getStatus,\n getFormKind: (): FormKind => fields.view().snapshot?.formKind ?? 'none',\n refresh: (options) => ctx.cancellable(options?.signal, fields.refresh()),\n get: (ref) => fieldByRef(fields.view(), ref),\n getFieldForWidget: (widget) => fieldForWidget(fields.view(), widgetObjectOf(widget)),\n getWidget: (widget) => widgetRowOf(fields.view(), widgetObjectOf(widget)),\n getWidgets: (ref) => widgetsByKey(canonicalKey(fields.view(), ref)),\n list,\n getValue: (ref) => valueByKey(canonicalKey(fields.view(), ref)),\n getSelectedField,\n validate,\n exportValues,\n } satisfies Partial<FormCapability>,\n };\n}\n","/**\n * A field's settings, described for a settings panel the way an annotation\n * kind describes its look: which settings the field's family has, how each is\n * edited, and its value. `update()` writes them.\n */\nimport { memoByKey } from '@embedpdf/core';\nimport type { FormFieldDTO, FormFieldRef } from '@embedpdf/engine-core/runtime';\n\nimport type { FormCapability, FormFieldSetting, FormFieldSettings } from '../contract';\nimport { canonicalKey, fieldByKey } from '../model';\nimport type { FormServices } from '../services';\n\n/** What every field has. */\nconst COMMON: readonly FormFieldSetting[] = [\n { key: 'name', control: 'text', label: 'Name', labelKey: 'form.settings.name' },\n { key: 'alternateName', control: 'text', label: 'Tooltip', labelKey: 'form.settings.tooltip' },\n { key: 'required', control: 'flag', label: 'Required', labelKey: 'form.settings.required' },\n { key: 'readOnly', control: 'flag', label: 'Read-only', labelKey: 'form.settings.readOnly' },\n { key: 'noExport', control: 'flag', label: \"Don't export\", labelKey: 'form.settings.noExport' },\n];\n\nconst DEFAULT_VALUE = { label: 'Default value', labelKey: 'form.settings.defaultValue' } as const;\nconst OPTIONS: FormFieldSetting = {\n key: 'options',\n control: 'options',\n label: 'Options',\n labelKey: 'form.settings.options',\n};\n\n/** What each family adds. */\nfunction familySettings(field: FormFieldDTO): readonly FormFieldSetting[] {\n switch (field.family) {\n case 'text':\n return [\n { key: 'defaultValue', control: 'text', ...DEFAULT_VALUE },\n {\n key: 'maxLength',\n control: 'number',\n label: 'Maximum length',\n labelKey: 'form.settings.maxLength',\n min: 1,\n },\n {\n key: 'multiline',\n control: 'flag',\n label: 'Several lines',\n labelKey: 'form.settings.multiline',\n },\n { key: 'password', control: 'flag', label: 'Password', labelKey: 'form.settings.password' },\n {\n key: 'comb',\n control: 'flag',\n label: 'One character per box',\n labelKey: 'form.settings.comb',\n },\n ];\n case 'radio':\n return [\n {\n key: 'radiosInUnison',\n control: 'flag',\n label: 'Buttons with one value turn on together',\n labelKey: 'form.settings.radiosInUnison',\n },\n {\n key: 'noToggleToOff',\n control: 'flag',\n label: 'Keep one on',\n labelKey: 'form.settings.keepOneOn',\n },\n ];\n case 'combobox':\n return [\n OPTIONS,\n {\n key: 'edit',\n control: 'flag',\n label: 'Allow typing',\n labelKey: 'form.settings.allowTyping',\n },\n {\n key: 'defaultValue',\n control: 'choice',\n ...DEFAULT_VALUE,\n options: field.options.map((option) => option.value),\n free: field.edit,\n },\n ];\n case 'listbox':\n return [\n OPTIONS,\n {\n key: 'multiSelect',\n control: 'flag',\n label: 'Several choices',\n labelKey: 'form.settings.multiSelect',\n },\n {\n key: 'defaultValue',\n control: 'choices',\n ...DEFAULT_VALUE,\n options: field.options.map((option) => option.value),\n },\n ];\n default:\n return [];\n }\n}\n\n/** Each setting's value, as the field holds it. */\nfunction valuesOf(\n field: FormFieldDTO,\n settings: readonly FormFieldSetting[],\n): Record<string, unknown> {\n const held = field as unknown as Record<string, unknown>;\n const values: Record<string, unknown> = {};\n for (const { key } of settings) {\n if (key === 'name') values.name = field.name.slice(field.name.lastIndexOf('.') + 1);\n else if (key === 'alternateName') values.alternateName = field.alternateName ?? '';\n else values[key] = held[key] ?? null;\n }\n return values;\n}\n\nexport function createFieldSettings({ fields }: Pick<FormServices, 'fields'>) {\n const settingsByKey = memoByKey(\n (key: string) => [fieldByKey(fields.view(), key)],\n (_key, field): FormFieldSettings | null => {\n if (!field) return null;\n const properties = [...COMMON, ...familySettings(field)];\n return { properties, values: valuesOf(field, properties) };\n },\n { maxEntries: 256 },\n );\n return {\n api: {\n getFieldSettings: (ref: FormFieldRef) => settingsByKey(canonicalKey(fields.view(), ref)),\n } satisfies Partial<FormCapability>,\n };\n}\n","/**\n * The widget projection: what a framework draws for one page's fields. Pure\n * data in page space (top-left origin, y-down PDF points), the same space\n * annotation render items use, so layers position with the page transform\n * and never re-derive scale.\n *\n * Where a widget is and how it looks come from the form's widget rows (`/Rect`\n * and `/MK`), identity, value and behavior from its field.\n */\nimport type {\n AnnotationRef,\n FormFieldDTO,\n FormFieldOption,\n FormFieldRef,\n} from '@embedpdf/engine-core/runtime';\n\nimport {\n fieldKeyOf,\n type Box,\n type FieldIndex,\n type FieldKey,\n type FormWidgetLook,\n type PageWidget,\n type PageWidgets,\n} from '../model';\n\nexport type { Box, FormWidgetLook } from '../model';\n\ninterface FormWidgetItemBase {\n key: FieldKey;\n /** The field this widget belongs to: what the write verbs take. */\n fieldRef: FormFieldRef;\n /** The widget's annotation object number. */\n annotObjectNumber: number;\n /** The widget's annotation address (null until the engine has placed it). */\n annotationRef: AnnotationRef | null;\n /** Where the widget is on its page. */\n box: Box;\n /** How the widget looks in the PDF. */\n look: FormWidgetLook;\n /** A read-only field, no permission to fill, filling it turned off (`fillable`), or a write on its way: draw it, don't take input. */\n disabled: boolean;\n /** Accessible name: the field's tooltip (`/TU`) when it has one, else its full name. */\n label: string;\n}\n\n/** One widget as a fill control draws it: where, how it looks, its control and its value. */\nexport type FormWidgetItem = FormWidgetItemBase &\n (\n | {\n control: 'text';\n value: string;\n multiline: boolean;\n password: boolean;\n maxLength: number | null;\n comb: boolean;\n }\n | {\n control: 'toggle';\n kind: 'checkbox' | 'radio';\n checked: boolean;\n /** The export value that checks this widget. */\n exportValue: string;\n }\n | {\n control: 'choice';\n kind: 'combo' | 'list';\n edit: boolean;\n multi: boolean;\n options: FormFieldOption[];\n selected: string[];\n }\n | { control: 'button' }\n /**\n * A signature field's widget. `signed`: it carries a `/V` (a signature\n * dictionary), so the field is final and its appearance sealed, and the\n * control shows what the signature says rather than signing. Unsigned, it\n * is \"sign here\": signing belongs to the signature plugin.\n */\n | { control: 'signature'; signed: boolean }\n );\n\n/**\n * Project one widget of a field into a fill control; `fillable`: the user may\n * fill the field in (a signature field: sign it). Null for families with no\n * fill control.\n */\nexport function projectWidget(\n field: FormFieldDTO,\n annotObjectNumber: number,\n widget: PageWidget,\n fillable: boolean,\n): FormWidgetItem | null {\n const key = fieldKeyOf(field);\n const base: FormWidgetItemBase = {\n key,\n fieldRef: field.ref,\n annotObjectNumber,\n annotationRef:\n field.widgets.find((candidate) => candidate.objectNumber === annotObjectNumber)?.ref ?? null,\n box: widget.box,\n look: widget.look,\n disabled: field.readOnly || !fillable,\n label: field.alternateName ?? field.name,\n };\n switch (field.family) {\n case 'text':\n return {\n ...base,\n control: 'text',\n value: field.value,\n multiline: field.multiline,\n password: field.password,\n maxLength: field.maxLength,\n comb: field.comb,\n };\n case 'checkbox': {\n const toggle = field.widgets.find(\n (candidate) => candidate.objectNumber === annotObjectNumber,\n );\n return {\n ...base,\n control: 'toggle',\n kind: 'checkbox',\n checked: field.checked,\n exportValue: toggle && 'exportValue' in toggle ? toggle.exportValue : field.exportValue,\n };\n }\n case 'radio': {\n const toggle = field.widgets.find(\n (candidate) => candidate.objectNumber === annotObjectNumber,\n );\n return {\n ...base,\n control: 'toggle',\n kind: 'radio',\n checked: toggle && 'checked' in toggle ? toggle.checked : false,\n exportValue: toggle && 'exportValue' in toggle ? toggle.exportValue : '',\n };\n }\n case 'combobox':\n return {\n ...base,\n control: 'choice',\n kind: 'combo',\n edit: field.edit,\n multi: false,\n options: field.options,\n selected: field.value === '' ? [] : [field.value],\n };\n case 'listbox':\n return {\n ...base,\n control: 'choice',\n kind: 'list',\n edit: false,\n multi: field.multiSelect,\n options: field.options,\n selected: field.selectedValues,\n };\n case 'pushbutton':\n return { ...base, control: 'button' };\n case 'signature':\n return { ...base, control: 'signature', signed: field.valueEntry.kind !== 'none' };\n default:\n return null;\n }\n}\n\n/**\n * Project one page's widgets into fill controls, each disabled when the user\n * may not fill its field in, or sign it (`mayFill`). Widgets whose page has not loaded (or\n * that are direct objects with no join key) are skipped; the projection runs\n * again when the page's widgets land.\n */\nexport function fillItems(\n index: FieldIndex,\n pageObjectNumber: number,\n widgets: PageWidgets | undefined,\n mayFill: (field: FormFieldDTO) => boolean,\n): FormWidgetItem[] {\n if (!index.snapshot || !widgets) return [];\n const items: FormWidgetItem[] = [];\n for (const field of index.snapshot.fields) {\n for (const widget of field.widgets) {\n if (widget.page?.objectNumber !== pageObjectNumber) continue;\n const placed = widgets[widget.objectNumber];\n if (!placed) continue;\n const item = projectWidget(field, widget.objectNumber, placed, mayFill(field));\n if (item) items.push(item);\n }\n }\n return items;\n}\n","/**\n * The widgets' reads: each page's widgets (from the form's widget rows), the\n * ones it shows for the form layer to paint (and the painter's scene of each,\n * `services/looks.ts`), the fill projection with the session's fill permission\n * folded in, and the widget hit test.\n */\nimport { memoByKey } from '@embedpdf/core';\nimport type { FormFieldDTO, FormFieldFamily, PageRef } from '@embedpdf/engine-core/runtime';\n\nimport type { FillableFields } from '../contract';\nimport type { FormHostCapability } from '../host-contract';\nimport { pageWidgetsOf, widgetAt, type Box, type ShownWidget, type WidgetHit } from '../model';\nimport type { FormContext, FormServices } from '../services';\nimport { fillItems, type FormWidgetItem } from './fill-items';\n\nconst NO_WIDGETS: readonly FormWidgetItem[] = Object.freeze([]);\n\n/** Whether the `fillable` setting lets people fill in a field of this family by hand. */\nconst isFillableByHand = (fillable: FillableFields, family: FormFieldFamily): boolean =>\n typeof fillable === 'boolean' ? fillable : fillable.includes(family);\nconst NOTHING_SHOWN: readonly ShownWidget[] = Object.freeze([]);\n\nexport function createWidgetReads(\n ctx: FormContext,\n {\n fields,\n rights,\n looks,\n pictures,\n }: Pick<FormServices, 'fields' | 'rights' | 'looks' | 'pictures'>,\n) {\n /** Every page's widgets come with the form: one read for the document. */\n const loadWidgets = (_page: PageRef): Promise<void> => fields.settled();\n\n const widgetsOn = memoByKey(\n (pageObjectNumber: number) => [fields.view()],\n (pageObjectNumber, index) => pageWidgetsOf(index, pageObjectNumber),\n );\n\n /** The widget under a page point. */\n const getWidgetAt = (\n pageArgument: PageRef | number,\n point: { x: number; y: number },\n ): WidgetHit | null => {\n const page = ctx.getPage(pageArgument)?.ref;\n if (!page) return null;\n return widgetAt(fields.view(), widgetsOn(page.objectNumber), point);\n };\n\n // A field the user may not fill in (a signature field: sign), or one the\n // `fillable` setting leaves out, has its widgets `disabled`, the same flag a\n // field's read-only flag sets, so the controls never offer a write the\n // engine would refuse, nor one the app turned off.\n const fillable = (): FillableFields => ctx.settings().get().fillable;\n const mayWrite = (field: FormFieldDTO): boolean =>\n isFillableByHand(fillable(), field.family) &&\n (field.family === 'signature' ? rights.maySign(field) : rights.mayFill(field));\n const widgetsOfPage = memoByKey(\n (pageObjectNumber: number) => [\n fields.view(),\n widgetsOn(pageObjectNumber),\n rights.key(),\n fillable(),\n ],\n (pageObjectNumber, index, widgets): readonly FormWidgetItem[] =>\n fillItems(index, pageObjectNumber, widgets, mayWrite),\n );\n\n /** The page's content box (`{0, 0, width, height}`), for page-bound placement. */\n const getPageBox = (page: PageRef): Box | null => {\n const size = ctx.getPage(page)?.size;\n return size ? { x: 0, y: 0, width: size.width, height: size.height } : null;\n };\n\n return {\n getPageBox,\n api: {\n listWidgets: (pageArgument) => {\n const page = ctx.getPage(pageArgument)?.ref;\n return page ? widgetsOfPage(page.objectNumber) : NO_WIDGETS;\n },\n listShownWidgets: (pageArgument) => {\n const page = ctx.getPage(pageArgument)?.ref;\n return page ? looks.listShownWidgets(page.objectNumber) : NOTHING_SHOWN;\n },\n getAppearanceEpoch: pictures.epoch,\n renderAppearances: pictures.render,\n getWidgetPainting: looks.getWidgetPainting,\n getTextEditorLayout: looks.getTextEditorLayout,\n ensureLoaded: loadWidgets,\n getWidgetAt,\n getPageBox,\n } satisfies Partial<FormHostCapability>,\n };\n}\n","/**\n * What this session asked for and the engine hasn't answered, on top of the\n * form: `predictFormOp`, the fields mirror's `predict` (the view replays it\n * op by op), and `undoLookOf`, what undoing a change looks like. Both follow\n * the engine's own rules (engine-core's form prediction helpers). Pure.\n */\nimport type { PredictedOp } from '@embedpdf/core';\nimport {\n annotationKey,\n fieldAfterReset,\n fieldAfterValue,\n formFieldAfter,\n formFieldOfDraft,\n reorderedList,\n widgetAfterPatch,\n widgetsAfterDisplay,\n type AnnotationRef,\n type FieldWithWidgets,\n type FormFieldDTO,\n type FormFieldRef,\n type FormWidget,\n type WidgetAnnotation,\n} from '@embedpdf/engine-core/runtime';\n\nimport {\n fieldByKey,\n fieldByRef,\n fieldForWidget,\n fieldKeyOf,\n fieldKeyOfRef,\n indexFields,\n removeField,\n removeWidgets,\n reorderWidgetRows,\n upsertFields,\n upsertWidgets,\n widgetRowOf,\n withCalculationOrder,\n type FieldIndex,\n type FieldKey,\n} from '../model';\n\nconst widgetNumber = (widget: WidgetAnnotation): number =>\n widget.ref.kind === 'objectNumber' ? widget.ref.objectNumber : 0;\n\n/** The rows of a field's widgets, in its widget order. */\nfunction rowsOfField(index: FieldIndex, field: FormFieldDTO): WidgetAnnotation[] {\n return field.widgets.flatMap((widget) => {\n const row = widgetRowOf(index, widget.objectNumber);\n return row ? [row] : [];\n });\n}\n\n/** A field and the rows of its widgets, as the index holds them. */\nconst withRows = (index: FieldIndex, field: FormFieldDTO): FieldWithWidgets => ({\n field,\n widgets: rowsOfField(index, field),\n});\n\n/** Fields and their widget rows put into the index, all at once. */\nfunction withFields(index: FieldIndex, parts: readonly FieldWithWidgets[]): FieldIndex {\n if (parts.length === 0) return index;\n return upsertWidgets(\n upsertFields(\n index,\n parts.map((part) => part.field),\n ),\n parts.flatMap((part) => part.widgets),\n );\n}\n\n/** The fields a reset of the whole form puts back: the ones that hold a value. */\nconst resetTargets = (index: FieldIndex): FormFieldDTO[] =>\n (index.snapshot?.fields ?? []).filter((field) => RESET_FAMILIES.has(field.family));\n\nconst RESET_FAMILIES = new Set(['text', 'checkbox', 'radio', 'combobox', 'listbox']);\n\n/**\n * One op of a change this session staged, shown before the engine answers,\n * by the engine's own rules (`fieldAfterValue`, `fieldAfterReset`,\n * `widgetsAfterDisplay`, `formFieldOfDraft`, `formFieldAfter`,\n * `widgetAfterPatch`): what the fields and their widgets hold after it. An op\n * those rules refuse shows nothing; one whose values only the engine's schemas\n * refuse shows until the engine's refusal takes the change away.\n * A create shows once it names its numbers; taking a widget out of its field\n * shows once the engine answers.\n *\n * The view replays every pending change each time any change is staged; the\n * same op over the same form gives the same form, so a field keeps its object\n * while nothing about it changed.\n */\nexport function predictFormOp(index: FieldIndex, op: PredictedOp): FieldIndex {\n let byOp = predictions.get(index);\n const known = byOp?.get(op);\n if (known) return known;\n const next = predictOnce(index, op);\n if (!byOp) predictions.set(index, (byOp = new WeakMap()));\n byOp.set(op, next);\n return next;\n}\n\nconst predictions = new WeakMap<FieldIndex, WeakMap<PredictedOp, FieldIndex>>();\n\nfunction predictOnce(index: FieldIndex, op: PredictedOp): FieldIndex {\n try {\n switch (op.type) {\n case 'forms.setValue': {\n const field = fieldByRef(index, op.field);\n return field\n ? withFields(index, [fieldAfterValue(withRows(index, field), op.value)])\n : index;\n }\n case 'forms.reset': {\n const targets = op.fields\n ? op.fields.flatMap((ref) => fieldByRef(index, ref) ?? [])\n : resetTargets(index);\n return withFields(\n index,\n targets.map((field) => fieldAfterReset(withRows(index, field))),\n );\n }\n case 'forms.setDisplay': {\n const field = fieldByRef(index, op.field);\n if (!field) return index;\n return upsertWidgets(index, widgetsAfterDisplay(rowsOfField(index, field), op.display));\n }\n case 'forms.restore':\n return withFields(index, [op]);\n case 'forms.restoreWidget': {\n const restored = upsertWidgets(index, [op.widget]);\n return op.field ? upsertFields(restored, [op.field]) : restored;\n }\n case 'forms.create':\n return createdField(index, op);\n case 'forms.update': {\n const field = fieldByRef(index, op.field);\n return field\n ? withFields(index, [formFieldAfter(withRows(index, field), op.patch)])\n : index;\n }\n case 'forms.delete': {\n const field = fieldByRef(index, op.field);\n if (!field || !index.snapshot) return index;\n const gone = removeWidgets(removeField(index, field.ref), field.widgets);\n return withCalculationOrder(\n gone,\n index.snapshot.calculationOrder.filter((ref) => !sameField(ref, field.ref)),\n );\n }\n case 'forms.updateWidget': {\n const row = rowOfRef(index, op.widget);\n return row ? upsertWidgets(index, [widgetAfterPatch(row, op.patch)]) : index;\n }\n case 'forms.deleteWidget': {\n const row = rowOfRef(index, op.widget);\n if (!row) return index;\n const number = widgetNumber(row);\n const field = fieldForWidget(index, number);\n const gone = removeWidgets(index, [{ objectNumber: number, page: row.page } as FormWidget]);\n if (!field) return gone;\n const widgets = field.widgets.filter((widget) => widget.objectNumber !== number);\n return upsertFields(gone, [{ ...field, widgets } as FormFieldDTO]);\n }\n case 'forms.reorderWidgets': {\n if (!index.snapshot) return index;\n const onPage = index.snapshot.widgets\n .filter((row) => row.page.objectNumber === op.page.objectNumber)\n .map((row) => row.ref);\n const order = reorderedList(onPage, op.widgets, op.position, annotationKey);\n return reorderWidgetRows(index, op.page, order);\n }\n case 'forms.reorderCalculations': {\n if (!index.snapshot) return index;\n const order = index.snapshot.calculationOrder.filter(\n (ref): ref is FormFieldRef => ref !== null,\n );\n return withCalculationOrder(\n index,\n reorderedList(order, op.fields, op.position, fieldKeyOfRef),\n );\n }\n default:\n return index;\n }\n } catch {\n return index;\n }\n}\n\n/** A widget's row, by its annotation ref. */\nconst rowOfRef = (index: FieldIndex, ref: AnnotationRef): WidgetAnnotation | null =>\n ref.kind === 'objectNumber' ? widgetRowOf(index, ref.objectNumber) : null;\n\nconst sameField = (left: FormFieldRef | null, right: FormFieldRef): boolean =>\n left !== null && fieldKeyOfRef(left) === fieldKeyOfRef(right);\n\n/**\n * `forms.create`, once it names the numbers it takes: the field and its\n * widgets as a read of them returns them, last in the form, and last in the\n * calculation order when it calculates.\n */\nfunction createdField(\n index: FieldIndex,\n op: Extract<PredictedOp, { type: 'forms.create' }>,\n): FieldIndex {\n const placements = op.draft.widgets ?? [];\n const numbers = op.widgetObjectNumbers ?? [];\n if (op.objectNumber === undefined || numbers.length !== placements.length) return index;\n const snapshot = index.snapshot;\n if (!snapshot || fieldByRef(index, { kind: 'objectNumber', objectNumber: op.objectNumber })) {\n return index;\n }\n const created = formFieldOfDraft(op.draft, {\n objectNumber: op.objectNumber,\n widgets: placements.map((placement, at) => ({\n kind: 'objectNumber' as const,\n page: placement.page,\n objectNumber: numbers[at]!,\n })),\n });\n // The first field of a document without a form creates its /AcroForm.\n const formed =\n snapshot.formKind === 'none'\n ? indexFields({ ...snapshot, formKind: 'acroform' }, index.pictureVersions)\n : index;\n const next = withFields(formed, [created]);\n return op.draft.actions?.calculate\n ? withCalculationOrder(next, [...snapshot.calculationOrder, created.field.ref])\n : next;\n}\n\n/** The fields a change's ops write a value or a look to, each once, in op order. */\nexport function fieldsNamedBy(index: FieldIndex, ops: readonly PredictedOp[]): FormFieldDTO[] {\n const named = new Map<FieldKey, FormFieldDTO>();\n const add = (field: FormFieldDTO | null): void => {\n if (field && !named.has(fieldKeyOf(field))) named.set(fieldKeyOf(field), field);\n };\n for (const op of ops) {\n switch (op.type) {\n case 'forms.setValue':\n case 'forms.setDisplay':\n case 'forms.setAppearanceText':\n add(fieldByRef(index, op.field));\n break;\n case 'forms.reset':\n for (const field of op.fields\n ? op.fields.map((ref) => fieldByRef(index, ref))\n : resetTargets(index)) {\n add(field);\n }\n break;\n default:\n break;\n }\n }\n return [...named.values()];\n}\n\n/** `index` with these fields, and their widget rows, as `source` holds them. */\nexport function withFieldsFrom(\n index: FieldIndex,\n source: FieldIndex,\n fields: readonly FormFieldDTO[],\n): FieldIndex {\n return withFields(\n index,\n fields.flatMap((field) => {\n const held = fieldByKey(source, fieldKeyOf(field));\n return held ? [withRows(source, held)] : [];\n }),\n );\n}\n\n/** A field and its widgets back as `index` holds them. */\nconst restoreOf = (index: FieldIndex, field: FormFieldDTO): PredictedOp => ({\n type: 'forms.restore',\n field,\n widgets: rowsOfField(index, field),\n});\n\n/** A widget's row back as `index` holds it, with its field as it is there. */\nconst restoreWidgetOf = (index: FieldIndex, row: WidgetAnnotation): PredictedOp => ({\n type: 'forms.restoreWidget',\n widget: row,\n field: fieldForWidget(index, widgetNumber(row)),\n});\n\n/** What undoing one op looks like, over the form it applies to. */\nfunction undoOfOp(index: FieldIndex, op: PredictedOp): PredictedOp[] {\n switch (op.type) {\n case 'forms.create':\n return op.objectNumber === undefined\n ? []\n : [\n {\n type: 'forms.delete',\n field: { kind: 'objectNumber', objectNumber: op.objectNumber },\n },\n ];\n case 'forms.update':\n case 'forms.delete': {\n const field = fieldByRef(index, op.field);\n return field ? [restoreOf(index, field)] : [];\n }\n case 'forms.updateWidget':\n case 'forms.deleteWidget': {\n const row = rowOfRef(index, op.widget);\n return row ? [restoreWidgetOf(index, row)] : [];\n }\n case 'forms.removeWidget': {\n const field = fieldByRef(index, op.field);\n const row = rowOfRef(index, op.widget);\n return [\n ...(row ? [restoreWidgetOf(index, row)] : []),\n ...(field ? [restoreOf(index, field)] : []),\n ];\n }\n case 'forms.reorderWidgets': {\n // The page's whole order as it was.\n const widgets = (index.snapshot?.widgets ?? [])\n .filter((row) => row.page.objectNumber === op.page.objectNumber)\n .map((row) => row.ref);\n return [{ type: 'forms.reorderWidgets', page: op.page, widgets, position: 'start' }];\n }\n case 'forms.reorderCalculations': {\n const fields = (index.snapshot?.calculationOrder ?? []).filter(\n (ref): ref is FormFieldRef => ref !== null,\n );\n return [{ type: 'forms.reorderCalculations', fields, position: 'start' }];\n }\n default:\n return fieldsNamedBy(index, [op]).map((field) => restoreOf(index, field));\n }\n}\n\n/**\n * What undoing `ops` looks like, read off the form they apply to, each over\n * what the ones before it left: the ops that bring the form back, the last\n * op's first. Drawing only: the engine undoes a change by its own record of\n * it.\n */\nexport function undoLookOf(before: FieldIndex, ops: readonly PredictedOp[]): PredictedOp[] {\n const undo: PredictedOp[][] = [];\n let current = before;\n for (const op of ops) {\n undo.push(undoOfOp(current, op));\n current = predictFormOp(current, op);\n }\n return undo.reverse().flat();\n}\n","/**\n * The field tree, mirrored from the engine. It changes only by loads and by\n * confirmed form events, whoever caused them: the plugin's own writes, the\n * document's scripts, or another session. Its view shows this session's\n * pending changes on top (`predictFormOp`). This is also the one place the\n * value and field events fire.\n */\nimport type { Mirror } from '@embedpdf/core';\n\nimport { emptyFieldIndex, foldFormEvent, indexLoadedFields, type FieldIndex } from '../model';\nimport { predictFormOp } from './predict';\nimport type { FormContext } from '../services/context';\nimport type { FormEvents } from '../services/events';\n\nexport function createFieldsMirror(ctx: FormContext, events: FormEvents): Mirror<FieldIndex> {\n const fields: Mirror<FieldIndex> = ctx.mirror<FieldIndex>({\n name: 'fields',\n initial: emptyFieldIndex,\n // A reviewer-shaped token without `doc.forms.read` is a common narrowed\n // scope: skip the doomed read and report `forbidden`.\n readable: () => ctx.allows('doc.forms.read'),\n load: async (doc) => ({ value: indexLoadedFields(fields.get(), await doc.forms.list()) }),\n fold: foldFormEvent,\n predict: predictFormOp,\n changed: ({ cause, event, next }) => {\n if (cause === 'load') {\n if (next.snapshot) events.resynced.emit({ snapshot: next.snapshot });\n return;\n }\n if (!event || !('origin' in event)) return;\n const { origin } = event;\n switch (event.type) {\n case 'forms.valueSet':\n events.valueChanged.emit({ field: event.field, origin });\n return;\n case 'forms.created':\n events.fieldCreated.emit({ field: event.field, origin });\n return;\n case 'forms.updated':\n case 'forms.widgetAdded':\n case 'forms.widgetRemoved':\n events.fieldUpdated.emit({ field: event.field, origin });\n return;\n case 'forms.widgetDeleted':\n case 'forms.widgetRestored':\n if (event.field) events.fieldUpdated.emit({ field: event.field, origin });\n return;\n case 'forms.deleted':\n if (event.deleted) events.fieldDeleted.emit({ ref: event.deleted, origin });\n return;\n default:\n return;\n }\n },\n });\n return fields;\n}\n","/**\n * Whether the form's widgets are lent to the annotation plugin now\n * (write/lending.ts): the session may design, the annotation plugin is there,\n * and the active tool doesn't fill. Then the annotation layer draws and edits\n * the widgets, and the form layer leaves them out.\n */\nimport { InteractionToken } from '@embedpdf/plugin-interaction/contract/host';\n\nimport type { FormContext } from './context';\nimport type { FormSiblings } from './siblings';\n\nexport interface FormDesign {\n lending(): boolean;\n}\n\nexport function createDesign(ctx: FormContext, siblings: FormSiblings): FormDesign {\n const interaction = ctx.tryGet(InteractionToken);\n return {\n lending: () =>\n siblings.annotation() !== null &&\n interaction !== null &&\n ctx.allows('doc.forms.modify') &&\n !(interaction.getActiveTool()?.enables.has('form-fill') ?? false),\n };\n}\n","/** The form plugin's events. Fact events fire from the fields mirror; see `sync/fields.ts`. */\nimport type {\n FormFieldCreatedEvent,\n FormFieldDeletedEvent,\n FormFieldUpdatedEvent,\n FormResyncedEvent,\n FormValidationRejectedEvent,\n FormValueChangedEvent,\n} from '../contract';\nimport type { FormContext } from './context';\n\nexport function createEvents(ctx: FormContext) {\n return {\n valueChanged: ctx.events.source<FormValueChangedEvent>(),\n fieldCreated: ctx.events.source<FormFieldCreatedEvent>(),\n fieldUpdated: ctx.events.source<FormFieldUpdatedEvent>(),\n fieldDeleted: ctx.events.source<FormFieldDeletedEvent>(),\n validationRejected: ctx.events.source<FormValidationRejectedEvent>(),\n resynced: ctx.events.source<FormResyncedEvent>(),\n };\n}\nexport type FormEvents = ReturnType<typeof createEvents>;\n","/**\n * Who may fill in, and sign, which field: the engine's own answer per field\n * (`ctx.allowsField`), so a control gated on it never disagrees with the\n * write. A field's group decides: a `fields:fill` (`fields:sign`) permission\n * for its group, or `doc.forms.fill` (`doc.sign`) for every field.\n */\nimport { memo, type Mirror } from '@embedpdf/core';\n\nimport type { FieldIndex } from '../model';\nimport type { FormContext } from './context';\n\n/** What decides who may fill a field in: its group. */\ninterface Grouped {\n readonly groupId: string | null;\n}\n\nexport interface FillRights {\n /** Whether the session may fill in this field. */\n mayFill(field: Grouped): boolean;\n /** Whether the session may sign this signature field. */\n maySign(field: Grouped): boolean;\n /** Refuse a write to this field when the session may not fill it in, naming what it takes. */\n assertMayFill(field: Grouped, operation: string): void;\n /** What the session may fill in and sign, as a key that changes when that does: for memos. */\n key(): string;\n}\n\nexport function createFillRights(ctx: FormContext, fields: Mirror<FieldIndex>): FillRights {\n const mayFill = (field: Grouped): boolean => ctx.allowsField('fill', field);\n const maySign = (field: Grouped): boolean => ctx.allowsField('sign', field);\n\n /** The form's groups, `null` (no group) among them. */\n const groups = memo(\n () => [fields.view()],\n (index) => [...new Set((index.snapshot?.fields ?? []).map((field) => field.groupId))],\n );\n\n return {\n mayFill,\n maySign,\n assertMayFill: (field, operation) => ctx.assertAllowedField('fill', field, operation),\n key: () =>\n groups()\n .map((groupId) => `${mayFill({ groupId }) ? 1 : 0}${maySign({ groupId }) ? 1 : 0}`)\n .join(''),\n };\n}\n","/**\n * The texts this session's format scripts wrote. The engine draws a field's\n * formatted text into its picture but doesn't say what it was (a\n * `forms.setAppearanceText` answers as `forms.updated`), so the painter takes\n * it from here: the text each change wrote, for the value the field had.\n * Looked up by the value the field has now, so a refused change, or another\n * session's fill, falls back to the value itself.\n */\nimport type { Mirror } from '@embedpdf/core';\nimport type { ChangeOp, FormFieldDTO } from '@embedpdf/engine-core/runtime';\n\nimport { fieldByRef, fieldKeyOf, type FieldIndex, type FieldKey } from '../model';\nimport type { FormContext } from './context';\n\n/** The values remembered per field: enough for an undo or two. */\nconst KEPT_PER_FIELD = 8;\n\nexport interface FormattedTexts {\n /** The text the field shows for its value, as this session formatted it; `null` when it didn't. */\n textOf(field: FormFieldDTO): string | null;\n /** Moves when a text is remembered. */\n version(): number;\n}\n\nconst valueOf = (field: FormFieldDTO): string | null =>\n field.family === 'text' || field.family === 'combobox' ? field.value : null;\n\nexport function createFormattedTexts(ctx: FormContext, fields: Mirror<FieldIndex>): FormattedTexts {\n const texts = new Map<FieldKey, Map<string, string>>();\n let version = 0;\n ctx.listen(ctx.changes.onStaged, (change) => {\n // Staged: the view shows the change, its fields at the values it wrote.\n const view = fields.view();\n for (const op of change.shows as readonly ChangeOp[]) {\n if (op.type !== 'forms.setAppearanceText') continue;\n const field = fieldByRef(view, op.field);\n const value = field ? valueOf(field) : null;\n if (!field || value === null) continue;\n const key = fieldKeyOf(field);\n const kept = texts.get(key) ?? new Map<string, string>();\n kept.delete(value);\n kept.set(value, op.text);\n while (kept.size > KEPT_PER_FIELD) kept.delete(kept.keys().next().value!);\n texts.set(key, kept);\n version += 1;\n }\n });\n return {\n textOf(field) {\n const value = valueOf(field);\n return value === null ? null : (texts.get(fieldKeyOf(field))?.get(value) ?? null);\n },\n version: () => version,\n };\n}\n","/**\n * What a shown widget looks like now: the engine's picture, or the painter's\n * drawing of it (`@embedpdf/core-form`).\n *\n * A widget's look is everything its picture depends on: its size and turn,\n * its style, and what it shows (the value, as this session formatted it). Its\n * place isn't (a move keeps the look), nor the state a toggle shows (its\n * picture of every state is held). A widget is `pending` while its look in\n * the view isn't its confirmed look: a value typed or calculated, a restyle,\n * a field just placed. The layer then draws the painter's scene, as it does\n * while the picture it holds is older than the widget's look.\n */\nimport { memoByKey, type Mirror } from '@embedpdf/core';\nimport type { SceneNode } from '@embedpdf/core-annotation';\nimport {\n paints,\n textEditorLayout,\n widgetDrawing,\n widgetScene,\n type TextEditorLayout,\n} from '@embedpdf/core-form';\nimport type { AnnotationRef, FormFieldDTO, WidgetAnnotation } from '@embedpdf/engine-core/runtime';\n\nimport {\n fieldForWidget,\n pictureVersionOf,\n shownWidgetsOf,\n widgetRowOf,\n type Box,\n type FieldIndex,\n type ShownWidget,\n} from '../model';\nimport type { FormDesign } from './design';\nimport type { FormattedTexts } from './formatted';\n\nconst NOTHING_SHOWN: readonly ShownWidget[] = Object.freeze([]);\n\n/** A widget as the painter draws it: its scene on the page (its text carries the faces it needs). */\nexport interface WidgetPainting {\n readonly scene: readonly SceneNode[];\n}\n\nconst numberOf = (ref: AnnotationRef): number =>\n ref.kind === 'objectNumber' ? ref.objectNumber : -1;\n\nexport type WidgetLooks = ReturnType<typeof createWidgetLooks>;\n\nexport function createWidgetLooks({\n fields,\n formatted,\n design,\n}: {\n readonly fields: Mirror<FieldIndex>;\n readonly formatted: FormattedTexts;\n readonly design: FormDesign;\n}) {\n /** What the widget's picture depends on, as one string. */\n const lookKeyOf = (row: WidgetAnnotation, field: FormFieldDTO | null): string => {\n const box = row.box ?? row.rect;\n const content = (() => {\n switch (field?.family) {\n case 'text':\n return [\n formatted.textOf(field) ?? field.value,\n field.multiline,\n field.password,\n field.comb,\n field.maxLength,\n ];\n case 'combobox':\n return [formatted.textOf(field) ?? field.value];\n case 'listbox':\n return [field.topIndex, field.options.map((option) => [option.label, option.selected])];\n default:\n return [field?.family ?? null];\n }\n })();\n return JSON.stringify([\n box.width,\n box.height,\n row.rotation ?? 0,\n row.color ?? null,\n row.interiorColor ?? null,\n row.strokeWidth ?? null,\n row.borderStyle ?? null,\n row.dashArray ?? null,\n row.fontFamily ?? null,\n row.fontSize ?? null,\n row.fontColor ?? null,\n row.textAlign ?? null,\n row.caption ?? null,\n row.checkStyle ?? null,\n content,\n ]);\n };\n\n const lookOf = (index: FieldIndex, number: number): string | null => {\n const row = widgetRowOf(index, number);\n return row ? lookKeyOf(row, fieldForWidget(index, number)) : null;\n };\n\n // In design mode the annotation layer draws the widgets it borrowed.\n const shownOn = memoByKey(\n (_pageObjectNumber: number) =>\n [fields.view(), fields.get(), formatted.version(), design.lending()] as const,\n (pageObjectNumber, view, truth, _formatted, lent): readonly ShownWidget[] =>\n lent\n ? NOTHING_SHOWN\n : shownWidgetsOf(view, pageObjectNumber, (row) => {\n const number = numberOf(row.ref);\n return {\n pending: lookOf(view, number) !== lookOf(truth, number),\n pictureVersion: pictureVersionOf(truth, number),\n };\n }),\n );\n\n /** The painter's drawing of `row` (in the view's field, as this session formatted it) at `box`, turned. */\n const paint = (\n row: WidgetAnnotation,\n box: Box,\n rotation: number | null | undefined,\n ): readonly SceneNode[] | null => {\n const view = fields.view();\n const field = fieldForWidget(view, numberOf(row.ref));\n if (!field) return null;\n const text = formatted.textOf(field);\n const drawing = widgetDrawing({ ...row, box }, field, text === null ? {} : { text });\n return drawing && widgetScene(drawing, { box, rotation });\n };\n\n /** The painter's drawing of a widget as the view has it; `null` for one it doesn't draw. */\n const sceneOf = memoByKey(\n (number: number) => {\n const view = fields.view();\n const row = widgetRowOf(view, number);\n const field = row ? fieldForWidget(view, number) : null;\n return [row, field, field ? formatted.textOf(field) : null] as const;\n },\n (_number, row): WidgetPainting | null => {\n const scene = row && paint(row, row.box ?? row.rect, row.rotation);\n return scene ? { scene } : null;\n },\n );\n\n return {\n listShownWidgets: (pageObjectNumber: number) => shownOn(pageObjectNumber),\n getWidgetPainting: (ref: AnnotationRef) => sceneOf(numberOf(ref)),\n /** The widget's look in the view isn't its confirmed look yet: it draws live until its picture is. */\n isPending: (ref: AnnotationRef): boolean => {\n const number = numberOf(ref);\n return lookOf(fields.view(), number) !== lookOf(fields.get(), number);\n },\n /**\n * How the painter draws a widget row live, upright in a box (where a gesture has it); `null`\n * for one whose field it doesn't draw (a signature).\n */\n painterOf: (row: WidgetAnnotation): ((box: Box) => readonly SceneNode[]) | null => {\n const field = fieldForWidget(fields.view(), numberOf(row.ref));\n return field && paints(field) ? (box) => paint(row, box, 0) ?? [] : null;\n },\n getTextEditorLayout: (ref: AnnotationRef, text: string): TextEditorLayout | null => {\n const view = fields.view();\n const number = numberOf(ref);\n const row = widgetRowOf(view, number);\n const field = row ? fieldForWidget(view, number) : null;\n return row && field ? textEditorLayout(row, field, text) : null;\n },\n };\n}\n","/**\n * The engine's pictures of each page's widgets, through the render plugin's\n * one door. The form layer draws them, and the annotation plugin draws the\n * widgets it borrows from the same ones (design mode), so switching modes\n * fetches nothing. A page's pictures depend on its widgets' picture versions\n * (the mirror's) and nothing else: a checkbox that only switches its state\n * fetches nothing.\n */\nimport { memoByKey, type Mirror } from '@embedpdf/core';\nimport type { AnnotationRef, PageRef } from '@embedpdf/engine-core/runtime';\nimport type { AppearanceItem, AppearancePicture } from '@embedpdf/plugin-render/contract/host';\n\nimport { pictureVersionOf, type FieldIndex } from '../model';\nimport type { FormSiblings } from './siblings';\n\nexport interface WidgetPictures {\n /** What the page's pictures depend on, `5@2|6@7`: a new value means new pictures. */\n epoch(page: PageRef): string;\n /** Every picture of the page's widgets, at rest, in every state, each with its widget's version. */\n render(page: PageRef, scale: number, signal?: AbortSignal): Promise<readonly AppearancePicture[]>;\n /** The widget's confirmed picture version. */\n versionOf(widget: AnnotationRef): number;\n}\n\nconst NO_PICTURES: readonly AppearancePicture[] = Object.freeze([]);\n\nexport function createWidgetPictures(\n fields: Mirror<FieldIndex>,\n { render }: Pick<FormSiblings, 'render'>,\n): WidgetPictures {\n /** The page's widgets, as the engine confirmed them, each at its picture version. */\n const itemsOn = memoByKey(\n (_pageObjectNumber: number) => [fields.get()] as const,\n (pageObjectNumber, index): readonly AppearanceItem[] =>\n (index.snapshot?.widgets ?? []).flatMap((row) =>\n row.page.objectNumber === pageObjectNumber && row.ref.kind === 'objectNumber'\n ? [{ ref: row.ref, version: pictureVersionOf(index, row.ref.objectNumber) }]\n : [],\n ),\n );\n const epochOn = memoByKey(\n (pageObjectNumber: number) => [itemsOn(pageObjectNumber)] as const,\n (_pageObjectNumber, items) =>\n items\n .map(\n ({ ref, version }) => `${ref.kind === 'objectNumber' ? ref.objectNumber : ''}@${version}`,\n )\n .sort()\n .join('|'),\n );\n return {\n epoch: (page) => epochOn(page.objectNumber),\n render: (page, scale, signal) => {\n const renderer = render();\n return renderer\n ? renderer.renderAppearances(page, {\n family: 'widgets',\n scale,\n items: itemsOn(page.objectNumber),\n ...(signal ? { signal } : {}),\n })\n : Promise.resolve(NO_PICTURES);\n },\n versionOf: (widget) =>\n widget.kind === 'objectNumber' ? pictureVersionOf(fields.get(), widget.objectNumber) : 0,\n };\n}\n","/**\n * The keystroke, validate, calculate and format script pipeline. Scripts run\n * in the actions plugin's per-document realm: when that realm offers a\n * transaction port, JavaScript is on (the switch is\n * `actionsPlugin({ javascript })`). The `validation` setting decides, at each\n * write, whether the pipeline runs; this plugin owns only the pipeline.\n */\nimport type { ActionOrigin } from '@embedpdf/plugin-actions/contract';\nimport type { ScriptCommitSurface } from '@embedpdf/plugin-actions/contract/host';\n\nimport { formHasScripts, type FieldIndex } from '../model';\nimport {\n createFormScriptingController,\n type FormScriptingController,\n} from '../scripting/controller';\nimport type { FormContext } from './context';\nimport type { FormSiblings } from './siblings';\n\nexport function createScriptingSeam(ctx: FormContext, siblings: FormSiblings) {\n // The pipeline over the actions plugin's realm, made the first time one is there.\n let pipeline: FormScriptingController | null = null;\n const pipelineOf = (): FormScriptingController | null => {\n if (pipeline) return pipeline;\n const realm = siblings.actions()?.scriptRealm ?? null;\n if (!realm) return null;\n const made = createFormScriptingController({\n document: () => ctx.document(),\n transaction: realm.transaction.bind(realm),\n budget: realm.budget,\n });\n ctx.cleanup(() => made.dispose());\n pipeline = made;\n return made;\n };\n const settings = ctx.settings();\n const controller = (): FormScriptingController | null =>\n settings.get().validation === 'scripts' ? pipelineOf() : null;\n\n // A one-shot developer hint: a form with scripts and no realm fills without them.\n let warnedNoRealm = false;\n const scriptsFor = (form: FieldIndex): FormScriptingController | null => {\n if (!formHasScripts(form)) return null;\n if (!pipelineOf() && !warnedNoRealm && settings.get().validation === 'scripts') {\n warnedNoRealm = true;\n console.warn(\n \"[form] this form has scripts, but they don't run: add the actions plugin with \" +\n 'JavaScript on (`actionsPlugin({ javascript: { enabled: true, sandboxFactory } })`), ' +\n \"or set the form's `validation` to 'none' to fill it in without them.\",\n );\n }\n return controller();\n };\n\n let warmed = false;\n return {\n /** The script pipeline when the document's scripts run, else `null`. */\n controller,\n /** The script pipeline for a write to this form: `null` too when no field has a script. */\n scriptsFor,\n /** Start the realm before the first write needs it, once, when the form has scripts. */\n warm(form: FieldIndex): void {\n if (warmed || !form.snapshot) return;\n const scripts = scriptsFor(form);\n if (!scripts) return;\n warmed = true;\n void scripts.warm(form.snapshot).catch(() => {\n /* the first write starts the realm, and reports why it can't */\n });\n },\n /** Script results (UI effects, diagnostics, errors) are surfaced through the\n * actions plugin, with the origin that caused them. */\n surface: (result: ScriptCommitSurface, origin: ActionOrigin): void => {\n siblings.actions()?.surfaceScriptCommit(result, { origin, realm: 'document' });\n },\n };\n}\nexport type FormScripting = ReturnType<typeof createScriptingSeam>;\n","/** The optional sibling planes, looked up each time they're used, not once\n * at construction: what a sibling is depends on no creation order. A\n * fill-only setup may have none; every area guards on null. */\nimport { ActionsToken as ActionsHostToken } from '@embedpdf/plugin-actions/contract/host';\nimport { AnnotationToken as AnnotationHostToken } from '@embedpdf/plugin-annotation/contract/host';\nimport { RenderToken as RenderHostToken } from '@embedpdf/plugin-render/contract/host';\n\nimport type { FormContext } from './context';\n\nexport function resolveSiblings(ctx: FormContext) {\n return {\n /** The annotation plugin: design mode's selection, tools, ghosts and placement previews. */\n annotation: () => ctx.tryGet(AnnotationHostToken),\n /** The script realm owner and the one surface port for script results. */\n actions: () => ctx.tryGet(ActionsHostToken),\n /** The page renderer: the widgets' pictures, shared by the form layer and design mode. */\n render: () => ctx.tryGet(RenderHostToken),\n };\n}\nexport type FormSiblings = ReturnType<typeof resolveSiblings>;\n","/**\n * Plugin-private services every area is built on: the form's mirror (the\n * field tree and every widget row), who may fill in which field, the events,\n * the sibling plugins, the scripting seam, and the one write queue. The rest\n * of the session's authority is the context's (`ctx.allows`,\n * `ctx.assertAllowed`).\n */\nimport type { Mirror, SerialQueue } from '@embedpdf/core';\nimport type { FormFieldRef } from '@embedpdf/engine-core/runtime';\n\nimport { canonicalKey, type FieldIndex, type FieldKey } from '../model';\nimport { createFieldsMirror } from '../sync/fields';\nimport type { FormContext } from './context';\nimport { createDesign, type FormDesign } from './design';\nimport { createEvents, type FormEvents } from './events';\nimport { createFillRights, type FillRights } from './fill-rights';\nimport { createFormattedTexts, type FormattedTexts } from './formatted';\nimport { createWidgetLooks, type WidgetLooks } from './looks';\nimport { createWidgetPictures, type WidgetPictures } from './pictures';\nimport { createScriptingSeam, type FormScripting } from './scripting';\nimport { resolveSiblings, type FormSiblings } from './siblings';\n\nexport type { FormContext } from './context';\n\nexport interface FormServices {\n readonly fields: Mirror<FieldIndex>;\n /** Who may fill in which field. */\n readonly rights: FillRights;\n readonly events: FormEvents;\n readonly siblings: FormSiblings;\n readonly scripting: FormScripting;\n /** Whether the widgets are lent to the annotation plugin now (design mode). */\n readonly design: FormDesign;\n /** The texts this session's format scripts wrote, for the painter. */\n readonly formatted: FormattedTexts;\n /** The engine's pictures of each page's widgets, at their picture versions. */\n readonly pictures: WidgetPictures;\n /** What each widget looks like now: pending or confirmed, and the painter's drawing of it. */\n readonly looks: WidgetLooks;\n /**\n * Fills take turns on one serial queue until they are sent (write/fill.ts),\n * and a repair until the engine answers.\n */\n readonly enqueue: SerialQueue;\n /** The key a field is known by, whichever ref names it (`toFieldRef(name)` too). */\n readonly keyOf: (ref: FormFieldRef) => FieldKey;\n}\n\nexport function createServices(ctx: FormContext): FormServices {\n const siblings = resolveSiblings(ctx);\n const events = createEvents(ctx);\n const fields = createFieldsMirror(ctx, events);\n const design = createDesign(ctx, siblings);\n const formatted = createFormattedTexts(ctx, fields);\n return {\n fields,\n rights: createFillRights(ctx, fields),\n events,\n siblings,\n scripting: createScriptingSeam(ctx, siblings),\n design,\n formatted,\n pictures: createWidgetPictures(fields, siblings),\n looks: createWidgetLooks({ fields, formatted, design }),\n enqueue: ctx.serialQueue('writes'),\n keyOf: (ref) => canonicalKey(fields.view(), ref),\n };\n}\n","/**\n * Widget activation and the widget DOM-event feed into the actions plane.\n * A click first offers the widget's `/A` tree to the dispatcher; only a\n * tree-less widget falls back to the form's own scripted activation.\n */\nimport { PluginError, type OperationOptions } from '@embedpdf/core';\nimport { type AnnotationRef, type FormFieldRef } from '@embedpdf/engine-core/runtime';\nimport { ActionsToken, createHoverPump } from '@embedpdf/plugin-actions/contract';\nimport type { ActionSource } from '@embedpdf/plugin-actions/contract';\n\nimport type { FormCommitResult, WidgetActivationResult } from '../contract';\nimport type { FormHostCapability } from '../host-contract';\nimport { fieldForWidget, widgetRowOf } from '../model';\nimport { widgetObjectOf } from '../read/fields';\nimport type { FormContext, FormServices } from '../services';\nimport type { Fills } from './fill';\n\nexport function createActivation(\n ctx: FormContext,\n services: Pick<FormServices, 'fields' | 'siblings' | 'scripting'>,\n { fill }: Fills,\n) {\n const { fields, scripting } = services;\n\n /** The widget's activation action, from its row in the form. */\n const annotationActivation = async (ref: AnnotationRef) => {\n await fields.settled();\n const row = ref.kind === 'objectNumber' ? widgetRowOf(fields.view(), ref.objectNumber) : null;\n return row?.actions?.activate ?? null;\n };\n\n /** The widget's activation through the form's own scripts: what they change is one fill. */\n const activateThroughScripts = async (\n ref: FormFieldRef,\n annotationRef: AnnotationRef,\n options?: OperationOptions,\n ): Promise<FormCommitResult> => {\n const pipeline = scripting.controller();\n if (!pipeline) {\n return {\n status: 'unchanged',\n scripted: false,\n uiEffects: [],\n diagnostics: [],\n };\n }\n const action = await annotationActivation(annotationRef);\n if (!action) {\n return {\n status: 'unchanged',\n scripted: true,\n uiEffects: [],\n diagnostics: [],\n };\n }\n const { result } = await fill(\n { ops: [], scripts: { kind: 'activate', field: ref, action }, origin: 'user' },\n options,\n );\n return result;\n };\n\n // ── widget DOM-event feed helpers ───────────────────────────────────────\n const widgetSource = (field: FormFieldRef, annotationRef: AnnotationRef): ActionSource => ({\n kind: 'widget',\n field,\n annotation: annotationRef,\n page: annotationRef.page,\n });\n\n /**\n * One shared hover pump (an exit and the next enter delivered as one\n * ordered pair; intermediate hovers skipped), created on first use.\n */\n let widgetPump: ReturnType<typeof createHoverPump> | null = null;\n const widgetHoverPump = (actions: {\n dispatch: Parameters<typeof createHoverPump>[0];\n }): ReturnType<typeof createHoverPump> => {\n widgetPump ??= createHoverPump(actions.dispatch);\n return widgetPump;\n };\n\n const widgetHoverFlags = (\n annotationRef: AnnotationRef,\n ): { enter: boolean; exit: boolean } | null => {\n const row =\n annotationRef.kind === 'objectNumber'\n ? widgetRowOf(fields.view(), annotationRef.objectNumber)\n : null;\n if (!row) return null;\n return {\n enter: Boolean(row.actions?.cursorEnter?.root),\n exit: Boolean(row.actions?.cursorExit?.root),\n };\n };\n\n return {\n api: {\n activateWidget: async (annotationRef, options): Promise<WidgetActivationResult> => {\n const field = fieldForWidget(fields.view(), widgetObjectOf(annotationRef));\n if (!field) throw new PluginError('not-found', 'form', 'no form field owns this widget');\n const actions = ctx.tryGet(ActionsToken);\n if (actions) {\n const result = await ctx.cancellable(\n options?.signal,\n actions.dispatch({\n scope: 'activate',\n ref: annotationRef,\n page: annotationRef.page,\n source: widgetSource(field.ref, annotationRef),\n }),\n );\n const noTree =\n result.status === 'inert' &&\n result.steps.length === 0 &&\n result.diagnostics.length === 0;\n if (!noTree) return { kind: 'dispatched', result };\n }\n return {\n kind: 'form',\n result: await activateThroughScripts(field.ref, annotationRef, options),\n };\n },\n notifyWidgetEvent: (fieldRef, annotationRef, event) => {\n const actions = ctx.tryGet(ActionsToken);\n if (!actions) return;\n const source = widgetSource(fieldRef, annotationRef);\n if (event === 'cursorEnter' || event === 'cursorExit') {\n if (event === 'cursorExit') {\n widgetHoverPump(actions).hover(null);\n return;\n }\n // Check for an enter/exit action tree through the annotation plugin\n // when it is present, so a widget without one costs no dispatch.\n // Without the annotation plugin the flags stay unknown and the\n // dispatcher resolves them in its queue.\n const flags = widgetHoverFlags(annotationRef);\n if (flags && !flags.enter && !flags.exit) return;\n widgetHoverPump(actions).hover({\n ref: annotationRef,\n page: annotationRef.page,\n source,\n ...(flags ? { events: flags } : {}),\n });\n return;\n }\n // The first field to take focus starts the realm, so the first commit doesn't wait.\n if (event === 'focus') scripting.warm(fields.view());\n // Down, up, focus and blur are fire-and-forget: dispatch never\n // rejects, the dispatcher's queue orders them, and results surface\n // through the actions events. The dispatcher also applies the rule\n // that /A shadows the up event (ISO 32000-2 Table 197).\n void actions.dispatch({\n scope: 'annotation',\n event,\n ref: annotationRef,\n page: annotationRef.page,\n source,\n });\n },\n } satisfies Partial<FormHostCapability>,\n };\n}\n","/**\n * The object numbers a new field and its widgets take: final names from the\n * document's pool (`ctx.changes`), so a field shows under the ref it keeps\n * from its first frame. A few taken and not used yet wait here for the next\n * create; one the engine reclaims leaves.\n */\nimport type { FormContext } from './context';\n\nexport interface ObjectNumbers {\n /** `count` numbers now, or `null` when the pool has too few (it refills as it goes). */\n takeNow(count: number): number[] | null;\n /** `count` numbers, once the pool has them. */\n take(count: number): Promise<number[]>;\n}\n\nexport function createObjectNumbers(ctx: Pick<FormContext, 'changes' | 'doc'>): ObjectNumbers {\n const held: number[] = [];\n let watching = false;\n const watchLost = (): void => {\n if (watching || !ctx.doc) return;\n watching = true;\n ctx.doc.objectNumbers.onLost(({ numbers }) => {\n const lost = new Set(numbers);\n held.splice(0, held.length, ...held.filter((number) => !lost.has(number)));\n });\n };\n\n const takeNow = (count: number): number[] | null => {\n watchLost();\n while (held.length < count) {\n const number = ctx.changes.takeObjectNumber();\n if (number === null) return null;\n held.push(number);\n }\n return held.splice(0, count);\n };\n\n return {\n takeNow,\n async take(count) {\n for (;;) {\n const taken = takeNow(count);\n if (taken) return taken;\n await ctx.changes.reserveObjectNumbers(count - held.length);\n }\n },\n };\n}\n","/**\n * Where a field's new widget goes when `addWidget()` gets no place for it: next in line after\n * the field's widgets on the page. A column of buttons grows downward and a row grows sideways,\n * each step the same as the one between the last two buttons; one button gets the next below\n * it, half its height away. Where the next step leaves the page, the line starts again beside\n * the group (a column) or under it (a row). Page space: top-left origin, y down.\n */\nimport type { Box } from '../model';\n\n/** The page's size, as the widgets' boxes are measured on it. */\ninterface PageSize {\n readonly width: number;\n readonly height: number;\n}\n\nconst fits = (box: Box, page: PageSize): boolean =>\n box.x >= 0 && box.y >= 0 && box.x + box.width <= page.width && box.y + box.height <= page.height;\n\n/** The box after `boxes`, the field's widgets on one page in the field's order. */\nexport function nextInLine(boxes: readonly Box[], page: PageSize): Box {\n const last = boxes.at(-1);\n if (!last) return { x: 0, y: 0, width: 0, height: 0 };\n const { width, height } = last;\n const previous = boxes.at(-2);\n // The step between the last two, or half a button's height below the only one.\n const step =\n previous && (previous.x !== last.x || previous.y !== last.y)\n ? { x: last.x - previous.x, y: last.y - previous.y }\n : { x: 0, y: height * 1.5 };\n const next = { x: last.x + step.x, y: last.y + step.y, width, height };\n if (fits(next, page)) return next;\n\n const column = Math.abs(step.y) >= Math.abs(step.x);\n const left = Math.min(...boxes.map((box) => box.x));\n const top = Math.min(...boxes.map((box) => box.y));\n const right = Math.max(...boxes.map((box) => box.x + box.width));\n const bottom = Math.max(...boxes.map((box) => box.y + box.height));\n // The gap between two buttons along the line: the new line keeps the same one.\n const gap = Math.max(column ? Math.abs(step.y) - height : Math.abs(step.x) - width, 0);\n const restart = column\n ? { x: right + (gap || width / 2), y: top, width, height }\n : { x: left, y: bottom + (gap || height / 2), width, height };\n if (fits(restart, page)) return restart;\n // No room beside the group either: on the page, at the last button's place shifted in.\n return {\n x: Math.min(Math.max(next.x, 0), Math.max(page.width - width, 0)),\n y: Math.min(Math.max(next.y, 0), Math.max(page.height - height, 0)),\n width,\n height,\n };\n}\n","/**\n * Building the form: every design verb is one change on the document's queue\n * (`ctx.changes`). It shows at once (the fields mirror predicts it), it is a\n * step of the history, and it resolves with the engine's answer. A create\n * takes its field's and widgets' object numbers first, so their refs are final\n * from the first frame and the new widget can be selected straight away.\n */\nimport {\n PluginError,\n toPluginError,\n type ChangeLabel,\n type OperationOptions,\n type PendingChange,\n} from '@embedpdf/core';\nimport {\n draftWritesScripts,\n writesScripts,\n type ChangeItem,\n type ChangeOp,\n type FormFieldDTO,\n type WidgetAnnotation,\n type WidgetPlacement,\n} from '@embedpdf/engine-core/runtime';\n\nimport type { FormCapability, FormFieldResult } from '../contract';\nimport { fieldByRef, widgetRowOf } from '../model';\nimport type { FormContext, FormServices } from '../services';\nimport { createObjectNumbers } from '../services/object-numbers';\nimport { undoLookOf } from '../sync/predict';\nimport { nextInLine } from './next-in-line';\n\n/**\n * A widget's look, as `addWidget()` copies it from the field's last widget onto the new one:\n * the engine's widget style fields (`WIDGET_STYLE_NAMES`), and its turn.\n */\nconst LOOK = [\n 'color',\n 'interiorColor',\n 'strokeWidth',\n 'borderStyle',\n 'dashArray',\n 'fontFamily',\n 'fontSize',\n 'fontColor',\n 'textAlign',\n 'caption',\n 'checkStyle',\n 'rotation',\n] as const;\n\nconst lookOf = (widget: WidgetAnnotation | undefined): Partial<WidgetPlacement> => {\n if (!widget) return {};\n const held = widget as unknown as Record<string, unknown>;\n const look: Record<string, unknown> = {};\n for (const name of LOOK)\n if (held[name] !== undefined && held[name] !== null) look[name] = held[name];\n return look as Partial<WidgetPlacement>;\n};\n\n/**\n * The export value a field's new widget gets when none is given: a radio group's next free\n * `Choice<n>` (the radio tool names its first button `Choice1`), a checkbox's own value, so\n * the boxes check together. Other families take none.\n */\nfunction exportValueFor(field: FormFieldDTO): string | undefined {\n if (field.family === 'checkbox') return field.exportValue;\n if (field.family !== 'radio') return undefined;\n const taken = new Set(field.widgets.map((widget) => widget.exportValue));\n let n = field.widgets.length + 1;\n while (taken.has(`Choice${n}`)) n += 1;\n return `Choice${n}`;\n}\n\n/** Whether the field's dictionary is its only widget's too, which adding a widget splits. */\nconst isMerged = (field: FormFieldDTO): boolean =>\n field.ref.kind === 'objectNumber' &&\n field.widgets.some(\n (widget) => widget.objectNumber === (field.ref as { objectNumber: number }).objectNumber,\n );\n\nconst MODIFY = 'doc.forms.modify';\nconst SCRIPT = 'doc.forms.script';\n\n/** The answer's item for the change's only op, of the type it names. */\ntype ItemOf<T extends ChangeItem['type']> = Extract<ChangeItem, { type: T }>;\n\nexport function createFieldWrites(\n ctx: FormContext,\n { fields, enqueue }: Pick<FormServices, 'fields' | 'enqueue'>,\n) {\n const numbers = createObjectNumbers(ctx);\n\n /** Refuse up front without `doc.forms.modify`, and without `doc.forms.script` when it writes scripts. */\n const allow = (operation: string, scripts = false): void => {\n ctx.assertAllowed(MODIFY, operation);\n if (scripts) ctx.assertAllowed(SCRIPT, operation);\n };\n\n /** Stage one design op as its own change: it shows at once, and undoing it shows the form as it was. */\n const stage = (verb: string, op: ChangeOp): PendingChange =>\n ctx.changes.stage({\n label: { key: `form.${verb}` } satisfies ChangeLabel,\n ops: [op],\n undo: undoLookOf(fields.view(), [op]),\n });\n\n /** The engine's answer to a staged design change: its one item. */\n const answer = async <T extends ChangeItem['type']>(\n change: PendingChange,\n options?: OperationOptions,\n ): Promise<ItemOf<T>> => {\n try {\n const result = await ctx.cancellable(options?.signal, change.result);\n return result.items[0] as ItemOf<T>;\n } catch (error) {\n throw toPluginError('form', error);\n }\n };\n\n const create: FormCapability['create'] = async (draft, options) => {\n allow('form.create', draftWritesScripts(draft));\n // The field, then each widget, in the draft's order.\n const count = 1 + (draft.widgets?.length ?? 0);\n const [objectNumber, ...widgetObjectNumbers] =\n numbers.takeNow(count) ?? (await numbers.take(count));\n const change = stage('create', {\n type: 'forms.create',\n draft,\n objectNumber,\n widgetObjectNumbers,\n });\n const item = await answer<'forms.create'>(change, options);\n return { field: item.field } satisfies FormFieldResult;\n };\n\n const addWidget: FormCapability['addWidget'] = async (ref, placement = {}, options) => {\n allow('form.addWidget', writesScripts(placement.actions));\n const index = fields.view();\n const field = fieldByRef(index, ref);\n if (!field) throw new PluginError('not-found', 'form', 'no form field has this ref');\n const rows = field.widgets\n .map((widget) => widgetRowOf(index, widget.objectNumber))\n .filter((row): row is WidgetAnnotation => row !== null);\n const last = rows.at(-1);\n const page = placement.page ?? last?.page;\n if (!page) {\n throw new PluginError(\n 'invalid-input',\n 'form',\n 'the field shows on no page: give `page` and `rect`',\n );\n }\n const size = ctx.getPage(page)?.size;\n const onPage = rows.filter((row) => row.page.objectNumber === page.objectNumber);\n const rect =\n placement.rect ??\n placement.box ??\n (size && onPage.length > 0\n ? nextInLine(\n onPage.map((row) => row.box),\n size,\n )\n : undefined);\n if (!rect) {\n throw new PluginError(\n 'invalid-input',\n 'form',\n 'no widget of the field on that page: give `rect`',\n );\n }\n const exportValue = placement.exportValue ?? exportValueFor(field);\n const split = isMerged(field);\n const [objectNumber, splitObjectNumber] =\n numbers.takeNow(split ? 2 : 1) ?? (await numbers.take(split ? 2 : 1));\n const change = stage('addWidget', {\n type: 'forms.addWidget',\n field: field.ref,\n placement: {\n ...lookOf(last),\n ...placement,\n page,\n ...(placement.box ? {} : { rect }),\n ...(exportValue === undefined ? {} : { exportValue }),\n },\n objectNumber,\n ...(split ? { splitObjectNumber } : {}),\n });\n const item = await answer<'forms.addWidget'>(change, options);\n const widget =\n item.widgets.find(\n (row) => row.ref.kind === 'objectNumber' && row.ref.objectNumber === objectNumber,\n ) ?? item.widgets.at(-1)!;\n return { field: item.field, widget };\n };\n\n return {\n api: {\n create,\n addWidget,\n update: async (ref, patch, options) => {\n allow('form.update', writesScripts(patch.actions));\n const change = stage('update', { type: 'forms.update', field: ref, patch });\n return { field: (await answer<'forms.update'>(change, options)).field };\n },\n reorderCalculations: async (fields, position, options) => {\n allow('form.reorderCalculations');\n const change = stage('reorderCalculations', {\n type: 'forms.reorderCalculations',\n fields,\n position,\n });\n const item = await answer<'forms.reorderCalculations'>(change, options);\n return { calculationOrder: item.calculationOrder };\n },\n delete: async (ref, options) => {\n allow('form.delete');\n await answer(stage('delete', { type: 'forms.delete', field: ref }), options);\n },\n removeWidget: async (ref, widget, options) => {\n allow('form.removeWidget');\n const change = stage('removeWidget', { type: 'forms.removeWidget', field: ref, widget });\n return { field: (await answer<'forms.removeWidget'>(change, options)).field };\n },\n updateWidget: async (widget, patch, options) => {\n allow('form.updateWidget');\n const change = stage('updateWidget', { type: 'forms.updateWidget', widget, patch });\n return { widget: (await answer<'forms.updateWidget'>(change, options)).widget };\n },\n deleteWidget: async (widget, options) => {\n allow('form.deleteWidget');\n const change = stage('deleteWidget', { type: 'forms.deleteWidget', widget });\n return { field: (await answer<'forms.deleteWidget'>(change, options)).field };\n },\n // A repair reads the whole form and fixes it where it stands: not a change of ops.\n repair: async (options) => {\n allow('form.repair');\n const { signal, ...repair } = options ?? {};\n const run = () => (options ? ctx.doc.forms.repair(repair) : ctx.doc.forms.repair());\n return enqueue(() => ctx.cancellable(signal, run()), options);\n },\n } satisfies Partial<FormCapability>,\n };\n}\n","/**\n * Filling the form in. Every fill is one change, whatever started it: a value, a batch of\n * values, a reset, a widget's activation, a script's or an action's effects.\n *\n * 1. What the user did shows at once: the change is held with the user's own ops.\n * 2. When its turn comes, the form's scripts run against the view, in one realm transaction.\n * 3. Inside that transaction the change gets every op the scripts asked for, and is sent.\n *\n * Fills take turns up to their send, not their answer: the next fill's scripts read this one in\n * the view while the engine answers it. A validation refusal cancels the change. A change the\n * engine refuses leaves the view, and the calculations run again against what is left, outside\n * the history: the fills after it were calculated with its values.\n */\nimport {\n PluginError,\n toPluginError,\n type ChangeLabel,\n type HeldChange,\n type OperationOptions,\n type PendingChange,\n} from '@embedpdf/core';\nimport {\n fieldValueOf,\n formEffectOps,\n type ChangeOp,\n type FormFieldDTO,\n type FormFieldRef,\n type FormFieldValue,\n type PdfActionTree,\n} from '@embedpdf/engine-core/runtime';\nimport type { ActionOrigin } from '@embedpdf/plugin-actions/contract';\n\nimport type { FormCommitResult } from '../contract';\nimport { fieldByKey, fieldKeyOf, type FieldIndex } from '../model';\nimport type { FormScriptResult, FormScripts } from '../scripting/controller';\nimport { scriptError } from '../scripting/results';\nimport type { FormContext, FormServices } from '../services';\nimport { fieldsNamedBy, predictFormOp, undoLookOf, withFieldsFrom } from '../sync/predict';\n\n/** The scripts a fill runs before it is sent, when the document's scripts run. */\nexport type FillScripts =\n /** A field's new value through its own scripts, then the calculations: they make the change. */\n | { readonly kind: 'commit'; readonly field: FormFieldRef; readonly value: FormFieldValue }\n /** A widget's activation action: what it changes is the change. */\n | {\n readonly kind: 'activate';\n readonly field: FormFieldRef;\n readonly action: PdfActionTree<unknown>;\n }\n /** The calculations the user's ops cause: what they change follows the user's ops. */\n | { readonly kind: 'recalculate' };\n\nexport interface FillRequest {\n /** What the change is called; a fill of the fields its ops name when left out. */\n readonly label?: ChangeLabel;\n /** What the user did: shown at once. */\n readonly ops: readonly ChangeOp[];\n readonly scripts: FillScripts | null;\n /** Who started it, for the alerts its scripts raise. */\n readonly origin: ActionOrigin;\n}\n\n/** How a fill ended, once the engine answered. */\nexport interface FillOutcome {\n readonly result: FormCommitResult;\n /** The form before the fill, as the view showed it. */\n readonly before: FieldIndex;\n /** The form once the fill had all its ops, as the view showed it. */\n readonly after: FieldIndex;\n}\n\n/** A fill shown, waiting for its turn. */\ninterface Begun {\n readonly request: FillRequest;\n /** The form before the user's ops showed. */\n readonly before: FieldIndex;\n /** The form as the user's ops showed it. */\n readonly shown: FieldIndex;\n readonly hold: HeldChange | null;\n}\n\n/** A fill sent, waiting for the engine. */\ninterface Sent {\n readonly script: FormScriptResult | null;\n /** The changes it was sent as: one, or two when the hold went before the scripts finished. */\n readonly changes: readonly PendingChange[];\n readonly after: FieldIndex;\n}\n\n/** A refused value writes only what the document's open scripts did, outside the history. */\nconst SCRIPTS_LABEL: ChangeLabel = { key: 'form.scripts' };\n/** The calculations again, outside the history: after a refused fill, or a stale one. */\nconst RECALCULATE_LABEL: ChangeLabel = { key: 'form.recalculate' };\n/** The changes that, refused, leave calculations made with their values. */\nconst FILLS = new Set(['form.fill', 'form.reset']);\n\nconst sameOp = (left: ChangeOp, right: ChangeOp): boolean =>\n JSON.stringify(left) === JSON.stringify(right);\n\nconst sameValue = (left: FormFieldDTO | null, right: FormFieldDTO | null): boolean =>\n JSON.stringify(left?.valueEntry ?? null) === JSON.stringify(right?.valueEntry ?? null);\n\nexport function createFill(\n ctx: FormContext,\n { fields, scripting, enqueue }: Pick<FormServices, 'fields' | 'scripting' | 'enqueue'>,\n) {\n const labelOf = (request: FillRequest, index: FieldIndex, ops: readonly ChangeOp[]) =>\n request.label ?? { key: 'form.fill', count: fieldsNamedBy(index, ops).length };\n\n /** Step 1: what the user did shows at once. */\n const begin = (request: FillRequest): Begun => {\n const before = fields.view();\n const shown = request.ops.reduce(predictFormOp, before);\n if (request.ops.length === 0) return { request, before, shown, hold: null };\n const hold = ctx.changes.hold(labelOf(request, before, request.ops));\n hold.set(request.ops, undoLookOf(before, request.ops));\n return { request, before, shown, hold };\n };\n\n /**\n * The form the change is undone to: as it is now, with the user's own fields as they were\n * before the user's ops showed.\n */\n const baseOf = ({ request, before }: Begun): FieldIndex =>\n withFieldsFrom(fields.view(), before, fieldsNamedBy(before, request.ops));\n\n /** Whether the hold went with the user's ops before the scripts finished. */\n const sentEarly = ({ hold }: Begun): boolean => hold !== null && !hold.open && !!hold.change;\n\n /** Whether the form still shows the values the user's ops wrote: the scripts ran for those. */\n const stillShown = ({ request, shown }: Begun): boolean => {\n const now = fields.view();\n return fieldsNamedBy(shown, request.ops).every((field) =>\n sameValue(fieldByKey(now, fieldKeyOf(field)), field),\n );\n };\n\n /** Step 3: the change with all its ops, sent. */\n const send = (begun: Begun, ops: readonly ChangeOp[], script: FormScriptResult | null): Sent => {\n const { request, hold } = begun;\n if (ops.length === 0) {\n hold?.cancel();\n return { script, changes: [], after: fields.view() };\n }\n if (!hold) {\n const label = labelOf(request, fields.view(), ops);\n const change = ctx.changes.stage({ label, ops, undo: undoLookOf(baseOf(begun), ops) });\n return { script, changes: [change], after: fields.view() };\n }\n if (hold.open) {\n hold.set(ops, undoLookOf(baseOf(begun), ops));\n const change = hold.send();\n return { script, changes: change ? [change] : [], after: fields.view() };\n }\n // Something sent the hold with the user's ops while the scripts ran (another plugin's\n // change, a download): the rest is a change of its own.\n const sent = hold.change;\n const rest = ops.filter((op) => !sent?.shows.some((shown) => sameOp(shown as ChangeOp, op)));\n const changes = sent ? [sent] : [];\n if (rest.length > 0) {\n const label = labelOf(request, fields.view(), rest);\n changes.push(ctx.changes.stage({ label, ops: rest, undo: undoLookOf(fields.view(), rest) }));\n }\n return { script, changes, after: fields.view() };\n };\n\n /** The user's ops went on their own and the scripts refused them: their fields are written back. */\n const takeBack = ({ request, before }: Begun): void => {\n const ops = fieldsNamedBy(before, request.ops).flatMap((field): ChangeOp[] => {\n const value = fieldValueOf(field);\n return value ? [{ type: 'forms.setValue', field: field.ref, value }] : [];\n });\n if (ops.length === 0) return;\n ctx.changes.stage({ label: labelOf(request, before, ops), ops, history: false });\n };\n\n /** The calculations again, against what the form shows now: one change, outside the history. */\n const recalculateNow = async (scripts: FormScripts, origin: ActionOrigin): Promise<void> => {\n const shown = fields.view().snapshot;\n if (!shown) return;\n const script = await scripts.recalculate(shown);\n scripting.surface(script, origin);\n if (script.status !== 'accepted' || script.effects.length === 0) return;\n ctx.changes.stage({\n label: RECALCULATE_LABEL,\n ops: formEffectOps(script.effects),\n history: false,\n });\n };\n\n /** Step 2: the scripts, against the view. */\n const runScripts = (\n scripts: FormScripts,\n begun: Begun,\n plan: FillScripts,\n ): Promise<FormScriptResult> | null => {\n const shown = fields.view().snapshot;\n if (!shown) return null;\n switch (plan.kind) {\n case 'commit': {\n // The value's own scripts read the form without it.\n const form = baseOf(begun).snapshot ?? shown;\n return scripts.commit(form, plan.field, plan.value);\n }\n case 'activate':\n return scripts.activate(shown, plan.field, plan.action);\n case 'recalculate':\n return scripts.recalculate(shown);\n }\n };\n\n /** Steps 2 and 3, when the fill's turn comes. */\n const finish = async (begun: Begun): Promise<Sent> => {\n const { request, hold } = begun;\n const plan = request.scripts;\n // A widget's action runs its own script; a value's scripts are the form's fields'.\n const pipeline = !plan\n ? null\n : plan.kind === 'activate'\n ? scripting.controller()\n : scripting.scriptsFor(fields.view());\n if (!plan || !pipeline) return send(begun, request.ops, null);\n if (!fields.view().snapshot) await fields.settled();\n try {\n // The ops are set inside the realm transaction: the next one reads the form with them.\n return await pipeline.transaction(async (scripts) => {\n const running = runScripts(scripts, begun, plan);\n if (!running) return send(begun, request.ops, null);\n const script = await running;\n scripting.surface(script, request.origin);\n const early = sentEarly(begun);\n if (script.status !== 'accepted') {\n hold?.cancel();\n if (early) takeBack(begun);\n if (script.status === 'rejected' && script.bootEffects.length > 0) {\n ctx.changes.stage({\n label: SCRIPTS_LABEL,\n ops: formEffectOps(script.bootEffects),\n history: false,\n });\n }\n return { script, changes: [], after: fields.view() };\n }\n if (early && !stillShown(begun)) {\n // The form shows other values for the user's fields now (an undo, a later fill): what\n // the scripts made of the user's values is stale, and the calculations run again.\n await recalculateNow(scripts, request.origin);\n return { script, changes: [hold!.change!], after: fields.view() };\n }\n const effects = formEffectOps(script.effects);\n return send(\n begun,\n plan.kind === 'recalculate' ? [...request.ops, ...effects] : effects,\n script,\n );\n });\n } catch (error) {\n hold?.cancel();\n throw error;\n }\n };\n\n /** What a sent fill did, once the engine answered. */\n const answered = async (begun: Begun, sent: Sent): Promise<FillOutcome> => {\n const { script } = sent;\n const scripted = script !== null;\n const reported = {\n scripted,\n uiEffects: script?.uiEffects ?? [],\n diagnostics: script?.diagnostics ?? [],\n ...(script?.error ? { error: script.error } : {}),\n };\n const outcome = (status: FormCommitResult['status']): FillOutcome => ({\n result: { status, ...reported },\n before: begun.before,\n after: sent.after,\n });\n if (script?.status === 'failed') return outcome('failed');\n if (script?.status === 'rejected') return outcome('rejected');\n let undoable = false;\n for (const change of sent.changes) {\n try {\n undoable = (await change.result).meta.undoable || undoable;\n } catch (error) {\n throw toPluginError('form', error);\n }\n }\n return outcome(undoable ? 'applied' : 'unchanged');\n };\n\n /**\n * Fill the form in: shown at once, sent when its turn comes; resolves once the engine\n * answered. A change the engine refuses rejects.\n */\n const fill = async (request: FillRequest, options?: OperationOptions): Promise<FillOutcome> => {\n const begun = begin(request);\n let sent: Sent;\n try {\n sent = await enqueue(() => finish(begun), options);\n } catch (error) {\n begun.hold?.cancel();\n throw toPluginError('form', error);\n }\n return ctx.cancellable(options?.signal, answered(begun, sent));\n };\n\n /**\n * Fill the form in without waiting: what a script's effects need, written while its own\n * transaction still runs. A failure is reported as the scripts' error.\n */\n const fillSoon = (request: FillRequest): void => {\n const begun = begin(request);\n void enqueue(() => finish(begun)).catch((error: unknown) => {\n begun.hold?.cancel();\n const message = toPluginError('form', error).message;\n scripting.surface(\n { uiEffects: [], diagnostics: [], error: scriptError(message) },\n request.origin,\n );\n });\n };\n\n // A fill the engine refused leaves the view, and the fills after it were calculated with its\n // values: the calculations run again against what is left.\n let recalculating = false;\n const recalculate = (): Promise<void> =>\n enqueue(async () => {\n recalculating = false;\n const pipeline = scripting.controller();\n if (pipeline) await pipeline.transaction((scripts) => recalculateNow(scripts, 'user'));\n });\n ctx.changes.onSettled((settled) => {\n if (settled.status !== 'refused' || settled.change.undoOf !== null) return;\n if (!FILLS.has(settled.change.label.key) || recalculating) return;\n const order = fields.view().snapshot?.calculationOrder ?? [];\n if (!scripting.controller() || !order.some((ref) => ref !== null)) return;\n recalculating = true;\n void recalculate().catch(() => {\n /* the scripts' failure is surfaced; a refused recalculation is reported by the queue */\n });\n });\n\n // A download waits for the fills on their way, and for the engine's answers to them.\n ctx.onSettle(async () => {\n await enqueue.idle();\n await ctx.changes.whenSettled();\n });\n\n return { fill, fillSoon };\n}\n\nexport type Fills = ReturnType<typeof createFill>;\n\n/** A fill that failed in the form's own scripts, as the verbs report it. */\nexport function failedFill(result: FormCommitResult): PluginError {\n return new PluginError(\n 'operation-failed',\n 'form',\n result.error?.message ?? result.diagnostics[0]?.message ?? 'the write failed',\n );\n}\n","/**\n * Fields in and out as bundles: whole fields with their widgets, values and\n * scripts, taken out of one document and copied into another, or the same.\n */\nimport type { FormCapability } from '../contract';\nimport type { FormContext, FormServices } from '../services';\n\nexport function createInterchange(\n ctx: FormContext,\n services: Pick<FormServices, 'siblings' | 'enqueue'>,\n) {\n const { enqueue, siblings } = services;\n\n const exportBundle: FormCapability['export'] = async (selection = {}, options) => {\n ctx.assertAllowed('doc.forms.read', 'form.export');\n ctx.assertAllowed('doc.download', 'form.export');\n const pages = selection.pages?.map((page) => ctx.pageOf(page).ref);\n // What the user sees is what the bundle carries: pending writes land first.\n return enqueue(\n () =>\n ctx.cancellable(\n options?.signal,\n ctx.doc.forms.export({\n ...(selection.fields ? { fields: selection.fields } : {}),\n ...(pages ? { pages } : {}),\n }),\n ),\n options,\n );\n };\n\n const importBundle: FormCapability['import'] = async (bundle, options = {}) => {\n const { signal, ...importOptions } = options;\n ctx.assertAllowed('doc.forms.modify', 'form.import');\n if ((importOptions.attribution ?? 'restore') === 'restore') {\n ctx.assertAllowed('doc.forms.import', 'form.import');\n }\n return enqueue(async () => {\n const result = await ctx.cancellable(signal, ctx.doc.forms.import(bundle, importOptions));\n // Wait for the annotation plugin to read the new widgets, as `create()` does.\n const annotationHost = siblings.annotation();\n if (annotationHost) await annotationHost.whenSynced();\n return { fields: result.fields, refMap: result.refMap, dropped: result.dropped };\n }, options);\n };\n\n return {\n api: { export: exportBundle, import: importBundle } satisfies Partial<FormCapability>,\n };\n}\n","/**\n * Design mode: the form's widgets, lent to the annotation plugin\n * (`AnnotationLender`, its host contract). While the session may design and\n * the active tool doesn't fill, the annotation plugin shows the widgets among\n * its records and edits them with its tools: select, move, resize, restyle,\n * reorder, delete. Each edit comes back here as the form's ops, in the same\n * change as the rest of it. While the tool fills, nothing is lent, and the\n * form layer draws and fills every widget.\n */\nimport { memo } from '@embedpdf/core';\nimport { refOf, type Effect, type Model } from '@embedpdf/core-annotation';\nimport {\n type AnnotationRef,\n type ChangeOp,\n type FormFieldDTO,\n type PageRef,\n type WidgetAnnotation,\n type WidgetPatch,\n} from '@embedpdf/engine-core/runtime';\nimport type { AnnotationLender } from '@embedpdf/plugin-annotation/contract/host';\n\nimport { fieldForWidget, fieldKeyOf } from '../model';\nimport type { FormContext, FormServices } from '../services';\nimport { undoLookOf } from '../sync/predict';\n\nconst objectNumberOf = (ref: AnnotationRef): number =>\n ref.kind === 'objectNumber' ? ref.objectNumber : -1;\n\nexport function createWidgetLender(\n ctx: FormContext,\n {\n fields,\n design,\n pictures,\n looks,\n }: Pick<FormServices, 'fields' | 'design' | 'pictures' | 'looks'>,\n): AnnotationLender {\n const records = memo(\n () => [design.lending(), fields.get().snapshot, fields.view().snapshot] as const,\n (lending, confirmed, shown) =>\n lending && confirmed && shown ? { confirmed: confirmed.widgets, shown: shown.widgets } : null,\n );\n\n /**\n * Deleted widgets, as the form's ops: a widget leaves its field\n * (`deleteWidget`), and a field whose every widget goes is deleted whole\n * (a merged field and widget among them).\n */\n const deleteOps = (deleted: readonly WidgetAnnotation[]): ChangeOp[] => {\n const index = fields.view();\n const ops: ChangeOp[] = [];\n const byField = new Map<string, { field: FormFieldDTO; widgets: WidgetAnnotation[] }>();\n for (const row of deleted) {\n const field = fieldForWidget(index, objectNumberOf(row.ref));\n if (!field) {\n ops.push({ type: 'forms.deleteWidget', widget: row.ref });\n continue;\n }\n const entry = byField.get(fieldKeyOf(field)) ?? { field, widgets: [] };\n entry.widgets.push(row);\n byField.set(fieldKeyOf(field), entry);\n }\n for (const { field, widgets } of byField.values()) {\n const going = new Set(widgets.map((row) => objectNumberOf(row.ref)));\n if (field.widgets.every((widget) => going.has(widget.objectNumber))) {\n ops.push({ type: 'forms.delete', field: field.ref });\n } else {\n ops.push(\n ...widgets.map((row): ChangeOp => ({ type: 'forms.deleteWidget', widget: row.ref })),\n );\n }\n }\n return ops;\n };\n\n return {\n owner: 'form',\n records,\n opsOf(effects: readonly Effect[], model: Model, before: Model) {\n const ops: ChangeOp[] = [];\n const deleted: WidgetAnnotation[] = [];\n for (const effect of effects) {\n if (effect.type === 'patch') {\n const ref = refOf(model.byId[effect.id]);\n if (!ref) continue;\n const { subtype: _subtype, ...patch } = effect.patch as WidgetPatch & {\n subtype?: string;\n };\n ops.push({ type: 'forms.updateWidget', widget: ref, patch: patch as WidgetPatch });\n } else if (effect.type === 'delete') {\n const record = before.byId[effect.id];\n if (record) deleted.push(record.annotation as WidgetAnnotation);\n }\n }\n return [...ops, ...deleteOps(deleted)];\n },\n undoOf: (ops) => undoLookOf(fields.view(), ops),\n reorderOps: (page: PageRef, refs, position) => [\n { type: 'forms.reorderWidgets', page, widgets: [...refs], position },\n ],\n authority: () => {\n const may = ctx.allows('doc.forms.modify');\n return { update: may, delete: may };\n },\n // The pictures the form layer draws too, from one store: switching modes\n // fetches nothing, and a page's pictures change only with its widgets.\n pictureEpoch: pictures.epoch,\n pictureVersion: pictures.versionOf,\n renderAppearances: pictures.render,\n // A widget draws live, by the painter, while a gesture reshapes it, while its look isn't\n // confirmed (a restyle, a resize, a field just placed), and until its new picture is there.\n pending: looks.isPending,\n painter: (record) =>\n record.subtype === 'widget' ? looks.painterOf(record as WidgetAnnotation) : null,\n };\n}\n","import type {\n FormFieldDTO,\n FormFieldRef,\n FormSubmissionEntry,\n PdfActionTargetRef,\n} from '@embedpdf/engine-core/runtime';\nimport type { ActionDiagnostic, SubmitIntent } from '@embedpdf/plugin-actions/contract';\n\n/**\n * ISO field selection, written once for ResetForm (Tables 241/242) and\n * SubmitForm (Tables 239/240): a name target selects the field and its\n * descendants (FQN dot-prefix — `parent` selects `parent.c1`, the rule the\n * old exact-match resolution violated); an objectNumber target selects that\n * field dictionary. Include mode keeps the selection; exclude mode keeps\n * the complement (a name excludes its subtree the same way it includes\n * it). `targets === null` (the key absent) selects everything and the flag\n * is ignored; `[]` + include selects nothing while `[]` + exclude selects\n * everything — presence and emptiness are different states.\n *\n * `listed` reports whether a field was addressed by the target list\n * (directly or through its subtree) — the \"explicitly listed\" predicate the\n * submit honesty diagnostics key on.\n */\nexport const resolveFieldSelection = <F extends { name: string; ref: FormFieldRef }>(\n all: readonly F[],\n targets: PdfActionTargetRef[] | null,\n exclude: boolean,\n): { selected: F[]; listed: (field: F) => boolean } => {\n if (targets === null) return { selected: [...all], listed: () => false };\n const names = targets.filter((target) => target.kind === 'name').map((target) => target.name);\n const objectNumbers = new Set(\n targets.filter((target) => target.kind === 'objectNumber').map((target) => target.objectNumber),\n );\n const listed = (field: F): boolean =>\n (field.ref.kind === 'objectNumber' && objectNumbers.has(field.ref.objectNumber)) ||\n names.some((name) => field.name === name || field.name.startsWith(`${name}.`));\n const selected = exclude ? all.filter((field) => !listed(field)) : all.filter(listed);\n return { selected, listed };\n};\n\n/**\n * Build the resolved submission dataset from a live field list (Tables\n * 239/240 semantics; pure — the capability supplies a fresh engine read so\n * no model-lag class exists):\n *\n * - the unconditional **NoExport veto** — even an explicit include cannot\n * override it (diagnosed when explicitly listed, so the veto is\n * observable, silent when swept in implicitly);\n * - **push-buttons and signatures** never contribute entries in v1 —\n * ISO's explicit-pushbutton-`/AP`-in-FDF rule is unrepresentable in the\n * current DTO, so an explicitly listed one is diagnosed\n * (`submit-entry-unsupported`), never silently dropped;\n * - an **unsupported `/V` shape** is always diagnosed (silent omission\n * would be data loss);\n * - a valueless field becomes a name-only entry (`value: null`) only under\n * IncludeNoValueFields, else it is skipped (the ISO default);\n * - values are entry-faithful: scalar → string, array (multi-select list\n * box) → string[]; the submitted name is the fully qualified name.\n */\nexport const buildSubmitEntries = (\n fields: readonly FormFieldDTO[],\n intent: SubmitIntent,\n diagnose: (diagnostic: ActionDiagnostic) => void,\n): FormSubmissionEntry[] => {\n const { selected, listed } = resolveFieldSelection(fields, intent.fields, intent.exclude);\n const explicitInclude = intent.fields !== null && !intent.exclude;\n const entries: FormSubmissionEntry[] = [];\n for (const field of selected) {\n const explicit = explicitInclude && listed(field);\n if (field.family === 'pushbutton' || field.family === 'signature') {\n if (explicit) {\n diagnose({\n code: 'submit-entry-unsupported',\n message: `submit: '${field.name}' (${field.family}) has no representable submission value in v1 — skipped`,\n });\n }\n continue;\n }\n if (field.noExport) {\n if (explicit) {\n diagnose({\n code: 'submit-entry-unsupported',\n message: `submit: '${field.name}' carries the NoExport flag — the veto is unconditional (ISO 12.7.6.2), skipped`,\n });\n }\n continue;\n }\n const entry = field.valueEntry;\n if (entry.kind === 'scalar') {\n entries.push({ name: field.name, value: entry.value });\n } else if (entry.kind === 'array') {\n entries.push({ name: field.name, value: entry.values });\n } else if (entry.kind === 'none') {\n if (intent.includeNoValueFields) entries.push({ name: field.name, value: null });\n } else {\n diagnose({\n code: 'submit-entry-unsupported',\n message: `submit: '${field.name}' has an unsupported /V shape — skipped (would otherwise be silent data loss)`,\n });\n }\n }\n return entries;\n};\n","/**\n * Resets: one shared core (one fill: the reset, then the recalculation when the document's\n * scripts run) used by both the ResetForm action executor and the public `reset`, so the two\n * cannot diverge. A reset resets the fields it selects that the user may fill in: another\n * signer's fields stay as they are.\n */\nimport type { OperationOptions } from '@embedpdf/core';\nimport type { FormFieldDTO, FormFieldRef, PdfActionTargetRef } from '@embedpdf/engine-core/runtime';\nimport type { ActionOrigin } from '@embedpdf/plugin-actions/contract';\n\nimport type { FormCommitResult } from '../contract';\nimport { resolveFieldSelection } from '../field-selection';\nimport type { FormHostCapability } from '../host-contract';\nimport { fieldByRef, fieldsWithChangedValues } from '../model';\nimport type { FormContext, FormServices } from '../services';\nimport type { FillOutcome, Fills } from './fill';\n\n/** A reset of no fields: what the executor reports as inert. */\nconst NOTHING_RESET: FormCommitResult = {\n status: 'unchanged',\n scripted: false,\n uiEffects: [],\n diagnostics: [],\n};\n\n/** A field ref as an action's target: by object number, or by full name. */\nconst targetOf = (ref: FormFieldRef): PdfActionTargetRef =>\n ref.kind === 'objectNumber'\n ? { kind: 'objectNumber', objectNumber: ref.objectNumber }\n : { kind: 'name', name: ref.name };\n\nexport function createResetWrites(\n _ctx: FormContext,\n services: Pick<FormServices, 'fields' | 'rights'>,\n { fill }: Fills,\n) {\n const { fields, rights } = services;\n\n /**\n * Whether a reset puts this field back: the engine refuses push button and\n * signature refs, and another signer's fields are theirs.\n */\n const resettable = (field: FormFieldDTO): boolean =>\n field.family !== 'pushbutton' && field.family !== 'signature' && rights.mayFill(field);\n\n /**\n * Reset the selected fields, then recalculate, as one change. `origin` is carried through to\n * the surfaced recalculation results, so a ResetForm run by a page or hover trigger never\n * reports its alerts as a user action. `null` when it selects nothing; a refused reset throws:\n * none of it was written.\n */\n const resetSelection = async (\n targets: PdfActionTargetRef[] | null,\n exclude: boolean,\n origin: ActionOrigin,\n options?: OperationOptions,\n ): Promise<FillOutcome | null> => {\n if (!fields.view().snapshot) await fields.settled();\n // ISO 32000-2 Tables 241/242: a parent name resets its descendants too.\n const { selected } = resolveFieldSelection(\n fields.view().snapshot?.fields ?? [],\n targets,\n exclude,\n );\n // An exclude-mode complement always includes the form's buttons. Zero refs must not reach\n // the engine (it refuses an empty reset); an include list of `[]` resets nothing.\n const refs = selected.filter(resettable).map((field) => field.ref);\n if (refs.length === 0) return null;\n return fill(\n {\n label: { key: 'form.reset', count: refs.length },\n ops: [{ type: 'forms.reset', fields: refs }],\n scripts: { kind: 'recalculate' },\n origin,\n },\n options,\n );\n };\n\n const reset: FormHostCapability['reset'] = async (refs, options) => {\n // A field you name is one you mean: one you may not fill in refuses the reset.\n for (const ref of refs ?? []) {\n const field = fieldByRef(fields.view(), ref);\n if (field) rights.assertMayFill(field, 'form.reset');\n }\n if (refs && refs.length === 0) return { fields: [] };\n const outcome = await resetSelection(refs ? refs.map(targetOf) : null, false, 'user', options);\n // What changed is what holds another value after the reset and its recalculation.\n return { fields: outcome ? fieldsWithChangedValues(outcome.before, outcome.after) : [] };\n };\n\n return {\n api: {\n reset,\n resetFormAction: async (targets, exclude, origin = 'user') => {\n const outcome = await resetSelection(targets, exclude, origin);\n if (!outcome) return NOTHING_RESET;\n // The action ran, even on fields already at their defaults.\n const { result } = outcome;\n return result.status === 'unchanged' ? { ...result, status: 'applied' } : result;\n },\n } satisfies Partial<FormHostCapability>,\n };\n}\n","/**\n * The actions plugin's seams into the form plugin: the form-effects commit\n * sink (script `setValue`, `setDisplay` and reset effects are written through\n * the plugin that owns the fields, as one fill with the calculations they\n * cause) and the submit dataset resolver.\n */\nimport {\n formEffectOps,\n serializeError,\n type FormEffect,\n type FormFieldRef,\n} from '@embedpdf/engine-core/runtime';\nimport type {\n ActionContext,\n ActionDiagnostic,\n ActionSubmitRequest,\n SubmitIntent,\n} from '@embedpdf/plugin-actions/contract';\n\nimport { buildSubmitEntries } from '../field-selection';\nimport type { FormHostCapability } from '../host-contract';\nimport { fieldByRef } from '../model';\nimport type { FormContext, FormServices } from '../services';\nimport type { Fills } from './fill';\n\n/** The fields a script's effects write to. */\nconst refsOf = (effects: readonly FormEffect[]): FormFieldRef[] =>\n effects.flatMap((effect) => (effect.kind === 'reset' ? effect.refs : [effect.ref]));\n\nexport function createScriptEffects(\n ctx: FormContext,\n { fields, rights, enqueue }: Pick<FormServices, 'fields' | 'rights' | 'enqueue'>,\n { fillSoon }: Fills,\n) {\n /**\n * The submit dataset: the fields as the user sees them once every fill on its way is\n * answered, then the pure ISO builder. Selection, veto and value semantics live in\n * `field-selection.ts`; this only supplies the fields and assembles the request.\n */\n const resolveSubmitDataset = async (\n intent: SubmitIntent,\n actionContext: ActionContext,\n diagnose: (diagnostic: ActionDiagnostic) => void,\n ): Promise<ActionSubmitRequest> => {\n await enqueue.idle();\n await ctx.changes.whenSettled();\n if (!fields.view().snapshot) await fields.settled();\n return {\n url: intent.url,\n method: intent.method,\n format: intent.format,\n flagsRaw: intent.flagsRaw,\n ...(intent.charSet === undefined ? {} : { charSet: intent.charSet }),\n entries: buildSubmitEntries(fields.view().snapshot?.fields ?? [], intent, diagnose),\n origin: actionContext.origin,\n event: actionContext.event,\n };\n };\n\n return {\n api: {\n resolveSubmitDataset,\n commitScriptFormEffects: async (effects) => {\n try {\n // A field the session may not fill in is refused here, at once: the script learns\n // its write failed, as it would from the engine.\n for (const ref of refsOf(effects)) {\n const field = fieldByRef(fields.view(), ref);\n if (field) rights.assertMayFill(field, 'form.fill');\n }\n // The script's realm transaction is still running: the effects show at once, and\n // the calculations a value causes run once it ends, in the same change.\n const recalculates = effects.some(\n (effect) => effect.kind === 'setValue' || effect.kind === 'reset',\n );\n fillSoon({\n ops: formEffectOps(effects),\n scripts: recalculates ? { kind: 'recalculate' } : null,\n origin: 'user',\n });\n return { status: 'applied' };\n } catch (error) {\n // The sink never throws: a change it can't stage reports why.\n return { status: 'failed', error: serializeError(error).message };\n }\n },\n } satisfies Partial<FormHostCapability>,\n };\n}\n","/**\n * The text someone is typing in a field, before it's written. A text field commits on blur or\n * Enter, when its scripts run (as in Acrobat), so what is typed waits here, one draft per field.\n * A download writes the drafts first (`ctx.onSettle`), the way Acrobat commits the field being\n * edited before it saves.\n */\nimport type { FormFieldRef } from '@embedpdf/engine-core/runtime';\n\nimport type { FormSetValueResult } from '../contract';\nimport type { FormContext, FormServices } from '../services';\n\nexport function createTyping(\n ctx: Pick<FormContext, 'onSettle'>,\n { keyOf }: Pick<FormServices, 'keyOf'>,\n setText: (field: FormFieldRef, text: string) => Promise<FormSetValueResult>,\n) {\n /** The text typed in each field and not written yet, by field key. */\n const drafts = new Map<string, { readonly field: FormFieldRef; readonly text: string }>();\n\n /** Write the field's draft, if it has one; `null` when there is nothing to write. */\n const commitDraftText = async (field: FormFieldRef): Promise<FormSetValueResult | null> => {\n const key = keyOf(field);\n const draft = drafts.get(key);\n if (!draft) return null;\n drafts.delete(key);\n return setText(draft.field, draft.text);\n };\n\n ctx.onSettle(async () => {\n await Promise.all([...drafts.values()].map((draft) => commitDraftText(draft.field)));\n });\n\n return {\n api: {\n draftText: (field: FormFieldRef, text: string): void => {\n drafts.set(keyOf(field), { field, text });\n },\n commitDraftText,\n discardDraftText: (field: FormFieldRef): void => {\n drafts.delete(keyOf(field));\n },\n },\n };\n}\n","/**\n * Value writes, each one fill (write/fill.ts): one field through the form's scripts (when the\n * `validation` setting runs them), and the batch verbs, whose plain values go as one change\n * with one recalculation, as a script's `field.value` assignments do in Acrobat.\n */\nimport {\n PluginError,\n toPluginError,\n toPluginErrorInfo,\n type BatchResult,\n type OperationOptions,\n type PluginErrorInfo,\n} from '@embedpdf/core';\nimport {\n fieldValueWriteOf,\n type ChangeOp,\n type FormFieldRef,\n type FormFieldValue,\n} from '@embedpdf/engine-core/runtime';\n\nimport type { FormCapability, FormSetValueResult } from '../contract';\nimport { fieldByRef } from '../model';\nimport { writeOfPlainValue } from '../read/fields';\nimport type { FormContext, FormServices } from '../services';\nimport { failedFill, type Fills } from './fill';\n\n/** A batch that stops when its caller cancels it. */\nfunction throwIfCancelled(options?: OperationOptions): void {\n if (options?.signal?.aborted) {\n throw new PluginError('operation-cancelled', 'form', 'operation cancelled', {\n cause: options.signal.reason,\n });\n }\n}\n\nconst setValueOp = (field: FormFieldRef, value: FormFieldValue): ChangeOp => ({\n type: 'forms.setValue',\n field,\n value,\n});\n\nexport function createValueWrites(\n _ctx: FormContext,\n services: Pick<FormServices, 'events' | 'fields' | 'rights'>,\n { fill }: Fills,\n) {\n const { validationRejected } = services.events;\n const { fields, rights } = services;\n\n /** One field's value through its scripts: shown at once, written as one change. */\n const commit = async (\n ref: FormFieldRef,\n value: FormFieldValue,\n operation: string,\n options?: OperationOptions,\n ): Promise<FormSetValueResult> => {\n const known = fieldByRef(fields.view(), ref);\n // A field the form doesn't show yet is the engine's to answer (`not-found`).\n if (known) rights.assertMayFill(known, operation);\n const { result } = await fill(\n {\n ops: [setValueOp(ref, value)],\n scripts: { kind: 'commit', field: ref, value },\n origin: 'user',\n },\n options,\n );\n if (result.status === 'failed') throw failedFill(result);\n const field = fieldByRef(fields.get(), ref);\n if (!field) throw new PluginError('not-found', 'form', 'no form field has this ref');\n if (result.status === 'rejected') {\n validationRejected.emit({ field, issues: result.diagnostics });\n return { field, status: 'rejected' };\n }\n return { field, status: result.status };\n };\n\n /**\n * Plain values for several fields, as one change with one recalculation. A value its field\n * can't take, or a field the session may not fill in, fails on its own; the rest go together,\n * and fail together when the engine refuses them.\n */\n const fillPlain = async (\n entries: readonly { readonly ref: FormFieldRef; readonly value: FormFieldValue }[],\n options?: OperationOptions,\n ): Promise<{\n applied: FormFieldRef[];\n failed: { ref: FormFieldRef; error: PluginErrorInfo }[];\n }> => {\n if (!fields.view().snapshot) await fields.settled();\n const index = fields.view();\n const accepted: { ref: FormFieldRef; value: FormFieldValue }[] = [];\n const failed: { ref: FormFieldRef; error: PluginErrorInfo }[] = [];\n for (const entry of entries) {\n try {\n const field = fieldByRef(index, entry.ref);\n if (!field) throw new PluginError('not-found', 'form', 'no form field has this ref');\n rights.assertMayFill(field, 'form.setValues');\n fieldValueWriteOf(field, entry.value);\n accepted.push({ ref: field.ref, value: entry.value });\n } catch (error) {\n failed.push({ ref: entry.ref, error: toPluginErrorInfo(toPluginError('form', error)) });\n }\n }\n if (accepted.length === 0) return { applied: [], failed };\n throwIfCancelled(options);\n try {\n const { result } = await fill(\n {\n ops: accepted.map((entry) => setValueOp(entry.ref, entry.value)),\n scripts: { kind: 'recalculate' },\n origin: 'user',\n },\n options,\n );\n if (result.status === 'failed') throw failedFill(result);\n return { applied: accepted.map((entry) => entry.ref), failed };\n } catch (error) {\n const info = toPluginErrorInfo(toPluginError('form', error));\n return {\n applied: [],\n failed: [...failed, ...accepted.map(({ ref }) => ({ ref, error: info }))],\n };\n }\n };\n\n const setValues: FormCapability['setValues'] = async (entries, options) => {\n throwIfCancelled(options);\n const { applied, failed } = await fillPlain(entries, options);\n return { applied, skipped: [], failed };\n };\n\n const importValues: FormCapability['importValues'] = async (values, options) => {\n throwIfCancelled(options);\n if (!fields.view().snapshot) await fields.settled();\n const index = fields.view();\n const skipped: { ref: string; reason: string }[] = [];\n const entries: { ref: FormFieldRef; value: FormFieldValue }[] = [];\n const names = new Map<string, string>();\n for (const [name, plain] of Object.entries(values)) {\n const field = fieldByRef(index, { kind: 'fqn', name });\n if (!field) {\n skipped.push({ ref: name, reason: 'the form has no field with this name' });\n continue;\n }\n if (!rights.mayFill(field)) {\n skipped.push({ ref: name, reason: 'you may not fill in this field' });\n continue;\n }\n const value = writeOfPlainValue(field, plain);\n if (!value) {\n skipped.push({ ref: name, reason: `a ${field.family} field can't take this value` });\n continue;\n }\n entries.push({ ref: field.ref, value });\n names.set(JSON.stringify(field.ref), name);\n }\n const { applied, failed } = await fillPlain(entries, options);\n return {\n applied,\n skipped,\n failed: failed.map(({ ref, error }) => ({\n ref: names.get(JSON.stringify(ref)) ?? '',\n error,\n })),\n } satisfies BatchResult<FormFieldRef, string>;\n };\n\n return {\n /** A text field's write, for the text being typed (write/typing.ts). */\n setText: (ref: FormFieldRef, text: string): Promise<FormSetValueResult> =>\n commit(ref, { value: text }, 'form.setValue'),\n api: {\n setValue: (ref, value, options) => commit(ref, value, 'form.setValue', options),\n setValues,\n importValues,\n } satisfies Partial<FormCapability>,\n };\n}\n","/**\n * The form controller: the composition root. It builds the plugin's services\n * once, wires each area with the services it declares, and assembles the\n * host capability from the areas' API slices. No behavior lives here: every\n * verb and read has a home in `read/`, `write/` or `sync/`.\n */\nimport { composeApi } from '@embedpdf/core';\nimport type { FormFieldRef } from '@embedpdf/engine-core/runtime';\n\nimport { connectForm } from './connect';\nimport type { FormHostCapability } from './host-contract';\nimport { fieldByRef } from './model';\nimport { createFieldReads } from './read/fields';\nimport { createFieldSettings } from './read/settings';\nimport { createWidgetReads } from './read/widgets';\nimport { createServices, type FormContext } from './services';\nimport { createActivation } from './write/activation';\nimport { createFieldWrites } from './write/fields';\nimport { createFill } from './write/fill';\nimport { createInterchange } from './write/interchange';\nimport { createWidgetLender } from './write/lending';\nimport { createResetWrites } from './write/reset';\nimport { createScriptEffects } from './write/script-effects';\nimport { createTyping } from './write/typing';\nimport { createValueWrites } from './write/values';\n\nexport function createFormController(ctx: FormContext) {\n const services = createServices(ctx);\n const { events, rights } = services;\n const settings = ctx.settings();\n\n const fields = createFieldReads(ctx, services);\n const widgets = createWidgetReads(ctx, services);\n const settingsReads = createFieldSettings(services);\n\n const fills = createFill(ctx, services);\n const values = createValueWrites(ctx, services, fills);\n const typing = createTyping(ctx, services, values.setText);\n const resets = createResetWrites(ctx, services, fills);\n const design = createFieldWrites(ctx, services);\n const interchange = createInterchange(ctx, services);\n const activation = createActivation(ctx, services, fills);\n const scripts = createScriptEffects(ctx, services, fills);\n\n const api: FormHostCapability = composeApi('form', [\n settings.api,\n fields.api,\n widgets.api,\n settingsReads.api,\n values.api,\n typing.api,\n resets.api,\n design.api,\n interchange.api,\n activation.api,\n scripts.api,\n {\n canRead: () => ctx.allows('doc.forms.read'),\n canFill: (ref: FormFieldRef) => {\n const field = fieldByRef(services.fields.view(), ref);\n return field !== null && rights.mayFill(field);\n },\n canDesign: () => ctx.allows('doc.forms.modify'),\n canRestoreAttribution: () => ctx.allows('doc.forms.import'),\n canWriteScripts: () => ctx.allows('doc.forms.script'),\n onValueChanged: events.valueChanged.on,\n onFieldCreated: events.fieldCreated.on,\n onFieldUpdated: events.fieldUpdated.on,\n onFieldDeleted: events.fieldDeleted.on,\n onValidationRejected: events.validationRejected.on,\n onResynced: events.resynced.on,\n },\n ]);\n\n return {\n api,\n connect: () => connectForm(ctx, api, createWidgetLender(ctx, services)),\n };\n}\n","import { definePlugin } from '@embedpdf/core';\nimport { ActionsToken } from '@embedpdf/plugin-actions/contract';\nimport { AnnotationToken } from '@embedpdf/plugin-annotation/contract';\nimport { InteractionToken } from '@embedpdf/plugin-interaction/contract/host';\nimport { RenderToken } from '@embedpdf/plugin-render/contract';\n\nimport { FORM_DEFAULTS, type FormConfig } from './contract';\nimport { createFormController } from './controller';\nimport { FormToken } from './host-contract';\nimport { initialFormState } from './model';\n\n/**\n * The form plugin: the field plane. Document-scoped; requires the\n * interaction hub. Filling works without the annotation plugin, because\n * widget geometry is read from the engine's widget records. The active tool\n * is the mode switch: while it carries 'form-fill' (the built-in pointer and\n * pan tools do, so filling is the resting state), the form layer draws and\n * fills every widget. Design mode is the 'form-edit' and palette tools: with\n * the annotation plugin present, the form lends it the widgets, which its\n * tools then select, move, restyle and delete. The render plugin draws the\n * widgets' pictures in both modes. `config` is the settings the app\n * registers, over {@link FORM_DEFAULTS}.\n */\nexport const formPlugin = (config?: FormConfig) =>\n definePlugin({\n id: 'form',\n token: FormToken,\n scope: 'document',\n requires: [InteractionToken],\n optional: [AnnotationToken, ActionsToken, RenderToken],\n state: initialFormState,\n settings: { defaults: FORM_DEFAULTS, registered: config },\n create: createFormController,\n });\n","/**\n * The form page's State table as code: what `useFormState()` returns, and the\n * same fields in every other framework. One field's value has its own hook\n * (`useFormValue(ref)`), so a total in your own UI re-renders only when that\n * field changes.\n */\nimport { defineState } from '@embedpdf/core';\nimport type { FormFieldDTO } from '@embedpdf/engine-core/runtime';\n\nimport { FormToken } from './contract';\n\nconst NO_FIELDS: readonly FormFieldDTO[] = Object.freeze([]);\n\nexport const formState = defineState(FormToken, {\n read: (form) => ({\n fields: form.list(),\n status: form.getStatus(),\n formKind: form.getFormKind(),\n selectedField: form.getSelectedField(),\n }),\n empty: {\n fields: NO_FIELDS,\n status: 'idle',\n formKind: 'none',\n selectedField: null,\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;AA4CA,MAAa,aAAa,CAAC,cAAc,iBAAiB;AAE1D,MAAM,eAAiC;CACrC,eAAe;CACf,OAAO;CACP,aAAa;AACf;AAEA,MAAa,aAAqC;CAChD;EACE,IAAI;EACJ,QAAQ;EACR,YAAY;EACZ,aAAa;GAAE,OAAO;GAAK,QAAQ;EAAG;EACtC,UAAU;GAAE,GAAG;GAAc,UAAU;EAAG;EAC1C,QAAQ;CACV;CACA;EACE,IAAI;EACJ,QAAQ;EACR,YAAY;EACZ,aAAa;GAAE,OAAO;GAAI,QAAQ;EAAG;EACrC,UAAU;EACV,QAAQ;CACV;CACA;EACE,IAAI;EACJ,QAAQ;EAER,YAAY;EACZ,aAAa;GAAE,OAAO;GAAI,QAAQ;EAAG;EACrC,UAAU;EACV,QAAQ;CACV;CACA;EACE,IAAI;EACJ,QAAQ;EACR,YAAY;EACZ,aAAa;GAAE,OAAO;GAAK,QAAQ;EAAG;EACtC,UAAU;GAAE,GAAG;GAAc,UAAU;EAAG;EAC1C,QAAQ;CACV;CACA;EACE,IAAI;EACJ,QAAQ;EACR,YAAY;EACZ,aAAa;GAA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