@embedpdf/plugin-form 3.0.0-next.9 → 3.1.0

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