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