@embedpdf/plugin-form 3.0.0-next.2 → 3.0.0-next.20

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.js CHANGED
@@ -1,128 +1,950 @@
1
- import { createCapabilityToken, definePlugin } from "@embedpdf/core";
2
- import { AnnotationToken, MIN_DRAG, resolveClickPlacement, widgetAppearanceFromProps } from "@embedpdf/plugin-annotation";
3
- import { AnnotationToken as AnnotationToken$1 } from "@embedpdf/plugin-annotation/internal";
4
- import { InteractionToken, samplePointOn } from "@embedpdf/plugin-interaction";
5
- import { DEFAULT_SCRIPT_BUDGET, javaScriptProgramFromActionTree, scriptFieldsFromSnapshot } from "@embedpdf/core-acrojs";
6
- //#region src/core/model.ts
7
- const fieldKeyOf = (field) => field.fieldObjectNumber > 0 ? `obj:${field.fieldObjectNumber}` : `fqn:${field.name}`;
8
- const initialModel = () => ({
1
+ import { i as FormToken, n as FormTransfer, r as toFieldRef, t as FORM_DEFAULTS } from "./contract-BdEaLXUK.js";
2
+ import { n as createFormScriptingController, r as scriptError, t as FormScriptingController } from "./controller-Sr5M_8G8.js";
3
+ import { FormToken as FormToken$1 } from "./contract/host.js";
4
+ import { PluginError, composeApi, definePlugin, defineState, memo, memoByKey, reload, toPluginError, toPluginErrorInfo } from "@embedpdf/core";
5
+ import { ActionsToken, createHoverPump } from "@embedpdf/plugin-actions/contract";
6
+ import { AnnotationToken } from "@embedpdf/plugin-annotation/contract";
7
+ import { FontsToken } from "@embedpdf/plugin-fonts/contract";
8
+ import { InteractionToken, samplePointOn } from "@embedpdf/plugin-interaction/contract/host";
9
+ import { RenderToken } from "@embedpdf/plugin-render/contract";
10
+ import { annotationKey, draftWritesScripts, fieldAfterReset, fieldAfterValue, fieldValueOf, fieldValueWriteOf, formEffectOps, formFieldAfter, formFieldOfDraft, isStandardFontName, pageRefsEqual, reorderPart, reorderedList, serializeError, tabOrderOf, toFieldRef as toFieldRef$1, widgetAfterPatch, widgetsAfterDisplay, writesScripts } from "@embedpdf/engine-core/runtime";
11
+ import { ActionsToken as ActionsToken$1 } from "@embedpdf/plugin-actions/contract/host";
12
+ import { AnnotationToken as AnnotationToken$1 } from "@embedpdf/plugin-annotation/contract/host";
13
+ import { gesturePlacement, refOf, widgetAppearanceOf } from "@embedpdf/core-annotation";
14
+ import { StageToken } from "@embedpdf/plugin-stage/contract";
15
+ import { paints, textEditorLayout, widgetDrawing, widgetScene, widgetText } from "@embedpdf/core-form";
16
+ import { standardFontCss, standardFontOf } from "@embedpdf/core-fonts";
17
+ import { RenderToken as RenderToken$1 } from "@embedpdf/plugin-render/contract/host";
18
+ //#region src/tools/definitions.ts
19
+ /** Palette tools keep widgets editable right after placement. */
20
+ const PLACE_TAGS = ["form-place", "annotation-edit"];
21
+ const FIELD_CHROME = {
22
+ interiorColor: "#ffffff",
23
+ color: "#6b7280",
24
+ strokeWidth: 1
25
+ };
26
+ const FORM_TOOLS = [
27
+ {
28
+ id: "form-text",
29
+ family: "text",
30
+ visualKind: "widget-text",
31
+ clickCreate: {
32
+ width: 160,
33
+ height: 24
34
+ },
35
+ defaults: {
36
+ ...FIELD_CHROME,
37
+ fontSize: 12
38
+ },
39
+ cursor: "crosshair"
40
+ },
41
+ {
42
+ id: "form-checkbox",
43
+ family: "checkbox",
44
+ visualKind: "widget-toggle",
45
+ clickCreate: {
46
+ width: 18,
47
+ height: 18
48
+ },
49
+ defaults: FIELD_CHROME,
50
+ cursor: "crosshair"
51
+ },
52
+ {
53
+ id: "form-radio",
54
+ family: "radio",
55
+ visualKind: "widget-radio",
56
+ clickCreate: {
57
+ width: 18,
58
+ height: 18
59
+ },
60
+ defaults: FIELD_CHROME,
61
+ cursor: "crosshair"
62
+ },
63
+ {
64
+ id: "form-combobox",
65
+ family: "combobox",
66
+ visualKind: "widget-choice",
67
+ clickCreate: {
68
+ width: 140,
69
+ height: 24
70
+ },
71
+ defaults: {
72
+ ...FIELD_CHROME,
73
+ fontSize: 12
74
+ },
75
+ cursor: "crosshair"
76
+ },
77
+ {
78
+ id: "form-listbox",
79
+ family: "listbox",
80
+ visualKind: "widget-choice",
81
+ clickCreate: {
82
+ width: 140,
83
+ height: 72
84
+ },
85
+ defaults: {
86
+ ...FIELD_CHROME,
87
+ fontSize: 12
88
+ },
89
+ cursor: "crosshair"
90
+ },
91
+ {
92
+ id: "form-button",
93
+ family: "pushbutton",
94
+ visualKind: "widget-button",
95
+ clickCreate: {
96
+ width: 100,
97
+ height: 28
98
+ },
99
+ defaults: {
100
+ ...FIELD_CHROME,
101
+ interiorColor: "#e5e7eb",
102
+ fontSize: 12
103
+ },
104
+ cursor: "crosshair"
105
+ },
106
+ {
107
+ id: "form-signature",
108
+ family: "signature",
109
+ visualKind: "widget-box",
110
+ clickCreate: {
111
+ width: 160,
112
+ height: 48
113
+ },
114
+ defaults: FIELD_CHROME,
115
+ cursor: "crosshair"
116
+ }
117
+ ];
118
+ const FORM_TOOL_BY_ID = new Map(FORM_TOOLS.map((tool) => [tool.id, tool]));
119
+ //#endregion
120
+ //#region src/tools/handlers.ts
121
+ /** A name for a field placed with a tool: `text_1`, `text_2`, …, the first one the form doesn't have. */
122
+ function nextFieldName(family, taken) {
123
+ let count = 1;
124
+ while (taken.has(`${family}_${count}`)) count++;
125
+ return `${family}_${count}`;
126
+ }
127
+ /** The part of a box on the page; `null` when too little of it is. */
128
+ function clampToPage(box, page) {
129
+ const x = Math.max(page.x, Math.min(box.x, page.width));
130
+ const y = Math.max(page.y, Math.min(box.y, page.height));
131
+ const clamped = {
132
+ x,
133
+ y,
134
+ width: Math.max(0, Math.min(box.x + box.width, page.width) - x),
135
+ height: Math.max(0, Math.min(box.y + box.height, page.height) - y)
136
+ };
137
+ return clamped.width < 1 || clamped.height < 1 ? null : clamped;
138
+ }
139
+ /**
140
+ * The field a palette tool places: one widget at `widget`, named like
141
+ * `text_1`. A radio button stands for `'Choice1'` and a dropdown or a list
142
+ * starts with two options, as in Acrobat; rename and change them in a
143
+ * settings panel.
144
+ */
145
+ function toolDraft(tool, name, widget) {
146
+ switch (tool.family) {
147
+ case "radio": return {
148
+ family: "radio",
149
+ name,
150
+ widgets: [{
151
+ ...widget,
152
+ exportValue: "Choice1"
153
+ }]
154
+ };
155
+ case "combobox":
156
+ case "listbox": return {
157
+ family: tool.family,
158
+ name,
159
+ widgets: [widget],
160
+ options: [{
161
+ label: "Option 1",
162
+ value: "Option 1"
163
+ }, {
164
+ label: "Option 2",
165
+ value: "Option 2"
166
+ }]
167
+ };
168
+ case "pushbutton": return {
169
+ family: "pushbutton",
170
+ name,
171
+ widgets: [{
172
+ ...widget,
173
+ caption: "Button"
174
+ }]
175
+ };
176
+ default: return {
177
+ family: tool.family,
178
+ name,
179
+ widgets: [widget]
180
+ };
181
+ }
182
+ }
183
+ /**
184
+ * Draw-to-place: drag a box or just click. The commit creates the field and
185
+ * its widget through `form.create()`, styled from the tool's live defaults.
186
+ * Where the field goes is `gesturePlacement`, the call the annotation core
187
+ * makes for its own drawings: the dragged box once the gesture is a drag
188
+ * (the shared click ↔ drag threshold), else the tool's `clickCreate` box.
189
+ * What follows is the annotation plugin's `afterCreate` setting, as for
190
+ * every tool: select the new widget, and keep the tool or go back to the
191
+ * default one.
192
+ *
193
+ * With the annotation plugin, the tool's ghost shows the field a click
194
+ * places: this handler's hover puts it where the click would reach it (no
195
+ * widget or annotation under the pointer claims it) and the user may design
196
+ * forms. The gesture reports itself (`previewPlacement`), so once it drags
197
+ * the page paints the field the release places, a radio button round.
198
+ *
199
+ * Gesture rules match the annotation handlers: page-anchored via the sample
200
+ * projection (the box keeps sizing along the edge when the cursor overshoots
201
+ * or crosses a gap), and the up sample is the final point.
202
+ */
203
+ function createPlaceHandler(form, interaction, annotation) {
204
+ let origin = null;
205
+ /** Drop the gesture and what it painted: its placement and the tool's ghost. */
206
+ const endGesture = () => {
207
+ origin = null;
208
+ annotation?.clearPlacementPreview();
209
+ annotation?.clearGhost();
210
+ };
211
+ const place = async (tool, page, box) => {
212
+ const pageBox = form.getPageBox(page);
213
+ const rect = pageBox ? clampToPage(box, pageBox) : null;
214
+ if (!rect) return;
215
+ const look = widgetAppearanceOf(annotation ? annotation.tools.getDefaults(tool.id) : tool.defaults);
216
+ const name = nextFieldName(tool.family, new Set(form.list().map((field) => field.name)));
217
+ const created = form.create(toolDraft(tool, name, {
218
+ page,
219
+ rect,
220
+ ...look
221
+ }));
222
+ const field = form.get({
223
+ kind: "fqn",
224
+ name
225
+ }) ?? (await created).field;
226
+ if (!annotation || interaction.getActiveToolId() !== tool.id) return;
227
+ const policy = annotation.getSettings().afterCreate;
228
+ const widget = field.widgets.find((candidate) => candidate.page?.objectNumber === page.objectNumber);
229
+ if (policy.select && widget?.ref) annotation.selection.set([widget.ref]);
230
+ if (policy.tool === "default") interaction.activateTool("form-edit");
231
+ await created;
232
+ };
233
+ return {
234
+ id: "form-place",
235
+ priority: 95,
236
+ enabledFor: (tool) => tool.enables.has("form-place"),
237
+ onHover: (sample) => {
238
+ if (!annotation) return;
239
+ const toolId = interaction.getActiveToolId();
240
+ if (sample.page && FORM_TOOL_BY_ID.has(toolId) && form.canDesign() && !interaction.hasCursorClaim()) annotation.hoverGhostAt(toolId, sample.page.ref, sample.page.point, sample.page.rotation, sample.page.zoom);
241
+ else annotation.clearGhost();
242
+ },
243
+ onDown: (sample) => {
244
+ if (!sample.page || !FORM_TOOL_BY_ID.has(interaction.getActiveToolId())) return false;
245
+ if (!form.canDesign()) return false;
246
+ origin = {
247
+ page: sample.page.ref,
248
+ start: sample.page.point,
249
+ last: sample.page.point
250
+ };
251
+ return true;
252
+ },
253
+ onMove: (sample) => {
254
+ if (!origin) return;
255
+ const point = samplePointOn(sample, origin.page);
256
+ if (!point) return;
257
+ origin.last = point;
258
+ annotation?.previewPlacement(interaction.getActiveToolId(), origin.page, origin.start, point);
259
+ },
260
+ onUp: (sample) => {
261
+ if (!origin) return;
262
+ const gesture = origin;
263
+ endGesture();
264
+ const tool = FORM_TOOL_BY_ID.get(interaction.getActiveToolId());
265
+ if (!tool) return;
266
+ const end = samplePointOn(sample, gesture.page) ?? gesture.last;
267
+ const placement = gesturePlacement("box", gesture.start, end, tool.clickCreate, { pageBox: form.getPageBox(gesture.page) ?? void 0 });
268
+ if (placement?.kind !== "box") return;
269
+ place(tool, gesture.page, placement.rect).catch((error) => {
270
+ globalThis.console?.error("[form] placing the field failed:", error);
271
+ });
272
+ },
273
+ onCancel: endGesture
274
+ };
275
+ }
276
+ //#endregion
277
+ //#region src/connect.ts
278
+ /**
279
+ * The form plugin's wiring to its siblings, run once every capability exists:
280
+ * its tools and place handler on the interaction hub, its widgets lent to the
281
+ * annotation plugin for design, and the reset executor, commit sink, form
282
+ * reader and submit resolver on the actions plugin. Every registration is released with
283
+ * the document.
284
+ */
285
+ function connectForm(ctx, form, lender) {
286
+ const interaction = ctx.get(InteractionToken);
287
+ const annotation = ctx.tryGet(AnnotationToken$1);
288
+ ctx.cleanup(interaction.registerTool({
289
+ id: "form-fill",
290
+ cursor: "default",
291
+ enables: /* @__PURE__ */ new Set(["form-fill", "link-nav"])
292
+ }));
293
+ ctx.cleanup(interaction.registerTool({
294
+ id: "form-edit",
295
+ cursor: "default",
296
+ enables: /* @__PURE__ */ new Set(["annotation-edit", "annotation-marquee"])
297
+ }));
298
+ for (const tool of FORM_TOOLS) ctx.cleanup(annotation ? annotation.tools.register({
299
+ id: tool.id,
300
+ subtype: tool.visualKind,
301
+ cursor: tool.cursor,
302
+ enables: [...PLACE_TAGS],
303
+ clickCreate: tool.clickCreate,
304
+ defaults: tool.defaults,
305
+ ghost: true
306
+ }) : interaction.registerTool({
307
+ id: tool.id,
308
+ cursor: tool.cursor,
309
+ enables: new Set(PLACE_TAGS)
310
+ }));
311
+ ctx.cleanup(interaction.registerHandler(createPlaceHandler(form, interaction, annotation)));
312
+ if (annotation && ctx.allows("doc.forms.modify")) ctx.cleanup(annotation.lend(lender));
313
+ const actions = ctx.tryGet(ActionsToken$1);
314
+ if (!actions) return;
315
+ ctx.cleanup(actions.registerFormCommitSink((effects) => form.commitScriptFormEffects(effects)));
316
+ ctx.cleanup(actions.registerFormReader(() => form.getSnapshot()));
317
+ ctx.cleanup(actions.registerFormFocus((name) => form.focus(toFieldRef$1(name))));
318
+ ctx.cleanup(actions.registerSubmitResolver((intent, actionContext, diagnose) => form.resolveSubmitDataset(intent, actionContext, diagnose)));
319
+ ctx.cleanup(actions.registerExecutor("reset-form", async (node, actionContext) => {
320
+ if (node.type !== "reset-form") return {
321
+ status: "inert",
322
+ reason: "not a reset-form node"
323
+ };
324
+ const result = await form.resetFormAction(node.fields, node.exclude, actionContext.origin);
325
+ if (result.status === "failed") return {
326
+ status: "failed",
327
+ error: result.error?.message ?? "reset failed"
328
+ };
329
+ if (result.status === "unchanged") return {
330
+ status: "inert",
331
+ reason: result.diagnostics[0]?.message ?? "reset-form resolved no fields"
332
+ };
333
+ return { status: "executed" };
334
+ }));
335
+ }
336
+ //#endregion
337
+ //#region src/model.ts
338
+ /**
339
+ * The form plugin's data, all pure:
340
+ *
341
+ * - `FieldIndex` is the form as the engine confirmed it: the field tree and
342
+ * every widget row, indexed by field key and by widget. It is the value of
343
+ * the plugin's `fields` mirror and changes only through `foldFormEvent` and
344
+ * loads; `predictFormOp` (sync/predict.ts) shows this session's changes on
345
+ * top of it.
346
+ * - `PageWidgets` is one page's widgets, where each is and how it looks,
347
+ * derived from the index's widget rows (`pageWidgetsOf`).
348
+ *
349
+ * The text being typed in a field is not here: it waits in `write/typing.ts`
350
+ * until it is committed.
351
+ */
352
+ const fieldKeyOfRef = (ref) => ref.kind === "objectNumber" ? `obj:${ref.objectNumber}` : `fqn:${ref.name}`;
353
+ /** A field's ref is its object number, or its name when it has none. */
354
+ const fieldKeyOf = (field) => fieldKeyOfRef(field.ref);
355
+ const emptyFieldIndex = () => ({
9
356
  snapshot: null,
10
357
  byKey: {},
358
+ byName: {},
11
359
  byWidget: {},
12
- writing: {},
13
- geom: {},
14
- seq: 0
360
+ rowByWidget: {},
361
+ pictureVersions: {}
15
362
  });
16
- function index(snapshot) {
363
+ function indexFields(snapshot, pictureVersions = {}) {
17
364
  const byKey = {};
365
+ const byName = {};
18
366
  const byWidget = {};
19
- snapshot.fields.forEach((field, i) => {
20
- byKey[fieldKeyOf(field)] = i;
21
- for (const w of field.widgets) if (w.annotObjectNumber > 0) byWidget[w.annotObjectNumber] = i;
367
+ const rowByWidget = {};
368
+ snapshot.fields.forEach((field, position) => {
369
+ var _field$name;
370
+ byKey[fieldKeyOf(field)] = position;
371
+ byName[_field$name = field.name] ?? (byName[_field$name] = position);
372
+ for (const widget of field.widgets) if (widget.objectNumber > 0) byWidget[widget.objectNumber] = position;
373
+ });
374
+ snapshot.widgets.forEach((row, position) => {
375
+ if (row.ref.kind === "objectNumber") rowByWidget[row.ref.objectNumber] = position;
22
376
  });
23
377
  return {
378
+ snapshot,
24
379
  byKey,
25
- byWidget
380
+ byName,
381
+ byWidget,
382
+ rowByWidget,
383
+ pictureVersions
26
384
  };
27
385
  }
28
- function update(model, msg) {
29
- switch (msg.t) {
30
- case "snapshot": return {
31
- ...model,
32
- snapshot: msg.snapshot,
33
- ...index(msg.snapshot),
34
- writing: {},
35
- seq: model.seq + 1
36
- };
37
- case "writeStart": return {
38
- ...model,
39
- writing: {
40
- ...model.writing,
41
- [msg.key]: true
42
- },
43
- seq: model.seq + 1
44
- };
45
- case "writeDone": {
46
- if (!model.snapshot) return model;
47
- const i = model.byKey[msg.key];
48
- if (i === void 0) return model;
49
- const fields = model.snapshot.fields.slice();
50
- fields[i] = msg.field;
51
- const { [msg.key]: _done, ...writing } = model.writing;
52
- const snapshot = {
53
- ...model.snapshot,
54
- fields
55
- };
56
- return {
57
- ...model,
58
- snapshot,
59
- ...index(snapshot),
60
- writing,
61
- seq: model.seq + 1
62
- };
63
- }
64
- case "writeFailed": {
65
- const { [msg.key]: _failed, ...writing } = model.writing;
66
- return {
67
- ...model,
68
- writing,
69
- seq: model.seq + 1
70
- };
386
+ /** The index of `snapshot`, keeping `index`'s picture versions. */
387
+ const reindex = (index, snapshot) => indexFields(snapshot, index.pictureVersions);
388
+ /**
389
+ * A fresh read of the whole form: every widget's picture version moves past
390
+ * the one it had, so a reload re-fetches every picture (the pictures may
391
+ * have changed while the event stream wasn't trusted). A new widget starts at 0.
392
+ */
393
+ function indexLoadedFields(previous, snapshot) {
394
+ const pictureVersions = {};
395
+ for (const [number, version] of Object.entries(previous.pictureVersions)) pictureVersions[Number(number)] = version + 1;
396
+ for (const row of snapshot.widgets) {
397
+ const number = widgetNumber$1(row);
398
+ if (number > 0) pictureVersions[number] ?? (pictureVersions[number] = 0);
399
+ }
400
+ return indexFields(snapshot, pictureVersions);
401
+ }
402
+ /** The picture version of a widget; 0 for one the index has never seen. */
403
+ const pictureVersionOf = (index, annotObjectNumber) => index.pictureVersions[annotObjectNumber] ?? 0;
404
+ /** Replace a field by key, or append it when it is new. */
405
+ function upsertFields(index, fields) {
406
+ if (!index.snapshot || fields.length === 0) return index;
407
+ const next = index.snapshot.fields.slice();
408
+ for (const field of fields) {
409
+ const position = index.byKey[fieldKeyOf(field)];
410
+ if (position === void 0) next.push(field);
411
+ else next[position] = field;
412
+ }
413
+ return reindex(index, {
414
+ ...index.snapshot,
415
+ fields: next
416
+ });
417
+ }
418
+ const widgetNumber$1 = (widget) => widget.ref.kind === "objectNumber" ? widget.ref.objectNumber : 0;
419
+ /** Replace widget rows by object number, or append the ones that are new. */
420
+ function upsertWidgets(index, rows) {
421
+ if (!index.snapshot || rows.length === 0) return index;
422
+ const incoming = new Map(rows.map((row) => [widgetNumber$1(row), row]));
423
+ const next = index.snapshot.widgets.map((row) => {
424
+ const replaced = incoming.get(widgetNumber$1(row));
425
+ if (replaced) incoming.delete(widgetNumber$1(row));
426
+ return replaced ?? row;
427
+ });
428
+ return reindex(index, {
429
+ ...index.snapshot,
430
+ widgets: [...next, ...incoming.values()]
431
+ });
432
+ }
433
+ /** The page's widget rows in `order` (bottom to top), in their slots: other pages' keep theirs. */
434
+ function reorderWidgetRows(index, page, order) {
435
+ if (!index.snapshot) return index;
436
+ const widgets = reorderPart(index.snapshot.widgets, (row) => row.page.objectNumber === page.objectNumber, order.map(annotationKey), (row) => annotationKey(row.ref));
437
+ return reindex(index, {
438
+ ...index.snapshot,
439
+ widgets
440
+ });
441
+ }
442
+ /** Drop the rows of widgets that went (with their field, or with their page). */
443
+ function removeWidgets(index, gone) {
444
+ if (!index.snapshot || gone.length === 0) return index;
445
+ const numbers = new Set(gone.map((widget) => widget.objectNumber));
446
+ const widgets = index.snapshot.widgets.filter((row) => !numbers.has(widgetNumber$1(row)));
447
+ if (widgets.length === index.snapshot.widgets.length) return index;
448
+ return reindex(index, {
449
+ ...index.snapshot,
450
+ widgets
451
+ });
452
+ }
453
+ function removeField(index, ref) {
454
+ if (!index.snapshot) return index;
455
+ const fields = index.snapshot.fields.filter((field) => ref.kind === "objectNumber" ? !(field.ref.kind === "objectNumber" && field.ref.objectNumber === ref.objectNumber) : field.name !== ref.name);
456
+ if (fields.length === index.snapshot.fields.length) return index;
457
+ return reindex(index, {
458
+ ...index.snapshot,
459
+ fields
460
+ });
461
+ }
462
+ /**
463
+ * Apply one confirmed document event to the field index. Every form event
464
+ * carries the fields and the widget rows it touched as the engine read them
465
+ * back, so the index never needs a re-read except for a repair, whose result
466
+ * reports only counts, and for writes that remove widgets with their pages.
467
+ * The widgets the engine drew again take a new picture version.
468
+ */
469
+ function foldFormEvent(index, event) {
470
+ return foldFormFacts(withRedrawnPictures(index, redrawnWidgetsOf(event)), event);
471
+ }
472
+ /**
473
+ * The widgets a confirmed fact drew again: the ones the engine says it
474
+ * redrew (`meta.redrawnWidgets`: a checkbox that only switched its state isn't
475
+ * one), else the ones it changed; the signed widget of a signing.
476
+ */
477
+ function redrawnWidgetsOf(event) {
478
+ if (event.type === "signatures.completed") return event.signature.widget ? [event.signature.widget] : [];
479
+ if (!event.type.startsWith("forms.") || !("meta" in event)) return [];
480
+ const meta = event.meta;
481
+ return meta.redrawnWidgets ?? meta.changedWidgets ?? [];
482
+ }
483
+ /** Each widget drawn again takes a new picture version; one named by its page only, all of that page's. */
484
+ function withRedrawnPictures(index, redrawn) {
485
+ if (redrawn.length === 0) return index;
486
+ const numbers = /* @__PURE__ */ new Set();
487
+ for (const widget of redrawn) if (widget.objectNumber) numbers.add(widget.objectNumber);
488
+ else if (widget.page) {
489
+ for (const row of index.snapshot?.widgets ?? []) if (row.page.objectNumber === widget.page.objectNumber) numbers.add(widgetNumber$1(row));
490
+ }
491
+ if (numbers.size === 0) return index;
492
+ const pictureVersions = { ...index.pictureVersions };
493
+ for (const number of numbers) pictureVersions[number] = (pictureVersions[number] ?? 0) + 1;
494
+ return {
495
+ ...index,
496
+ pictureVersions
497
+ };
498
+ }
499
+ /**
500
+ * A merged field split as it took a second widget: its widget half moved to a new number (one
501
+ * of the event's widgets), and the row at the field's own number is gone with it.
502
+ */
503
+ function withoutSplitRow(index, field) {
504
+ if (field.ref.kind !== "objectNumber") return index;
505
+ const own = field.ref.objectNumber;
506
+ if (field.widgets.some((widget) => widget.objectNumber === own)) return index;
507
+ const row = widgetRowOf(index, own);
508
+ return row ? removeWidgets(index, [{
509
+ ref: row.ref,
510
+ objectNumber: own,
511
+ page: row.page
512
+ }]) : index;
513
+ }
514
+ function foldFormFacts(index, event) {
515
+ switch (event.type) {
516
+ case "forms.widgetAdded": return withoutSplitRow(upsertWidgets(upsertFields(index, [event.field]), event.widgets), event.field);
517
+ case "forms.valueSet":
518
+ case "forms.widgetRemoved":
519
+ case "forms.restored": return upsertWidgets(upsertFields(index, [event.field]), event.widgets);
520
+ case "forms.updated": return withCalculationOrder(upsertWidgets(upsertFields(index, [event.field]), event.widgets), event.calculationOrder);
521
+ case "forms.created": {
522
+ const created = upsertWidgets(upsertFields(index, [event.field]), event.widgets);
523
+ return withCalculationOrder(created.snapshot?.formKind === "none" ? reindex(created, {
524
+ ...created.snapshot,
525
+ formKind: "acroform"
526
+ }) : created, event.calculationOrder);
71
527
  }
72
- case "pageGeom": return {
73
- ...model,
74
- geom: {
75
- ...model.geom,
76
- [msg.pageObjectNumber]: msg.boxes
77
- },
78
- seq: model.seq + 1
79
- };
80
- case "clearGeom": {
81
- if (msg.pageObjectNumber === void 0) return {
82
- ...model,
83
- geom: {},
84
- seq: model.seq + 1
85
- };
86
- const geom = { ...model.geom };
87
- delete geom[msg.pageObjectNumber];
88
- return {
89
- ...model,
90
- geom,
91
- seq: model.seq + 1
92
- };
528
+ case "forms.calculationsReordered": return withCalculationOrder(index, event.calculationOrder);
529
+ case "forms.widgetDeleted": {
530
+ const gone = removeWidgets(index, event.meta.changedWidgets);
531
+ return event.field ? upsertFields(gone, [event.field]) : gone;
93
532
  }
533
+ case "forms.widgetRestored": return upsertWidgets(event.field ? upsertFields(index, [event.field]) : index, event.widgets);
534
+ case "forms.widgetUpdated": return upsertWidgets(index, [event.widget]);
535
+ case "forms.widgetsReordered": return reorderWidgetRows(index, event.page, event.order);
536
+ case "forms.deleted": return event.deleted ? withCalculationOrder(removeWidgets(removeField(index, event.deleted), event.meta.changedWidgets), event.calculationOrder) : reload();
537
+ case "forms.repaired":
538
+ case "pages.deleted":
539
+ case "pages.inserted":
540
+ case "pages.restored":
541
+ case "pages.flattened":
542
+ case "annotations.flattened":
543
+ case "redaction.applied": return reload();
544
+ default: return index;
94
545
  }
95
546
  }
96
- const fieldByKey = (model, key) => {
97
- const i = model.byKey[key];
98
- return i === void 0 ? null : model.snapshot?.fields[i] ?? null;
547
+ /** Whether any field has a keystroke, validate, calculate or format script. */
548
+ function formHasScripts(index) {
549
+ return (index.snapshot?.fields ?? []).some(({ actions }) => !!(actions?.keystroke || actions?.validate || actions?.calculate || actions?.format));
550
+ }
551
+ /** The index with the calculation order a write answered, when the write changed it. */
552
+ function withCalculationOrder(index, order) {
553
+ if (!order || !index.snapshot) return index;
554
+ return reindex(index, {
555
+ ...index.snapshot,
556
+ calculationOrder: [...order]
557
+ });
558
+ }
559
+ const fieldByKey = (index, key) => {
560
+ const position = index.byKey[key];
561
+ return position === void 0 ? null : index.snapshot?.fields[position] ?? null;
562
+ };
563
+ /** The field a ref names: by object number, or by full name for `toFieldRef(name)`. */
564
+ function fieldByRef(index, ref) {
565
+ const position = ref.kind === "fqn" ? index.byName[ref.name] : index.byKey[fieldKeyOfRef(ref)];
566
+ return position === void 0 ? null : index.snapshot?.fields[position] ?? null;
567
+ }
568
+ /** The key a field is known by, whichever ref names it: a name ref resolves to its field's key. */
569
+ const canonicalKey = (index, ref) => {
570
+ const field = fieldByRef(index, ref);
571
+ return field ? fieldKeyOf(field) : fieldKeyOfRef(ref);
99
572
  };
100
- const fieldForWidget = (model, annotObjectNumber) => {
101
- const i = model.byWidget[annotObjectNumber];
102
- return i === void 0 ? null : model.snapshot?.fields[i] ?? null;
573
+ const fieldForWidget = (index, annotObjectNumber) => {
574
+ const position = index.byWidget[annotObjectNumber];
575
+ return position === void 0 ? null : index.snapshot?.fields[position] ?? null;
576
+ };
577
+ /** The fields whose value entry differs between two indexes (new fields included). */
578
+ function fieldsWithChangedValues(previous, next) {
579
+ return (next.snapshot?.fields ?? []).filter((field) => {
580
+ const before = fieldByKey(previous, fieldKeyOf(field));
581
+ return !before || JSON.stringify(valueEntryOf(before)) !== JSON.stringify(valueEntryOf(field));
582
+ });
583
+ }
584
+ const valueEntryOf = (field) => "valueEntry" in field ? field.valueEntry : null;
585
+ /** Whether a widget shows on screen: its `hidden` and `noView` flags hide it. */
586
+ const shownOnScreen = (row) => !row.hidden && !row.noView;
587
+ /** The widgets one page shows, from the form's widget rows. */
588
+ function pageWidgetsOf(index, pageObjectNumber) {
589
+ const widgets = {};
590
+ for (const row of index.snapshot?.widgets ?? []) {
591
+ if (row.page.objectNumber !== pageObjectNumber || row.ref.kind !== "objectNumber") continue;
592
+ if (!shownOnScreen(row)) continue;
593
+ widgets[row.ref.objectNumber] = {
594
+ box: row.rect,
595
+ look: {
596
+ border: row.color ?? null,
597
+ borderWidth: row.strokeWidth ?? 1,
598
+ borderStyle: row.borderStyle ?? "solid",
599
+ background: row.interiorColor ?? null,
600
+ color: row.fontColor ?? null,
601
+ fontFamily: row.fontFamily ?? null,
602
+ fontSize: row.fontSize ?? null,
603
+ textAlign: row.textAlign ?? "left"
604
+ }
605
+ };
606
+ }
607
+ return widgets;
608
+ }
609
+ const AT_REST = {
610
+ pending: false,
611
+ pictureVersion: 0
103
612
  };
613
+ /** The widgets one page shows, in the order the page draws them. */
614
+ function shownWidgetsOf(index, pageObjectNumber, lookOf = () => AT_REST) {
615
+ const shown = [];
616
+ for (const row of index.snapshot?.widgets ?? []) {
617
+ if (row.page.objectNumber !== pageObjectNumber || !shownOnScreen(row)) continue;
618
+ shown.push({
619
+ ref: row.ref,
620
+ rect: row.rect,
621
+ appearanceState: row.appearanceState,
622
+ ...lookOf(row)
623
+ });
624
+ }
625
+ return shown;
626
+ }
627
+ function widgetRowOf(index, annotObjectNumber) {
628
+ const position = index.rowByWidget[annotObjectNumber];
629
+ return position === void 0 ? null : index.snapshot?.widgets[position] ?? null;
630
+ }
631
+ const boxContains = (box, point) => point.x >= box.x && point.x <= box.x + box.width && point.y >= box.y && point.y <= box.y + box.height;
632
+ /** The widget under a page-space point; nested widgets resolve to the smallest box. */
633
+ function widgetAt(index, widgets, point) {
634
+ if (!widgets) return null;
635
+ let best = null;
636
+ for (const [key, { box }] of Object.entries(widgets)) {
637
+ if (!boxContains(box, point)) continue;
638
+ const annotObjectNumber = Number(key);
639
+ const field = fieldForWidget(index, annotObjectNumber);
640
+ if (!field) continue;
641
+ if (!best || box.width * box.height < best.box.width * best.box.height) best = {
642
+ annotObjectNumber,
643
+ field,
644
+ box
645
+ };
646
+ }
647
+ return best;
648
+ }
649
+ const initialFormModel = () => ({ focused: null });
104
650
  //#endregion
105
- //#region src/core/fill-items.ts
106
- const ZERO_BOX = {
107
- x: 0,
108
- y: 0,
109
- width: 0,
110
- height: 0
651
+ //#region src/read/fields.ts
652
+ /**
653
+ * Reads over the mirrored field tree: fields, values, the joins between a
654
+ * field and its widgets' rows, the field of the selected widget, and the
655
+ * required-field check.
656
+ */
657
+ const NO_FIELDS$1 = Object.freeze([]);
658
+ const NOTHING_SELECTED = Object.freeze([]);
659
+ /** A widget address as the annotation object number the field index is keyed by. */
660
+ const widgetObjectOf = (widget) => "kind" in widget ? widget.kind === "objectNumber" ? widget.objectNumber : 0 : widget.objectNumber;
661
+ /** A field's value in the write vocabulary, or null for a valueless or unsupported entry. */
662
+ function valueOf$1(field) {
663
+ const entry = field.valueEntry;
664
+ if (entry.kind === "none" || entry.kind === "unsupported") return null;
665
+ switch (field.family) {
666
+ case "text": return { value: field.value };
667
+ case "checkbox": return { checked: field.checked };
668
+ case "radio": return { value: field.value === "Off" ? null : field.value };
669
+ case "combobox": return { value: field.value === "" ? null : field.value };
670
+ case "listbox": return { selectedValues: [...field.selectedValues] };
671
+ default: return null;
672
+ }
673
+ }
674
+ /** A field's value as plain data: what `exportValues()` gives and `importValues()` takes. */
675
+ function plainValueOf(field) {
676
+ const value = valueOf$1(field);
677
+ if (!value) return void 0;
678
+ if ("checked" in value) return value.checked;
679
+ if ("selectedValues" in value) return value.selectedValues;
680
+ return value.value;
681
+ }
682
+ /**
683
+ * The write a plain value makes for a field of this family, or null when the
684
+ * family can't take it (a list given `true`, a value for a push button).
685
+ */
686
+ function writeOfPlainValue(field, value) {
687
+ switch (field.family) {
688
+ case "checkbox":
689
+ if (typeof value === "boolean") return { checked: value };
690
+ return typeof value === "string" || value === null ? { value } : null;
691
+ case "text":
692
+ case "radio":
693
+ case "combobox": return typeof value === "string" || value === null ? { value } : null;
694
+ case "listbox":
695
+ if (value === null) return { selectedValues: [] };
696
+ if (typeof value === "string") return { selectedValues: [value] };
697
+ return Array.isArray(value) ? { selectedValues: [...value] } : null;
698
+ default: return null;
699
+ }
700
+ }
701
+ /** Whether a field holds nothing a required check would accept. */
702
+ function isEmpty(field) {
703
+ switch (field.family) {
704
+ case "text":
705
+ case "combobox": return field.value === "";
706
+ case "checkbox": return !field.checked;
707
+ case "radio": return field.value === "Off" || field.value === "";
708
+ case "listbox": return field.selectedValues.length === 0;
709
+ case "signature": return field.valueEntry.kind === "none";
710
+ default: return false;
711
+ }
712
+ }
713
+ function createFieldReads(ctx, { fields, rights, siblings }) {
714
+ const all = () => fields.view().snapshot?.fields ?? NO_FIELDS$1;
715
+ const list = (filter) => {
716
+ if (!filter) return all();
717
+ const page = filter.page === void 0 ? void 0 : ctx.getPage(filter.page)?.ref;
718
+ if (filter.page !== void 0 && !page) return NO_FIELDS$1;
719
+ return all().filter((field) => (!filter.family || field.family === filter.family) && (filter.name === void 0 || field.name === filter.name) && (!page || field.widgets.some((widget) => widget.page && pageRefsEqual(widget.page, page))));
720
+ };
721
+ const valueByKey = memoByKey((key) => {
722
+ const field = fieldByKey(fields.view(), key);
723
+ return [field ? JSON.stringify(valueOf$1(field)) : null];
724
+ }, (_key, value) => value === null ? null : JSON.parse(value), { maxEntries: 1024 });
725
+ const widgetsByKey = memoByKey((key) => {
726
+ const index = fields.view();
727
+ return (fieldByKey(index, key)?.widgets ?? []).map((widget) => widgetRowOf(index, widget.objectNumber));
728
+ }, (_key, ...rows) => Object.freeze(rows.filter((row) => row !== null)), { maxEntries: 1024 });
729
+ const exportValues = memo(() => [fields.view()], (index) => {
730
+ const values = {};
731
+ for (const field of index.snapshot?.fields ?? []) {
732
+ const value = plainValueOf(field);
733
+ if (value !== void 0) values[field.name] = value;
734
+ }
735
+ return values;
736
+ });
737
+ /** Where a field first shows: its page's index, then top to bottom, then left to right. */
738
+ const placeOf = (field) => {
739
+ const index = fields.view();
740
+ const row = field.widgets.map((widget) => widgetRowOf(index, widget.objectNumber)).find((candidate) => candidate !== null);
741
+ return [
742
+ row ? ctx.getPage(row.page)?.index ?? Infinity : Infinity,
743
+ row?.rect.y ?? 0,
744
+ row?.rect.x ?? 0
745
+ ];
746
+ };
747
+ const validate = memo(() => [
748
+ fields.view(),
749
+ ctx.document(),
750
+ rights.key()
751
+ ], (index) => {
752
+ const missing = (index.snapshot?.fields ?? []).filter((field) => field.required && isEmpty(field) && rights.mayFill(field)).map((field) => ({
753
+ field,
754
+ place: placeOf(field)
755
+ })).sort((left, right) => left.place[0] - right.place[0] || left.place[1] - right.place[1] || left.place[2] - right.place[2]).map(({ field }) => field);
756
+ return {
757
+ valid: missing.length === 0,
758
+ missing
759
+ };
760
+ });
761
+ const getSelectedField = memo(() => [fields.view(), siblings.annotation()?.selection.list() ?? NOTHING_SELECTED], (index, selected) => {
762
+ const [annotation] = selected;
763
+ if (selected.length !== 1 || !annotation?.subtype.startsWith("widget")) return null;
764
+ return fieldForWidget(index, widgetObjectOf(annotation.ref));
765
+ });
766
+ return { api: {
767
+ getSnapshot: () => fields.view().snapshot,
768
+ getStatus: fields.getStatus,
769
+ getFormKind: () => fields.view().snapshot?.formKind ?? "none",
770
+ refresh: (options) => ctx.cancellable(options?.signal, fields.refresh()),
771
+ get: (ref) => fieldByRef(fields.view(), ref),
772
+ getFieldForWidget: (widget) => fieldForWidget(fields.view(), widgetObjectOf(widget)),
773
+ getWidget: (widget) => widgetRowOf(fields.view(), widgetObjectOf(widget)),
774
+ getWidgets: (ref) => widgetsByKey(canonicalKey(fields.view(), ref)),
775
+ list,
776
+ getValue: (ref) => valueByKey(canonicalKey(fields.view(), ref)),
777
+ getSelectedField,
778
+ validate,
779
+ exportValues
780
+ } };
781
+ }
782
+ //#endregion
783
+ //#region src/read/settings.ts
784
+ /**
785
+ * A field's settings, described for a settings panel the way an annotation
786
+ * kind describes its look: which settings the field's family has, how each is
787
+ * edited, and its value. `update()` writes them.
788
+ */
789
+ /** What every field has. */
790
+ const COMMON = [
791
+ {
792
+ key: "name",
793
+ control: "text",
794
+ label: "Name",
795
+ labelKey: "form.settings.name"
796
+ },
797
+ {
798
+ key: "alternateName",
799
+ control: "text",
800
+ label: "Tooltip",
801
+ labelKey: "form.settings.tooltip"
802
+ },
803
+ {
804
+ key: "required",
805
+ control: "flag",
806
+ label: "Required",
807
+ labelKey: "form.settings.required"
808
+ },
809
+ {
810
+ key: "readOnly",
811
+ control: "flag",
812
+ label: "Read-only",
813
+ labelKey: "form.settings.readOnly"
814
+ },
815
+ {
816
+ key: "noExport",
817
+ control: "flag",
818
+ label: "Don't export",
819
+ labelKey: "form.settings.noExport"
820
+ }
821
+ ];
822
+ const DEFAULT_VALUE = {
823
+ label: "Default value",
824
+ labelKey: "form.settings.defaultValue"
111
825
  };
826
+ const OPTIONS = {
827
+ key: "options",
828
+ control: "options",
829
+ label: "Options",
830
+ labelKey: "form.settings.options"
831
+ };
832
+ /** What each family adds. */
833
+ function familySettings(field) {
834
+ switch (field.family) {
835
+ case "text": return [
836
+ {
837
+ key: "defaultValue",
838
+ control: "text",
839
+ ...DEFAULT_VALUE
840
+ },
841
+ {
842
+ key: "maxLength",
843
+ control: "number",
844
+ label: "Maximum length",
845
+ labelKey: "form.settings.maxLength",
846
+ min: 1
847
+ },
848
+ {
849
+ key: "multiline",
850
+ control: "flag",
851
+ label: "Several lines",
852
+ labelKey: "form.settings.multiline"
853
+ },
854
+ {
855
+ key: "password",
856
+ control: "flag",
857
+ label: "Password",
858
+ labelKey: "form.settings.password"
859
+ },
860
+ {
861
+ key: "comb",
862
+ control: "flag",
863
+ label: "One character per box",
864
+ labelKey: "form.settings.comb"
865
+ }
866
+ ];
867
+ case "radio": return [{
868
+ key: "radiosInUnison",
869
+ control: "flag",
870
+ label: "Buttons with one value turn on together",
871
+ labelKey: "form.settings.radiosInUnison"
872
+ }, {
873
+ key: "noToggleToOff",
874
+ control: "flag",
875
+ label: "Keep one on",
876
+ labelKey: "form.settings.keepOneOn"
877
+ }];
878
+ case "combobox": return [
879
+ OPTIONS,
880
+ {
881
+ key: "edit",
882
+ control: "flag",
883
+ label: "Allow typing",
884
+ labelKey: "form.settings.allowTyping"
885
+ },
886
+ {
887
+ key: "defaultValue",
888
+ control: "choice",
889
+ ...DEFAULT_VALUE,
890
+ options: field.options.map((option) => option.value),
891
+ free: field.edit
892
+ }
893
+ ];
894
+ case "listbox": return [
895
+ OPTIONS,
896
+ {
897
+ key: "multiSelect",
898
+ control: "flag",
899
+ label: "Several choices",
900
+ labelKey: "form.settings.multiSelect"
901
+ },
902
+ {
903
+ key: "defaultValue",
904
+ control: "choices",
905
+ ...DEFAULT_VALUE,
906
+ options: field.options.map((option) => option.value)
907
+ }
908
+ ];
909
+ default: return [];
910
+ }
911
+ }
912
+ /** Each setting's value, as the field holds it. */
913
+ function valuesOf(field, settings) {
914
+ const held = field;
915
+ const values = {};
916
+ for (const { key } of settings) if (key === "name") values.name = field.name.slice(field.name.lastIndexOf(".") + 1);
917
+ else if (key === "alternateName") values.alternateName = field.alternateName ?? "";
918
+ else values[key] = held[key] ?? null;
919
+ return values;
920
+ }
921
+ function createFieldSettings({ fields }) {
922
+ const settingsByKey = memoByKey((key) => [fieldByKey(fields.view(), key)], (_key, field) => {
923
+ if (!field) return null;
924
+ const properties = [...COMMON, ...familySettings(field)];
925
+ return {
926
+ properties,
927
+ values: valuesOf(field, properties)
928
+ };
929
+ }, { maxEntries: 256 });
930
+ return { api: { getFieldSettings: (ref) => settingsByKey(canonicalKey(fields.view(), ref)) } };
931
+ }
932
+ //#endregion
933
+ //#region src/read/fill-items.ts
112
934
  /**
113
- * Project ONE widget of a field into a fill control. `box` is supplied by the
114
- * caller: the page projection reads the model's widget geometry; a consumer
115
- * that already owns a live box (the annotation plane's RenderItem) passes it —
116
- * or nothing, when only the semantics matter. Null for families with no fill
117
- * control (signature/unknown: rendered by the annotation plane only).
935
+ * Project one widget of a field into a fill control; `fillable`: the user may
936
+ * fill the field in (a signature field: sign it). Null for families with no
937
+ * fill control.
118
938
  */
119
- function projectWidget(model, field, annotObjectNumber, box = ZERO_BOX) {
120
- const key = fieldKeyOf(field);
939
+ function projectWidget(field, annotObjectNumber, widget, fillable) {
121
940
  const base = {
122
- key,
941
+ key: fieldKeyOf(field),
942
+ fieldRef: field.ref,
123
943
  annotObjectNumber,
124
- box,
125
- disabled: field.flags.readOnly || model.writing[key] === true,
944
+ annotationRef: field.widgets.find((candidate) => candidate.objectNumber === annotObjectNumber)?.ref ?? null,
945
+ box: widget.box,
946
+ look: widget.look,
947
+ disabled: field.readOnly || !fillable,
126
948
  label: field.alternateName ?? field.name
127
949
  };
128
950
  switch (field.family) {
@@ -136,23 +958,23 @@ function projectWidget(model, field, annotObjectNumber, box = ZERO_BOX) {
136
958
  comb: field.comb
137
959
  };
138
960
  case "checkbox": {
139
- const toggle = field.widgets.find((w) => w.annotObjectNumber === annotObjectNumber);
961
+ const toggle = field.widgets.find((candidate) => candidate.objectNumber === annotObjectNumber);
140
962
  return {
141
963
  ...base,
142
964
  control: "toggle",
143
965
  kind: "checkbox",
144
966
  checked: field.checked,
145
- onState: toggle && "onState" in toggle ? toggle.onState : "Yes"
967
+ exportValue: toggle && "exportValue" in toggle ? toggle.exportValue : field.exportValue
146
968
  };
147
969
  }
148
970
  case "radio": {
149
- const toggle = field.widgets.find((w) => w.annotObjectNumber === annotObjectNumber);
971
+ const toggle = field.widgets.find((candidate) => candidate.objectNumber === annotObjectNumber);
150
972
  return {
151
973
  ...base,
152
974
  control: "toggle",
153
975
  kind: "radio",
154
976
  checked: toggle && "checked" in toggle ? toggle.checked : false,
155
- onState: toggle && "onState" in toggle ? toggle.onState : ""
977
+ exportValue: toggle && "exportValue" in toggle ? toggle.exportValue : ""
156
978
  };
157
979
  }
158
980
  case "combobox": return {
@@ -177,1232 +999,2282 @@ function projectWidget(model, field, annotObjectNumber, box = ZERO_BOX) {
177
999
  ...base,
178
1000
  control: "button"
179
1001
  };
1002
+ case "signature": return {
1003
+ ...base,
1004
+ control: "signature",
1005
+ signed: field.valueEntry.kind !== "none"
1006
+ };
180
1007
  default: return null;
181
1008
  }
182
1009
  }
183
1010
  /**
184
- * Project one page's widgets into fill controls. Widgets whose geometry has
185
- * not arrived yet (or that are direct objects with no join key) are skipped —
186
- * the shell re-runs the projection when `pageGeom` lands.
1011
+ * Project one page's widgets into fill controls, each disabled when the user
1012
+ * may not fill its field in, or sign it (`mayFill`). Widgets whose page has not loaded (or
1013
+ * that are direct objects with no join key) are skipped; the projection runs
1014
+ * again when the page's widgets land.
187
1015
  */
188
- function fillItems(model, pageObjectNumber) {
189
- const snapshot = model.snapshot;
190
- const geom = model.geom[pageObjectNumber];
191
- if (!snapshot || !geom) return [];
1016
+ function fillItems(index, pageObjectNumber, widgets, mayFill) {
1017
+ if (!index.snapshot || !widgets) return [];
192
1018
  const items = [];
193
- for (const field of snapshot.fields) for (const widget of field.widgets) {
194
- if (widget.pageObjectNumber !== pageObjectNumber) continue;
195
- const box = geom[widget.annotObjectNumber];
196
- if (!box) continue;
197
- const item = projectWidget(model, field, widget.annotObjectNumber, box);
1019
+ for (const field of index.snapshot.fields) for (const widget of field.widgets) {
1020
+ if (widget.page?.objectNumber !== pageObjectNumber) continue;
1021
+ const placed = widgets[widget.objectNumber];
1022
+ if (!placed) continue;
1023
+ const item = projectWidget(field, widget.objectNumber, placed, mayFill(field));
198
1024
  if (item) items.push(item);
199
1025
  }
200
1026
  return items;
201
1027
  }
1028
+ //#endregion
1029
+ //#region src/read/widgets.ts
1030
+ /**
1031
+ * The widgets' reads: each page's widgets (from the form's widget rows), the
1032
+ * ones it shows for the form layer to paint (and the painter's scene of each,
1033
+ * `services/looks.ts`), the fill projection with the session's fill permission
1034
+ * folded in, and the widget hit test.
1035
+ */
1036
+ const NO_WIDGETS = Object.freeze([]);
1037
+ const NOTHING_SHOWN$1 = Object.freeze([]);
1038
+ function createWidgetReads(ctx, { fields, rights, looks, pictures }) {
1039
+ /** Every page's widgets come with the form: one read for the document. */
1040
+ const loadWidgets = (_page) => fields.settled();
1041
+ const widgetsOn = memoByKey((pageObjectNumber) => [fields.view()], (pageObjectNumber, index) => pageWidgetsOf(index, pageObjectNumber));
1042
+ /** The widget under a page point. */
1043
+ const getWidgetAt = (pageArgument, point) => {
1044
+ const page = ctx.getPage(pageArgument)?.ref;
1045
+ if (!page) return null;
1046
+ return widgetAt(fields.view(), widgetsOn(page.objectNumber), point);
1047
+ };
1048
+ const widgetsOfPage = memoByKey((pageObjectNumber) => [
1049
+ fields.view(),
1050
+ widgetsOn(pageObjectNumber),
1051
+ rights.key(),
1052
+ ctx.settings().get().fillable
1053
+ ], (pageObjectNumber, index, widgets) => fillItems(index, pageObjectNumber, widgets, rights.mayFillByHand));
1054
+ /** The page's content box (`{0, 0, width, height}`), for page-bound placement. */
1055
+ const getPageBox = (page) => {
1056
+ const size = ctx.getPage(page)?.size;
1057
+ return size ? {
1058
+ x: 0,
1059
+ y: 0,
1060
+ width: size.width,
1061
+ height: size.height
1062
+ } : null;
1063
+ };
1064
+ return {
1065
+ getPageBox,
1066
+ api: {
1067
+ listWidgets: (pageArgument) => {
1068
+ const page = ctx.getPage(pageArgument)?.ref;
1069
+ return page ? widgetsOfPage(page.objectNumber) : NO_WIDGETS;
1070
+ },
1071
+ listShownWidgets: (pageArgument) => {
1072
+ const page = ctx.getPage(pageArgument)?.ref;
1073
+ return page ? looks.listShownWidgets(page.objectNumber) : NOTHING_SHOWN$1;
1074
+ },
1075
+ getAppearanceEpoch: pictures.epoch,
1076
+ renderAppearances: pictures.render,
1077
+ getWidgetPainting: looks.getWidgetPainting,
1078
+ getTextEditorLayout: looks.getTextEditorLayout,
1079
+ getWidgetFontCss: looks.getWidgetFontCss,
1080
+ ensureLoaded: loadWidgets,
1081
+ getWidgetAt,
1082
+ getPageBox
1083
+ }
1084
+ };
1085
+ }
1086
+ //#endregion
1087
+ //#region src/sync/predict.ts
1088
+ const widgetNumber = (widget) => widget.ref.kind === "objectNumber" ? widget.ref.objectNumber : 0;
1089
+ /** The rows of a field's widgets, in its widget order. */
1090
+ function rowsOfField(index, field) {
1091
+ return field.widgets.flatMap((widget) => {
1092
+ const row = widgetRowOf(index, widget.objectNumber);
1093
+ return row ? [row] : [];
1094
+ });
1095
+ }
1096
+ /** A field and the rows of its widgets, as the index holds them. */
1097
+ const withRows = (index, field) => ({
1098
+ field,
1099
+ widgets: rowsOfField(index, field)
1100
+ });
1101
+ /** Fields and their widget rows put into the index, all at once. */
1102
+ function withFields(index, parts) {
1103
+ if (parts.length === 0) return index;
1104
+ return upsertWidgets(upsertFields(index, parts.map((part) => part.field)), parts.flatMap((part) => part.widgets));
1105
+ }
1106
+ /** The fields a reset of the whole form puts back: the ones that hold a value. */
1107
+ const resetTargets = (index) => (index.snapshot?.fields ?? []).filter((field) => RESET_FAMILIES.has(field.family));
1108
+ const RESET_FAMILIES = /* @__PURE__ */ new Set([
1109
+ "text",
1110
+ "checkbox",
1111
+ "radio",
1112
+ "combobox",
1113
+ "listbox"
1114
+ ]);
202
1115
  /**
203
- * Project a SINGLE widget by its annotation object number — the join the
204
- * annotation-plane render layer uses (it owns a live box already, so the
205
- * model's cached geometry is used only when it happens to be loaded; the
206
- * item's semantics never depend on it). Null while the snapshot hasn't
207
- * landed, or for families with no fill control.
1116
+ * One op of a change this session staged, shown before the engine answers,
1117
+ * by the engine's own rules (`fieldAfterValue`, `fieldAfterReset`,
1118
+ * `widgetsAfterDisplay`, `formFieldOfDraft`, `formFieldAfter`,
1119
+ * `widgetAfterPatch`): what the fields and their widgets hold after it. An op
1120
+ * those rules refuse shows nothing; one whose values only the engine's schemas
1121
+ * refuse shows until the engine's refusal takes the change away.
1122
+ * A create shows once it names its numbers; taking a widget out of its field
1123
+ * shows once the engine answers.
1124
+ *
1125
+ * The view replays every pending change each time any change is staged; the
1126
+ * same op over the same form gives the same form, so a field keeps its object
1127
+ * while nothing about it changed.
208
1128
  */
209
- function fillItemForWidget(model, annotObjectNumber) {
210
- const field = fieldForWidget(model, annotObjectNumber);
211
- if (!field) return null;
212
- const widget = field.widgets.find((w) => w.annotObjectNumber === annotObjectNumber);
213
- if (!widget) return null;
214
- const box = model.geom[widget.pageObjectNumber]?.[annotObjectNumber];
215
- return projectWidget(model, field, annotObjectNumber, box);
1129
+ function predictFormOp(index, op) {
1130
+ let byOp = predictions.get(index);
1131
+ const known = byOp?.get(op);
1132
+ if (known) return known;
1133
+ const next = predictOnce(index, op);
1134
+ if (!byOp) predictions.set(index, byOp = /* @__PURE__ */ new WeakMap());
1135
+ byOp.set(op, next);
1136
+ return next;
1137
+ }
1138
+ const predictions = /* @__PURE__ */ new WeakMap();
1139
+ function predictOnce(index, op) {
1140
+ try {
1141
+ switch (op.type) {
1142
+ case "forms.setValue": {
1143
+ const field = fieldByRef(index, op.field);
1144
+ return field ? withFields(index, [fieldAfterValue(withRows(index, field), op.value)]) : index;
1145
+ }
1146
+ case "forms.reset": return withFields(index, (op.fields ? op.fields.flatMap((ref) => fieldByRef(index, ref) ?? []) : resetTargets(index)).map((field) => fieldAfterReset(withRows(index, field))));
1147
+ case "forms.setDisplay": {
1148
+ const field = fieldByRef(index, op.field);
1149
+ if (!field) return index;
1150
+ return upsertWidgets(index, widgetsAfterDisplay(rowsOfField(index, field), op.display));
1151
+ }
1152
+ case "forms.restore": return withFields(index, [op]);
1153
+ case "forms.restoreWidget": {
1154
+ const restored = upsertWidgets(index, [op.widget]);
1155
+ return op.field ? upsertFields(restored, [op.field]) : restored;
1156
+ }
1157
+ case "forms.create": return createdField(index, op);
1158
+ case "forms.update": {
1159
+ const field = fieldByRef(index, op.field);
1160
+ return field ? withFields(index, [formFieldAfter(withRows(index, field), op.patch)]) : index;
1161
+ }
1162
+ case "forms.delete": {
1163
+ const field = fieldByRef(index, op.field);
1164
+ if (!field || !index.snapshot) return index;
1165
+ return withCalculationOrder(removeWidgets(removeField(index, field.ref), field.widgets), index.snapshot.calculationOrder.filter((ref) => !sameField(ref, field.ref)));
1166
+ }
1167
+ case "forms.updateWidget": {
1168
+ const row = rowOfRef(index, op.widget);
1169
+ return row ? upsertWidgets(index, [widgetAfterPatch(row, op.patch)]) : index;
1170
+ }
1171
+ case "forms.deleteWidget": {
1172
+ const row = rowOfRef(index, op.widget);
1173
+ if (!row) return index;
1174
+ const number = widgetNumber(row);
1175
+ const field = fieldForWidget(index, number);
1176
+ const gone = removeWidgets(index, [{
1177
+ objectNumber: number,
1178
+ page: row.page
1179
+ }]);
1180
+ if (!field) return gone;
1181
+ const widgets = field.widgets.filter((widget) => widget.objectNumber !== number);
1182
+ return upsertFields(gone, [{
1183
+ ...field,
1184
+ widgets
1185
+ }]);
1186
+ }
1187
+ case "forms.reorderWidgets": {
1188
+ if (!index.snapshot) return index;
1189
+ const order = reorderedList(index.snapshot.widgets.filter((row) => row.page.objectNumber === op.page.objectNumber).map((row) => row.ref), op.widgets, op.position, annotationKey);
1190
+ return reorderWidgetRows(index, op.page, order);
1191
+ }
1192
+ case "forms.reorderCalculations":
1193
+ if (!index.snapshot) return index;
1194
+ return withCalculationOrder(index, reorderedList(index.snapshot.calculationOrder.filter((ref) => ref !== null), op.fields, op.position, fieldKeyOfRef));
1195
+ default: return index;
1196
+ }
1197
+ } catch {
1198
+ return index;
1199
+ }
1200
+ }
1201
+ /** A widget's row, by its annotation ref. */
1202
+ const rowOfRef = (index, ref) => ref.kind === "objectNumber" ? widgetRowOf(index, ref.objectNumber) : null;
1203
+ const sameField = (left, right) => left !== null && fieldKeyOfRef(left) === fieldKeyOfRef(right);
1204
+ /**
1205
+ * `forms.create`, once it names the numbers it takes: the field and its
1206
+ * widgets as a read of them returns them, last in the form, and last in the
1207
+ * calculation order when it calculates.
1208
+ */
1209
+ function createdField(index, op) {
1210
+ const placements = op.draft.widgets ?? [];
1211
+ const numbers = op.widgetObjectNumbers ?? [];
1212
+ if (op.objectNumber === void 0 || numbers.length !== placements.length) return index;
1213
+ const snapshot = index.snapshot;
1214
+ if (!snapshot || fieldByRef(index, {
1215
+ kind: "objectNumber",
1216
+ objectNumber: op.objectNumber
1217
+ })) return index;
1218
+ const created = formFieldOfDraft(op.draft, {
1219
+ objectNumber: op.objectNumber,
1220
+ widgets: placements.map((placement, at) => ({
1221
+ kind: "objectNumber",
1222
+ page: placement.page,
1223
+ objectNumber: numbers[at]
1224
+ }))
1225
+ });
1226
+ const next = withFields(snapshot.formKind === "none" ? indexFields({
1227
+ ...snapshot,
1228
+ formKind: "acroform"
1229
+ }, index.pictureVersions) : index, [created]);
1230
+ return op.draft.actions?.calculate ? withCalculationOrder(next, [...snapshot.calculationOrder, created.field.ref]) : next;
1231
+ }
1232
+ /** The fields a change's ops write a value or a look to, each once, in op order. */
1233
+ function fieldsNamedBy(index, ops) {
1234
+ const named = /* @__PURE__ */ new Map();
1235
+ const add = (field) => {
1236
+ if (field && !named.has(fieldKeyOf(field))) named.set(fieldKeyOf(field), field);
1237
+ };
1238
+ for (const op of ops) switch (op.type) {
1239
+ case "forms.setValue":
1240
+ case "forms.setDisplay":
1241
+ case "forms.setAppearanceText":
1242
+ add(fieldByRef(index, op.field));
1243
+ break;
1244
+ case "forms.reset":
1245
+ for (const field of op.fields ? op.fields.map((ref) => fieldByRef(index, ref)) : resetTargets(index)) add(field);
1246
+ break;
1247
+ default: break;
1248
+ }
1249
+ return [...named.values()];
1250
+ }
1251
+ /** `index` with these fields, and their widget rows, as `source` holds them. */
1252
+ function withFieldsFrom(index, source, fields) {
1253
+ return withFields(index, fields.flatMap((field) => {
1254
+ const held = fieldByKey(source, fieldKeyOf(field));
1255
+ return held ? [withRows(source, held)] : [];
1256
+ }));
1257
+ }
1258
+ /** A field and its widgets back as `index` holds them. */
1259
+ const restoreOf = (index, field) => ({
1260
+ type: "forms.restore",
1261
+ field,
1262
+ widgets: rowsOfField(index, field)
1263
+ });
1264
+ /** A widget's row back as `index` holds it, with its field as it is there. */
1265
+ const restoreWidgetOf = (index, row) => ({
1266
+ type: "forms.restoreWidget",
1267
+ widget: row,
1268
+ field: fieldForWidget(index, widgetNumber(row))
1269
+ });
1270
+ /** What undoing one op looks like, over the form it applies to. */
1271
+ function undoOfOp(index, op) {
1272
+ switch (op.type) {
1273
+ case "forms.create": return op.objectNumber === void 0 ? [] : [{
1274
+ type: "forms.delete",
1275
+ field: {
1276
+ kind: "objectNumber",
1277
+ objectNumber: op.objectNumber
1278
+ }
1279
+ }];
1280
+ case "forms.update":
1281
+ case "forms.delete": {
1282
+ const field = fieldByRef(index, op.field);
1283
+ return field ? [restoreOf(index, field)] : [];
1284
+ }
1285
+ case "forms.updateWidget":
1286
+ case "forms.deleteWidget": {
1287
+ const row = rowOfRef(index, op.widget);
1288
+ return row ? [restoreWidgetOf(index, row)] : [];
1289
+ }
1290
+ case "forms.removeWidget": {
1291
+ const field = fieldByRef(index, op.field);
1292
+ const row = rowOfRef(index, op.widget);
1293
+ return [...row ? [restoreWidgetOf(index, row)] : [], ...field ? [restoreOf(index, field)] : []];
1294
+ }
1295
+ case "forms.reorderWidgets": {
1296
+ const widgets = (index.snapshot?.widgets ?? []).filter((row) => row.page.objectNumber === op.page.objectNumber).map((row) => row.ref);
1297
+ return [{
1298
+ type: "forms.reorderWidgets",
1299
+ page: op.page,
1300
+ widgets,
1301
+ position: "start"
1302
+ }];
1303
+ }
1304
+ case "forms.reorderCalculations": return [{
1305
+ type: "forms.reorderCalculations",
1306
+ fields: (index.snapshot?.calculationOrder ?? []).filter((ref) => ref !== null),
1307
+ position: "start"
1308
+ }];
1309
+ default: return fieldsNamedBy(index, [op]).map((field) => restoreOf(index, field));
1310
+ }
1311
+ }
1312
+ /**
1313
+ * What undoing `ops` looks like, read off the form they apply to, each over
1314
+ * what the ones before it left: the ops that bring the form back, the last
1315
+ * op's first. Drawing only: the engine undoes a change by its own record of
1316
+ * it.
1317
+ */
1318
+ function undoLookOf(before, ops) {
1319
+ const undo = [];
1320
+ let current = before;
1321
+ for (const op of ops) {
1322
+ undo.push(undoOfOp(current, op));
1323
+ current = predictFormOp(current, op);
1324
+ }
1325
+ return undo.reverse().flat();
1326
+ }
1327
+ //#endregion
1328
+ //#region src/sync/fields.ts
1329
+ function createFieldsMirror(ctx, events) {
1330
+ const fields = ctx.mirror({
1331
+ name: "fields",
1332
+ initial: emptyFieldIndex,
1333
+ readable: () => ctx.allows("doc.forms.read"),
1334
+ load: async (doc) => ({ value: indexLoadedFields(fields.get(), await doc.forms.list()) }),
1335
+ fold: foldFormEvent,
1336
+ predict: predictFormOp,
1337
+ changed: ({ cause, event, next }) => {
1338
+ if (cause === "load") {
1339
+ if (next.snapshot) events.resynced.emit({ snapshot: next.snapshot });
1340
+ return;
1341
+ }
1342
+ if (!event || !("origin" in event)) return;
1343
+ const { origin } = event;
1344
+ switch (event.type) {
1345
+ case "forms.valueSet":
1346
+ events.valueChanged.emit({
1347
+ field: event.field,
1348
+ origin
1349
+ });
1350
+ return;
1351
+ case "forms.created":
1352
+ events.fieldCreated.emit({
1353
+ field: event.field,
1354
+ origin
1355
+ });
1356
+ return;
1357
+ case "forms.updated":
1358
+ case "forms.widgetAdded":
1359
+ case "forms.widgetRemoved":
1360
+ events.fieldUpdated.emit({
1361
+ field: event.field,
1362
+ origin
1363
+ });
1364
+ return;
1365
+ case "forms.widgetDeleted":
1366
+ case "forms.widgetRestored":
1367
+ if (event.field) events.fieldUpdated.emit({
1368
+ field: event.field,
1369
+ origin
1370
+ });
1371
+ return;
1372
+ case "forms.deleted":
1373
+ if (event.deleted) events.fieldDeleted.emit({
1374
+ ref: event.deleted,
1375
+ origin
1376
+ });
1377
+ return;
1378
+ default: return;
1379
+ }
1380
+ }
1381
+ });
1382
+ return fields;
1383
+ }
1384
+ //#endregion
1385
+ //#region src/services/cursor.ts
1386
+ /** How long a box asked for keeps its claim on the cursor while its page comes in. */
1387
+ const PENDING_MS = 2e3;
1388
+ function createCursor(ctx, fields, events) {
1389
+ const targets = /* @__PURE__ */ new Map();
1390
+ let pending = null;
1391
+ let leaving = null;
1392
+ let last = null;
1393
+ const setFocused = (next) => {
1394
+ const previous = ctx.state.get().focused;
1395
+ if (previous?.widget === next?.widget && previous?.field === next?.field) return;
1396
+ ctx.state.update((state) => ({
1397
+ ...state,
1398
+ focused: next
1399
+ }));
1400
+ const field = next ? fieldByKey(fields.view(), next.field) : null;
1401
+ const row = next ? widgetRowOf(fields.view(), next.widget) : null;
1402
+ events.focusChanged.emit({
1403
+ field,
1404
+ widget: row?.ref ?? null
1405
+ });
1406
+ };
1407
+ const clearPending = () => {
1408
+ pending?.expire();
1409
+ pending = null;
1410
+ };
1411
+ return {
1412
+ focused: () => ctx.state.get().focused,
1413
+ last: () => last,
1414
+ note(event, fieldRef, widgetRef) {
1415
+ const widget = widgetObjectOf(widgetRef);
1416
+ if (event === "focus") {
1417
+ leaving?.();
1418
+ leaving = null;
1419
+ if (pending && pending.widget !== widget) clearPending();
1420
+ const field = fieldByRef(fields.view(), fieldRef);
1421
+ last = widget;
1422
+ setFocused(field ? {
1423
+ field: fieldKeyOf(field),
1424
+ widget
1425
+ } : null);
1426
+ } else if (ctx.state.get().focused?.widget === widget) {
1427
+ leaving?.();
1428
+ leaving = ctx.clock.after(0, () => {
1429
+ leaving = null;
1430
+ setFocused(null);
1431
+ });
1432
+ }
1433
+ },
1434
+ goTo(row, select) {
1435
+ const widget = widgetObjectOf(row.ref);
1436
+ const stage = ctx.tryGet(StageToken);
1437
+ stage?.reveal(row.page, { rect: row.rect });
1438
+ clearPending();
1439
+ const target = targets.get(widget);
1440
+ if (target) {
1441
+ target.focus({ select });
1442
+ return true;
1443
+ }
1444
+ if (!stage) return false;
1445
+ pending = {
1446
+ widget,
1447
+ select,
1448
+ expire: ctx.clock.after(PENDING_MS, () => {
1449
+ if (pending?.widget === widget) pending = null;
1450
+ })
1451
+ };
1452
+ return true;
1453
+ },
1454
+ attach(widgetRef, target) {
1455
+ const widget = widgetObjectOf(widgetRef);
1456
+ targets.set(widget, target);
1457
+ if (pending?.widget === widget) {
1458
+ const { select } = pending;
1459
+ clearPending();
1460
+ target.focus({ select });
1461
+ }
1462
+ return () => {
1463
+ if (targets.get(widget) === target) targets.delete(widget);
1464
+ };
1465
+ }
1466
+ };
1467
+ }
1468
+ //#endregion
1469
+ //#region src/services/design.ts
1470
+ /**
1471
+ * Whether the form's widgets are lent to the annotation plugin now
1472
+ * (write/lending.ts): the session may design, the annotation plugin is there,
1473
+ * and the active tool doesn't fill. Then the annotation layer draws and edits
1474
+ * the widgets, and the form layer leaves them out.
1475
+ */
1476
+ function createDesign(ctx, siblings) {
1477
+ const interaction = ctx.tryGet(InteractionToken);
1478
+ return { lending: () => siblings.annotation() !== null && interaction !== null && ctx.allows("doc.forms.modify") && !(interaction.getActiveTool()?.enables.has("form-fill") ?? false) };
1479
+ }
1480
+ //#endregion
1481
+ //#region src/services/events.ts
1482
+ function createEvents(ctx) {
1483
+ return {
1484
+ valueChanged: ctx.events.source(),
1485
+ fieldCreated: ctx.events.source(),
1486
+ fieldUpdated: ctx.events.source(),
1487
+ fieldDeleted: ctx.events.source(),
1488
+ validationRejected: ctx.events.source(),
1489
+ resynced: ctx.events.source(),
1490
+ focusChanged: ctx.events.source()
1491
+ };
1492
+ }
1493
+ //#endregion
1494
+ //#region src/services/fill-rights.ts
1495
+ /**
1496
+ * Who may fill in, and sign, which field: the engine's own answer per field
1497
+ * (`ctx.allowsField`), so a control gated on it never disagrees with the
1498
+ * write. A field's group decides: a `fields:fill` (`fields:sign`) permission
1499
+ * for its group, or `doc.forms.fill` (`doc.sign`) for every field.
1500
+ */
1501
+ /** Whether the `fillable` setting lets people fill in a field of this family by hand. */
1502
+ const isFillableByHand = (fillable, family) => typeof fillable === "boolean" ? fillable : fillable.includes(family);
1503
+ function createFillRights(ctx, fields) {
1504
+ const mayFill = (field) => ctx.allowsField("fill", field);
1505
+ const maySign = (field) => ctx.allowsField("sign", field);
1506
+ const mayFillByHand = (field) => isFillableByHand(ctx.settings().get().fillable, field.family) && (field.family === "signature" ? maySign(field) : mayFill(field));
1507
+ /** The form's groups, `null` (no group) among them. */
1508
+ const groups = memo(() => [fields.view()], (index) => [...new Set((index.snapshot?.fields ?? []).map((field) => field.groupId))]);
1509
+ return {
1510
+ mayFill,
1511
+ maySign,
1512
+ mayFillByHand,
1513
+ takesInput: (field) => !field.readOnly && mayFillByHand(field),
1514
+ assertMayFill: (field, operation) => ctx.assertAllowedField("fill", field, operation),
1515
+ key: () => groups().map((groupId) => `${mayFill({ groupId }) ? 1 : 0}${maySign({ groupId }) ? 1 : 0}`).join("")
1516
+ };
1517
+ }
1518
+ //#endregion
1519
+ //#region src/services/formatted.ts
1520
+ /** The values remembered per field: enough for an undo or two. */
1521
+ const KEPT_PER_FIELD = 8;
1522
+ const valueOf = (field) => field.family === "text" || field.family === "combobox" ? field.value : null;
1523
+ function createFormattedTexts(ctx, fields) {
1524
+ const texts = /* @__PURE__ */ new Map();
1525
+ let version = 0;
1526
+ ctx.listen(ctx.changes.onStaged, (change) => {
1527
+ const view = fields.view();
1528
+ for (const op of change.shows) {
1529
+ if (op.type !== "forms.setAppearanceText") continue;
1530
+ const field = fieldByRef(view, op.field);
1531
+ const value = field ? valueOf(field) : null;
1532
+ if (!field || value === null) continue;
1533
+ const key = fieldKeyOf(field);
1534
+ const kept = texts.get(key) ?? /* @__PURE__ */ new Map();
1535
+ kept.delete(value);
1536
+ kept.set(value, op.text);
1537
+ while (kept.size > KEPT_PER_FIELD) kept.delete(kept.keys().next().value);
1538
+ texts.set(key, kept);
1539
+ version += 1;
1540
+ }
1541
+ });
1542
+ return {
1543
+ textOf(field) {
1544
+ const value = valueOf(field);
1545
+ return value === null ? null : texts.get(fieldKeyOf(field))?.get(value) ?? null;
1546
+ },
1547
+ version: () => version
1548
+ };
1549
+ }
1550
+ //#endregion
1551
+ //#region src/services/looks.ts
1552
+ /**
1553
+ * What a shown widget looks like now: the engine's picture, or the painter's
1554
+ * drawing of it (`@embedpdf/core-form`).
1555
+ *
1556
+ * A widget's look is everything its picture depends on: its size and turn,
1557
+ * its style, and what it shows (the value, as this session formatted it). Its
1558
+ * place isn't (a move keeps the look), nor the state a toggle shows (its
1559
+ * picture of every state is held). A widget is `pending` while its look in
1560
+ * the view isn't its confirmed look: a value typed or calculated, a restyle,
1561
+ * a field just placed. The layer then draws the painter's scene, as it does
1562
+ * while the picture it holds is older than the widget's look.
1563
+ */
1564
+ const NOTHING_SHOWN = Object.freeze([]);
1565
+ const numberOf = (ref) => ref.kind === "objectNumber" ? ref.objectNumber : -1;
1566
+ function createWidgetLooks({ fields, formatted, design, fonts }) {
1567
+ /** Moves when the fonts plugin may draw a widget's text differently. */
1568
+ const fontsEpoch = () => fonts()?.getPaintFontsEpoch() ?? 0;
1569
+ /**
1570
+ * The fonts `row` draws `text` in: the fonts plugin's (`null` while it finds them), else
1571
+ * `undefined`, the widget's standard font.
1572
+ */
1573
+ const paintFontsOf = (row, text) => fonts()?.getPaintFonts(row.fontFamily ?? "helvetica", text);
1574
+ /** What the widget's picture depends on, as one string. */
1575
+ const lookKeyOf = (row, field) => {
1576
+ const box = row.box ?? row.rect;
1577
+ const content = (() => {
1578
+ switch (field?.family) {
1579
+ case "text": return [
1580
+ formatted.textOf(field) ?? field.value,
1581
+ field.multiline,
1582
+ field.password,
1583
+ field.comb,
1584
+ field.maxLength
1585
+ ];
1586
+ case "combobox": return [formatted.textOf(field) ?? field.value];
1587
+ case "listbox": return [field.topIndex, field.options.map((option) => [option.label, option.selected])];
1588
+ default: return [field?.family ?? null];
1589
+ }
1590
+ })();
1591
+ return JSON.stringify([
1592
+ box.width,
1593
+ box.height,
1594
+ row.rotation ?? 0,
1595
+ row.color ?? null,
1596
+ row.interiorColor ?? null,
1597
+ row.strokeWidth ?? null,
1598
+ row.borderStyle ?? null,
1599
+ row.dashArray ?? null,
1600
+ row.fontFamily ?? null,
1601
+ row.fontSize ?? null,
1602
+ row.fontColor ?? null,
1603
+ row.textAlign ?? null,
1604
+ row.caption ?? null,
1605
+ row.checkStyle ?? null,
1606
+ content
1607
+ ]);
1608
+ };
1609
+ const lookOf = (index, number) => {
1610
+ const row = widgetRowOf(index, number);
1611
+ return row ? lookKeyOf(row, fieldForWidget(index, number)) : null;
1612
+ };
1613
+ const shownOn = memoByKey((_pageObjectNumber) => [
1614
+ fields.view(),
1615
+ fields.get(),
1616
+ formatted.version(),
1617
+ design.lending(),
1618
+ fontsEpoch()
1619
+ ], (pageObjectNumber, view, truth, _formatted, lent) => lent ? NOTHING_SHOWN : shownWidgetsOf(view, pageObjectNumber, (row) => {
1620
+ const number = numberOf(row.ref);
1621
+ return {
1622
+ pending: lookOf(view, number) !== lookOf(truth, number),
1623
+ pictureVersion: pictureVersionOf(truth, number)
1624
+ };
1625
+ }));
1626
+ /**
1627
+ * The painter's drawing of `row` (in the view's field, as this session formatted it) at `box`,
1628
+ * turned. While the fonts its text needs are found, `null`, so the engine's picture stays;
1629
+ * unless `now`, then in the widget's standard font.
1630
+ */
1631
+ const paint = (row, box, rotation, now = false) => {
1632
+ const field = fieldForWidget(fields.view(), numberOf(row.ref));
1633
+ if (!field) return null;
1634
+ const text = formatted.textOf(field);
1635
+ const shown = text === null ? {} : { text };
1636
+ const painted = paintFontsOf(row, widgetText(row, field, shown));
1637
+ if (painted === null && !now) return null;
1638
+ const drawing = widgetDrawing({
1639
+ ...row,
1640
+ box
1641
+ }, field, shown, painted ?? void 0);
1642
+ return drawing && widgetScene(drawing, {
1643
+ box,
1644
+ rotation
1645
+ });
1646
+ };
1647
+ /** The painter's drawing of a widget as the view has it; `null` for one it doesn't draw. */
1648
+ const sceneOf = memoByKey((number) => {
1649
+ const view = fields.view();
1650
+ const row = widgetRowOf(view, number);
1651
+ const field = row ? fieldForWidget(view, number) : null;
1652
+ return [
1653
+ row,
1654
+ field,
1655
+ field ? formatted.textOf(field) : null,
1656
+ fontsEpoch()
1657
+ ];
1658
+ }, (_number, row) => {
1659
+ const scene = row && paint(row, row.box ?? row.rect, row.rotation);
1660
+ return scene ? { scene } : null;
1661
+ });
1662
+ /**
1663
+ * How a browser draws text in a widget's font: the fonts plugin's CSS for
1664
+ * it (the first widget in a font that isn't standard reads the document's
1665
+ * fonts); without the plugin, the standard font the engine falls back to.
1666
+ */
1667
+ const fontCssOf = (font) => fonts()?.getFontCss(font) ?? standardFontCss(standardFontOf(font));
1668
+ /**
1669
+ * Until the fonts plugin has found a field's fonts, the layout in its own
1670
+ * font, when it isn't a standard one: its program, the fallbacks and the
1671
+ * last resort, as the fonts plugin draws it. The layout's numbers stay the
1672
+ * standard face's until then.
1673
+ */
1674
+ const inItsFont = (layout, font) => {
1675
+ if (!fonts() || !font || isStandardFontName(font)) return layout;
1676
+ const css = fontCssOf(font);
1677
+ return {
1678
+ ...layout,
1679
+ programs: css.programs,
1680
+ fontFamily: css.fontFamily,
1681
+ fontWeight: css.fontWeight,
1682
+ fontStyle: css.fontStyle
1683
+ };
1684
+ };
1685
+ return {
1686
+ listShownWidgets: (pageObjectNumber) => shownOn(pageObjectNumber),
1687
+ getWidgetPainting: (ref) => sceneOf(numberOf(ref)),
1688
+ /** The widget's look in the view isn't its confirmed look yet: it draws live until its picture is. */
1689
+ isPending: (ref) => {
1690
+ const number = numberOf(ref);
1691
+ return lookOf(fields.view(), number) !== lookOf(fields.get(), number);
1692
+ },
1693
+ /**
1694
+ * How the painter draws a widget row live, upright in a box (where a gesture has it); `null`
1695
+ * for one whose field it doesn't draw (a signature).
1696
+ */
1697
+ painterOf: (row) => {
1698
+ const field = fieldForWidget(fields.view(), numberOf(row.ref));
1699
+ return field && paints(field) ? (box) => paint(row, box, 0, true) ?? [] : null;
1700
+ },
1701
+ getTextEditorLayout: (ref, text) => {
1702
+ const view = fields.view();
1703
+ const number = numberOf(ref);
1704
+ const row = widgetRowOf(view, number);
1705
+ const field = row ? fieldForWidget(view, number) : null;
1706
+ if (!row || !field) return null;
1707
+ const painted = paintFontsOf(row, widgetText(row, field, { text }));
1708
+ const layout = textEditorLayout(row, field, text, painted ?? void 0);
1709
+ return layout && (painted ? layout : inItsFont(layout, row.fontFamily ?? null));
1710
+ },
1711
+ getWidgetFontCss: (ref) => {
1712
+ const row = widgetRowOf(fields.view(), numberOf(ref));
1713
+ return row ? fontCssOf(row.fontFamily ?? "helvetica") : null;
1714
+ }
1715
+ };
1716
+ }
1717
+ //#endregion
1718
+ //#region src/services/pictures.ts
1719
+ /**
1720
+ * The engine's pictures of each page's widgets, through the render plugin's
1721
+ * one door. The form layer draws them, and the annotation plugin draws the
1722
+ * widgets it borrows from the same ones (design mode), so switching modes
1723
+ * fetches nothing. A page's pictures depend on its widgets' picture versions
1724
+ * (the mirror's) and nothing else: a checkbox that only switches its state
1725
+ * fetches nothing.
1726
+ */
1727
+ const NO_PICTURES = Object.freeze([]);
1728
+ function createWidgetPictures(fields, { render }) {
1729
+ /** The page's widgets, as the engine confirmed them, each at its picture version. */
1730
+ const itemsOn = memoByKey((_pageObjectNumber) => [fields.get()], (pageObjectNumber, index) => (index.snapshot?.widgets ?? []).flatMap((row) => row.page.objectNumber === pageObjectNumber && row.ref.kind === "objectNumber" ? [{
1731
+ ref: row.ref,
1732
+ version: pictureVersionOf(index, row.ref.objectNumber)
1733
+ }] : []));
1734
+ const epochOn = memoByKey((pageObjectNumber) => [itemsOn(pageObjectNumber)], (_pageObjectNumber, items) => items.map(({ ref, version }) => `${ref.kind === "objectNumber" ? ref.objectNumber : ""}@${version}`).sort().join("|"));
1735
+ return {
1736
+ epoch: (page) => epochOn(page.objectNumber),
1737
+ render: (page, scale, signal) => {
1738
+ const renderer = render();
1739
+ return renderer ? renderer.renderAppearances(page, {
1740
+ family: "widgets",
1741
+ scale,
1742
+ items: itemsOn(page.objectNumber),
1743
+ ...signal ? { signal } : {}
1744
+ }) : Promise.resolve(NO_PICTURES);
1745
+ },
1746
+ versionOf: (widget) => widget.kind === "objectNumber" ? pictureVersionOf(fields.get(), widget.objectNumber) : 0
1747
+ };
216
1748
  }
217
1749
  //#endregion
218
- //#region src/mutationQueue.ts
219
- /** Small promise-tail queue: failures never poison later mutations. */
220
- function createSerialMutationQueue() {
221
- let tail = Promise.resolve();
222
- return (operation) => {
223
- const result = tail.then(operation, operation);
224
- tail = result.then(() => void 0, () => void 0);
225
- return result;
1750
+ //#region src/services/scripting.ts
1751
+ function createScriptingSeam(ctx, siblings) {
1752
+ let pipeline = null;
1753
+ const pipelineOf = () => {
1754
+ if (pipeline) return pipeline;
1755
+ const realm = siblings.actions()?.scriptRealm ?? null;
1756
+ if (!realm) return null;
1757
+ const made = createFormScriptingController({
1758
+ document: () => ctx.document(),
1759
+ transaction: realm.transaction.bind(realm),
1760
+ budget: realm.budget
1761
+ });
1762
+ ctx.cleanup(() => made.dispose());
1763
+ pipeline = made;
1764
+ return made;
1765
+ };
1766
+ const settings = ctx.settings();
1767
+ const controller = () => settings.get().validation === "scripts" ? pipelineOf() : null;
1768
+ let warnedNoRealm = false;
1769
+ const scriptsFor = (form) => {
1770
+ if (!formHasScripts(form)) return null;
1771
+ if (!pipelineOf() && !warnedNoRealm && settings.get().validation === "scripts") {
1772
+ warnedNoRealm = true;
1773
+ console.warn("[form] this form has scripts, but they don't run: add the actions plugin with JavaScript on (`actionsPlugin({ javascript: { enabled: true, sandboxFactory } })`), or set the form's `validation` to 'none' to fill it in without them.");
1774
+ }
1775
+ return controller();
1776
+ };
1777
+ let warmed = false;
1778
+ return {
1779
+ /** The script pipeline when the document's scripts run, else `null`. */
1780
+ controller,
1781
+ /** The script pipeline for a write to this form: `null` too when no field has a script. */
1782
+ scriptsFor,
1783
+ /** Start the realm before the first write needs it, once, when the form has scripts. */
1784
+ warm(form) {
1785
+ if (warmed || !form.snapshot) return;
1786
+ const scripts = scriptsFor(form);
1787
+ if (!scripts) return;
1788
+ warmed = true;
1789
+ scripts.warm(form.snapshot).catch(() => {});
1790
+ },
1791
+ /** Script results (UI effects, diagnostics, errors) are surfaced through the
1792
+ * actions plugin, with the origin that caused them. */
1793
+ surface: (result, origin) => {
1794
+ siblings.actions()?.surfaceScriptCommit(result, {
1795
+ origin,
1796
+ realm: "document"
1797
+ });
1798
+ }
226
1799
  };
227
1800
  }
228
1801
  //#endregion
229
- //#region src/scripting.ts
230
- const refKey = (ref) => ref.kind === "objectNumber" ? `obj:${ref.fieldObjectNumber}` : `fqn:${ref.name}`;
231
- const sameRef = (left, right) => refKey(left) === refKey(right);
232
- const cloneValue = (value) => Array.isArray(value) ? [...value] : value;
233
- const sameValue = (left, right) => Array.isArray(left) && Array.isArray(right) ? left.length === right.length && left.every((value, index) => value === right[index]) : left === right;
234
- function cloneFields(fields) {
235
- return fields.map((field) => ({
236
- ...field,
237
- ref: { ...field.ref },
238
- value: cloneValue(field.value),
239
- defaultValue: cloneValue(field.defaultValue),
240
- ...field.options ? { options: field.options.map((option) => ({ ...option })) } : {}
241
- }));
242
- }
243
- function fieldByRef(fields, ref) {
244
- return fields.find((field) => sameRef(field.ref, ref));
245
- }
246
- function snapshotField(snapshot, ref) {
247
- return snapshot.fields.find((field) => sameRef(field.ref, ref));
1802
+ //#region src/services/siblings.ts
1803
+ /** The optional sibling planes, looked up each time they're used, not once
1804
+ * at construction: what a sibling is depends on no creation order. A
1805
+ * fill-only setup may have none; every area guards on null. */
1806
+ function resolveSiblings(ctx) {
1807
+ return {
1808
+ /** The annotation plugin: design mode's selection, tools, ghosts and placement previews. */
1809
+ annotation: () => ctx.tryGet(AnnotationToken$1),
1810
+ /** The script realm owner and the one surface port for script results. */
1811
+ actions: () => ctx.tryGet(ActionsToken$1),
1812
+ /** The page renderer: the widgets' pictures, shared by the form layer and design mode. */
1813
+ render: () => ctx.tryGet(RenderToken$1)
1814
+ };
248
1815
  }
249
- function scriptValueFromFormValue(field, value) {
250
- if (field.family === "text" && value.type === "text") return value.value;
251
- if ((field.family === "checkbox" || field.family === "radio") && value.type === "toggle") return value.state ?? "Off";
252
- if (field.family === "combobox" && value.type === "choice") return value.values[0] ?? "";
253
- if (field.family === "listbox" && value.type === "choice") return [...value.values];
254
- throw new Error(`Form value type '${value.type}' does not match field family '${field.family}'`);
1816
+ //#endregion
1817
+ //#region src/services/index.ts
1818
+ function createServices(ctx) {
1819
+ const siblings = resolveSiblings(ctx);
1820
+ const events = createEvents(ctx);
1821
+ const fields = createFieldsMirror(ctx, events);
1822
+ const design = createDesign(ctx, siblings);
1823
+ const formatted = createFormattedTexts(ctx, fields);
1824
+ return {
1825
+ fields,
1826
+ rights: createFillRights(ctx, fields),
1827
+ events,
1828
+ cursor: createCursor(ctx, fields, events),
1829
+ siblings,
1830
+ scripting: createScriptingSeam(ctx, siblings),
1831
+ design,
1832
+ formatted,
1833
+ pictures: createWidgetPictures(fields, siblings),
1834
+ looks: createWidgetLooks({
1835
+ fields,
1836
+ formatted,
1837
+ design,
1838
+ fonts: () => ctx.tryGet(FontsToken)
1839
+ }),
1840
+ enqueue: ctx.serialQueue("writes"),
1841
+ keyOf: (ref) => canonicalKey(fields.view(), ref)
1842
+ };
255
1843
  }
256
- function formValueFromScriptValue(field) {
257
- switch (field.family) {
258
- case "text": return {
259
- type: "text",
260
- value: String(field.value ?? "")
261
- };
262
- case "checkbox":
263
- case "radio": return {
264
- type: "toggle",
265
- state: field.value === null || field.value === void 0 || String(field.value) === "Off" ? null : String(field.value)
1844
+ //#endregion
1845
+ //#region src/write/activation.ts
1846
+ /**
1847
+ * Widget activation and the widget DOM-event feed into the actions plane.
1848
+ * A click first offers the widget's `/A` tree to the dispatcher; only a
1849
+ * tree-less widget falls back to the form's own scripted activation.
1850
+ */
1851
+ function createActivation(ctx, services, { fill }) {
1852
+ const { fields, scripting, cursor } = services;
1853
+ /** The widget's activation action, from its row in the form. */
1854
+ const annotationActivation = async (ref) => {
1855
+ await fields.settled();
1856
+ return (ref.kind === "objectNumber" ? widgetRowOf(fields.view(), ref.objectNumber) : null)?.actions?.activate ?? null;
1857
+ };
1858
+ /** The widget's activation through the form's own scripts: what they change is one fill. */
1859
+ const activateThroughScripts = async (ref, annotationRef, options) => {
1860
+ if (!scripting.controller()) return {
1861
+ status: "unchanged",
1862
+ scripted: false,
1863
+ uiEffects: [],
1864
+ diagnostics: []
266
1865
  };
267
- case "combobox": return {
268
- type: "choice",
269
- values: Array.isArray(field.value) ? field.value.slice(0, 1) : [String(field.value ?? "")]
1866
+ const action = await annotationActivation(annotationRef);
1867
+ if (!action) return {
1868
+ status: "unchanged",
1869
+ scripted: true,
1870
+ uiEffects: [],
1871
+ diagnostics: []
270
1872
  };
271
- case "listbox": return {
272
- type: "choice",
273
- values: Array.isArray(field.value) ? [...field.value] : [String(field.value ?? "")]
1873
+ const { result } = await fill({
1874
+ ops: [],
1875
+ scripts: {
1876
+ kind: "activate",
1877
+ field: ref,
1878
+ action
1879
+ },
1880
+ origin: "user"
1881
+ }, options);
1882
+ return result;
1883
+ };
1884
+ const widgetSource = (field, annotationRef) => ({
1885
+ kind: "widget",
1886
+ field,
1887
+ annotation: annotationRef,
1888
+ page: annotationRef.page
1889
+ });
1890
+ /**
1891
+ * One shared hover pump (an exit and the next enter delivered as one
1892
+ * ordered pair; intermediate hovers skipped), created on first use.
1893
+ */
1894
+ let widgetPump = null;
1895
+ const widgetHoverPump = (actions) => {
1896
+ widgetPump ?? (widgetPump = createHoverPump(actions.dispatch));
1897
+ return widgetPump;
1898
+ };
1899
+ const widgetHoverFlags = (annotationRef) => {
1900
+ const row = annotationRef.kind === "objectNumber" ? widgetRowOf(fields.view(), annotationRef.objectNumber) : null;
1901
+ if (!row) return null;
1902
+ return {
1903
+ enter: Boolean(row.actions?.cursorEnter?.root),
1904
+ exit: Boolean(row.actions?.cursorExit?.root)
274
1905
  };
275
- default: return null;
276
- }
277
- }
278
- function applyEffects(overlay, effects) {
279
- for (const effect of effects) {
280
- if (effect.kind === "reset") {
281
- for (const ref of effect.refs) {
282
- const field = fieldByRef(overlay.fields, ref);
283
- if (!field) continue;
284
- field.value = cloneValue(field.defaultValue);
285
- overlay.resetKeys.add(refKey(ref));
1906
+ };
1907
+ return { api: {
1908
+ activateWidget: async (annotationRef, options) => {
1909
+ const field = fieldForWidget(fields.view(), widgetObjectOf(annotationRef));
1910
+ if (!field) throw new PluginError("not-found", "form", "no form field owns this widget");
1911
+ const actions = ctx.tryGet(ActionsToken);
1912
+ if (actions) {
1913
+ const result = await ctx.cancellable(options?.signal, actions.dispatch({
1914
+ scope: "activate",
1915
+ ref: annotationRef,
1916
+ page: annotationRef.page,
1917
+ source: widgetSource(field.ref, annotationRef)
1918
+ }));
1919
+ if (!(result.status === "inert" && result.steps.length === 0 && result.diagnostics.length === 0)) return {
1920
+ kind: "dispatched",
1921
+ result
1922
+ };
286
1923
  }
287
- continue;
288
- }
289
- const field = fieldByRef(overlay.fields, effect.ref);
290
- if (!field) continue;
291
- const key = refKey(effect.ref);
292
- if (effect.kind === "setValue") {
293
- field.value = scriptValueFromFormValue(field, effect.value);
294
- overlay.resetKeys.delete(key);
295
- } else if (effect.kind === "setDisplay") field.display = effect.display;
296
- else overlay.appearances.set(key, {
297
- ref: effect.ref,
298
- text: effect.text
299
- });
300
- }
301
- }
302
- function canonicalEffects(overlay) {
303
- const effects = [];
304
- const resets = [];
305
- for (const field of overlay.fields) {
306
- const original = fieldByRef(overlay.original, field.ref);
307
- if (!original) continue;
308
- if (!sameValue(original.value, field.value)) {
309
- const key = refKey(field.ref);
310
- if (overlay.resetKeys.has(key) && sameValue(field.value, field.defaultValue)) resets.push(field.ref);
311
- else {
312
- const value = formValueFromScriptValue(field);
313
- if (value) effects.push({
314
- kind: "setValue",
315
- ref: field.ref,
316
- value
1924
+ return {
1925
+ kind: "form",
1926
+ result: await activateThroughScripts(field.ref, annotationRef, options)
1927
+ };
1928
+ },
1929
+ notifyWidgetEvent: (fieldRef, annotationRef, event) => {
1930
+ if (event === "focus" || event === "blur") cursor.note(event, fieldRef, annotationRef);
1931
+ const actions = ctx.tryGet(ActionsToken);
1932
+ if (!actions) return;
1933
+ const source = widgetSource(fieldRef, annotationRef);
1934
+ if (event === "cursorEnter" || event === "cursorExit") {
1935
+ if (event === "cursorExit") {
1936
+ widgetHoverPump(actions).hover(null);
1937
+ return;
1938
+ }
1939
+ const flags = widgetHoverFlags(annotationRef);
1940
+ if (flags && !flags.enter && !flags.exit) return;
1941
+ widgetHoverPump(actions).hover({
1942
+ ref: annotationRef,
1943
+ page: annotationRef.page,
1944
+ source,
1945
+ ...flags ? { events: flags } : {}
317
1946
  });
1947
+ return;
318
1948
  }
1949
+ if (event === "focus") scripting.warm(fields.view());
1950
+ actions.dispatch({
1951
+ scope: "annotation",
1952
+ event,
1953
+ ref: annotationRef,
1954
+ page: annotationRef.page,
1955
+ source
1956
+ });
319
1957
  }
320
- if (original.display !== field.display) effects.push({
321
- kind: "setDisplay",
322
- ref: field.ref,
323
- display: field.display
1958
+ } };
1959
+ }
1960
+ //#endregion
1961
+ //#region src/services/object-numbers.ts
1962
+ function createObjectNumbers(ctx) {
1963
+ const held = [];
1964
+ let watching = false;
1965
+ const watchLost = () => {
1966
+ if (watching || !ctx.doc) return;
1967
+ watching = true;
1968
+ ctx.doc.objectNumbers.onLost(({ numbers }) => {
1969
+ const lost = new Set(numbers);
1970
+ held.splice(0, held.length, ...held.filter((number) => !lost.has(number)));
324
1971
  });
325
- }
326
- if (resets.length > 0) effects.unshift({
327
- kind: "reset",
328
- refs: resets
329
- });
330
- effects.push(...Array.from(overlay.appearances.values(), ({ ref, text }) => ({
331
- kind: "setAppearanceText",
332
- ref,
333
- text
334
- })));
335
- return effects;
336
- }
337
- function scriptError(message) {
1972
+ };
1973
+ const takeNow = (count) => {
1974
+ watchLost();
1975
+ while (held.length < count) {
1976
+ const number = ctx.changes.takeObjectNumber();
1977
+ if (number === null) return null;
1978
+ held.push(number);
1979
+ }
1980
+ return held.splice(0, count);
1981
+ };
338
1982
  return {
339
- kind: "invalid-output",
340
- message
341
- };
342
- }
343
- function utf8Length(value) {
344
- let length = 0;
345
- for (let index = 0; index < value.length; index += 1) {
346
- const code = value.charCodeAt(index);
347
- if (code < 128) length += 1;
348
- else if (code < 2048) length += 2;
349
- else if (code >= 55296 && code <= 56319 && index + 1 < value.length) {
350
- length += 4;
351
- index += 1;
352
- } else length += 3;
353
- }
354
- return length;
355
- }
356
- function seedFrom(documentId, sequence) {
357
- let hash = 2166136261;
358
- for (const char of `${documentId}:${sequence}`) {
359
- hash ^= char.charCodeAt(0);
360
- hash = Math.imul(hash, 16777619);
361
- }
362
- return hash >>> 0;
1983
+ takeNow,
1984
+ async take(count) {
1985
+ for (;;) {
1986
+ const taken = takeNow(count);
1987
+ if (taken) return taken;
1988
+ await ctx.changes.reserveObjectNumbers(count - held.length);
1989
+ }
1990
+ }
1991
+ };
363
1992
  }
364
- function resolvedIdentity(doc, config) {
365
- const claims = doc.security.identity;
366
- const supplied = typeof config.identity === "function" ? config.identity() : config.identity ?? {};
1993
+ //#endregion
1994
+ //#region src/write/next-in-line.ts
1995
+ const fits = (box, page) => box.x >= 0 && box.y >= 0 && box.x + box.width <= page.width && box.y + box.height <= page.height;
1996
+ /** The box after `boxes`, the field's widgets on one page in the field's order. */
1997
+ function nextInLine(boxes, page) {
1998
+ const last = boxes.at(-1);
1999
+ if (!last) return {
2000
+ x: 0,
2001
+ y: 0,
2002
+ width: 0,
2003
+ height: 0
2004
+ };
2005
+ const { width, height } = last;
2006
+ const previous = boxes.at(-2);
2007
+ const step = previous && (previous.x !== last.x || previous.y !== last.y) ? {
2008
+ x: last.x - previous.x,
2009
+ y: last.y - previous.y
2010
+ } : {
2011
+ x: 0,
2012
+ y: height * 1.5
2013
+ };
2014
+ const next = {
2015
+ x: last.x + step.x,
2016
+ y: last.y + step.y,
2017
+ width,
2018
+ height
2019
+ };
2020
+ if (fits(next, page)) return next;
2021
+ const column = Math.abs(step.y) >= Math.abs(step.x);
2022
+ const left = Math.min(...boxes.map((box) => box.x));
2023
+ const top = Math.min(...boxes.map((box) => box.y));
2024
+ const right = Math.max(...boxes.map((box) => box.x + box.width));
2025
+ const bottom = Math.max(...boxes.map((box) => box.y + box.height));
2026
+ const gap = Math.max(column ? Math.abs(step.y) - height : Math.abs(step.x) - width, 0);
2027
+ const restart = column ? {
2028
+ x: right + (gap || width / 2),
2029
+ y: top,
2030
+ width,
2031
+ height
2032
+ } : {
2033
+ x: left,
2034
+ y: bottom + (gap || height / 2),
2035
+ width,
2036
+ height
2037
+ };
2038
+ if (fits(restart, page)) return restart;
367
2039
  return {
368
- name: supplied.name ?? claims?.display_name ?? claims?.user_id ?? "",
369
- loginName: supplied.loginName ?? claims?.user_id ?? "",
370
- corporation: supplied.corporation ?? claims?.group_id ?? "",
371
- email: supplied.email ?? ""
372
- };
373
- }
374
- function pageNumberFor(meta, field) {
375
- const pon = field.widgets.find((widget) => widget.pageObjectNumber > 0)?.pageObjectNumber;
376
- if (!meta || pon === void 0) return 0;
377
- const index = meta.pages.findIndex((page) => page.pageObjectNumber === pon);
378
- return Math.max(0, index);
379
- }
380
- function statusFromEffects(result) {
381
- if (result.results.some(({ status }) => status === "failed" || status === "skipped")) return "failed";
382
- if (result.results.some(({ status }) => status === "rejected")) return "failed";
383
- return result.results.some(({ status }) => status === "applied") ? "applied" : "unchanged";
384
- }
385
- var FormScriptingController = class {
386
- constructor(options) {
387
- this.options = options;
388
- this.sandboxPromise = null;
389
- this.booted = false;
390
- this.disposed = false;
391
- this.sequence = 0;
392
- }
393
- dispose() {
394
- if (this.disposed) return;
395
- this.disposed = true;
396
- this.sandboxPromise?.then((sandbox) => sandbox.dispose()).catch(() => void 0);
397
- }
398
- async commit(snapshot, ref, proposed) {
399
- return this.transact(snapshot, ref, proposed);
400
- }
401
- /** Execute one originating widget's activation action (`/A`, including `/Next`). */
402
- async activate(snapshot, ref, action) {
403
- return this.transact(snapshot, ref, void 0, action);
404
- }
405
- /** Run lazy document boot plus the `/CO` chain without a user field change. */
406
- async recalculate(snapshot) {
407
- const target = snapshot.calculationOrder.find((ref) => ref !== null && snapshotField(snapshot, ref) !== void 0) ?? snapshot.fields[0]?.ref;
408
- if (!target) return {
409
- status: "unchanged",
410
- scripted: true,
411
- effectsResult: null,
412
- uiEffects: [],
413
- diagnostics: []
414
- };
415
- return this.transact(snapshot, target);
416
- }
417
- async transact(snapshot, ref, proposed, activation) {
418
- if (this.disposed) throw new Error("Form scripting controller is disposed");
419
- const target = snapshotField(snapshot, ref);
420
- if (!target) return this.failed([], [], scriptError(`Form field '${refKey(ref)}' no longer exists`));
421
- const original = scriptFieldsFromSnapshot(snapshot);
422
- const overlay = {
423
- original,
424
- fields: cloneFields(original),
425
- resetKeys: /* @__PURE__ */ new Set(),
426
- appearances: /* @__PURE__ */ new Map()
427
- };
428
- const targetInput = fieldByRef(overlay.fields, ref);
429
- if (!targetInput) return this.failed([], [], scriptError(`Form field '${refKey(ref)}' has no script view`));
430
- const hasProposedValue = proposed !== void 0;
431
- let proposedValue = cloneValue(targetInput.value);
432
- if (proposed) try {
433
- proposedValue = scriptValueFromFormValue(targetInput, proposed);
2040
+ x: Math.min(Math.max(next.x, 0), Math.max(page.width - width, 0)),
2041
+ y: Math.min(Math.max(next.y, 0), Math.max(page.height - height, 0)),
2042
+ width,
2043
+ height
2044
+ };
2045
+ }
2046
+ //#endregion
2047
+ //#region src/write/fields.ts
2048
+ /**
2049
+ * Building the form: every design verb is one change on the document's queue
2050
+ * (`ctx.changes`). It shows at once (the fields mirror predicts it), it is a
2051
+ * step of the history, and it resolves with the engine's answer. A create
2052
+ * takes its field's and widgets' object numbers first, so their refs are final
2053
+ * from the first frame and the new widget can be selected straight away.
2054
+ */
2055
+ /**
2056
+ * A widget's look, as `addWidget()` copies it from the field's last widget onto the new one:
2057
+ * the engine's widget style fields (`WIDGET_STYLE_NAMES`), and its turn.
2058
+ */
2059
+ const LOOK = [
2060
+ "color",
2061
+ "interiorColor",
2062
+ "strokeWidth",
2063
+ "borderStyle",
2064
+ "dashArray",
2065
+ "fontFamily",
2066
+ "fontSize",
2067
+ "fontColor",
2068
+ "textAlign",
2069
+ "caption",
2070
+ "checkStyle",
2071
+ "rotation"
2072
+ ];
2073
+ const lookOf = (widget) => {
2074
+ if (!widget) return {};
2075
+ const held = widget;
2076
+ const look = {};
2077
+ for (const name of LOOK) if (held[name] !== void 0 && held[name] !== null) look[name] = held[name];
2078
+ return look;
2079
+ };
2080
+ /**
2081
+ * The export value a field's new widget gets when none is given: a radio group's next free
2082
+ * `Choice<n>` (the radio tool names its first button `Choice1`), a checkbox's own value, so
2083
+ * the boxes check together. Other families take none.
2084
+ */
2085
+ function exportValueFor(field) {
2086
+ if (field.family === "checkbox") return field.exportValue;
2087
+ if (field.family !== "radio") return void 0;
2088
+ const taken = new Set(field.widgets.map((widget) => widget.exportValue));
2089
+ let n = field.widgets.length + 1;
2090
+ while (taken.has(`Choice${n}`)) n += 1;
2091
+ return `Choice${n}`;
2092
+ }
2093
+ /** Whether the field's dictionary is its only widget's too, which adding a widget splits. */
2094
+ const isMerged = (field) => field.ref.kind === "objectNumber" && field.widgets.some((widget) => widget.objectNumber === field.ref.objectNumber);
2095
+ const MODIFY = "doc.forms.modify";
2096
+ const SCRIPT = "doc.forms.script";
2097
+ function createFieldWrites(ctx, { fields, enqueue }) {
2098
+ const numbers = createObjectNumbers(ctx);
2099
+ /** Refuse up front without `doc.forms.modify`, and without `doc.forms.script` when it writes scripts. */
2100
+ const allow = (operation, scripts = false) => {
2101
+ ctx.assertAllowed(MODIFY, operation);
2102
+ if (scripts) ctx.assertAllowed(SCRIPT, operation);
2103
+ };
2104
+ /** Stage one design op as its own change: it shows at once, and undoing it shows the form as it was. */
2105
+ const stage = (verb, op) => ctx.changes.stage({
2106
+ label: { key: `form.${verb}` },
2107
+ ops: [op],
2108
+ undo: undoLookOf(fields.view(), [op])
2109
+ });
2110
+ /** The engine's answer to a staged design change: its one item. */
2111
+ const answer = async (change, options) => {
2112
+ try {
2113
+ return (await ctx.cancellable(options?.signal, change.result)).items[0];
434
2114
  } catch (error) {
435
- return this.failed([], [], scriptError(error instanceof Error ? error.message : String(error)));
2115
+ throw toPluginError("form", error);
436
2116
  }
437
- const uiEffects = [];
438
- const diagnostics = [];
439
- const meta = this.options.document();
440
- const nowMs = this.options.config.now?.() ?? Date.now();
441
- const inputBase = {
442
- document: {
443
- id: this.options.doc.id,
444
- fileName: this.options.config.fileName?.() ?? meta?.name ?? this.options.doc.id,
445
- pageCount: meta?.pageCount ?? 0,
446
- pageNumber: pageNumberFor(meta, target)
2117
+ };
2118
+ const create = async (draft, options) => {
2119
+ allow("form.create", draftWritesScripts(draft));
2120
+ const count = 1 + (draft.widgets?.length ?? 0);
2121
+ const [objectNumber, ...widgetObjectNumbers] = numbers.takeNow(count) ?? await numbers.take(count);
2122
+ const change = stage("create", {
2123
+ type: "forms.create",
2124
+ draft,
2125
+ objectNumber,
2126
+ widgetObjectNumbers
2127
+ });
2128
+ return { field: (await answer(change, options)).field };
2129
+ };
2130
+ const addWidget = async (ref, placement = {}, options) => {
2131
+ allow("form.addWidget", writesScripts(placement.actions));
2132
+ const index = fields.view();
2133
+ const field = fieldByRef(index, ref);
2134
+ if (!field) throw new PluginError("not-found", "form", "no form field has this ref");
2135
+ const rows = field.widgets.map((widget) => widgetRowOf(index, widget.objectNumber)).filter((row) => row !== null);
2136
+ const last = rows.at(-1);
2137
+ const page = placement.page ?? last?.page;
2138
+ if (!page) throw new PluginError("invalid-input", "form", "the field shows on no page: give `page` and `rect`");
2139
+ const size = ctx.getPage(page)?.size;
2140
+ const onPage = rows.filter((row) => row.page.objectNumber === page.objectNumber);
2141
+ const rect = placement.rect ?? placement.box ?? (size && onPage.length > 0 ? nextInLine(onPage.map((row) => row.box), size) : void 0);
2142
+ if (!rect) throw new PluginError("invalid-input", "form", "no widget of the field on that page: give `rect`");
2143
+ const exportValue = placement.exportValue ?? exportValueFor(field);
2144
+ const split = isMerged(field);
2145
+ const [objectNumber, splitObjectNumber] = numbers.takeNow(split ? 2 : 1) ?? await numbers.take(split ? 2 : 1);
2146
+ const change = stage("addWidget", {
2147
+ type: "forms.addWidget",
2148
+ field: field.ref,
2149
+ placement: {
2150
+ ...lookOf(last),
2151
+ ...placement,
2152
+ page,
2153
+ ...placement.box ? {} : { rect },
2154
+ ...exportValue === void 0 ? {} : { exportValue }
447
2155
  },
448
- identity: resolvedIdentity(this.options.doc, this.options.config),
449
- environment: {
450
- nowMs,
451
- utcOffsetMinutes: this.options.config.utcOffsetMinutes?.() ?? -new Date(nowMs).getTimezoneOffset(),
452
- randomSeed: this.options.config.randomSeed?.() ?? seedFrom(this.options.doc.id, this.sequence++)
453
- }
2156
+ objectNumber,
2157
+ ...split ? { splitObjectNumber } : {}
2158
+ });
2159
+ const item = await answer(change, options);
2160
+ const widget = item.widgets.find((row) => row.ref.kind === "objectNumber" && row.ref.objectNumber === objectNumber) ?? item.widgets.at(-1);
2161
+ return {
2162
+ field: item.field,
2163
+ widget
454
2164
  };
455
- const budget = this.options.config.budget ?? DEFAULT_SCRIPT_BUDGET;
456
- let executionMs = 0;
457
- let aggregateOutputSize = 0;
458
- const consume = (output, phase) => {
459
- aggregateOutputSize += utf8Length(JSON.stringify(output));
460
- uiEffects.push(...output.uiEffects.map((effect) => ({
461
- ...effect,
462
- phase
463
- })));
464
- diagnostics.push(...output.diagnostics);
465
- if (aggregateOutputSize > budget.maxOutputBytes) return {
466
- kind: "budget",
467
- message: `Form script transaction output exceeded ${budget.maxOutputBytes} bytes`
468
- };
469
- return output.error ?? null;
2165
+ };
2166
+ return { api: {
2167
+ create,
2168
+ addWidget,
2169
+ update: async (ref, patch, options) => {
2170
+ allow("form.update", writesScripts(patch.actions));
2171
+ const change = stage("update", {
2172
+ type: "forms.update",
2173
+ field: ref,
2174
+ patch
2175
+ });
2176
+ return { field: (await answer(change, options)).field };
2177
+ },
2178
+ reorderCalculations: async (fields, position, options) => {
2179
+ allow("form.reorderCalculations");
2180
+ const change = stage("reorderCalculations", {
2181
+ type: "forms.reorderCalculations",
2182
+ fields,
2183
+ position
2184
+ });
2185
+ return { calculationOrder: (await answer(change, options)).calculationOrder };
2186
+ },
2187
+ delete: async (ref, options) => {
2188
+ allow("form.delete");
2189
+ await answer(stage("delete", {
2190
+ type: "forms.delete",
2191
+ field: ref
2192
+ }), options);
2193
+ },
2194
+ removeWidget: async (ref, widget, options) => {
2195
+ allow("form.removeWidget");
2196
+ const change = stage("removeWidget", {
2197
+ type: "forms.removeWidget",
2198
+ field: ref,
2199
+ widget
2200
+ });
2201
+ return { field: (await answer(change, options)).field };
2202
+ },
2203
+ updateWidget: async (widget, patch, options) => {
2204
+ allow("form.updateWidget");
2205
+ const change = stage("updateWidget", {
2206
+ type: "forms.updateWidget",
2207
+ widget,
2208
+ patch
2209
+ });
2210
+ return { widget: (await answer(change, options)).widget };
2211
+ },
2212
+ deleteWidget: async (widget, options) => {
2213
+ allow("form.deleteWidget");
2214
+ const change = stage("deleteWidget", {
2215
+ type: "forms.deleteWidget",
2216
+ widget
2217
+ });
2218
+ return { field: (await answer(change, options)).field };
2219
+ },
2220
+ repair: async (options) => {
2221
+ allow("form.repair");
2222
+ const { signal, ...repair } = options ?? {};
2223
+ const run = () => options ? ctx.doc.forms.repair(repair) : ctx.doc.forms.repair();
2224
+ return enqueue(() => ctx.cancellable(signal, run()), options);
2225
+ }
2226
+ } };
2227
+ }
2228
+ //#endregion
2229
+ //#region src/write/fill.ts
2230
+ /**
2231
+ * Filling the form in. Every fill is one change, whatever started it: a value, a batch of
2232
+ * values, a reset, a widget's activation, a script's or an action's effects.
2233
+ *
2234
+ * 1. What the user did shows at once: the change is held with the user's own ops.
2235
+ * 2. When its turn comes, the form's scripts run against the view, in one realm transaction.
2236
+ * 3. Inside that transaction the change gets every op the scripts asked for, and is sent.
2237
+ *
2238
+ * Fills take turns up to their send, not their answer: the next fill's scripts read this one in
2239
+ * the view while the engine answers it. A validation refusal cancels the change. A change the
2240
+ * engine refuses leaves the view, and the calculations run again against what is left, outside
2241
+ * the history: the fills after it were calculated with its values.
2242
+ */
2243
+ /** A refused value writes only what the document's open scripts did, outside the history. */
2244
+ const SCRIPTS_LABEL = { key: "form.scripts" };
2245
+ /** The calculations again, outside the history: after a refused fill, or a stale one. */
2246
+ const RECALCULATE_LABEL = { key: "form.recalculate" };
2247
+ /** The changes that, refused, leave calculations made with their values. */
2248
+ const FILLS = /* @__PURE__ */ new Set(["form.fill", "form.reset"]);
2249
+ const sameOp = (left, right) => JSON.stringify(left) === JSON.stringify(right);
2250
+ const sameValue = (left, right) => JSON.stringify(left?.valueEntry ?? null) === JSON.stringify(right?.valueEntry ?? null);
2251
+ function createFill(ctx, { fields, scripting, enqueue }) {
2252
+ const labelOf = (request, index, ops) => request.label ?? {
2253
+ key: "form.fill",
2254
+ count: fieldsNamedBy(index, ops).length
2255
+ };
2256
+ /** Step 1: what the user did shows at once. */
2257
+ const begin = (request) => {
2258
+ const before = fields.view();
2259
+ const shown = request.ops.reduce(predictFormOp, before);
2260
+ if (request.ops.length === 0) return {
2261
+ request,
2262
+ before,
2263
+ shown,
2264
+ hold: null
470
2265
  };
471
- const remainingBudget = () => {
472
- const remaining = budget.maxExecutionMs - executionMs;
473
- return remaining <= 0 ? null : {
474
- ...budget,
475
- maxExecutionMs: remaining
476
- };
2266
+ const hold = ctx.changes.hold(labelOf(request, before, request.ops));
2267
+ hold.set(request.ops, undoLookOf(before, request.ops));
2268
+ return {
2269
+ request,
2270
+ before,
2271
+ shown,
2272
+ hold
477
2273
  };
478
- const run = async (kind, source, input) => {
479
- const remaining = remainingBudget();
480
- if (!remaining) return { error: {
481
- kind: "budget",
482
- message: "Form script transaction timed out"
483
- } };
484
- let output;
485
- try {
486
- const sandbox = await this.sandbox();
487
- const startedAt = Date.now();
488
- output = kind === "boot" ? sandbox.boot(source, input, remaining) : sandbox.run(source, input, remaining);
489
- executionMs += Date.now() - startedAt;
490
- } catch (error) {
491
- return { error: scriptError(error instanceof Error ? error.message : String(error)) };
492
- }
493
- const error = consume(output, kind === "boot" ? "boot" : "user");
494
- return error ? { error } : { output };
2274
+ };
2275
+ /**
2276
+ * The form the change is undone to: as it is now, with the user's own fields as they were
2277
+ * before the user's ops showed.
2278
+ */
2279
+ const baseOf = ({ request, before }) => withFieldsFrom(fields.view(), before, fieldsNamedBy(before, request.ops));
2280
+ /** Whether the hold went with the user's ops before the scripts finished. */
2281
+ const sentEarly = ({ hold }) => hold !== null && !hold.open && !!hold.change;
2282
+ /** Whether the form still shows the values the user's ops wrote: the scripts ran for those. */
2283
+ const stillShown = ({ request, shown }) => {
2284
+ const now = fields.view();
2285
+ return fieldsNamedBy(shown, request.ops).every((field) => sameValue(fieldByKey(now, fieldKeyOf(field)), field));
2286
+ };
2287
+ /** Step 3: the change with all its ops, sent. */
2288
+ const send = (begun, ops, script) => {
2289
+ const { request, hold } = begun;
2290
+ if (ops.length === 0) {
2291
+ hold?.cancel();
2292
+ return {
2293
+ script,
2294
+ changes: [],
2295
+ after: fields.view()
2296
+ };
2297
+ }
2298
+ if (!hold) {
2299
+ const label = labelOf(request, fields.view(), ops);
2300
+ return {
2301
+ script,
2302
+ changes: [ctx.changes.stage({
2303
+ label,
2304
+ ops,
2305
+ undo: undoLookOf(baseOf(begun), ops)
2306
+ })],
2307
+ after: fields.view()
2308
+ };
2309
+ }
2310
+ if (hold.open) {
2311
+ hold.set(ops, undoLookOf(baseOf(begun), ops));
2312
+ const change = hold.send();
2313
+ return {
2314
+ script,
2315
+ changes: change ? [change] : [],
2316
+ after: fields.view()
2317
+ };
2318
+ }
2319
+ const sent = hold.change;
2320
+ const rest = ops.filter((op) => !sent?.shows.some((shown) => sameOp(shown, op)));
2321
+ const changes = sent ? [sent] : [];
2322
+ if (rest.length > 0) {
2323
+ const label = labelOf(request, fields.view(), rest);
2324
+ changes.push(ctx.changes.stage({
2325
+ label,
2326
+ ops: rest,
2327
+ undo: undoLookOf(fields.view(), rest)
2328
+ }));
2329
+ }
2330
+ return {
2331
+ script,
2332
+ changes,
2333
+ after: fields.view()
495
2334
  };
496
- if (!this.booted) {
497
- this.booted = true;
498
- let sources = [];
499
- let bootError = null;
500
- try {
501
- sources = (this.options.doc.actions ? await this.options.doc.actions.read() : null)?.nameTreeScripts.map(({ action }) => javaScriptProgramFromActionTree(action)) ?? [];
502
- } catch (error) {
503
- bootError = scriptError(error instanceof Error ? error.message : String(error));
504
- }
505
- if (!bootError && sources.length > 0) {
506
- const boot = await run("boot", sources, {
507
- ...inputBase,
508
- fields: overlay.fields,
509
- event: { kind: "name-tree-boot" }
510
- });
511
- if (boot.error) bootError = boot.error;
512
- else applyEffects(overlay, boot.output.formEffects);
2335
+ };
2336
+ /** The user's ops went on their own and the scripts refused them: their fields are written back. */
2337
+ const takeBack = ({ request, before }) => {
2338
+ const ops = fieldsNamedBy(before, request.ops).flatMap((field) => {
2339
+ const value = fieldValueOf(field);
2340
+ return value ? [{
2341
+ type: "forms.setValue",
2342
+ field: field.ref,
2343
+ value
2344
+ }] : [];
2345
+ });
2346
+ if (ops.length === 0) return;
2347
+ ctx.changes.stage({
2348
+ label: labelOf(request, before, ops),
2349
+ ops,
2350
+ history: false
2351
+ });
2352
+ };
2353
+ /** The calculations again, against what the form shows now: one change, outside the history. */
2354
+ const recalculateNow = async (scripts, origin) => {
2355
+ const shown = fields.view().snapshot;
2356
+ if (!shown) return;
2357
+ const script = await scripts.recalculate(shown);
2358
+ scripting.surface(script, origin);
2359
+ if (script.status !== "accepted" || script.effects.length === 0) return;
2360
+ ctx.changes.stage({
2361
+ label: RECALCULATE_LABEL,
2362
+ ops: formEffectOps(script.effects),
2363
+ history: false
2364
+ });
2365
+ };
2366
+ /** Step 2: the scripts, against the view. */
2367
+ const runScripts = (scripts, begun, plan) => {
2368
+ const shown = fields.view().snapshot;
2369
+ if (!shown) return null;
2370
+ switch (plan.kind) {
2371
+ case "commit": {
2372
+ const form = baseOf(begun).snapshot ?? shown;
2373
+ return scripts.commit(form, plan.field, plan.value);
513
2374
  }
514
- if (bootError) diagnostics.push({
515
- code: "script-error",
516
- message: `Document boot script failed (continuing without it): ${bootError.message}`
2375
+ case "activate": return scripts.activate(shown, plan.field, plan.action);
2376
+ case "recalculate": return scripts.recalculate(shown);
2377
+ }
2378
+ };
2379
+ /** Steps 2 and 3, when the fill's turn comes. */
2380
+ const finish = async (begun) => {
2381
+ const { request, hold } = begun;
2382
+ const plan = request.scripts;
2383
+ const pipeline = !plan ? null : plan.kind === "activate" ? scripting.controller() : scripting.scriptsFor(fields.view());
2384
+ if (!plan || !pipeline) return send(begun, request.ops, null);
2385
+ if (!fields.view().snapshot) await fields.settled();
2386
+ try {
2387
+ return await pipeline.transaction(async (scripts) => {
2388
+ const running = runScripts(scripts, begun, plan);
2389
+ if (!running) return send(begun, request.ops, null);
2390
+ const script = await running;
2391
+ scripting.surface(script, request.origin);
2392
+ const early = sentEarly(begun);
2393
+ if (script.status !== "accepted") {
2394
+ hold?.cancel();
2395
+ if (early) takeBack(begun);
2396
+ if (script.status === "rejected" && script.bootEffects.length > 0) ctx.changes.stage({
2397
+ label: SCRIPTS_LABEL,
2398
+ ops: formEffectOps(script.bootEffects),
2399
+ history: false
2400
+ });
2401
+ return {
2402
+ script,
2403
+ changes: [],
2404
+ after: fields.view()
2405
+ };
2406
+ }
2407
+ if (early && !stillShown(begun)) {
2408
+ await recalculateNow(scripts, request.origin);
2409
+ return {
2410
+ script,
2411
+ changes: [hold.change],
2412
+ after: fields.view()
2413
+ };
2414
+ }
2415
+ const effects = formEffectOps(script.effects);
2416
+ return send(begun, plan.kind === "recalculate" ? [...request.ops, ...effects] : effects, script);
517
2417
  });
2418
+ } catch (error) {
2419
+ hold?.cancel();
2420
+ throw error;
518
2421
  }
519
- const bootEffects = canonicalEffects(overlay);
520
- if (activation) {
521
- let program;
522
- try {
523
- program = javaScriptProgramFromActionTree(activation);
524
- } catch (error) {
525
- return this.failed(uiEffects, diagnostics, scriptError(error instanceof Error ? error.message : String(error)));
526
- }
527
- if (program) {
528
- const activated = await run("run", program, {
529
- ...inputBase,
530
- fields: overlay.fields,
531
- event: {
532
- kind: "widget-activate",
533
- target: ref,
534
- source: ref,
535
- value: targetInput.value
536
- }
537
- });
538
- if (activated.error) return this.failed(uiEffects, diagnostics, activated.error);
539
- applyEffects(overlay, activated.output.formEffects);
540
- }
2422
+ };
2423
+ /** What a sent fill did, once the engine answered. */
2424
+ const answered = async (begun, sent) => {
2425
+ const { script } = sent;
2426
+ const reported = {
2427
+ scripted: script !== null,
2428
+ uiEffects: script?.uiEffects ?? [],
2429
+ diagnostics: script?.diagnostics ?? [],
2430
+ ...script?.error ? { error: script.error } : {}
2431
+ };
2432
+ const outcome = (status) => ({
2433
+ result: {
2434
+ status,
2435
+ ...reported
2436
+ },
2437
+ before: begun.before,
2438
+ after: sent.after
2439
+ });
2440
+ if (script?.status === "failed") return outcome("failed");
2441
+ if (script?.status === "rejected") return outcome("rejected");
2442
+ let undoable = false;
2443
+ for (const change of sent.changes) try {
2444
+ undoable = (await change.result).meta.undoable || undoable;
2445
+ } catch (error) {
2446
+ throw toPluginError("form", error);
541
2447
  }
542
- if (!activation && hasProposedValue && target.actions?.keystroke && target.family === "text") {
543
- let program;
544
- try {
545
- program = javaScriptProgramFromActionTree(target.actions.keystroke);
546
- } catch (error) {
547
- return this.failed(uiEffects, diagnostics, scriptError(error instanceof Error ? error.message : String(error)));
548
- }
549
- if (program) {
550
- const oldValue = String(targetInput.value ?? "");
551
- const key = await run("run", program, {
552
- ...inputBase,
553
- fields: overlay.fields,
554
- event: {
555
- kind: "field-keystroke",
556
- target: ref,
557
- source: ref,
558
- value: oldValue,
559
- change: String(proposedValue ?? ""),
560
- selStart: 0,
561
- selEnd: oldValue.length,
562
- willCommit: true
563
- }
564
- });
565
- if (key.error) return this.failed(uiEffects, diagnostics, key.error);
566
- if (!key.output.event.rc) return this.finishRejected(bootEffects, uiEffects, diagnostics);
567
- applyEffects(overlay, key.output.formEffects);
568
- const event = key.output.event;
569
- const base = String(event.value ?? "");
570
- proposedValue = base.slice(0, event.selStart) + event.change + base.slice(Math.max(event.selStart, event.selEnd));
2448
+ return outcome(undoable ? "applied" : "unchanged");
2449
+ };
2450
+ /**
2451
+ * Fill the form in: shown at once, sent when its turn comes; resolves once the engine
2452
+ * answered. A change the engine refuses rejects.
2453
+ */
2454
+ const fill = async (request, options) => {
2455
+ const begun = begin(request);
2456
+ let sent;
2457
+ try {
2458
+ sent = await enqueue(() => finish(begun), options);
2459
+ } catch (error) {
2460
+ begun.hold?.cancel();
2461
+ throw toPluginError("form", error);
2462
+ }
2463
+ return ctx.cancellable(options?.signal, answered(begun, sent));
2464
+ };
2465
+ /**
2466
+ * Fill the form in without waiting: what a script's effects need, written while its own
2467
+ * transaction still runs. A failure is reported as the scripts' error.
2468
+ */
2469
+ const fillSoon = (request) => {
2470
+ const begun = begin(request);
2471
+ enqueue(() => finish(begun)).catch((error) => {
2472
+ begun.hold?.cancel();
2473
+ const message = toPluginError("form", error).message;
2474
+ scripting.surface({
2475
+ uiEffects: [],
2476
+ diagnostics: [],
2477
+ error: scriptError(message)
2478
+ }, request.origin);
2479
+ });
2480
+ };
2481
+ let recalculating = false;
2482
+ const recalculate = () => enqueue(async () => {
2483
+ recalculating = false;
2484
+ const pipeline = scripting.controller();
2485
+ if (pipeline) await pipeline.transaction((scripts) => recalculateNow(scripts, "user"));
2486
+ });
2487
+ ctx.changes.onSettled((settled) => {
2488
+ if (settled.status !== "refused" || settled.change.undoOf !== null) return;
2489
+ if (!FILLS.has(settled.change.label.key) || recalculating) return;
2490
+ const order = fields.view().snapshot?.calculationOrder ?? [];
2491
+ if (!scripting.controller() || !order.some((ref) => ref !== null)) return;
2492
+ recalculating = true;
2493
+ recalculate().catch(() => {});
2494
+ });
2495
+ ctx.onSettle(async () => {
2496
+ await enqueue.idle();
2497
+ await ctx.changes.whenSettled();
2498
+ });
2499
+ return {
2500
+ fill,
2501
+ fillSoon
2502
+ };
2503
+ }
2504
+ /** A fill that failed in the form's own scripts, as the verbs report it. */
2505
+ function failedFill(result) {
2506
+ return new PluginError("operation-failed", "form", result.error?.message ?? result.diagnostics[0]?.message ?? "the write failed");
2507
+ }
2508
+ //#endregion
2509
+ //#region src/write/focus.ts
2510
+ /**
2511
+ * Moving the cursor between fields: `focus()`, `focusNext()` (what Tab does), the arrow keys in a
2512
+ * radio group, and the field the cursor is in. This area decides where the cursor goes: which
2513
+ * field, which of its boxes, in Tab's order (the engine's `tabOrderOf()`); the cursor service
2514
+ * (`services/cursor.ts`) brings the box into view and hands it to its control.
2515
+ */
2516
+ /** A radio button as its field lists it: whether it's the checked one, and the value it picks. */
2517
+ const radioButtonOf = (field, widget) => field.family === "radio" ? field.widgets.find((candidate) => candidate.objectNumber === widget) ?? null : null;
2518
+ function createFocus(ctx, { fields, rights, events, cursor }, fill) {
2519
+ /** Every box that shows, in Tab's order, and the ones Tab stops at. */
2520
+ const order = memo(() => [
2521
+ fields.view(),
2522
+ ctx.document()?.pages,
2523
+ rights.key(),
2524
+ ctx.settings().get().fillable
2525
+ ], (index, pages) => {
2526
+ const rows = tabOrderOf((index.snapshot?.widgets ?? []).filter(shownOnScreen), pages ?? []);
2527
+ const position = /* @__PURE__ */ new Map();
2528
+ const stops = [];
2529
+ const groups = /* @__PURE__ */ new Set();
2530
+ rows.forEach((row, at) => {
2531
+ const widget = widgetObjectOf(row.ref);
2532
+ position.set(widget, at);
2533
+ const field = fieldForWidget(index, widget);
2534
+ if (!field || !rights.takesInput(field)) return;
2535
+ if (field.family === "radio") {
2536
+ const group = `${fieldKeyOf(field)}@${row.page.objectNumber}`;
2537
+ if (groups.has(group)) return;
2538
+ groups.add(group);
571
2539
  }
2540
+ stops.push({
2541
+ row,
2542
+ field,
2543
+ at
2544
+ });
2545
+ });
2546
+ return {
2547
+ rows,
2548
+ position,
2549
+ stops
2550
+ };
2551
+ });
2552
+ /** The buttons of a radio group, in Tab's order; on one page, with `page`. */
2553
+ const buttonsOf = (field, page) => order().rows.filter((row) => (page === void 0 || row.page.objectNumber === page) && fieldForWidget(fields.view(), widgetObjectOf(row.ref)) === field);
2554
+ /**
2555
+ * The box that takes the cursor at a stop: a radio group's checked button on that page, else
2556
+ * its first, or its last when Shift+Tab comes to it from after it.
2557
+ */
2558
+ const boxAt = (stop, backward) => {
2559
+ if (stop.field.family !== "radio") return stop.row;
2560
+ const buttons = buttonsOf(stop.field, stop.row.page.objectNumber);
2561
+ return buttons.find((button) => radioButtonOf(stop.field, widgetObjectOf(button.ref))?.checked) ?? (backward ? buttons.at(-1) ?? stop.row : stop.row);
2562
+ };
2563
+ const focus = (ref, options = {}) => {
2564
+ const index = fields.view();
2565
+ const field = fieldByRef(index, ref);
2566
+ if (!field || !rights.takesInput(field)) return false;
2567
+ let row;
2568
+ if (options.widget) {
2569
+ const widget = widgetObjectOf(options.widget);
2570
+ if (fieldForWidget(index, widget) !== field) return false;
2571
+ row = order().rows.find((candidate) => widgetObjectOf(candidate.ref) === widget);
2572
+ } else {
2573
+ const stop = order().stops.find((candidate) => candidate.field === field);
2574
+ row = stop && boxAt(stop, false);
572
2575
  }
573
- if (!activation && hasProposedValue) {
574
- targetInput.value = cloneValue(proposedValue);
575
- overlay.resetKeys.delete(refKey(ref));
2576
+ return row ? cursor.goTo(row, options.select ?? false) : false;
2577
+ };
2578
+ const focusNext = (options = {}) => {
2579
+ const index = fields.view();
2580
+ const { position, stops } = order();
2581
+ const backward = options.backward ?? false;
2582
+ const fromField = options.from ? fieldByRef(index, options.from) : null;
2583
+ const from = options.from ? fromField?.widgets.map(({ objectNumber }) => objectNumber).find((w) => position.has(w)) ?? null : cursor.focused()?.widget ?? cursor.last();
2584
+ const at = from === null ? null : position.get(from) ?? null;
2585
+ const field = from === null ? null : fieldForWidget(index, from);
2586
+ const page = from === null ? null : widgetRowOf(index, from)?.page.objectNumber;
2587
+ const candidates = stops.filter((stop) => (!options.empty || isEmpty(stop.field)) && !(stop.field === field && field.family === "radio" && stop.row.page.objectNumber === page));
2588
+ const ahead = candidates.filter((stop) => at === null ? true : backward ? stop.at < at : stop.at > at);
2589
+ const next = (backward ? ahead.at(-1) : ahead[0]) ?? (options.wrap ? backward ? candidates.at(-1) : candidates[0] : void 0);
2590
+ return next ? cursor.goTo(boxAt(next, backward), true) : false;
2591
+ };
2592
+ const moveInGroup = (ref, backward) => {
2593
+ const widget = widgetObjectOf(ref);
2594
+ const field = fieldForWidget(fields.view(), widget);
2595
+ if (!field || field.family !== "radio" || !rights.takesInput(field)) return false;
2596
+ const buttons = buttonsOf(field);
2597
+ const here = buttons.findIndex((row) => widgetObjectOf(row.ref) === widget);
2598
+ if (here < 0 || buttons.length < 2) return false;
2599
+ const next = buttons[(here + (backward ? buttons.length - 1 : 1)) % buttons.length];
2600
+ if (!cursor.goTo(next, false)) return false;
2601
+ const button = radioButtonOf(field, widgetObjectOf(next.ref));
2602
+ if (button) {
2603
+ const activate = () => void fill.activateWidget(next.ref).catch(() => {});
2604
+ fill.setValue(field.ref, { value: button.exportValue }).then(activate, activate);
576
2605
  }
577
- if (!activation && hasProposedValue && target.actions?.validate) {
578
- let program;
579
- try {
580
- program = javaScriptProgramFromActionTree(target.actions.validate);
581
- } catch (error) {
582
- return this.failed(uiEffects, diagnostics, scriptError(error instanceof Error ? error.message : String(error)));
583
- }
584
- if (program) {
585
- const validation = await run("run", program, {
586
- ...inputBase,
587
- fields: overlay.fields,
588
- event: {
589
- kind: "field-validate",
590
- target: ref,
591
- source: ref,
592
- value: proposedValue,
593
- willCommit: true
594
- }
2606
+ return true;
2607
+ };
2608
+ return { api: {
2609
+ focus,
2610
+ focusNext,
2611
+ getFocusedField: memo(() => [fields.view(), cursor.focused()], (index, focused) => focused ? fieldByKey(index, focused.field) : null),
2612
+ onFocusChanged: events.focusChanged.on,
2613
+ moveInGroup,
2614
+ attachFocusTarget: cursor.attach
2615
+ } };
2616
+ }
2617
+ //#endregion
2618
+ //#region src/write/interchange.ts
2619
+ function createInterchange(ctx, services) {
2620
+ const { enqueue, siblings } = services;
2621
+ const exportBundle = async (selection = {}, options) => {
2622
+ ctx.assertAllowed("doc.forms.read", "form.export");
2623
+ ctx.assertAllowed("doc.download", "form.export");
2624
+ const pages = selection.pages?.map((page) => ctx.pageOf(page).ref);
2625
+ return enqueue(() => ctx.cancellable(options?.signal, ctx.doc.forms.export({
2626
+ ...selection.fields ? { fields: selection.fields } : {},
2627
+ ...pages ? { pages } : {}
2628
+ })), options);
2629
+ };
2630
+ const importBundle = async (bundle, options = {}) => {
2631
+ const { signal, ...importOptions } = options;
2632
+ ctx.assertAllowed("doc.forms.modify", "form.import");
2633
+ if ((importOptions.attribution ?? "restore") === "restore") ctx.assertAllowed("doc.forms.import", "form.import");
2634
+ return enqueue(async () => {
2635
+ const result = await ctx.cancellable(signal, ctx.doc.forms.import(bundle, importOptions));
2636
+ const annotationHost = siblings.annotation();
2637
+ if (annotationHost) await annotationHost.whenSynced();
2638
+ return {
2639
+ fields: result.fields,
2640
+ refMap: result.refMap,
2641
+ dropped: result.dropped
2642
+ };
2643
+ }, options);
2644
+ };
2645
+ return { api: {
2646
+ export: exportBundle,
2647
+ import: importBundle
2648
+ } };
2649
+ }
2650
+ //#endregion
2651
+ //#region src/write/lending.ts
2652
+ /**
2653
+ * Design mode: the form's widgets, lent to the annotation plugin
2654
+ * (`AnnotationLender`, its host contract). While the session may design and
2655
+ * the active tool doesn't fill, the annotation plugin shows the widgets among
2656
+ * its records and edits them with its tools: select, move, resize, restyle,
2657
+ * reorder, delete. Each edit comes back here as the form's ops, in the same
2658
+ * change as the rest of it. While the tool fills, nothing is lent, and the
2659
+ * form layer draws and fills every widget.
2660
+ */
2661
+ const objectNumberOf = (ref) => ref.kind === "objectNumber" ? ref.objectNumber : -1;
2662
+ function createWidgetLender(ctx, { fields, design, pictures, looks }) {
2663
+ const records = memo(() => [
2664
+ design.lending(),
2665
+ fields.get().snapshot,
2666
+ fields.view().snapshot
2667
+ ], (lending, confirmed, shown) => lending && confirmed && shown ? {
2668
+ confirmed: confirmed.widgets,
2669
+ shown: shown.widgets
2670
+ } : null);
2671
+ /**
2672
+ * Deleted widgets, as the form's ops: a widget leaves its field
2673
+ * (`deleteWidget`), and a field whose every widget goes is deleted whole
2674
+ * (a merged field and widget among them).
2675
+ */
2676
+ const deleteOps = (deleted) => {
2677
+ const index = fields.view();
2678
+ const ops = [];
2679
+ const byField = /* @__PURE__ */ new Map();
2680
+ for (const row of deleted) {
2681
+ const field = fieldForWidget(index, objectNumberOf(row.ref));
2682
+ if (!field) {
2683
+ ops.push({
2684
+ type: "forms.deleteWidget",
2685
+ widget: row.ref
595
2686
  });
596
- if (validation.error) return this.failed(uiEffects, diagnostics, validation.error);
597
- if (!validation.output.event.rc) return this.finishRejected(bootEffects, uiEffects, diagnostics);
598
- targetInput.value = cloneValue(validation.output.event.value);
599
- applyEffects(overlay, validation.output.formEffects);
2687
+ continue;
600
2688
  }
2689
+ const entry = byField.get(fieldKeyOf(field)) ?? {
2690
+ field,
2691
+ widgets: []
2692
+ };
2693
+ entry.widgets.push(row);
2694
+ byField.set(fieldKeyOf(field), entry);
601
2695
  }
602
- const formatRefs = !activation && hasProposedValue ? [ref] : [];
603
- for (const calculationRef of activation ? [] : snapshot.calculationOrder) {
604
- if (!calculationRef) continue;
605
- const calculated = snapshotField(snapshot, calculationRef);
606
- const tree = calculated?.actions?.calculate;
607
- if (!calculated || !tree) continue;
608
- let program;
609
- try {
610
- program = javaScriptProgramFromActionTree(tree);
611
- } catch (error) {
612
- return this.failed(uiEffects, diagnostics, scriptError(error instanceof Error ? error.message : String(error)));
613
- }
614
- const calculatedInput = fieldByRef(overlay.fields, calculationRef);
615
- if (program && calculatedInput) {
616
- const calculation = await run("run", program, {
617
- ...inputBase,
618
- fields: overlay.fields,
619
- event: {
620
- kind: "field-calculate",
621
- target: calculationRef,
622
- ...hasProposedValue ? { source: ref } : {},
623
- value: calculatedInput.value
624
- }
2696
+ for (const { field, widgets } of byField.values()) {
2697
+ const going = new Set(widgets.map((row) => objectNumberOf(row.ref)));
2698
+ if (field.widgets.every((widget) => going.has(widget.objectNumber))) ops.push({
2699
+ type: "forms.delete",
2700
+ field: field.ref
2701
+ });
2702
+ else ops.push(...widgets.map((row) => ({
2703
+ type: "forms.deleteWidget",
2704
+ widget: row.ref
2705
+ })));
2706
+ }
2707
+ return ops;
2708
+ };
2709
+ return {
2710
+ owner: "form",
2711
+ records,
2712
+ opsOf(effects, model, before) {
2713
+ const ops = [];
2714
+ const deleted = [];
2715
+ for (const effect of effects) if (effect.type === "patch") {
2716
+ const ref = refOf(model.byId[effect.id]);
2717
+ if (!ref) continue;
2718
+ const { subtype: _subtype, ...patch } = effect.patch;
2719
+ ops.push({
2720
+ type: "forms.updateWidget",
2721
+ widget: ref,
2722
+ patch
625
2723
  });
626
- if (calculation.error) return this.failed(uiEffects, diagnostics, calculation.error);
627
- applyEffects(overlay, calculation.output.formEffects);
2724
+ } else if (effect.type === "delete") {
2725
+ const record = before.byId[effect.id];
2726
+ if (record) deleted.push(record.annotation);
628
2727
  }
629
- if (!formatRefs.some((candidate) => sameRef(candidate, calculationRef))) formatRefs.push(calculationRef);
2728
+ return [...ops, ...deleteOps(deleted)];
2729
+ },
2730
+ undoOf: (ops) => undoLookOf(fields.view(), ops),
2731
+ reorderOps: (page, refs, position) => [{
2732
+ type: "forms.reorderWidgets",
2733
+ page,
2734
+ widgets: [...refs],
2735
+ position
2736
+ }],
2737
+ authority: () => {
2738
+ const may = ctx.allows("doc.forms.modify");
2739
+ return {
2740
+ update: may,
2741
+ delete: may
2742
+ };
2743
+ },
2744
+ pictureEpoch: pictures.epoch,
2745
+ pictureVersion: pictures.versionOf,
2746
+ renderAppearances: pictures.render,
2747
+ pending: looks.isPending,
2748
+ painter: (record) => record.subtype === "widget" ? looks.painterOf(record) : null
2749
+ };
2750
+ }
2751
+ //#endregion
2752
+ //#region src/field-selection.ts
2753
+ /**
2754
+ * ISO field selection, written once for ResetForm (Tables 241/242) and
2755
+ * SubmitForm (Tables 239/240): a name target selects the field and its
2756
+ * descendants (FQN dot-prefix — `parent` selects `parent.c1`, the rule the
2757
+ * old exact-match resolution violated); an objectNumber target selects that
2758
+ * field dictionary. Include mode keeps the selection; exclude mode keeps
2759
+ * the complement (a name excludes its subtree the same way it includes
2760
+ * it). `targets === null` (the key absent) selects everything and the flag
2761
+ * is ignored; `[]` + include selects nothing while `[]` + exclude selects
2762
+ * everything — presence and emptiness are different states.
2763
+ *
2764
+ * `listed` reports whether a field was addressed by the target list
2765
+ * (directly or through its subtree) — the "explicitly listed" predicate the
2766
+ * submit honesty diagnostics key on.
2767
+ */
2768
+ const resolveFieldSelection = (all, targets, exclude) => {
2769
+ if (targets === null) return {
2770
+ selected: [...all],
2771
+ listed: () => false
2772
+ };
2773
+ const names = targets.filter((target) => target.kind === "name").map((target) => target.name);
2774
+ const objectNumbers = new Set(targets.filter((target) => target.kind === "objectNumber").map((target) => target.objectNumber));
2775
+ const listed = (field) => field.ref.kind === "objectNumber" && objectNumbers.has(field.ref.objectNumber) || names.some((name) => field.name === name || field.name.startsWith(`${name}.`));
2776
+ return {
2777
+ selected: exclude ? all.filter((field) => !listed(field)) : all.filter(listed),
2778
+ listed
2779
+ };
2780
+ };
2781
+ /**
2782
+ * Build the resolved submission dataset from a live field list (Tables
2783
+ * 239/240 semantics; pure — the capability supplies a fresh engine read so
2784
+ * no model-lag class exists):
2785
+ *
2786
+ * - the unconditional **NoExport veto** — even an explicit include cannot
2787
+ * override it (diagnosed when explicitly listed, so the veto is
2788
+ * observable, silent when swept in implicitly);
2789
+ * - **push-buttons and signatures** never contribute entries in v1 —
2790
+ * ISO's explicit-pushbutton-`/AP`-in-FDF rule is unrepresentable in the
2791
+ * current DTO, so an explicitly listed one is diagnosed
2792
+ * (`submit-entry-unsupported`), never silently dropped;
2793
+ * - an **unsupported `/V` shape** is always diagnosed (silent omission
2794
+ * would be data loss);
2795
+ * - a valueless field becomes a name-only entry (`value: null`) only under
2796
+ * IncludeNoValueFields, else it is skipped (the ISO default);
2797
+ * - values are entry-faithful: scalar → string, array (multi-select list
2798
+ * box) → string[]; the submitted name is the fully qualified name.
2799
+ */
2800
+ const buildSubmitEntries = (fields, intent, diagnose) => {
2801
+ const { selected, listed } = resolveFieldSelection(fields, intent.fields, intent.exclude);
2802
+ const explicitInclude = intent.fields !== null && !intent.exclude;
2803
+ const entries = [];
2804
+ for (const field of selected) {
2805
+ const explicit = explicitInclude && listed(field);
2806
+ if (field.family === "pushbutton" || field.family === "signature") {
2807
+ if (explicit) diagnose({
2808
+ code: "submit-entry-unsupported",
2809
+ message: `submit: '${field.name}' (${field.family}) has no representable submission value in v1 — skipped`
2810
+ });
2811
+ continue;
630
2812
  }
631
- for (const formatRef of formatRefs) {
632
- const field = snapshotField(snapshot, formatRef);
633
- const tree = field?.actions?.format;
634
- const overlayField = fieldByRef(overlay.fields, formatRef);
635
- if (!field || !tree || !overlayField) continue;
636
- let program;
637
- try {
638
- program = javaScriptProgramFromActionTree(tree);
639
- } catch (error) {
640
- return this.failed(uiEffects, diagnostics, scriptError(error instanceof Error ? error.message : String(error)));
641
- }
642
- if (!program) continue;
643
- const format = await run("run", program, {
644
- ...inputBase,
645
- fields: overlay.fields,
646
- event: {
647
- kind: "field-format",
648
- target: formatRef,
649
- ...hasProposedValue ? { source: ref } : {},
650
- value: overlayField.value
651
- }
2813
+ if (field.noExport) {
2814
+ if (explicit) diagnose({
2815
+ code: "submit-entry-unsupported",
2816
+ message: `submit: '${field.name}' carries the NoExport flag — the veto is unconditional (ISO 12.7.6.2), skipped`
652
2817
  });
653
- if (format.error) return this.failed(uiEffects, diagnostics, format.error);
654
- applyEffects(overlay, format.output.formEffects);
2818
+ continue;
655
2819
  }
656
- const effects = canonicalEffects(overlay);
657
- if (effects.length + uiEffects.length > budget.maxEffects) return this.failed(uiEffects, diagnostics, {
658
- kind: "budget",
659
- message: `Form script transaction exceeded ${budget.maxEffects} effects`
2820
+ const entry = field.valueEntry;
2821
+ if (entry.kind === "scalar") entries.push({
2822
+ name: field.name,
2823
+ value: entry.value
2824
+ });
2825
+ else if (entry.kind === "array") entries.push({
2826
+ name: field.name,
2827
+ value: entry.values
2828
+ });
2829
+ else if (entry.kind === "none") {
2830
+ if (intent.includeNoValueFields) entries.push({
2831
+ name: field.name,
2832
+ value: null
2833
+ });
2834
+ } else diagnose({
2835
+ code: "submit-entry-unsupported",
2836
+ message: `submit: '${field.name}' has an unsupported /V shape — skipped (would otherwise be silent data loss)`
660
2837
  });
661
- if (effects.length === 0) return {
662
- status: "unchanged",
663
- scripted: true,
664
- effectsResult: null,
665
- uiEffects,
666
- diagnostics
667
- };
668
- if (!this.options.doc.forms.applyEffects) return this.failed(uiEffects, diagnostics, scriptError("This engine does not support batched form effects"));
669
- const effectsResult = await this.options.doc.forms.applyEffects(effects);
670
- const status = statusFromEffects(effectsResult);
671
- return {
672
- status,
673
- scripted: true,
674
- effectsResult,
675
- uiEffects,
676
- diagnostics,
677
- ...status === "failed" ? { error: scriptError("One or more native form effects failed") } : {}
678
- };
679
- }
680
- async sandbox() {
681
- this.sandboxPromise ?? (this.sandboxPromise = this.options.sandboxFactory().then((sandbox) => {
682
- if (this.disposed) sandbox.dispose();
683
- return sandbox;
684
- }));
685
- return this.sandboxPromise;
686
- }
687
- failed(uiEffects, diagnostics, error) {
688
- return {
689
- status: "failed",
690
- scripted: true,
691
- effectsResult: null,
692
- uiEffects,
693
- diagnostics,
694
- error
695
- };
696
- }
697
- async finishRejected(bootEffects, uiEffects, diagnostics) {
698
- if (bootEffects.length === 0) return {
699
- status: "rejected",
700
- scripted: true,
701
- effectsResult: null,
702
- uiEffects,
703
- diagnostics
704
- };
705
- if (!this.options.doc.forms.applyEffects) return this.failed(uiEffects, diagnostics, scriptError("Batched form effects are unavailable"));
706
- const effectsResult = await this.options.doc.forms.applyEffects(bootEffects);
707
- if (statusFromEffects(effectsResult) === "failed") return this.failed(uiEffects, diagnostics, scriptError("A name-tree boot effect failed"));
708
- return {
709
- status: "rejected",
710
- scripted: true,
711
- effectsResult,
712
- uiEffects,
713
- diagnostics
714
- };
715
2838
  }
2839
+ return entries;
716
2840
  };
717
- function createFormScriptingController(options) {
718
- return new FormScriptingController(options);
719
- }
720
2841
  //#endregion
721
- //#region src/capability.ts
722
- /** PDF user-space rect (y-up) → content-space box (y-down, crop-relative). */
723
- const toBox = (rect, crop) => ({
724
- x: rect.left - crop.left,
725
- y: crop.top - rect.top,
726
- width: rect.right - rect.left,
727
- height: rect.top - rect.bottom
728
- });
729
- const sameAnnotationRef = (left, right) => {
730
- if (left.kind !== right.kind || left.pageObjectNumber !== right.pageObjectNumber) return false;
731
- if (left.kind === "objectNumber" && right.kind === "objectNumber") return left.annotObjectNumber === right.annotObjectNumber;
732
- if (left.kind === "nm" && right.kind === "nm") return left.nm === right.nm;
733
- return left.kind === "index" && right.kind === "index" && left.index === right.index && left.revision === right.revision;
2842
+ //#region src/write/reset.ts
2843
+ /** A reset of no fields: what the executor reports as inert. */
2844
+ const NOTHING_RESET = {
2845
+ status: "unchanged",
2846
+ scripted: false,
2847
+ uiEffects: [],
2848
+ diagnostics: []
2849
+ };
2850
+ /** A field ref as an action's target: by object number, or by full name. */
2851
+ const targetOf = (ref) => ref.kind === "objectNumber" ? {
2852
+ kind: "objectNumber",
2853
+ objectNumber: ref.objectNumber
2854
+ } : {
2855
+ kind: "name",
2856
+ name: ref.name
734
2857
  };
2858
+ function createResetWrites(_ctx, services, { fill }) {
2859
+ const { fields, rights } = services;
2860
+ /**
2861
+ * Whether a reset puts this field back: the engine refuses push button and
2862
+ * signature refs, and another signer's fields are theirs.
2863
+ */
2864
+ const resettable = (field) => field.family !== "pushbutton" && field.family !== "signature" && rights.mayFill(field);
2865
+ /**
2866
+ * Reset the selected fields, then recalculate, as one change. `origin` is carried through to
2867
+ * the surfaced recalculation results, so a ResetForm run by a page or hover trigger never
2868
+ * reports its alerts as a user action. `null` when it selects nothing; a refused reset throws:
2869
+ * none of it was written.
2870
+ */
2871
+ const resetSelection = async (targets, exclude, origin, options) => {
2872
+ if (!fields.view().snapshot) await fields.settled();
2873
+ const { selected } = resolveFieldSelection(fields.view().snapshot?.fields ?? [], targets, exclude);
2874
+ const refs = selected.filter(resettable).map((field) => field.ref);
2875
+ if (refs.length === 0) return null;
2876
+ return fill({
2877
+ label: {
2878
+ key: "form.reset",
2879
+ count: refs.length
2880
+ },
2881
+ ops: [{
2882
+ type: "forms.reset",
2883
+ fields: refs
2884
+ }],
2885
+ scripts: { kind: "recalculate" },
2886
+ origin
2887
+ }, options);
2888
+ };
2889
+ const reset = async (refs, options) => {
2890
+ for (const ref of refs ?? []) {
2891
+ const field = fieldByRef(fields.view(), ref);
2892
+ if (field) rights.assertMayFill(field, "form.reset");
2893
+ }
2894
+ if (refs && refs.length === 0) return { fields: [] };
2895
+ const outcome = await resetSelection(refs ? refs.map(targetOf) : null, false, "user", options);
2896
+ return { fields: outcome ? fieldsWithChangedValues(outcome.before, outcome.after) : [] };
2897
+ };
2898
+ return { api: {
2899
+ reset,
2900
+ resetFormAction: async (targets, exclude, origin = "user") => {
2901
+ const outcome = await resetSelection(targets, exclude, origin);
2902
+ if (!outcome) return NOTHING_RESET;
2903
+ const { result } = outcome;
2904
+ return result.status === "unchanged" ? {
2905
+ ...result,
2906
+ status: "applied"
2907
+ } : result;
2908
+ }
2909
+ } };
2910
+ }
2911
+ //#endregion
2912
+ //#region src/write/script-effects.ts
735
2913
  /**
736
- * The form shell. Pure `update` runs here; the resulting model is dispatched
737
- * to the store; engine calls happen around it. Every read the frameworks do
738
- * goes through memoized projections keyed on `model.seq`.
2914
+ * The actions plugin's seams into the form plugin: the form-effects commit
2915
+ * sink (script `setValue`, `setDisplay` and reset effects are written through
2916
+ * the plugin that owns the fields, as one fill with the calculations they
2917
+ * cause) and the submit dataset resolver.
739
2918
  */
740
- function createFormCapability(ctx, options = {}) {
741
- const model = () => ctx.getState().model;
742
- const apply = (msg) => {
743
- ctx.dispatch({
744
- type: "SET_MODEL",
745
- model: update(model(), msg)
746
- });
747
- };
748
- const refKeyOf = (key) => {
749
- if (key.startsWith("obj:")) return {
750
- kind: "objectNumber",
751
- fieldObjectNumber: Number(key.slice(4))
752
- };
2919
+ /** The fields a script's effects write to. */
2920
+ const refsOf = (effects) => effects.flatMap((effect) => effect.kind === "reset" ? effect.refs : [effect.ref]);
2921
+ function createScriptEffects(ctx, { fields, rights, enqueue }, { fillSoon }) {
2922
+ /**
2923
+ * The submit dataset: the fields as the user sees them once every fill on its way is
2924
+ * answered, then the pure ISO builder. Selection, veto and value semantics live in
2925
+ * `field-selection.ts`; this only supplies the fields and assembles the request.
2926
+ */
2927
+ const resolveSubmitDataset = async (intent, actionContext, diagnose) => {
2928
+ await enqueue.idle();
2929
+ await ctx.changes.whenSettled();
2930
+ if (!fields.view().snapshot) await fields.settled();
753
2931
  return {
754
- kind: "fqn",
755
- name: key.slice(4)
2932
+ url: intent.url,
2933
+ method: intent.method,
2934
+ format: intent.format,
2935
+ flagsRaw: intent.flagsRaw,
2936
+ ...intent.charSet === void 0 ? {} : { charSet: intent.charSet },
2937
+ entries: buildSubmitEntries(fields.view().snapshot?.fields ?? [], intent, diagnose),
2938
+ origin: actionContext.origin,
2939
+ event: actionContext.event
756
2940
  };
757
2941
  };
758
- const enqueueMutation = createSerialMutationQueue();
759
- const scripting = options.scripting?.enabled && ctx.doc ? createFormScriptingController({
760
- doc: ctx.doc,
761
- document: () => ctx.document(),
762
- config: options.scripting,
763
- sandboxFactory: options.scripting.sandboxFactory ?? (() => import("@embedpdf/core-js-sandbox").then(({ createQuickJsSandbox }) => createQuickJsSandbox()))
764
- }) : null;
765
- if (scripting) ctx.cleanup(() => scripting.dispose());
766
- let uiEffectProvider = null;
767
- const surfaceScriptingResult = (result) => {
768
- const observe = (callback) => {
769
- if (!callback) return;
2942
+ return { api: {
2943
+ resolveSubmitDataset,
2944
+ commitScriptFormEffects: async (effects) => {
770
2945
  try {
771
- callback();
2946
+ for (const ref of refsOf(effects)) {
2947
+ const field = fieldByRef(fields.view(), ref);
2948
+ if (field) rights.assertMayFill(field, "form.fill");
2949
+ }
2950
+ const recalculates = effects.some((effect) => effect.kind === "setValue" || effect.kind === "reset");
2951
+ fillSoon({
2952
+ ops: formEffectOps(effects),
2953
+ scripts: recalculates ? { kind: "recalculate" } : null,
2954
+ origin: "user"
2955
+ });
2956
+ return { status: "applied" };
772
2957
  } catch (error) {
773
- globalThis.console?.error("[form] scripting observer failed:", error);
2958
+ return {
2959
+ status: "failed",
2960
+ error: serializeError(error).message
2961
+ };
774
2962
  }
775
- };
776
- for (const effect of result.uiEffects) {
777
- observe(options.scripting?.onUiEffect ? () => options.scripting.onUiEffect(effect) : void 0);
778
- observe(uiEffectProvider ? () => uiEffectProvider(effect) : void 0);
779
2963
  }
780
- for (const diagnostic of result.diagnostics) observe(options.scripting?.onDiagnostic ? () => options.scripting.onDiagnostic(diagnostic) : void 0);
781
- if (result.error) observe(options.scripting?.onError ? () => options.scripting.onError(result.error) : void 0);
782
- };
783
- let refreshPromise = null;
784
- const refresh = async (force = false) => {
785
- const doc = ctx.doc;
786
- if (!doc) return;
787
- if (refreshPromise) {
788
- await refreshPromise;
789
- if (!force) return;
2964
+ } };
2965
+ }
2966
+ //#endregion
2967
+ //#region src/write/typing.ts
2968
+ function createTyping(ctx, { keyOf }, setText) {
2969
+ /** The text typed in each field and not written yet, by field key. */
2970
+ const drafts = /* @__PURE__ */ new Map();
2971
+ /** Write the field's draft, if it has one; `null` when there is nothing to write. */
2972
+ const commitDraftText = async (field) => {
2973
+ const key = keyOf(field);
2974
+ const draft = drafts.get(key);
2975
+ if (!draft) return null;
2976
+ drafts.delete(key);
2977
+ return setText(draft.field, draft.text);
2978
+ };
2979
+ ctx.onSettle(async () => {
2980
+ await Promise.all([...drafts.values()].map((draft) => commitDraftText(draft.field)));
2981
+ });
2982
+ return { api: {
2983
+ draftText: (field, text) => {
2984
+ drafts.set(keyOf(field), {
2985
+ field,
2986
+ text
2987
+ });
2988
+ },
2989
+ commitDraftText,
2990
+ discardDraftText: (field) => {
2991
+ drafts.delete(keyOf(field));
790
2992
  }
791
- refreshPromise = doc.forms.list().then((snapshot) => apply({
792
- t: "snapshot",
793
- snapshot
794
- })).finally(() => {
795
- refreshPromise = null;
796
- });
797
- return refreshPromise;
798
- };
799
- const geomLoading = /* @__PURE__ */ new Set();
800
- const ensureGeom = (pon) => {
801
- const doc = ctx.doc;
802
- if (!doc || geomLoading.has(pon) || model().geom[pon]) return;
803
- const crop = ctx.document()?.pages.find((p) => p.pageObjectNumber === pon)?.boxes.crop;
804
- if (!crop) return;
805
- geomLoading.add(pon);
806
- doc.page(pon).annotations.list().then(({ annotations }) => {
807
- const boxes = {};
808
- for (const dto of annotations) {
809
- if (dto.subtype !== "widget") continue;
810
- const objectNumber = dto.ref.kind === "objectNumber" ? dto.ref.annotObjectNumber : 0;
811
- if (objectNumber > 0) boxes[objectNumber] = toBox(dto.rect, crop);
812
- }
813
- apply({
814
- t: "pageGeom",
815
- pageObjectNumber: pon,
816
- boxes
2993
+ } };
2994
+ }
2995
+ //#endregion
2996
+ //#region src/write/values.ts
2997
+ /**
2998
+ * Value writes, each one fill (write/fill.ts): one field through the form's scripts (when the
2999
+ * `validation` setting runs them), and the batch verbs, whose plain values go as one change
3000
+ * with one recalculation, as a script's `field.value` assignments do in Acrobat.
3001
+ */
3002
+ /** A batch that stops when its caller cancels it. */
3003
+ function throwIfCancelled(options) {
3004
+ if (options?.signal?.aborted) throw new PluginError("operation-cancelled", "form", "operation cancelled", { cause: options.signal.reason });
3005
+ }
3006
+ const setValueOp = (field, value) => ({
3007
+ type: "forms.setValue",
3008
+ field,
3009
+ value
3010
+ });
3011
+ function createValueWrites(_ctx, services, { fill }) {
3012
+ const { validationRejected } = services.events;
3013
+ const { fields, rights } = services;
3014
+ /** One field's value through its scripts: shown at once, written as one change. */
3015
+ const commit = async (ref, value, operation, options) => {
3016
+ const known = fieldByRef(fields.view(), ref);
3017
+ if (known) rights.assertMayFill(known, operation);
3018
+ const { result } = await fill({
3019
+ ops: [setValueOp(ref, value)],
3020
+ scripts: {
3021
+ kind: "commit",
3022
+ field: ref,
3023
+ value
3024
+ },
3025
+ origin: "user"
3026
+ }, options);
3027
+ if (result.status === "failed") throw failedFill(result);
3028
+ const field = fieldByRef(fields.get(), ref);
3029
+ if (!field) throw new PluginError("not-found", "form", "no form field has this ref");
3030
+ if (result.status === "rejected") {
3031
+ validationRejected.emit({
3032
+ field,
3033
+ issues: result.diagnostics
817
3034
  });
818
- }).finally(() => {
819
- geomLoading.delete(pon);
820
- });
821
- };
822
- const fillCache = /* @__PURE__ */ new Map();
823
- const fillItems$1 = (pon) => {
824
- const m = model();
825
- const hit = fillCache.get(pon);
826
- if (hit && hit.seq === m.seq) return hit.items;
827
- const items = fillItems(m, pon);
828
- fillCache.set(pon, {
829
- seq: m.seq,
830
- items
831
- });
832
- return items;
833
- };
834
- const fillItemCache = /* @__PURE__ */ new Map();
835
- const fillItem = (annotObjectNumber) => {
836
- const m = model();
837
- const hit = fillItemCache.get(annotObjectNumber);
838
- if (hit && hit.seq === m.seq) return hit.item;
839
- const item = fillItemForWidget(m, annotObjectNumber);
840
- fillItemCache.set(annotObjectNumber, {
841
- seq: m.seq,
842
- item
843
- });
844
- return item;
845
- };
846
- const commitValueNow = async (ref, value) => {
847
- const doc = ctx.doc;
848
- if (!doc) throw new Error("no document");
849
- if (scripting) {
850
- const result = await scripting.commit(await doc.forms.list(), ref, value);
851
- surfaceScriptingResult(result);
852
- if (result.effectsResult !== null) await refresh(true);
853
- return result;
3035
+ return {
3036
+ field,
3037
+ status: "rejected"
3038
+ };
854
3039
  }
855
- const result = await doc.forms.setValue(ref, value);
856
- await refresh(true);
857
3040
  return {
858
- status: result.changedWidgets.length > 0 ? "applied" : "unchanged",
859
- scripted: false,
860
- effectsResult: null,
861
- uiEffects: [],
862
- diagnostics: []
3041
+ field,
3042
+ status: result.status
863
3043
  };
864
3044
  };
865
- const write = (key, value) => enqueueMutation(async () => {
866
- if (!ctx.doc) return;
867
- apply({
868
- t: "writeStart",
869
- key
870
- });
871
- try {
872
- const result = await commitValueNow(refKeyOf(key), value);
873
- if (result.status === "rejected" || result.status === "failed") apply({
874
- t: "writeFailed",
875
- key
876
- });
877
- else if (result.effectsResult === null && result.scripted) apply({
878
- t: "writeFailed",
879
- key
3045
+ /**
3046
+ * Plain values for several fields, as one change with one recalculation. A value its field
3047
+ * can't take, or a field the session may not fill in, fails on its own; the rest go together,
3048
+ * and fail together when the engine refuses them.
3049
+ */
3050
+ const fillPlain = async (entries, options) => {
3051
+ if (!fields.view().snapshot) await fields.settled();
3052
+ const index = fields.view();
3053
+ const accepted = [];
3054
+ const failed = [];
3055
+ for (const entry of entries) try {
3056
+ const field = fieldByRef(index, entry.ref);
3057
+ if (!field) throw new PluginError("not-found", "form", "no form field has this ref");
3058
+ rights.assertMayFill(field, "form.setValues");
3059
+ fieldValueWriteOf(field, entry.value);
3060
+ accepted.push({
3061
+ ref: field.ref,
3062
+ value: entry.value
880
3063
  });
881
- } catch (err) {
882
- apply({
883
- t: "writeFailed",
884
- key
3064
+ } catch (error) {
3065
+ failed.push({
3066
+ ref: entry.ref,
3067
+ error: toPluginErrorInfo(toPluginError("form", error))
885
3068
  });
886
- throw err;
887
3069
  }
888
- });
889
- const can = (cap) => ctx.doc?.security.allows(cap) ?? false;
890
- const annotationHost = ctx.tryGet(AnnotationToken$1);
891
- const annotationActivation = async (ref) => {
892
- const doc = ctx.doc;
893
- if (!doc) return null;
894
- const loaded = annotationHost?.get(ref);
895
- if (loaded?.subtype === "widget") return loaded.actions?.activate ?? null;
896
- const { annotations } = await doc.page(ref.pageObjectNumber).annotations.list();
897
- const annotation = annotations.find((candidate) => sameAnnotationRef(candidate.ref, ref));
898
- return annotation?.subtype === "widget" ? annotation.actions?.activate ?? null : null;
899
- };
900
- const activateWidgetNow = async (key, annotationRef) => {
901
- const doc = ctx.doc;
902
- if (!doc) throw new Error("no document");
903
- if (!scripting) return {
904
- status: "unchanged",
905
- scripted: false,
906
- effectsResult: null,
907
- uiEffects: [],
908
- diagnostics: []
909
- };
910
- const action = await annotationActivation(annotationRef);
911
- if (!action) return {
912
- status: "unchanged",
913
- scripted: true,
914
- effectsResult: null,
915
- uiEffects: [],
916
- diagnostics: []
3070
+ if (accepted.length === 0) return {
3071
+ applied: [],
3072
+ failed
917
3073
  };
918
- const result = await scripting.activate(await doc.forms.list(), refKeyOf(key), action);
919
- surfaceScriptingResult(result);
920
- if (result.effectsResult !== null) await refresh(true);
921
- return result;
922
- };
923
- const nudgeAnnotations = (pons) => {
924
- if (!annotationHost) return;
925
- for (const pon of new Set(pons)) annotationHost.reloadPage(pon);
926
- };
927
- /** Content-space box → PDF rect (inverse of `toBox`). */
928
- const toPdfRect = (box, crop) => ({
929
- left: box.x + crop.left,
930
- top: crop.top - box.y,
931
- right: box.x + crop.left + box.width,
932
- bottom: crop.top - box.y - box.height
933
- });
934
- /** The page's content box (`{0,0,w,h}`), for page-bound placement math. */
935
- const pageBox = (pon) => {
936
- const crop = ctx.document()?.pages.find((p) => p.pageObjectNumber === pon)?.boxes.crop;
937
- return crop ? {
938
- x: 0,
939
- y: 0,
940
- width: crop.right - crop.left,
941
- height: crop.top - crop.bottom
942
- } : null;
3074
+ throwIfCancelled(options);
3075
+ try {
3076
+ const { result } = await fill({
3077
+ ops: accepted.map((entry) => setValueOp(entry.ref, entry.value)),
3078
+ scripts: { kind: "recalculate" },
3079
+ origin: "user"
3080
+ }, options);
3081
+ if (result.status === "failed") throw failedFill(result);
3082
+ return {
3083
+ applied: accepted.map((entry) => entry.ref),
3084
+ failed
3085
+ };
3086
+ } catch (error) {
3087
+ const info = toPluginErrorInfo(toPluginError("form", error));
3088
+ return {
3089
+ applied: [],
3090
+ failed: [...failed, ...accepted.map(({ ref }) => ({
3091
+ ref,
3092
+ error: info
3093
+ }))]
3094
+ };
3095
+ }
943
3096
  };
944
- /** Deterministic, collision-free auto-name: `text_1`, `text_2`, … counted
945
- * against the CURRENT snapshot (rename in the field panel). */
946
- const autoName = (family) => {
947
- const names = new Set((model().snapshot?.fields ?? []).map((f) => f.name));
948
- let n = 1;
949
- while (names.has(`${family}_${n}`)) n++;
950
- return `${family}_${n}`;
951
- };
952
- const placeFieldNow = async (input) => {
953
- const doc = ctx.doc;
954
- const pon = input.pageObjectNumber;
955
- const crop = ctx.document()?.pages.find((p) => p.pageObjectNumber === pon)?.boxes.crop;
956
- if (!doc || !crop) throw new Error("[form] placeField: document/page not ready");
957
- const page = pageBox(pon);
958
- const x = Math.max(page.x, Math.min(input.box.x, page.width));
959
- const y = Math.max(page.y, Math.min(input.box.y, page.height));
960
- const box = {
961
- x,
962
- y,
963
- width: Math.max(0, Math.min(input.box.x + input.box.width, page.width) - x),
964
- height: Math.max(0, Math.min(input.box.y + input.box.height, page.height) - y)
965
- };
966
- if (box.width < 1 || box.height < 1) throw new Error("[form] placeField: degenerate box (size the box before placing)");
967
- const { family, appearance } = input;
968
- const name = autoName(family);
969
- const placement = {
970
- pageObjectNumber: pon,
971
- rect: toPdfRect(box, crop),
972
- ...appearance ? { appearance } : {}
973
- };
974
- const draft = family === "radio" ? {
975
- family,
976
- name,
977
- widgets: [{
978
- ...placement,
979
- onState: "option1"
980
- }]
981
- } : family === "combobox" || family === "listbox" ? {
982
- family,
983
- name,
984
- widget: placement,
985
- options: [{
986
- label: "Option 1",
987
- value: "Option 1"
988
- }, {
989
- label: "Option 2",
990
- value: "Option 2"
991
- }]
992
- } : {
993
- family,
994
- name,
995
- widget: placement
996
- };
997
- const result = await doc.forms.createField(draft);
998
- await refresh(true);
999
- apply({
1000
- t: "clearGeom",
1001
- pageObjectNumber: pon
1002
- });
1003
- if (annotationHost) await annotationHost.reloadPage(pon);
1004
- const widget = result.field.widgets.find((w) => w.pageObjectNumber === pon) ?? null;
3097
+ const setValues = async (entries, options) => {
3098
+ throwIfCancelled(options);
3099
+ const { applied, failed } = await fillPlain(entries, options);
1005
3100
  return {
1006
- field: result.field,
1007
- widget
3101
+ applied,
3102
+ skipped: [],
3103
+ failed
1008
3104
  };
1009
3105
  };
1010
- const updateFieldNow = async (key, patch) => {
1011
- const doc = ctx.doc;
1012
- if (!doc) return;
1013
- await doc.forms.updateField(refKeyOf(key), patch);
1014
- await refresh(true);
1015
- };
1016
- const deleteFieldNow = async (key) => {
1017
- const doc = ctx.doc;
1018
- if (!doc) return;
1019
- const pons = fieldByKey(model(), key)?.widgets.map((w) => w.pageObjectNumber).filter((p) => p > 0) ?? [];
1020
- await doc.forms.deleteField(refKeyOf(key));
1021
- await refresh(true);
1022
- for (const pon of new Set(pons)) apply({
1023
- t: "clearGeom",
1024
- pageObjectNumber: pon
1025
- });
1026
- nudgeAnnotations(pons);
1027
- };
1028
- const detachWidgetNow = async (key, annotObjectNumber) => {
1029
- const doc = ctx.doc;
1030
- if (!doc) return;
1031
- const widget = fieldByKey(model(), key)?.widgets.find((w) => w.annotObjectNumber === annotObjectNumber);
1032
- await doc.forms.detachWidget(refKeyOf(key), {
1033
- annotObjectNumber,
1034
- pageObjectNumber: widget?.pageObjectNumber ?? 0
1035
- });
1036
- await refresh(true);
1037
- if (widget && widget.pageObjectNumber > 0) {
1038
- apply({
1039
- t: "clearGeom",
1040
- pageObjectNumber: widget.pageObjectNumber
1041
- });
1042
- nudgeAnnotations([widget.pageObjectNumber]);
1043
- }
1044
- };
1045
- refresh();
1046
- return {
1047
- snapshot: () => model().snapshot,
1048
- refresh,
1049
- fillItems: fillItems$1,
1050
- fillItem,
1051
- ensureGeom,
1052
- field: (key) => fieldByKey(model(), key),
1053
- fieldForWidget: (annotObjectNumber) => fieldForWidget(model(), annotObjectNumber),
1054
- setText: (key, value) => write(key, {
1055
- type: "text",
1056
- value
1057
- }),
1058
- toggle: (key, onState) => write(key, {
1059
- type: "toggle",
1060
- state: onState
1061
- }),
1062
- choose: (key, values) => write(key, {
1063
- type: "choice",
1064
- values
1065
- }),
1066
- reset: (key) => enqueueMutation(async () => {
1067
- const doc = ctx.doc;
1068
- if (!doc) return;
1069
- apply({
1070
- t: "writeStart",
1071
- key
3106
+ const importValues = async (values, options) => {
3107
+ throwIfCancelled(options);
3108
+ if (!fields.view().snapshot) await fields.settled();
3109
+ const index = fields.view();
3110
+ const skipped = [];
3111
+ const entries = [];
3112
+ const names = /* @__PURE__ */ new Map();
3113
+ for (const [name, plain] of Object.entries(values)) {
3114
+ const field = fieldByRef(index, {
3115
+ kind: "fqn",
3116
+ name
1072
3117
  });
1073
- try {
1074
- const result = await doc.forms.reset(refKeyOf(key));
1075
- apply({
1076
- t: "writeDone",
1077
- key,
1078
- field: result.field
3118
+ if (!field) {
3119
+ skipped.push({
3120
+ ref: name,
3121
+ reason: "the form has no field with this name"
1079
3122
  });
1080
- } catch (err) {
1081
- apply({
1082
- t: "writeFailed",
1083
- key
3123
+ continue;
3124
+ }
3125
+ if (!rights.mayFill(field)) {
3126
+ skipped.push({
3127
+ ref: name,
3128
+ reason: "you may not fill in this field"
1084
3129
  });
1085
- throw err;
3130
+ continue;
1086
3131
  }
1087
- }),
1088
- commitValue: (ref, value) => enqueueMutation(() => commitValueNow(ref, value)),
1089
- activateWidget: (key, annotationRef) => enqueueMutation(() => activateWidgetNow(key, annotationRef)),
1090
- setUiEffectProvider: (provider) => {
1091
- uiEffectProvider = provider;
1092
- },
1093
- setValue: (ref, value) => enqueueMutation(async () => {
1094
- const doc = ctx.doc;
1095
- if (!doc) throw new Error("no document");
1096
- const result = await doc.forms.setValue(ref, value);
1097
- await refresh(true);
1098
- return result;
1099
- }),
1100
- exportData: async (format = "xfdf") => {
1101
- const doc = ctx.doc;
1102
- if (!doc) throw new Error("no document");
1103
- return doc.forms.exportData(format);
1104
- },
1105
- importData: (data, format) => enqueueMutation(async () => {
1106
- const doc = ctx.doc;
1107
- if (!doc) throw new Error("no document");
1108
- const result = await doc.forms.importData(data, format);
1109
- apply({
1110
- t: "snapshot",
1111
- snapshot: result.snapshot
3132
+ const value = writeOfPlainValue(field, plain);
3133
+ if (!value) {
3134
+ skipped.push({
3135
+ ref: name,
3136
+ reason: `a ${field.family} field can't take this value`
3137
+ });
3138
+ continue;
3139
+ }
3140
+ entries.push({
3141
+ ref: field.ref,
3142
+ value
1112
3143
  });
1113
- return result;
1114
- }),
1115
- repair: (repairOptions) => enqueueMutation(async () => {
1116
- const doc = ctx.doc;
1117
- if (!doc) throw new Error("no document");
1118
- const result = await doc.forms.repair(repairOptions);
1119
- await refresh(true);
1120
- return result;
1121
- }),
1122
- placeField: (input) => enqueueMutation(() => placeFieldNow(input)),
1123
- pageBox,
1124
- updateField: (key, patch) => enqueueMutation(() => updateFieldNow(key, patch)),
1125
- deleteField: (key) => enqueueMutation(() => deleteFieldNow(key)),
1126
- detachWidget: (key, annotObjectNumber) => enqueueMutation(() => detachWidgetNow(key, annotObjectNumber)),
1127
- canFill: () => can("doc.forms.fill"),
1128
- canModify: () => can("doc.forms.modify")
3144
+ names.set(JSON.stringify(field.ref), name);
3145
+ }
3146
+ const { applied, failed } = await fillPlain(entries, options);
3147
+ return {
3148
+ applied,
3149
+ skipped,
3150
+ failed: failed.map(({ ref, error }) => ({
3151
+ ref: names.get(JSON.stringify(ref)) ?? "",
3152
+ error
3153
+ }))
3154
+ };
1129
3155
  };
1130
- }
1131
- //#endregion
1132
- //#region src/effects.ts
1133
- const STRUCTURAL = /* @__PURE__ */ new Set([
1134
- "form.fieldCreated",
1135
- "form.fieldUpdated",
1136
- "form.fieldDeleted",
1137
- "form.widgetAttached",
1138
- "form.widgetDetached",
1139
- "form.repaired"
1140
- ]);
1141
- function registerFormEffects(ctx) {
1142
- const doc = ctx.doc;
1143
- if (!doc) return;
1144
- let refreshing = false;
1145
- const refresh = async () => {
1146
- if (refreshing) return;
1147
- refreshing = true;
1148
- try {
1149
- const snapshot = await doc.forms.list();
1150
- ctx.dispatch({
1151
- type: "SET_MODEL",
1152
- model: update(ctx.getState().model, {
1153
- t: "snapshot",
1154
- snapshot
1155
- })
1156
- });
1157
- } finally {
1158
- refreshing = false;
3156
+ return {
3157
+ /** A text field's write, for the text being typed (write/typing.ts). */
3158
+ setText: (ref, text) => commit(ref, { value: text }, "form.setValue"),
3159
+ api: {
3160
+ setValue: (ref, value, options) => commit(ref, value, "form.setValue", options),
3161
+ setValues,
3162
+ importValues
1159
3163
  }
1160
3164
  };
1161
- const unsubscribe = doc.events.subscribe((event) => {
1162
- if (!event.type.startsWith("form.")) return;
1163
- const structural = STRUCTURAL.has(event.type);
1164
- if (event.origin.kind !== "remote" && !structural) return;
1165
- if (structural) ctx.dispatch({
1166
- type: "SET_MODEL",
1167
- model: update(ctx.getState().model, { t: "clearGeom" })
1168
- });
1169
- refresh();
1170
- });
1171
- ctx.cleanup(unsubscribe);
1172
3165
  }
1173
3166
  //#endregion
1174
- //#region src/tools.ts
1175
- /** Palette tools keep widgets editable right after placement. */
1176
- const PLACE_TAGS = ["form-place", "annotation-edit"];
1177
- const FIELD_CHROME = {
1178
- interiorColor: "#ffffff",
1179
- color: "#6b7280",
1180
- strokeWidth: 1
1181
- };
1182
- const FORM_TOOLS = [
1183
- {
1184
- id: "form-text",
1185
- family: "text",
1186
- visualKind: "widget-text",
1187
- clickCreate: {
1188
- width: 160,
1189
- height: 24
1190
- },
1191
- defaults: {
1192
- ...FIELD_CHROME,
1193
- fontSize: 12
1194
- },
1195
- cursor: "crosshair"
1196
- },
1197
- {
1198
- id: "form-checkbox",
1199
- family: "checkbox",
1200
- visualKind: "widget-toggle",
1201
- clickCreate: {
1202
- width: 18,
1203
- height: 18
1204
- },
1205
- defaults: FIELD_CHROME,
1206
- cursor: "crosshair"
1207
- },
1208
- {
1209
- id: "form-radio",
1210
- family: "radio",
1211
- visualKind: "widget-toggle",
1212
- clickCreate: {
1213
- width: 18,
1214
- height: 18
1215
- },
1216
- defaults: FIELD_CHROME,
1217
- cursor: "crosshair"
1218
- },
1219
- {
1220
- id: "form-combobox",
1221
- family: "combobox",
1222
- visualKind: "widget-choice",
1223
- clickCreate: {
1224
- width: 140,
1225
- height: 24
1226
- },
1227
- defaults: {
1228
- ...FIELD_CHROME,
1229
- fontSize: 12
1230
- },
1231
- cursor: "crosshair"
1232
- },
1233
- {
1234
- id: "form-listbox",
1235
- family: "listbox",
1236
- visualKind: "widget-choice",
1237
- clickCreate: {
1238
- width: 140,
1239
- height: 72
1240
- },
1241
- defaults: {
1242
- ...FIELD_CHROME,
1243
- fontSize: 12
1244
- },
1245
- cursor: "crosshair"
1246
- }
1247
- ];
1248
- const FORM_TOOL_BY_ID = new Map(FORM_TOOLS.map((t) => [t.id, t]));
1249
- //#endregion
1250
- //#region src/handler.ts
1251
- const rectFrom = (a, b) => ({
1252
- x: Math.min(a.x, b.x),
1253
- y: Math.min(a.y, b.y),
1254
- width: Math.abs(b.x - a.x),
1255
- height: Math.abs(b.y - a.y)
1256
- });
3167
+ //#region src/controller.ts
1257
3168
  /**
1258
- * Draw-to-place: drag a box (live placement preview through the annotation
1259
- * plane's ghost pipeline) or just click (the tool's `clickCreate` policy,
1260
- * resolved by the SAME `resolveClickPlacement` the annotation core uses) —
1261
- * the commit creates field + widget through `doc.forms.placeField`, styled
1262
- * from the tool's live defaults. The tool stays active for repeat placement
1263
- * (v2 rubber-stamp feel) and the fresh widget is auto-selected.
1264
- *
1265
- * Gesture rules match the annotation handlers: page-anchored via the sample
1266
- * projection (the box keeps sizing along the edge when the cursor overshoots
1267
- * or crosses a gap), the UP sample is the final point, and a CLICK means
1268
- * width AND height under the shared threshold — a thin 100×2 drag is a drag.
3169
+ * The form controller: the composition root. It builds the plugin's services
3170
+ * once, wires each area with the services it declares, and assembles the
3171
+ * host capability from the areas' API slices. No behavior lives here: every
3172
+ * verb and read has a home in `read/`, `write/` or `sync/`.
1269
3173
  */
1270
- function createPlaceHandler(form, interaction, annotation) {
1271
- let origin = null;
1272
- return {
1273
- id: "form-place",
1274
- priority: 95,
1275
- enabledFor: (t) => t.enables.has("form-place"),
1276
- onDown: (s) => {
1277
- if (!s.page || !FORM_TOOL_BY_ID.has(interaction.activeToolId())) return false;
1278
- if (!form.canModify()) return false;
1279
- origin = {
1280
- pon: s.page.pon,
1281
- start: s.page.point,
1282
- last: s.page.point
1283
- };
1284
- return true;
1285
- },
1286
- onMove: (s) => {
1287
- if (!origin) return;
1288
- const point = samplePointOn(s, origin.pon);
1289
- if (!point) return;
1290
- origin.last = point;
1291
- const box = rectFrom(origin.start, point);
1292
- if (annotation) if (Math.max(box.width, box.height) >= MIN_DRAG) annotation.setPlacementPreview(interaction.activeToolId(), origin.pon, box);
1293
- else annotation.clearPlacementPreview();
1294
- },
1295
- onUp: (s) => {
1296
- if (!origin) return;
1297
- const o = origin;
1298
- origin = null;
1299
- annotation?.clearPlacementPreview();
1300
- const toolId = interaction.activeToolId();
1301
- const tool = FORM_TOOL_BY_ID.get(toolId);
1302
- if (!tool) return;
1303
- const end = samplePointOn(s, o.pon) ?? o.last;
1304
- const dragged = rectFrom(o.start, end);
1305
- const isClick = dragged.width < MIN_DRAG && dragged.height < MIN_DRAG;
1306
- const pageBox = form.pageBox(o.pon);
1307
- const box = isClick ? boxOfClick(o.start, tool.clickCreate, pageBox) : dragged;
1308
- form.placeField({
1309
- family: tool.family,
1310
- pageObjectNumber: o.pon,
1311
- box,
1312
- appearance: widgetAppearanceFromProps(annotation ? annotation.currentDefaults(toolId) : tool.defaults)
1313
- }).then((placed) => {
1314
- if (!annotation || interaction.activeToolId() !== toolId) return;
1315
- const widget = placed.widget;
1316
- if (!widget || widget.annotObjectNumber <= 0) return;
1317
- annotation.select({
1318
- kind: "objectNumber",
1319
- annotObjectNumber: widget.annotObjectNumber,
1320
- pageObjectNumber: o.pon
1321
- });
1322
- }).catch((err) => {
1323
- globalThis.console?.error("[form] placeField failed:", err);
1324
- });
3174
+ function createFormController(ctx) {
3175
+ const services = createServices(ctx);
3176
+ const { events, rights } = services;
3177
+ const settings = ctx.settings();
3178
+ const fields = createFieldReads(ctx, services);
3179
+ const widgets = createWidgetReads(ctx, services);
3180
+ const settingsReads = createFieldSettings(services);
3181
+ const fills = createFill(ctx, services);
3182
+ const values = createValueWrites(ctx, services, fills);
3183
+ const typing = createTyping(ctx, services, values.setText);
3184
+ const resets = createResetWrites(ctx, services, fills);
3185
+ const design = createFieldWrites(ctx, services);
3186
+ const interchange = createInterchange(ctx, services);
3187
+ const activation = createActivation(ctx, services, fills);
3188
+ const scripts = createScriptEffects(ctx, services, fills);
3189
+ const focus = createFocus(ctx, services, {
3190
+ setValue: values.api.setValue,
3191
+ activateWidget: activation.api.activateWidget
3192
+ });
3193
+ const api = composeApi("form", [
3194
+ settings.api,
3195
+ fields.api,
3196
+ widgets.api,
3197
+ settingsReads.api,
3198
+ values.api,
3199
+ typing.api,
3200
+ resets.api,
3201
+ design.api,
3202
+ interchange.api,
3203
+ activation.api,
3204
+ scripts.api,
3205
+ focus.api,
3206
+ {
3207
+ canRead: () => ctx.allows("doc.forms.read"),
3208
+ canFill: (ref) => {
3209
+ const field = fieldByRef(services.fields.view(), ref);
3210
+ return field !== null && rights.mayFill(field);
3211
+ },
3212
+ canDesign: () => ctx.allows("doc.forms.modify"),
3213
+ canRestoreAttribution: () => ctx.allows("doc.forms.import"),
3214
+ canWriteScripts: () => ctx.allows("doc.forms.script"),
3215
+ onValueChanged: events.valueChanged.on,
3216
+ onFieldCreated: events.fieldCreated.on,
3217
+ onFieldUpdated: events.fieldUpdated.on,
3218
+ onFieldDeleted: events.fieldDeleted.on,
3219
+ onValidationRejected: events.validationRejected.on,
3220
+ onResynced: events.resynced.on
1325
3221
  }
3222
+ ]);
3223
+ return {
3224
+ api,
3225
+ connect: () => connectForm(ctx, api, createWidgetLender(ctx, services))
1326
3226
  };
1327
3227
  }
1328
- /** The click-create box through the SHARED placement layer (fields are boxes;
1329
- * the policy anchor + page clamp are exactly the annotation click's). */
1330
- function boxOfClick(point, policy, pageBox) {
1331
- const placement = resolveClickPlacement(point, policy, { pageBox: pageBox ?? void 0 });
1332
- return placement.kind === "box" ? placement.rect : {
1333
- x: point.x,
1334
- y: point.y,
1335
- width: policy.width,
1336
- height: policy.height
1337
- };
1338
- }
1339
- //#endregion
1340
- //#region src/reducer.ts
1341
- const initialFormState = () => ({ model: initialModel() });
1342
- /** Dumb store: the pure core computes the next model; the shell dispatches it. */
1343
- const formReducer = (state, action) => action.type === "SET_MODEL" ? { model: action.model } : state;
1344
- //#endregion
1345
- //#region src/types.ts
1346
- const FormToken = createCapabilityToken("form");
1347
3228
  //#endregion
1348
3229
  //#region src/form.plugin.ts
1349
3230
  /**
1350
- * The form plugin: the FIELD plane. Document-scoped; requires the
1351
- * interaction hub. Fill mode works with no annotation plugin at all —
1352
- * geometry is read from the engine's widget DTOs. When the annotation
1353
- * plugin IS present, a Behavior keeps widgets geometry-inert while the
1354
- * active tool carries 'form-fill' (the built-in pointer/pan tools do, so
1355
- * filling is the resting state) and stands the fill controls down under
1356
- * every other tool — the single-active-tool hub IS the mode switch.
1357
- * Design mode = the 'form-edit' / palette tools: no 'form-fill' tag, so
1358
- * widgets become ordinary editable annotations.
3231
+ * The form plugin: the field plane. Document-scoped; requires the
3232
+ * interaction hub. Filling works without the annotation plugin, because
3233
+ * widget geometry is read from the engine's widget records. The active tool
3234
+ * is the mode switch: while it carries 'form-fill' (the built-in pointer and
3235
+ * pan tools do, so filling is the resting state), the form layer draws and
3236
+ * fills every widget. Design mode is the 'form-edit' and palette tools: with
3237
+ * the annotation plugin present, the form lends it the widgets, which its
3238
+ * tools then select, move, restyle and delete. The render plugin draws the
3239
+ * widgets' pictures in both modes. With the fonts plugin, a text field in a
3240
+ * font of its own is edited in that font's program. `config` is the settings the app
3241
+ * registers, over {@link FORM_DEFAULTS}.
1359
3242
  */
1360
- const formPlugin = (options = {}) => definePlugin({
3243
+ const formPlugin = (config) => definePlugin({
1361
3244
  id: "form",
1362
- token: FormToken,
3245
+ token: FormToken$1,
1363
3246
  scope: "document",
1364
3247
  requires: [InteractionToken],
1365
- optional: [AnnotationToken],
1366
- initialState: initialFormState,
1367
- reduce: formReducer,
1368
- capability: (ctx) => createFormCapability(ctx, options),
1369
- effects: registerFormEffects,
1370
- init: (ctx) => {
1371
- const interaction = ctx.get(InteractionToken);
1372
- const form = ctx.get(FormToken);
1373
- interaction.registerTool({
1374
- id: "form-fill",
1375
- cursor: "default",
1376
- enables: /* @__PURE__ */ new Set(["form-fill", "link-nav"])
1377
- });
1378
- interaction.registerTool({
1379
- id: "form-edit",
1380
- cursor: "default",
1381
- enables: /* @__PURE__ */ new Set(["annotation-edit", "annotation-marquee"])
1382
- });
1383
- const annotation = ctx.tryGet(AnnotationToken$1);
1384
- for (const t of FORM_TOOLS) if (annotation) annotation.registerTool({
1385
- id: t.id,
1386
- subtype: t.visualKind,
1387
- cursor: t.cursor,
1388
- enables: [...PLACE_TAGS],
1389
- clickCreate: t.clickCreate,
1390
- defaults: t.defaults
1391
- });
1392
- else interaction.registerTool({
1393
- id: t.id,
1394
- cursor: t.cursor,
1395
- enables: new Set(PLACE_TAGS)
1396
- });
1397
- interaction.registerHandler(createPlaceHandler(form, interaction, annotation));
1398
- if (annotation) annotation.registerBehavior({
1399
- id: "form-widgets",
1400
- matches: (a) => a.subtype.startsWith("widget"),
1401
- engaged: () => interaction.activeTool()?.enables.has("form-fill") ?? false
1402
- });
3248
+ optional: [
3249
+ AnnotationToken,
3250
+ ActionsToken,
3251
+ RenderToken,
3252
+ FontsToken
3253
+ ],
3254
+ state: initialFormModel,
3255
+ settings: {
3256
+ defaults: FORM_DEFAULTS,
3257
+ registered: config
3258
+ },
3259
+ create: createFormController
3260
+ });
3261
+ const formState = defineState(FormToken, {
3262
+ read: (form) => ({
3263
+ fields: form.list(),
3264
+ status: form.getStatus(),
3265
+ formKind: form.getFormKind(),
3266
+ selectedField: form.getSelectedField(),
3267
+ focusedField: form.getFocusedField()
3268
+ }),
3269
+ empty: {
3270
+ fields: Object.freeze([]),
3271
+ status: "idle",
3272
+ formKind: "none",
3273
+ selectedField: null,
3274
+ focusedField: null
1403
3275
  }
1404
3276
  });
1405
3277
  //#endregion
1406
- export { FORM_TOOLS, FORM_TOOL_BY_ID, FormScriptingController, FormToken, createFormScriptingController, createSerialMutationQueue, fieldKeyOf, formPlugin };
3278
+ export { FORM_DEFAULTS, FORM_TOOLS, FORM_TOOL_BY_ID, FormScriptingController, FormToken, FormTransfer, createFormScriptingController, formPlugin, formState, toFieldRef };
1407
3279
 
1408
3280
  //# sourceMappingURL=index.js.map