@embedpdf/plugin-form 3.1.0 → 3.3.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.js CHANGED
@@ -1,4 +1,4 @@
1
- import { i as FormToken, n as FormTransfer, r as toFieldRef, t as FORM_DEFAULTS } from "./contract-BdEaLXUK.js";
1
+ import { i as FormToken, n as FormTransfer, r as toFieldRef, t as FORM_DEFAULTS } from "./contract-Bu3RA2jA.js";
2
2
  import { n as createFormScriptingController, r as scriptError, t as FormScriptingController } from "./controller-BbC8XWpY.js";
3
3
  import { FormToken as FormToken$1 } from "./contract/host.js";
4
4
  import { PluginError, composeApi, definePlugin, defineState, memo, memoByKey, reload, toPluginError, toPluginErrorInfo } from "@embedpdf/core";
@@ -7,7 +7,7 @@ import { AnnotationToken } from "@embedpdf/plugin-annotation/contract";
7
7
  import { FontsToken } from "@embedpdf/plugin-fonts/contract";
8
8
  import { InteractionToken, samplePointOn } from "@embedpdf/plugin-interaction/contract/host";
9
9
  import { RenderToken } from "@embedpdf/plugin-render/contract";
10
- import { annotationKey, draftWritesScripts, fieldAfterReset, fieldAfterValue, fieldValueOf, fieldValueWriteOf, formEffectOps, formFieldAfter, formFieldOfDraft, isStandardFontName, pageRefsEqual, reorderPart, reorderedList, serializeError, tabOrderOf, toFieldRef as toFieldRef$1, widgetAfterPatch, widgetsAfterDisplay, writesScripts } from "@embedpdf/engine-core/runtime";
10
+ import { annotationKey, draftWritesScripts, fieldAfterReset, fieldAfterValue, fieldValueOf, fieldValueWriteOf, formEffectOps, formFieldAfter, formFieldOfDraft, isStandardFontName, pageRefsEqual, planFormCopies, reorderPart, reorderedList, serializeError, tabOrderOf, toFieldRef as toFieldRef$1, widgetAfterPatch, widgetFlagsOf, widgetPlacementOf, widgetsAfterDisplay, writesScripts } from "@embedpdf/engine-core/runtime";
11
11
  import { ActionsToken as ActionsToken$1 } from "@embedpdf/plugin-actions/contract/host";
12
12
  import { AnnotationToken as AnnotationToken$1 } from "@embedpdf/plugin-annotation/contract/host";
13
13
  import { gesturePlacement, refOf, widgetAppearanceOf } from "@embedpdf/core-annotation";
@@ -582,8 +582,16 @@ function fieldsWithChangedValues(previous, next) {
582
582
  });
583
583
  }
584
584
  const valueEntryOf = (field) => "valueEntry" in field ? field.valueEntry : null;
585
- /** Whether a widget shows on screen: its `hidden` and `noView` flags hide it. */
586
- const shownOnScreen = (row) => !row.hidden && !row.noView;
585
+ /**
586
+ * Whether a widget's box has an area. One of no size is how a PDF keeps a field that shows
587
+ * nowhere: the field of a document timestamp, an invisible signature.
588
+ */
589
+ const hasArea = (row) => row.rect.width > 0 && row.rect.height > 0;
590
+ /**
591
+ * Whether a widget shows on screen: its `hidden` and `noView` flags hide it, and a box of no
592
+ * size has nothing to show. What doesn't show gets no control, and Tab doesn't stop at it.
593
+ */
594
+ const shownOnScreen = (row) => !row.hidden && !row.noView && hasArea(row);
587
595
  /** The widgets one page shows, from the form's widget rows. */
588
596
  function pageWidgetsOf(index, pageObjectNumber) {
589
597
  const widgets = {};
@@ -759,9 +767,14 @@ function createFieldReads(ctx, { fields, rights, siblings }) {
759
767
  };
760
768
  });
761
769
  const getSelectedField = memo(() => [fields.view(), siblings.annotation()?.selection.getSelected() ?? NOTHING_SELECTED], (index, selected) => {
762
- const [annotation] = selected;
763
- if (selected.length !== 1 || !annotation?.subtype.startsWith("widget")) return null;
764
- return fieldForWidget(index, widgetObjectOf(annotation.ref));
770
+ let found = null;
771
+ for (const annotation of selected) {
772
+ if (!annotation.subtype.startsWith("widget")) return null;
773
+ const field = fieldForWidget(index, widgetObjectOf(annotation.ref));
774
+ if (!field || found && fieldKeyOf(found) !== fieldKeyOf(field)) return null;
775
+ found = field;
776
+ }
777
+ return found;
765
778
  });
766
779
  return { api: {
767
780
  getSnapshot: () => fields.view().snapshot,
@@ -1119,8 +1132,8 @@ const RESET_FAMILIES = /* @__PURE__ */ new Set([
1119
1132
  * `widgetAfterPatch`): what the fields and their widgets hold after it. An op
1120
1133
  * those rules refuse shows nothing; one whose values only the engine's schemas
1121
1134
  * refuse shows until the engine's refusal takes the change away.
1122
- * A create shows once it names its numbers; taking a widget out of its field
1123
- * shows once the engine answers.
1135
+ * A create, a copy and a new widget show once they name their numbers; taking
1136
+ * a widget out of its field shows once the engine answers.
1124
1137
  *
1125
1138
  * The view replays every pending change each time any change is staged; the
1126
1139
  * same op over the same form gives the same form, so a field keeps its object
@@ -1155,6 +1168,8 @@ function predictOnce(index, op) {
1155
1168
  return op.field ? upsertFields(restored, [op.field]) : restored;
1156
1169
  }
1157
1170
  case "forms.create": return createdField(index, op);
1171
+ case "forms.copy": return copiedFields(index, op);
1172
+ case "forms.addWidget": return addedWidget(index, op);
1158
1173
  case "forms.update": {
1159
1174
  const field = fieldByRef(index, op.field);
1160
1175
  return field ? withFields(index, [formFieldAfter(withRows(index, field), op.patch)]) : index;
@@ -1229,6 +1244,106 @@ function createdField(index, op) {
1229
1244
  }, index.pictureVersions) : index, [created]);
1230
1245
  return op.draft.actions?.calculate ? withCalculationOrder(next, [...snapshot.calculationOrder, created.field.ref]) : next;
1231
1246
  }
1247
+ /**
1248
+ * The fields a `forms.copy` makes, by the engine's own rule
1249
+ * (`planFormCopies`), each with the object numbers the op names: its own,
1250
+ * then its widgets'. None for a copy that doesn't name them all, which
1251
+ * shows when the engine answers, and none for one the engine would refuse.
1252
+ * What a script right leaves out is the engine's to say: nothing of it shows.
1253
+ */
1254
+ function copiesOf(index, op) {
1255
+ const { snapshot } = index;
1256
+ if (!snapshot || !op.objectNumbers) return [];
1257
+ let creates;
1258
+ try {
1259
+ creates = planFormCopies({
1260
+ form: snapshot,
1261
+ fields: op.fields,
1262
+ ...op.widgets ? { widgets: op.widgets } : {},
1263
+ placement: {
1264
+ ...op.page ? { page: op.page } : {},
1265
+ ...op.offset ? { offset: op.offset } : {}
1266
+ },
1267
+ values: op.values ?? true,
1268
+ mayScript: true
1269
+ }).creates;
1270
+ } catch {
1271
+ return [];
1272
+ }
1273
+ const needed = creates.reduce((count, create) => count + 1 + create.widgets.length, 0);
1274
+ if (op.objectNumbers.length !== needed) return [];
1275
+ let at = 0;
1276
+ return creates.map((create) => {
1277
+ const [objectNumber, ...widgetObjectNumbers] = op.objectNumbers.slice(at, at + 1 + create.widgets.length);
1278
+ at += 1 + create.widgets.length;
1279
+ return {
1280
+ ...create,
1281
+ objectNumber,
1282
+ widgetObjectNumbers
1283
+ };
1284
+ });
1285
+ }
1286
+ /**
1287
+ * `forms.copy`: each copy as a create of the same field shows (`createdField`),
1288
+ * then its widgets' flags, which a create writes none of, and its value.
1289
+ */
1290
+ function copiedFields(index, op) {
1291
+ let next = index;
1292
+ for (const copy of copiesOf(index, op)) {
1293
+ const ref = {
1294
+ kind: "objectNumber",
1295
+ objectNumber: copy.objectNumber
1296
+ };
1297
+ if (fieldByRef(next, ref)) continue;
1298
+ next = createdField(next, {
1299
+ type: "forms.create",
1300
+ draft: copy.draft,
1301
+ objectNumber: copy.objectNumber,
1302
+ widgetObjectNumbers: copy.widgetObjectNumbers
1303
+ });
1304
+ const made = fieldByRef(next, ref);
1305
+ if (!made) continue;
1306
+ next = upsertWidgets(next, rowsOfField(next, made).map((row, at) => widgetAfterPatch(row, copy.flags[at] ?? {})));
1307
+ if (copy.value) next = withFields(next, [fieldAfterValue(withRows(next, made), copy.value)]);
1308
+ }
1309
+ return next;
1310
+ }
1311
+ /**
1312
+ * `forms.addWidget`, once it names its widget's number: the widget as a
1313
+ * create of a field of that kind places it, last among the field's. One that
1314
+ * splits a merged field (the field's own widget moves to a new number) shows
1315
+ * when the engine answers.
1316
+ */
1317
+ function addedWidget(index, op) {
1318
+ if (op.objectNumber === void 0 || op.splitObjectNumber !== void 0) return index;
1319
+ const field = fieldByRef(index, op.field);
1320
+ if (!field || field.kind === "unknown" || field.ref.kind !== "objectNumber") return index;
1321
+ if (widgetRowOf(index, op.objectNumber)) return index;
1322
+ const options = "options" in field ? { options: field.options.map(({ label, value }) => ({
1323
+ label,
1324
+ value
1325
+ })) } : {};
1326
+ const made = formFieldOfDraft({
1327
+ kind: field.kind,
1328
+ name: field.name,
1329
+ ...options,
1330
+ widgets: [op.placement]
1331
+ }, {
1332
+ objectNumber: field.ref.objectNumber,
1333
+ widgets: [{
1334
+ kind: "objectNumber",
1335
+ page: op.placement.page,
1336
+ objectNumber: op.objectNumber
1337
+ }]
1338
+ });
1339
+ const [widget] = made.field.widgets;
1340
+ const [row] = made.widgets;
1341
+ if (!widget || !row) return index;
1342
+ return upsertWidgets(upsertFields(index, [{
1343
+ ...field,
1344
+ widgets: [...field.widgets, widget]
1345
+ }]), [row]);
1346
+ }
1232
1347
  /** The fields a change's ops write a value or a look to, each once, in op order. */
1233
1348
  function fieldsNamedBy(index, ops) {
1234
1349
  const named = /* @__PURE__ */ new Map();
@@ -1277,6 +1392,21 @@ function undoOfOp(index, op) {
1277
1392
  objectNumber: op.objectNumber
1278
1393
  }
1279
1394
  }];
1395
+ case "forms.copy": return copiesOf(index, op).map((copy) => ({
1396
+ type: "forms.delete",
1397
+ field: {
1398
+ kind: "objectNumber",
1399
+ objectNumber: copy.objectNumber
1400
+ }
1401
+ })).reverse();
1402
+ case "forms.addWidget": return op.objectNumber === void 0 ? [] : [{
1403
+ type: "forms.deleteWidget",
1404
+ widget: {
1405
+ kind: "objectNumber",
1406
+ page: op.placement.page,
1407
+ objectNumber: op.objectNumber
1408
+ }
1409
+ }];
1280
1410
  case "forms.update":
1281
1411
  case "forms.delete": {
1282
1412
  const field = fieldByRef(index, op.field);
@@ -1562,7 +1692,7 @@ function createFormattedTexts(ctx, fields) {
1562
1692
  * while the picture it holds is older than the widget's look.
1563
1693
  */
1564
1694
  const NOTHING_SHOWN = Object.freeze([]);
1565
- const numberOf = (ref) => ref.kind === "objectNumber" ? ref.objectNumber : -1;
1695
+ const numberOf$1 = (ref) => ref.kind === "objectNumber" ? ref.objectNumber : -1;
1566
1696
  function createWidgetLooks({ fields, formatted, design, fonts }) {
1567
1697
  /** Moves when the fonts plugin may draw a widget's text differently. */
1568
1698
  const fontsEpoch = () => fonts()?.getPaintFontsEpoch() ?? 0;
@@ -1617,7 +1747,7 @@ function createWidgetLooks({ fields, formatted, design, fonts }) {
1617
1747
  design.lending(),
1618
1748
  fontsEpoch()
1619
1749
  ], (pageObjectNumber, view, truth, _formatted, lent) => lent ? NOTHING_SHOWN : shownWidgetsOf(view, pageObjectNumber, (row) => {
1620
- const number = numberOf(row.ref);
1750
+ const number = numberOf$1(row.ref);
1621
1751
  return {
1622
1752
  pending: lookOf(view, number) !== lookOf(truth, number),
1623
1753
  pictureVersion: pictureVersionOf(truth, number)
@@ -1629,7 +1759,7 @@ function createWidgetLooks({ fields, formatted, design, fonts }) {
1629
1759
  * unless `now`, then in the widget's standard font.
1630
1760
  */
1631
1761
  const paint = (row, box, rotation, now = false) => {
1632
- const field = fieldForWidget(fields.view(), numberOf(row.ref));
1762
+ const field = fieldForWidget(fields.view(), numberOf$1(row.ref));
1633
1763
  if (!field) return null;
1634
1764
  const text = formatted.textOf(field);
1635
1765
  const shown = text === null ? {} : { text };
@@ -1684,10 +1814,10 @@ function createWidgetLooks({ fields, formatted, design, fonts }) {
1684
1814
  };
1685
1815
  return {
1686
1816
  listShownWidgets: (pageObjectNumber) => shownOn(pageObjectNumber),
1687
- getWidgetPainting: (ref) => sceneOf(numberOf(ref)),
1817
+ getWidgetPainting: (ref) => sceneOf(numberOf$1(ref)),
1688
1818
  /** The widget's look in the view isn't its confirmed look yet: it draws live until its picture is. */
1689
1819
  isPending: (ref) => {
1690
- const number = numberOf(ref);
1820
+ const number = numberOf$1(ref);
1691
1821
  return lookOf(fields.view(), number) !== lookOf(fields.get(), number);
1692
1822
  },
1693
1823
  /**
@@ -1695,12 +1825,12 @@ function createWidgetLooks({ fields, formatted, design, fonts }) {
1695
1825
  * for one whose field it doesn't draw, or with a mark in it, which only its picture shows.
1696
1826
  */
1697
1827
  painterOf: (row) => {
1698
- const field = fieldForWidget(fields.view(), numberOf(row.ref));
1828
+ const field = fieldForWidget(fields.view(), numberOf$1(row.ref));
1699
1829
  return field && paints(field) && !row.hasMark ? (box) => paint(row, box, 0, true) ?? [] : null;
1700
1830
  },
1701
1831
  getTextEditorLayout: (ref, text) => {
1702
1832
  const view = fields.view();
1703
- const number = numberOf(ref);
1833
+ const number = numberOf$1(ref);
1704
1834
  const row = widgetRowOf(view, number);
1705
1835
  const field = row ? fieldForWidget(view, number) : null;
1706
1836
  if (!row || !field) return null;
@@ -1709,7 +1839,7 @@ function createWidgetLooks({ fields, formatted, design, fonts }) {
1709
1839
  return layout && (painted ? layout : inItsFont(layout, row.fontFamily ?? null));
1710
1840
  },
1711
1841
  getWidgetFontCss: (ref) => {
1712
- const row = widgetRowOf(fields.view(), numberOf(ref));
1842
+ const row = widgetRowOf(fields.view(), numberOf$1(ref));
1713
1843
  return row ? fontCssOf(row.fontFamily ?? "helvetica") : null;
1714
1844
  }
1715
1845
  };
@@ -1991,6 +2121,182 @@ function createObjectNumbers(ctx) {
1991
2121
  };
1992
2122
  }
1993
2123
  //#endregion
2124
+ //#region src/write/new-widget.ts
2125
+ /**
2126
+ * The value a radio group's new button gets: the next free `Choice<n>`,
2127
+ * counting on from its buttons (the radio tool names its first `Choice1`).
2128
+ */
2129
+ function nextChoiceOf(exportValues) {
2130
+ const taken = new Set(exportValues);
2131
+ let n = exportValues.length + 1;
2132
+ while (taken.has(`Choice${n}`)) n += 1;
2133
+ return `Choice${n}`;
2134
+ }
2135
+ /** Whether the field's dictionary is its only widget's too, which adding a widget splits. */
2136
+ const isMerged = (field) => field.ref.kind === "objectNumber" && field.widgets.some((widget) => widget.objectNumber === field.ref.objectNumber);
2137
+ //#endregion
2138
+ //#region src/write/duplicate.ts
2139
+ /**
2140
+ * Duplicate, for a form's widgets. What a copy becomes follows from what its
2141
+ * widget is. A radio button is one answer of its group, so its copy is
2142
+ * another button of that group (`forms.addWidget`), with the next free value.
2143
+ * Any other widget is a whole question, so its copy is a new field
2144
+ * (`forms.copy`), and widgets of one field copied together become one new
2145
+ * field. Pure: the ops, given the object numbers they take.
2146
+ */
2147
+ /** The flags a widget has when a create or `addWidget` made it. */
2148
+ const NEW_WIDGET_FLAGS = {
2149
+ invisible: false,
2150
+ hidden: false,
2151
+ print: true,
2152
+ noZoom: false,
2153
+ noRotate: false,
2154
+ noView: false,
2155
+ readOnly: false,
2156
+ locked: false,
2157
+ toggleNoView: false,
2158
+ lockedContents: false
2159
+ };
2160
+ /** The flags of `row` a new widget doesn't have, as a widget patch. */
2161
+ function flagsToSet(row) {
2162
+ const flags = widgetFlagsOf(row);
2163
+ const fresh = NEW_WIDGET_FLAGS;
2164
+ return Object.fromEntries(Object.entries(flags).filter(([name, value]) => value !== fresh[name]));
2165
+ }
2166
+ const numberOf = (ref) => ref.kind === "objectNumber" ? ref.objectNumber : -1;
2167
+ /**
2168
+ * The ops that copy `widgets`, which the form shows, by the rule above.
2169
+ * `mayScript` is whether the session may write scripts, submits and links: a
2170
+ * copied radio button is a write of this plugin's, so it leaves them out
2171
+ * itself; a copied field is the engine's write, which leaves them out there.
2172
+ * Throws `not-found` for a widget the form doesn't show.
2173
+ */
2174
+ function widgetDuplicateOf(index, widgets, placement, options) {
2175
+ const { snapshot } = index;
2176
+ const offset = placement.offset ?? {
2177
+ x: 0,
2178
+ y: 0
2179
+ };
2180
+ const dropped = [];
2181
+ const rows = widgets.map((ref) => {
2182
+ const row = widgetRowOf(index, numberOf(ref));
2183
+ if (!row || !snapshot) throw new PluginError("not-found", "form", `no widget ${annotationKey(ref)}`);
2184
+ return row;
2185
+ });
2186
+ /** The fields copied whole or in part, in the order their first widget was given. */
2187
+ const fields = [];
2188
+ const only = [];
2189
+ /** Each radio button copied, with the new button's place, look and value. */
2190
+ const buttons = [];
2191
+ const values = /* @__PURE__ */ new Map();
2192
+ const split = /* @__PURE__ */ new Set();
2193
+ for (const row of rows) {
2194
+ const field = fieldForWidget(index, numberOf(row.ref));
2195
+ if (!field) {
2196
+ dropped.push({
2197
+ ref: null,
2198
+ widget: row.ref,
2199
+ reason: "no-field"
2200
+ });
2201
+ continue;
2202
+ }
2203
+ const key = fieldKeyOf(field);
2204
+ if (field.kind !== "radio") {
2205
+ if (!fields.some((known) => fieldKeyOf(known) === key)) fields.push(field);
2206
+ only.push(row.ref);
2207
+ continue;
2208
+ }
2209
+ const taken = values.get(key) ?? field.widgets.map((widget) => widget.exportValue);
2210
+ const exportValue = nextChoiceOf(taken);
2211
+ values.set(key, [...taken, exportValue]);
2212
+ const look = widgetPlacementOf(field, row, (same) => same, options.mayScript, dropped);
2213
+ buttons.push({
2214
+ row,
2215
+ field,
2216
+ placement: {
2217
+ ...look,
2218
+ ...placement.page ? { page: placement.page } : {},
2219
+ ...look.rect ? { rect: {
2220
+ ...look.rect,
2221
+ x: look.rect.x + offset.x,
2222
+ y: look.rect.y + offset.y
2223
+ } } : {},
2224
+ exportValue
2225
+ },
2226
+ split: isMerged(field) && !split.has(key)
2227
+ });
2228
+ split.add(key);
2229
+ }
2230
+ let plan = null;
2231
+ if (fields.length > 0 && snapshot) plan = planFormCopies({
2232
+ form: snapshot,
2233
+ fields: fields.map((field) => field.ref),
2234
+ widgets: only,
2235
+ placement,
2236
+ values: options.values,
2237
+ mayScript: true
2238
+ });
2239
+ const forFields = plan ? plan.creates.reduce((count, create) => count + 1 + create.widgets.length, 0) : 0;
2240
+ return {
2241
+ needs: forFields + buttons.reduce((count, button) => count + (button.split ? 2 : 1), 0),
2242
+ dropped,
2243
+ build(numbers) {
2244
+ const ops = [];
2245
+ const copyOf = /* @__PURE__ */ new Map();
2246
+ let at = 0;
2247
+ if (plan) {
2248
+ ops.push({
2249
+ type: "forms.copy",
2250
+ fields: fields.map((field) => field.ref),
2251
+ widgets: only,
2252
+ ...placement.page ? { page: placement.page } : {},
2253
+ ...placement.offset ? { offset: placement.offset } : {},
2254
+ values: options.values,
2255
+ objectNumbers: numbers.slice(0, forFields)
2256
+ });
2257
+ for (const create of plan.creates) {
2258
+ at += 1;
2259
+ create.widgets.forEach((source, widget) => {
2260
+ copyOf.set(annotationKey(source), {
2261
+ kind: "objectNumber",
2262
+ page: create.draft.widgets[widget].page,
2263
+ objectNumber: numbers[at + widget]
2264
+ });
2265
+ });
2266
+ at += create.widgets.length;
2267
+ }
2268
+ }
2269
+ for (const button of buttons) {
2270
+ const objectNumber = numbers[at];
2271
+ const copy = {
2272
+ kind: "objectNumber",
2273
+ page: button.placement.page,
2274
+ objectNumber
2275
+ };
2276
+ ops.push({
2277
+ type: "forms.addWidget",
2278
+ field: button.field.ref,
2279
+ placement: button.placement,
2280
+ objectNumber,
2281
+ ...button.split ? { splitObjectNumber: numbers[at + 1] } : {}
2282
+ });
2283
+ at += button.split ? 2 : 1;
2284
+ const flags = flagsToSet(button.row);
2285
+ if (Object.keys(flags).length > 0) ops.push({
2286
+ type: "forms.updateWidget",
2287
+ widget: copy,
2288
+ patch: flags
2289
+ });
2290
+ copyOf.set(annotationKey(button.row.ref), copy);
2291
+ }
2292
+ return {
2293
+ ops,
2294
+ copies: rows.flatMap((row) => copyOf.get(annotationKey(row.ref)) ?? [])
2295
+ };
2296
+ }
2297
+ };
2298
+ }
2299
+ //#endregion
1994
2300
  //#region src/write/next-in-line.ts
1995
2301
  const fits = (box, page) => box.x >= 0 && box.y >= 0 && box.x + box.width <= page.width && box.y + box.height <= page.height;
1996
2302
  /** The box after `boxes`, the field's widgets on one page in the field's order. */
@@ -2085,13 +2391,8 @@ const lookOf = (widget) => {
2085
2391
  function exportValueFor(field) {
2086
2392
  if (field.kind === "checkbox") return field.exportValue;
2087
2393
  if (field.kind !== "radio") return void 0;
2088
- const taken = new Set(field.widgets.map((widget) => widget.exportValue));
2089
- let n = field.widgets.length + 1;
2090
- while (taken.has(`Choice${n}`)) n += 1;
2091
- return `Choice${n}`;
2394
+ return nextChoiceOf(field.widgets.map((widget) => widget.exportValue));
2092
2395
  }
2093
- /** Whether the field's dictionary is its only widget's too, which adding a widget splits. */
2094
- const isMerged = (field) => field.ref.kind === "objectNumber" && field.widgets.some((widget) => widget.objectNumber === field.ref.objectNumber);
2095
2396
  const MODIFY = "doc.forms.modify";
2096
2397
  const SCRIPT = "doc.forms.script";
2097
2398
  function createFieldWrites(ctx, { fields, enqueue }) {
@@ -2107,6 +2408,12 @@ function createFieldWrites(ctx, { fields, enqueue }) {
2107
2408
  ops: [op],
2108
2409
  undo: undoLookOf(fields.view(), [op])
2109
2410
  });
2411
+ /** Stage the ops of one design verb as one change, one step of the history. */
2412
+ const stageAll = (verb, ops) => ctx.changes.stage({
2413
+ label: { key: `form.${verb}` },
2414
+ ops: [...ops],
2415
+ undo: undoLookOf(fields.view(), ops)
2416
+ });
2110
2417
  /** The engine's answer to a staged design change: its one item. */
2111
2418
  const answer = async (change, options) => {
2112
2419
  try {
@@ -2163,67 +2470,180 @@ function createFieldWrites(ctx, { fields, enqueue }) {
2163
2470
  widget
2164
2471
  };
2165
2472
  };
2166
- return { api: {
2167
- create,
2168
- addWidget,
2169
- update: async (ref, patch, options) => {
2170
- allow("form.update", writesScripts(patch.actions));
2171
- const change = stage("update", {
2172
- type: "forms.update",
2173
- field: ref,
2174
- patch
2175
- });
2176
- return { field: (await answer(change, options)).field };
2177
- },
2178
- reorderCalculations: async (fields, position, options) => {
2179
- allow("form.reorderCalculations");
2180
- const change = stage("reorderCalculations", {
2181
- type: "forms.reorderCalculations",
2182
- fields,
2183
- position
2184
- });
2185
- return { calculationOrder: (await answer(change, options)).calculationOrder };
2186
- },
2187
- delete: async (ref, options) => {
2188
- allow("form.delete");
2189
- await answer(stage("delete", {
2190
- type: "forms.delete",
2191
- field: ref
2192
- }), options);
2193
- },
2194
- removeWidget: async (ref, widget, options) => {
2195
- allow("form.removeWidget");
2196
- const change = stage("removeWidget", {
2197
- type: "forms.removeWidget",
2198
- field: ref,
2199
- widget
2200
- });
2201
- return { field: (await answer(change, options)).field };
2202
- },
2203
- updateWidget: async (widget, patch, options) => {
2204
- allow("form.updateWidget");
2205
- const change = stage("updateWidget", {
2206
- type: "forms.updateWidget",
2207
- widget,
2208
- patch
2209
- });
2210
- return { widget: (await answer(change, options)).widget };
2211
- },
2212
- deleteWidget: async (widget, options) => {
2213
- allow("form.deleteWidget");
2214
- const change = stage("deleteWidget", {
2215
- type: "forms.deleteWidget",
2216
- widget
2473
+ /** Where a duplicate's copies go, with a page index as that page's ref. */
2474
+ const placementOf = (options) => ({
2475
+ ...options.page === void 0 ? {} : { page: ctx.pageOf(options.page).ref },
2476
+ ...options.offset ? { offset: options.offset } : {}
2477
+ });
2478
+ /**
2479
+ * The ops that copy these widgets by the designer's rule (write/duplicate.ts),
2480
+ * under the object numbers they take, with each copy's ref and what was
2481
+ * left out before the engine is asked.
2482
+ */
2483
+ const copyOps = async (widgets, placement, values) => {
2484
+ let plan;
2485
+ try {
2486
+ plan = widgetDuplicateOf(fields.view(), widgets, placement, {
2487
+ values,
2488
+ mayScript: ctx.allows(SCRIPT)
2217
2489
  });
2218
- return { field: (await answer(change, options)).field };
2219
- },
2220
- repair: async (options) => {
2221
- allow("form.repair");
2222
- const { signal, ...repair } = options ?? {};
2223
- const run = () => options ? ctx.doc.forms.repair(repair) : ctx.doc.forms.repair();
2224
- return enqueue(() => ctx.cancellable(signal, run()), options);
2490
+ } catch (error) {
2491
+ throw toPluginError("form", error);
2225
2492
  }
2226
- } };
2493
+ const taken = plan.needs ? numbers.takeNow(plan.needs) ?? await numbers.take(plan.needs) : [];
2494
+ return {
2495
+ ...plan.build(taken),
2496
+ dropped: plan.dropped
2497
+ };
2498
+ };
2499
+ const duplicate = async (refs, options = {}) => {
2500
+ allow("form.duplicate");
2501
+ if (refs.length === 0) return {
2502
+ fields: [],
2503
+ widgets: [],
2504
+ dropped: []
2505
+ };
2506
+ const placement = placementOf(options);
2507
+ const values = options.values ?? false;
2508
+ const { snapshot } = fields.view();
2509
+ if (!snapshot) throw new PluginError("not-ready", "form", "the form is still loading");
2510
+ let count;
2511
+ try {
2512
+ count = planFormCopies({
2513
+ form: snapshot,
2514
+ fields: refs,
2515
+ placement,
2516
+ values,
2517
+ mayScript: true
2518
+ }).creates.reduce((sum, create) => sum + 1 + create.widgets.length, 0);
2519
+ } catch (error) {
2520
+ throw toPluginError("form", error);
2521
+ }
2522
+ const objectNumbers = count ? numbers.takeNow(count) ?? await numbers.take(count) : [];
2523
+ const change = stageAll("duplicate", [{
2524
+ type: "forms.copy",
2525
+ fields: refs,
2526
+ ...placement,
2527
+ values,
2528
+ objectNumbers
2529
+ }]);
2530
+ const item = await answer(change, options);
2531
+ return {
2532
+ fields: item.fields,
2533
+ widgets: item.widgets,
2534
+ dropped: item.dropped
2535
+ };
2536
+ };
2537
+ const duplicateWidgets = async (refs, options = {}) => {
2538
+ allow("form.duplicate");
2539
+ const copy = await copyOps(refs, placementOf(options), options.values ?? false);
2540
+ if (copy.ops.length === 0) return {
2541
+ fields: [],
2542
+ widgets: [],
2543
+ dropped: [...copy.dropped]
2544
+ };
2545
+ const change = stageAll("duplicate", copy.ops);
2546
+ let items;
2547
+ try {
2548
+ items = (await ctx.cancellable(options.signal, change.result)).items;
2549
+ } catch (error) {
2550
+ throw toPluginError("form", error);
2551
+ }
2552
+ return duplicateResultOf(items, copy.copies, copy.dropped);
2553
+ };
2554
+ return {
2555
+ copyOps,
2556
+ api: {
2557
+ create,
2558
+ addWidget,
2559
+ duplicate,
2560
+ duplicateWidgets,
2561
+ update: async (ref, patch, options) => {
2562
+ allow("form.update", writesScripts(patch.actions));
2563
+ const change = stage("update", {
2564
+ type: "forms.update",
2565
+ field: ref,
2566
+ patch
2567
+ });
2568
+ return { field: (await answer(change, options)).field };
2569
+ },
2570
+ reorderCalculations: async (fields, position, options) => {
2571
+ allow("form.reorderCalculations");
2572
+ const change = stage("reorderCalculations", {
2573
+ type: "forms.reorderCalculations",
2574
+ fields,
2575
+ position
2576
+ });
2577
+ return { calculationOrder: (await answer(change, options)).calculationOrder };
2578
+ },
2579
+ delete: async (ref, options) => {
2580
+ allow("form.delete");
2581
+ await answer(stage("delete", {
2582
+ type: "forms.delete",
2583
+ field: ref
2584
+ }), options);
2585
+ },
2586
+ removeWidget: async (ref, widget, options) => {
2587
+ allow("form.removeWidget");
2588
+ const change = stage("removeWidget", {
2589
+ type: "forms.removeWidget",
2590
+ field: ref,
2591
+ widget
2592
+ });
2593
+ return { field: (await answer(change, options)).field };
2594
+ },
2595
+ updateWidget: async (widget, patch, options) => {
2596
+ allow("form.updateWidget");
2597
+ const change = stage("updateWidget", {
2598
+ type: "forms.updateWidget",
2599
+ widget,
2600
+ patch
2601
+ });
2602
+ return { widget: (await answer(change, options)).widget };
2603
+ },
2604
+ deleteWidget: async (widget, options) => {
2605
+ allow("form.deleteWidget");
2606
+ const change = stage("deleteWidget", {
2607
+ type: "forms.deleteWidget",
2608
+ widget
2609
+ });
2610
+ return { field: (await answer(change, options)).field };
2611
+ },
2612
+ repair: async (options) => {
2613
+ allow("form.repair");
2614
+ const { signal, ...repair } = options ?? {};
2615
+ const run = () => options ? ctx.doc.forms.repair(repair) : ctx.doc.forms.repair();
2616
+ return enqueue(() => ctx.cancellable(signal, run()), options);
2617
+ }
2618
+ }
2619
+ };
2620
+ }
2621
+ /**
2622
+ * What a duplicate of widgets resolves, read off the engine's answer: the
2623
+ * fields it made and each field that got a new button, as they are after the
2624
+ * last op that named them; the copies' rows, in the order their originals
2625
+ * were given; and what was left out, here and by the engine.
2626
+ */
2627
+ function duplicateResultOf(items, copies, dropped) {
2628
+ const fields = /* @__PURE__ */ new Map();
2629
+ const rows = /* @__PURE__ */ new Map();
2630
+ const left = [...dropped];
2631
+ const hold = (row) => {
2632
+ if (row.ref.kind === "objectNumber") rows.set(row.ref.objectNumber, row);
2633
+ };
2634
+ for (const item of items) if (item.type === "forms.copy") {
2635
+ for (const field of item.fields) fields.set(fieldKeyOf(field), field);
2636
+ item.widgets.forEach(hold);
2637
+ left.push(...item.dropped);
2638
+ } else if (item.type === "forms.addWidget") {
2639
+ fields.set(fieldKeyOf(item.field), item.field);
2640
+ item.widgets.forEach(hold);
2641
+ } else if (item.type === "forms.updateWidget") hold(item.widget);
2642
+ return {
2643
+ fields: [...fields.values()],
2644
+ widgets: copies.flatMap((copy) => copy.kind === "objectNumber" ? rows.get(copy.objectNumber) ?? [] : []),
2645
+ dropped: left
2646
+ };
2227
2647
  }
2228
2648
  //#endregion
2229
2649
  //#region src/write/fill.ts
@@ -2628,17 +3048,32 @@ function createInterchange(ctx, services) {
2628
3048
  })), options);
2629
3049
  };
2630
3050
  const importBundle = async (bundle, options = {}) => {
2631
- const { signal, ...importOptions } = options;
3051
+ const { signal, history, ...importOptions } = options;
2632
3052
  ctx.assertAllowed("doc.forms.modify", "form.import");
2633
3053
  if ((importOptions.attribution ?? "restore") === "restore") ctx.assertAllowed("doc.forms.import", "form.import");
2634
3054
  return enqueue(async () => {
2635
- const result = await ctx.cancellable(signal, ctx.doc.forms.import(bundle, importOptions));
3055
+ const { items } = await ctx.changes.stage({
3056
+ label: { key: "form.import" },
3057
+ opId: importOptions.opId,
3058
+ history,
3059
+ send: (doc, { opId }) => ctx.cancellable(signal, doc.forms.import(bundle, {
3060
+ ...importOptions,
3061
+ opId
3062
+ })).then((result) => ({
3063
+ items: [{
3064
+ type: "forms.import",
3065
+ ...result
3066
+ }],
3067
+ meta: result.meta
3068
+ }))
3069
+ }).result;
3070
+ const imported = items[0];
2636
3071
  const annotationHost = siblings.annotation();
2637
3072
  if (annotationHost) await annotationHost.whenSynced();
2638
3073
  return {
2639
- fields: result.fields,
2640
- refMap: result.refMap,
2641
- dropped: result.dropped
3074
+ fields: imported.fields,
3075
+ refMap: imported.refMap,
3076
+ dropped: imported.dropped
2642
3077
  };
2643
3078
  }, options);
2644
3079
  };
@@ -2656,17 +3091,18 @@ function createInterchange(ctx, services) {
2656
3091
  * its records and edits them with its tools: select, move, resize, restyle,
2657
3092
  * reorder, delete. Each edit comes back here as the form's ops, in the same
2658
3093
  * change as the rest of it. While the tool fills, nothing is lent, and the
2659
- * form layer draws and fills every widget.
3094
+ * form layer draws and fills every widget. A widget of no size is never lent:
3095
+ * nobody can see it, so nobody should be able to select it by hand.
2660
3096
  */
2661
3097
  const objectNumberOf = (ref) => ref.kind === "objectNumber" ? ref.objectNumber : -1;
2662
- function createWidgetLender(ctx, { fields, design, pictures, looks }) {
3098
+ function createWidgetLender(ctx, { fields, design, pictures, looks }, copyOps) {
2663
3099
  const records = memo(() => [
2664
3100
  design.lending(),
2665
3101
  fields.get().snapshot,
2666
3102
  fields.view().snapshot
2667
3103
  ], (lending, confirmed, shown) => lending && confirmed && shown ? {
2668
- confirmed: confirmed.widgets,
2669
- shown: shown.widgets
3104
+ confirmed: confirmed.widgets.filter(hasArea),
3105
+ shown: shown.widgets.filter(hasArea)
2670
3106
  } : null);
2671
3107
  /**
2672
3108
  * Deleted widgets, as the form's ops: a widget leaves its field
@@ -2734,11 +3170,13 @@ function createWidgetLender(ctx, { fields, design, pictures, looks }) {
2734
3170
  widgets: [...refs],
2735
3171
  position
2736
3172
  }],
3173
+ copyOps: (refs, placement) => copyOps(refs, placement, false),
2737
3174
  getAuthority: () => {
2738
3175
  const may = ctx.allows("doc.forms.modify");
2739
3176
  return {
2740
3177
  update: may,
2741
- delete: may
3178
+ delete: may,
3179
+ copy: may
2742
3180
  };
2743
3181
  },
2744
3182
  getPictureEpoch: pictures.epoch,
@@ -3221,7 +3659,7 @@ function createFormController(ctx) {
3221
3659
  ]);
3222
3660
  return {
3223
3661
  api,
3224
- connect: () => connectForm(ctx, api, createWidgetLender(ctx, services))
3662
+ connect: () => connectForm(ctx, api, createWidgetLender(ctx, services, design.copyOps))
3225
3663
  };
3226
3664
  }
3227
3665
  //#endregion