@embedpdf/plugin-form 3.3.0 → 3.4.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-DO7k0ua0.cjs");
2
+ const require_contract = require("./contract-CMb6PYbf.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");
@@ -8,11 +8,11 @@ let _embedpdf_plugin_annotation_contract = require("@embedpdf/plugin-annotation/
8
8
  let _embedpdf_plugin_fonts_contract = require("@embedpdf/plugin-fonts/contract");
9
9
  let _embedpdf_plugin_interaction_contract_host = require("@embedpdf/plugin-interaction/contract/host");
10
10
  let _embedpdf_plugin_render_contract = require("@embedpdf/plugin-render/contract");
11
+ let _embedpdf_plugin_stage_contract = require("@embedpdf/plugin-stage/contract");
11
12
  let _embedpdf_engine_core_runtime = require("@embedpdf/engine-core/runtime");
12
13
  let _embedpdf_plugin_actions_contract_host = require("@embedpdf/plugin-actions/contract/host");
13
14
  let _embedpdf_plugin_annotation_contract_host = require("@embedpdf/plugin-annotation/contract/host");
14
15
  let _embedpdf_core_annotation = require("@embedpdf/core-annotation");
15
- let _embedpdf_plugin_stage_contract = require("@embedpdf/plugin-stage/contract");
16
16
  let _embedpdf_core_form = require("@embedpdf/core-form");
17
17
  let _embedpdf_core_fonts = require("@embedpdf/core-fonts");
18
18
  let _embedpdf_plugin_render_contract_host = require("@embedpdf/plugin-render/contract/host");
@@ -34,6 +34,7 @@ const FORM_TOOLS = [
34
34
  width: 160,
35
35
  height: 24
36
36
  },
37
+ upright: true,
37
38
  defaults: {
38
39
  ...FIELD_CHROME,
39
40
  fontSize: 12
@@ -48,6 +49,7 @@ const FORM_TOOLS = [
48
49
  width: 18,
49
50
  height: 18
50
51
  },
52
+ upright: true,
51
53
  defaults: FIELD_CHROME,
52
54
  cursor: "crosshair"
53
55
  },
@@ -59,6 +61,7 @@ const FORM_TOOLS = [
59
61
  width: 18,
60
62
  height: 18
61
63
  },
64
+ upright: true,
62
65
  defaults: FIELD_CHROME,
63
66
  cursor: "crosshair"
64
67
  },
@@ -70,6 +73,7 @@ const FORM_TOOLS = [
70
73
  width: 140,
71
74
  height: 24
72
75
  },
76
+ upright: true,
73
77
  defaults: {
74
78
  ...FIELD_CHROME,
75
79
  fontSize: 12
@@ -84,6 +88,7 @@ const FORM_TOOLS = [
84
88
  width: 140,
85
89
  height: 72
86
90
  },
91
+ upright: true,
87
92
  defaults: {
88
93
  ...FIELD_CHROME,
89
94
  fontSize: 12
@@ -98,6 +103,7 @@ const FORM_TOOLS = [
98
103
  width: 100,
99
104
  height: 28
100
105
  },
106
+ upright: true,
101
107
  defaults: {
102
108
  ...FIELD_CHROME,
103
109
  interiorColor: "#e5e7eb",
@@ -113,6 +119,7 @@ const FORM_TOOLS = [
113
119
  width: 160,
114
120
  height: 48
115
121
  },
122
+ upright: true,
116
123
  defaults: FIELD_CHROME,
117
124
  cursor: "crosshair"
118
125
  }
@@ -139,12 +146,37 @@ function clampToPage(box, page) {
139
146
  return clamped.width < 1 || clamped.height < 1 ? null : clamped;
140
147
  }
141
148
  /**
149
+ * A placed field's frame and turn, as its widget's placement states them
150
+ * (`placedBoxFields`), kept on the page: the rect the turned frame stands in
151
+ * is cut to the page (`clampToPage`), and the frame follows it. `null` when
152
+ * too little of it is on the page.
153
+ */
154
+ function placedOnPage(placement, page) {
155
+ const { box, rotation } = (0, _embedpdf_core_annotation.placedBoxFields)(placement);
156
+ const turn = rotation ?? 0;
157
+ const stands = clampToPage((0, _embedpdf_core_annotation.standingRect)(box, turn), page);
158
+ if (!stands) return null;
159
+ return {
160
+ box: (0, _embedpdf_core_annotation.standingRect)(stands, turn),
161
+ ...turn ? { rotation: turn } : {}
162
+ };
163
+ }
164
+ /**
142
165
  * 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.
166
+ * `text_1`, in `groupId` when the palette places for a group (the form's
167
+ * design group); without one it is in no group. A
168
+ * radio button stands for `'Choice1'` and a dropdown or a list starts with
169
+ * two options, as in Acrobat; rename and change them in a settings panel.
146
170
  */
147
- function toolDraft(tool, name, widget) {
171
+ function toolDraft(tool, name, widget, groupId = null) {
172
+ const draft = kindDraft(tool, name, widget);
173
+ return groupId === null ? draft : {
174
+ ...draft,
175
+ groupId
176
+ };
177
+ }
178
+ /** {@link toolDraft}'s field, as the tool's kind starts one. */
179
+ function kindDraft(tool, name, widget) {
148
180
  switch (tool.fieldKind) {
149
181
  case "radio": return {
150
182
  kind: "radio",
@@ -192,6 +224,12 @@ function toolDraft(tool, name, widget) {
192
224
  * every tool: select the new widget, and keep the tool or go back to the
193
225
  * default one.
194
226
  *
227
+ * An upright tool places the field as the author sees the page: the press's
228
+ * display rotation goes to `gesturePlacement`, and the widget takes the
229
+ * placed frame and its turn (`placedOnPage`), so on a page shown turned the
230
+ * field reads upright. The ghost and the drag's preview make the same call
231
+ * with the same turn.
232
+ *
195
233
  * With the annotation plugin, the tool's ghost shows the field a click
196
234
  * places: this handler's hover puts it where the click would reach it (no
197
235
  * widget or annotation under the pointer claims it) and the user may design
@@ -204,23 +242,25 @@ function toolDraft(tool, name, widget) {
204
242
  */
205
243
  function createPlaceHandler(form, interaction, annotation) {
206
244
  let origin = null;
245
+ /** Whether the tool places upright: the annotation plugin's tool says, else the tool table. */
246
+ const uprightOf = (tool) => annotation?.getResolvedTool(tool.id)?.upright ?? tool.upright;
207
247
  /** Drop the gesture and what it painted: its placement and the tool's ghost. */
208
248
  const endGesture = () => {
209
249
  origin = null;
210
250
  annotation?.clearPlacementPreview();
211
251
  annotation?.clearGhost();
212
252
  };
213
- const place = async (tool, page, box) => {
253
+ const place = async (tool, page, placement) => {
214
254
  const pageBox = form.getPageBox(page);
215
- const rect = pageBox ? clampToPage(box, pageBox) : null;
216
- if (!rect) return;
255
+ const placed = pageBox ? placedOnPage(placement, pageBox) : null;
256
+ if (!placed) return;
217
257
  const look = (0, _embedpdf_core_annotation.widgetAppearanceOf)(annotation ? annotation.tools.getDefaults(tool.id) : tool.defaults);
218
258
  const name = nextFieldName(tool.fieldKind, new Set(form.list().map((field) => field.name)));
219
259
  const created = form.create(toolDraft(tool, name, {
220
260
  page,
221
- rect,
261
+ ...placed,
222
262
  ...look
223
- }));
263
+ }, form.getDesignGroup()));
224
264
  const field = form.get({
225
265
  kind: "fqn",
226
266
  name
@@ -248,7 +288,8 @@ function createPlaceHandler(form, interaction, annotation) {
248
288
  origin = {
249
289
  page: sample.page.ref,
250
290
  start: sample.page.point,
251
- last: sample.page.point
291
+ last: sample.page.point,
292
+ displayRotation: sample.page.rotation
252
293
  };
253
294
  return true;
254
295
  },
@@ -257,7 +298,7 @@ function createPlaceHandler(form, interaction, annotation) {
257
298
  const point = (0, _embedpdf_plugin_interaction_contract_host.samplePointOn)(sample, origin.page);
258
299
  if (!point) return;
259
300
  origin.last = point;
260
- annotation?.previewPlacement(interaction.getActiveToolId(), origin.page, origin.start, point);
301
+ annotation?.previewPlacement(interaction.getActiveToolId(), origin.page, origin.start, point, origin.displayRotation);
261
302
  },
262
303
  onPointerUp: (sample) => {
263
304
  if (!origin) return;
@@ -266,9 +307,13 @@ function createPlaceHandler(form, interaction, annotation) {
266
307
  const tool = FORM_TOOL_BY_ID.get(interaction.getActiveToolId());
267
308
  if (!tool) return;
268
309
  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 });
310
+ const placement = (0, _embedpdf_core_annotation.gesturePlacement)("box", gesture.start, end, tool.clickCreate, {
311
+ pageBox: form.getPageBox(gesture.page) ?? void 0,
312
+ upright: uprightOf(tool),
313
+ displayRotation: gesture.displayRotation
314
+ });
270
315
  if (placement?.kind !== "box") return;
271
- place(tool, gesture.page, placement.rect).catch((error) => {
316
+ place(tool, gesture.page, placement).catch((error) => {
272
317
  globalThis.console?.error("[form] placing the field failed:", error);
273
318
  });
274
319
  },
@@ -303,6 +348,7 @@ function connectForm(ctx, form, lender) {
303
348
  cursor: tool.cursor,
304
349
  enables: [...PLACE_TAGS],
305
350
  clickCreate: tool.clickCreate,
351
+ upright: tool.upright,
306
352
  defaults: tool.defaults,
307
353
  ghost: true
308
354
  }) : interaction.registerTool({
@@ -584,6 +630,12 @@ function fieldsWithChangedValues(previous, next) {
584
630
  });
585
631
  }
586
632
  const valueEntryOf = (field) => "valueEntry" in field ? field.valueEntry : null;
633
+ /** A widget row's place: its frame (its rect, for a row without one), its turn and its rect. */
634
+ const placeOf = (row) => ({
635
+ box: row.box ?? row.rect,
636
+ rotation: row.box ? row.rotation ?? 0 : 0,
637
+ rect: row.rect
638
+ });
587
639
  /**
588
640
  * Whether a widget's box has an area. One of no size is how a PDF keeps a field that shows
589
641
  * nowhere: the field of a document timestamp, an invisible signature.
@@ -601,7 +653,8 @@ function pageWidgetsOf(index, pageObjectNumber) {
601
653
  if (row.page.objectNumber !== pageObjectNumber || row.ref.kind !== "objectNumber") continue;
602
654
  if (!shownOnScreen(row)) continue;
603
655
  widgets[row.ref.objectNumber] = {
604
- box: row.rect,
656
+ ref: row.ref,
657
+ ...placeOf(row),
605
658
  look: {
606
659
  border: row.color ?? null,
607
660
  borderWidth: row.strokeWidth ?? 1,
@@ -627,7 +680,7 @@ function shownWidgetsOf(index, pageObjectNumber, lookOf = () => AT_REST) {
627
680
  if (row.page.objectNumber !== pageObjectNumber || !shownOnScreen(row)) continue;
628
681
  shown.push({
629
682
  ref: row.ref,
630
- rect: row.rect,
683
+ ...placeOf(row),
631
684
  appearanceState: row.appearanceState,
632
685
  ...lookOf(row)
633
686
  });
@@ -639,24 +692,48 @@ function widgetRowOf(index, annotObjectNumber) {
639
692
  return position === void 0 ? null : index.snapshot?.widgets[position] ?? null;
640
693
  }
641
694
  const boxContains = (box, point) => point.x >= box.x && point.x <= box.x + box.width && point.y >= box.y && point.y <= box.y + box.height;
642
- /** The widget under a page-space point; nested widgets resolve to the smallest box. */
695
+ /** The widget under a page-space point; nested widgets resolve to the smallest one. */
643
696
  function widgetAt(index, widgets, point) {
644
697
  if (!widgets) return null;
645
698
  let best = null;
646
- for (const [key, { box }] of Object.entries(widgets)) {
647
- if (!boxContains(box, point)) continue;
699
+ for (const [key, { box, rotation, rect }] of Object.entries(widgets)) {
700
+ if (!boxContains(rect, point)) continue;
648
701
  const annotObjectNumber = Number(key);
649
702
  const field = fieldForWidget(index, annotObjectNumber);
650
703
  if (!field) continue;
651
- if (!best || box.width * box.height < best.box.width * best.box.height) best = {
704
+ if (!best || rect.width * rect.height < best.rect.width * best.rect.height) best = {
652
705
  annotObjectNumber,
653
706
  field,
654
- box
707
+ box,
708
+ rotation,
709
+ rect
655
710
  };
656
711
  }
657
712
  return best;
658
713
  }
659
- const initialFormModel = () => ({ focused: null });
714
+ const NO_NAMED_GROUPS = Object.freeze([]);
715
+ const initialFormModel = () => ({
716
+ focused: null,
717
+ designGroup: null,
718
+ groups: NO_NAMED_GROUPS
719
+ });
720
+ /** Name this document's groups: the whole list. The same list again changes nothing. */
721
+ function setGroups(state, groups) {
722
+ return groups.length === state.groups.length && groups.every((group, at) => {
723
+ const held = state.groups[at];
724
+ return group.id === held.id && group.label === held.label && group.color === held.color;
725
+ }) ? state : {
726
+ ...state,
727
+ groups
728
+ };
729
+ }
730
+ /** Name the group that fields placed with a tool go in; the same group changes nothing. */
731
+ function setDesignGroup(state, groupId) {
732
+ return state.designGroup === groupId ? state : {
733
+ ...state,
734
+ designGroup: groupId
735
+ };
736
+ }
660
737
  //#endregion
661
738
  //#region src/read/fields.ts
662
739
  /**
@@ -665,6 +742,7 @@ const initialFormModel = () => ({ focused: null });
665
742
  * required-field check.
666
743
  */
667
744
  const NO_FIELDS$1 = Object.freeze([]);
745
+ const NO_SELECTED_FIELDS = Object.freeze([]);
668
746
  const NOTHING_SELECTED = Object.freeze([]);
669
747
  /** A widget address as the annotation object number the field index is keyed by. */
670
748
  const widgetObjectOf = (widget) => "kind" in widget ? widget.kind === "objectNumber" ? widget.objectNumber : 0 : widget.objectNumber;
@@ -778,6 +856,16 @@ function createFieldReads(ctx, { fields, rights, siblings }) {
778
856
  }
779
857
  return found;
780
858
  });
859
+ /** Every field with a selected widget, in the selection's order, each once. */
860
+ const listSelectedFields = (0, _embedpdf_core.memo)(() => [fields.view(), siblings.annotation()?.selection.getSelected() ?? NOTHING_SELECTED], (index, selected) => {
861
+ const found = /* @__PURE__ */ new Map();
862
+ for (const annotation of selected) {
863
+ if (!annotation.subtype.startsWith("widget")) continue;
864
+ const field = fieldForWidget(index, widgetObjectOf(annotation.ref));
865
+ if (field && !found.has(fieldKeyOf(field))) found.set(fieldKeyOf(field), field);
866
+ }
867
+ return found.size === 0 ? NO_SELECTED_FIELDS : Object.freeze([...found.values()]);
868
+ });
781
869
  return { api: {
782
870
  getSnapshot: () => fields.view().snapshot,
783
871
  getStatus: fields.getStatus,
@@ -790,6 +878,7 @@ function createFieldReads(ctx, { fields, rights, siblings }) {
790
878
  list,
791
879
  getValue: (ref) => valueByKey(canonicalKey(fields.view(), ref)),
792
880
  getSelectedField,
881
+ listSelectedFields,
793
882
  validate,
794
883
  exportValues
795
884
  } };
@@ -799,7 +888,9 @@ function createFieldReads(ctx, { fields, rights, siblings }) {
799
888
  /**
800
889
  * A field's settings, described for a settings panel the way an annotation
801
890
  * kind describes its look: which settings the field's kind has, how each is
802
- * edited, and its value. `update()` writes them.
891
+ * edited, and its value. `update()` writes them. While the document has
892
+ * groups, a field's group is one of them: the choices are the groups the
893
+ * user may put a field in, and the one the field is in.
803
894
  */
804
895
  /** What every field has. */
805
896
  const COMMON = [
@@ -924,6 +1015,21 @@ function familySettings(field) {
924
1015
  default: return [];
925
1016
  }
926
1017
  }
1018
+ /**
1019
+ * Who fills the field in, among the document's groups: the ones the user may put a field in,
1020
+ * and the field's own. Nothing while the document has no groups.
1021
+ */
1022
+ function groupSetting(field, groups, maySet) {
1023
+ if (groups.length === 0) return [];
1024
+ return [{
1025
+ key: "groupId",
1026
+ control: "choice",
1027
+ label: "Filled in by",
1028
+ labelKey: "form.settings.group",
1029
+ options: groups.filter((group) => group.id === field.groupId || maySet(group.id)).map((group) => group.id),
1030
+ free: false
1031
+ }];
1032
+ }
927
1033
  /** Each setting's value, as the field holds it. */
928
1034
  function valuesOf(field, settings) {
929
1035
  const held = field;
@@ -933,10 +1039,14 @@ function valuesOf(field, settings) {
933
1039
  else values[key] = held[key] ?? null;
934
1040
  return values;
935
1041
  }
936
- function createFieldSettings({ fields }) {
937
- const settingsByKey = (0, _embedpdf_core.memoByKey)((key) => [fieldByKey(fields.view(), key)], (_key, field) => {
1042
+ function createFieldSettings({ fields, groups }) {
1043
+ const settingsByKey = (0, _embedpdf_core.memoByKey)((key) => [fieldByKey(fields.view(), key), groups.list()], (_key, field, listed) => {
938
1044
  if (!field) return null;
939
- const properties = [...COMMON, ...familySettings(field)];
1045
+ const properties = [
1046
+ ...COMMON,
1047
+ ...groupSetting(field, listed, groups.maySet),
1048
+ ...familySettings(field)
1049
+ ];
940
1050
  return {
941
1051
  properties,
942
1052
  values: valuesOf(field, properties)
@@ -946,21 +1056,43 @@ function createFieldSettings({ fields }) {
946
1056
  }
947
1057
  //#endregion
948
1058
  //#region src/read/fill-items.ts
1059
+ /** A radio button's accessible name: its group's, then the option it stands for. */
1060
+ const radioLabel = (group, option) => option === "" ? group : `${group}: ${option}`;
1061
+ /** A box's accessible name, then whose field it is, when the app says who the group is. */
1062
+ const ownedLabel = (name, owner) => owner === null ? name : `${name}, ${owner}`;
1063
+ /**
1064
+ * Whether the field still takes a value: it holds one (a push button doesn't), it isn't
1065
+ * read-only, nor a signed signature.
1066
+ */
1067
+ const takesValue = (field) => field.kind !== "pushbutton" && !field.readOnly && !(field.kind === "signature" && field.valueEntry.kind !== "none");
949
1068
  /**
950
- * Project one widget of a field into a fill control; `fillable`: the user may
951
- * fill the field in (a signature field: sign it). Null for kinds with no
952
- * fill control.
1069
+ * Project one widget of a field into a fill control. `fillable`: people fill
1070
+ * the field in by hand (a signature field: sign it), which the box is
1071
+ * `disabled` without; `canFill`: the session's permission alone, which the
1072
+ * `fillable` setting doesn't change; `inGroup`: where a radio button comes
1073
+ * among its group's; `group`: how the field's group shows, `null` for a field
1074
+ * in none. Null for kinds with no fill control.
953
1075
  */
954
- function projectWidget(field, annotObjectNumber, widget, fillable) {
1076
+ function projectWidget(field, annotObjectNumber, widget, fillable, canFill, inGroup = null, group = null) {
1077
+ const key = fieldKeyOf(field);
1078
+ const owner = group?.label ?? null;
955
1079
  const base = {
956
- key: fieldKeyOf(field),
1080
+ key,
957
1081
  fieldRef: field.ref,
958
1082
  annotObjectNumber,
959
1083
  annotationRef: field.widgets.find((candidate) => candidate.objectNumber === annotObjectNumber)?.ref ?? null,
1084
+ ref: widget.ref,
1085
+ groupId: field.groupId,
1086
+ canFill,
1087
+ required: field.required,
1088
+ empty: isEmpty(field),
1089
+ accent: canFill && takesValue(field) ? group?.accent ?? null : null,
960
1090
  box: widget.box,
1091
+ rotation: widget.rotation,
1092
+ rect: widget.rect,
961
1093
  look: widget.look,
962
1094
  disabled: field.readOnly || !fillable,
963
- label: field.alternateName ?? field.name
1095
+ label: ownedLabel(field.alternateName ?? field.name, owner)
964
1096
  };
965
1097
  switch (field.kind) {
966
1098
  case "text": return {
@@ -984,12 +1116,15 @@ function projectWidget(field, annotObjectNumber, widget, fillable) {
984
1116
  }
985
1117
  case "radio": {
986
1118
  const toggle = field.widgets.find((candidate) => candidate.objectNumber === annotObjectNumber);
1119
+ const exportValue = toggle && "exportValue" in toggle ? toggle.exportValue : "";
987
1120
  return {
988
1121
  ...base,
1122
+ label: ownedLabel(radioLabel(field.alternateName ?? field.name, exportValue), owner),
989
1123
  control: "toggle",
990
1124
  kind: "radio",
991
1125
  checked: toggle && "checked" in toggle ? toggle.checked : false,
992
- exportValue: toggle && "exportValue" in toggle ? toggle.exportValue : ""
1126
+ exportValue,
1127
+ inGroup
993
1128
  };
994
1129
  }
995
1130
  case "combobox": return {
@@ -1023,19 +1158,22 @@ function projectWidget(field, annotObjectNumber, widget, fillable) {
1023
1158
  }
1024
1159
  }
1025
1160
  /**
1026
- * Project one page's widgets into fill controls, each disabled when the user
1027
- * may not fill its field in, or sign it (`mayFill`). Widgets whose page has not loaded (or
1028
- * that are direct objects with no join key) are skipped; the projection runs
1029
- * again when the page's widgets land.
1161
+ * Project one page's widgets into fill controls, each disabled when people
1162
+ * don't fill its field in by hand (`mayFillByHand`), each saying whether the
1163
+ * session may fill it in, or sign it (`mayFill`, its permissions alone), and
1164
+ * each radio button with where it comes in its group (`groupPositionOf`),
1165
+ * and each with how its field's group shows (`groupLookOf`).
1166
+ * Widgets whose page has not loaded (or that are direct objects with no join
1167
+ * key) are skipped; the projection runs again when the page's widgets land.
1030
1168
  */
1031
- function fillItems(index, pageObjectNumber, widgets, mayFill) {
1169
+ function fillItems(index, pageObjectNumber, widgets, mayFillByHand, mayFill, groupPositionOf = () => null, groupLookOf = () => null) {
1032
1170
  if (!index.snapshot || !widgets) return [];
1033
1171
  const items = [];
1034
1172
  for (const field of index.snapshot.fields) for (const widget of field.widgets) {
1035
1173
  if (widget.page?.objectNumber !== pageObjectNumber) continue;
1036
1174
  const placed = widgets[widget.objectNumber];
1037
1175
  if (!placed) continue;
1038
- const item = projectWidget(field, widget.objectNumber, placed, mayFill(field));
1176
+ const item = projectWidget(field, widget.objectNumber, placed, mayFillByHand(field), mayFill(field), groupPositionOf(widget.objectNumber), field.groupId === null ? null : groupLookOf(field.groupId));
1039
1177
  if (item) items.push(item);
1040
1178
  }
1041
1179
  return items;
@@ -1050,7 +1188,7 @@ function fillItems(index, pageObjectNumber, widgets, mayFill) {
1050
1188
  */
1051
1189
  const NO_WIDGETS = Object.freeze([]);
1052
1190
  const NOTHING_SHOWN$1 = Object.freeze([]);
1053
- function createWidgetReads(ctx, { fields, rights, looks, pictures }) {
1191
+ function createWidgetReads(ctx, { fields, rights, looks, pictures, design, siblings, cursor, tabOrder, groups }) {
1054
1192
  /** Every page's widgets come with the form: one read for the document. */
1055
1193
  const loadWidgets = (_page) => fields.settled();
1056
1194
  const widgetsOn = (0, _embedpdf_core.memoByKey)((pageObjectNumber) => [fields.view()], (pageObjectNumber, index) => pageWidgetsOf(index, pageObjectNumber));
@@ -1064,8 +1202,11 @@ function createWidgetReads(ctx, { fields, rights, looks, pictures }) {
1064
1202
  fields.view(),
1065
1203
  widgetsOn(pageObjectNumber),
1066
1204
  rights.key(),
1067
- ctx.settings().get().fillable
1068
- ], (pageObjectNumber, index, widgets) => fillItems(index, pageObjectNumber, widgets, rights.mayFillByHand));
1205
+ ctx.settings().get().fillable,
1206
+ tabOrder.rows(),
1207
+ groups.list(),
1208
+ ctx.settings().get().fields.tint
1209
+ ], (pageObjectNumber, index, widgets) => fillItems(index, pageObjectNumber, widgets, rights.mayFillByHand, rights.mayFillOrSign, tabOrder.groupPositionOf, groups.lookOf));
1069
1210
  /** The page's content box (`{0, 0, width, height}`), for page-bound placement. */
1070
1211
  const getPageBox = (page) => {
1071
1212
  const size = ctx.getPage(page)?.size;
@@ -1076,6 +1217,19 @@ function createWidgetReads(ctx, { fields, rights, looks, pictures }) {
1076
1217
  height: size.height
1077
1218
  } : null;
1078
1219
  };
1220
+ const anchors = /* @__PURE__ */ new WeakMap();
1221
+ const getWidgetAnchor = (widget) => {
1222
+ const row = widgetRowOf(fields.view(), widgetObjectOf(widget));
1223
+ if (!row) return null;
1224
+ if (design.lending()) return siblings.annotation()?.getAnnotationAnchor(row.ref) ?? null;
1225
+ if (!shownOnScreen(row)) return null;
1226
+ let anchor = anchors.get(row);
1227
+ if (!anchor) anchors.set(row, anchor = {
1228
+ page: row.page,
1229
+ bounds: row.rect
1230
+ });
1231
+ return anchor;
1232
+ };
1079
1233
  return {
1080
1234
  getPageBox,
1081
1235
  api: {
@@ -1094,7 +1248,9 @@ function createWidgetReads(ctx, { fields, rights, looks, pictures }) {
1094
1248
  getWidgetFontCss: looks.getWidgetFontCss,
1095
1249
  ensureLoaded: loadWidgets,
1096
1250
  getWidgetAt,
1097
- getPageBox
1251
+ getPageBox,
1252
+ getWidgetAnchor,
1253
+ isWidgetFocused: (widget) => cursor.focused()?.widget === widgetObjectOf(widget)
1098
1254
  }
1099
1255
  };
1100
1256
  }
@@ -1517,6 +1673,10 @@ function createFieldsMirror(ctx, events) {
1517
1673
  //#region src/services/cursor.ts
1518
1674
  /** How long a box asked for keeps its claim on the cursor while its page comes in. */
1519
1675
  const PENDING_MS = 2e3;
1676
+ /** Whether a control takes the cursor: every one that doesn't say it takes none. */
1677
+ const takes = (target) => target.takesCursor?.() ?? true;
1678
+ /** Put the cursor in a control. `false` when it takes none: it says so, or nothing in it took it. */
1679
+ const enter = (target, select) => takes(target) && target.focus({ select }) !== false;
1520
1680
  function createCursor(ctx, fields, events) {
1521
1681
  const targets = /* @__PURE__ */ new Map();
1522
1682
  let pending = null;
@@ -1538,8 +1698,29 @@ function createCursor(ctx, fields, events) {
1538
1698
  };
1539
1699
  const clearPending = () => {
1540
1700
  pending?.expire();
1701
+ pending?.settle?.();
1541
1702
  pending = null;
1542
1703
  };
1704
+ /**
1705
+ * A box asked for came in holding nothing to focus. It is given the turn to draw what does (a
1706
+ * control of an app's own may render after its box), and if nothing in it takes the cursor
1707
+ * then, the cursor goes on.
1708
+ */
1709
+ const settleLater = (waiting) => {
1710
+ waiting.settle ?? (waiting.settle = ctx.clock.after(0, () => {
1711
+ waiting.settle = null;
1712
+ if (pending !== waiting) return;
1713
+ const now = targets.get(waiting.widget);
1714
+ if (!now) return;
1715
+ clearPending();
1716
+ if (!enter(now, waiting.select)) waiting.onward?.();
1717
+ }));
1718
+ };
1719
+ /** The box asked for has come in: its control takes the cursor, or gets its turn to. */
1720
+ const arrive = (waiting, target) => {
1721
+ if (!enter(target, waiting.select)) settleLater(waiting);
1722
+ else if (pending === waiting) clearPending();
1723
+ };
1543
1724
  return {
1544
1725
  focused: () => ctx.state.get().focused,
1545
1726
  last: () => last,
@@ -1563,34 +1744,34 @@ function createCursor(ctx, fields, events) {
1563
1744
  });
1564
1745
  }
1565
1746
  },
1566
- goTo(row, select) {
1747
+ goTo(row, select, onward) {
1567
1748
  const widget = widgetObjectOf(row.ref);
1749
+ const shown = targets.get(widget);
1750
+ if (shown && !takes(shown)) return "declined";
1568
1751
  const stage = ctx.tryGet(_embedpdf_plugin_stage_contract.StageToken);
1569
1752
  stage?.reveal(row.page, { rect: row.rect });
1570
1753
  clearPending();
1571
1754
  const target = targets.get(widget);
1572
- if (target) {
1573
- target.focus({ select });
1574
- return true;
1575
- }
1576
- if (!stage) return false;
1577
- pending = {
1755
+ if (target && enter(target, select)) return "taken";
1756
+ if (target && target === shown) return "declined";
1757
+ if (!stage) return "unreachable";
1758
+ const waiting = {
1578
1759
  widget,
1579
1760
  select,
1761
+ onward: onward ?? null,
1580
1762
  expire: ctx.clock.after(PENDING_MS, () => {
1581
- if (pending?.widget === widget) pending = null;
1582
- })
1763
+ if (pending === waiting) clearPending();
1764
+ }),
1765
+ settle: null
1583
1766
  };
1584
- return true;
1767
+ pending = waiting;
1768
+ if (target) settleLater(waiting);
1769
+ return "taken";
1585
1770
  },
1586
1771
  attach(widgetRef, target) {
1587
1772
  const widget = widgetObjectOf(widgetRef);
1588
1773
  targets.set(widget, target);
1589
- if (pending?.widget === widget) {
1590
- const { select } = pending;
1591
- clearPending();
1592
- target.focus({ select });
1593
- }
1774
+ if (pending?.widget === widget) arrive(pending, target);
1594
1775
  return () => {
1595
1776
  if (targets.get(widget) === target) targets.delete(widget);
1596
1777
  };
@@ -1612,15 +1793,21 @@ function createDesign(ctx, siblings) {
1612
1793
  //#endregion
1613
1794
  //#region src/services/events.ts
1614
1795
  function createEvents(ctx) {
1615
- return {
1796
+ const events = {
1616
1797
  valueChanged: ctx.events.source(),
1617
1798
  fieldCreated: ctx.events.source(),
1618
1799
  fieldUpdated: ctx.events.source(),
1619
1800
  fieldDeleted: ctx.events.source(),
1620
1801
  validationRejected: ctx.events.source(),
1621
1802
  resynced: ctx.events.source(),
1622
- focusChanged: ctx.events.source()
1803
+ focusChanged: ctx.events.source(),
1804
+ designGroupChanged: ctx.events.source(),
1805
+ groupsChanged: ctx.events.source()
1623
1806
  };
1807
+ ctx.state.onChange(({ previous, next }) => {
1808
+ if (previous.designGroup !== next.designGroup) events.designGroupChanged.emit({ groupId: next.designGroup });
1809
+ });
1810
+ return events;
1624
1811
  }
1625
1812
  //#endregion
1626
1813
  //#region src/services/fill-rights.ts
@@ -1635,12 +1822,14 @@ const isFillableByHand = (fillable, kind) => typeof fillable === "boolean" ? fil
1635
1822
  function createFillRights(ctx, fields) {
1636
1823
  const mayFill = (field) => ctx.allowsField("fill", field);
1637
1824
  const maySign = (field) => ctx.allowsField("sign", field);
1638
- const mayFillByHand = (field) => isFillableByHand(ctx.settings().get().fillable, field.kind) && (field.kind === "signature" ? maySign(field) : mayFill(field));
1825
+ const mayFillOrSign = (field) => field.kind === "signature" ? maySign(field) : mayFill(field);
1826
+ const mayFillByHand = (field) => isFillableByHand(ctx.settings().get().fillable, field.kind) && mayFillOrSign(field);
1639
1827
  /** The form's groups, `null` (no group) among them. */
1640
1828
  const groups = (0, _embedpdf_core.memo)(() => [fields.view()], (index) => [...new Set((index.snapshot?.fields ?? []).map((field) => field.groupId))]);
1641
1829
  return {
1642
1830
  mayFill,
1643
1831
  maySign,
1832
+ mayFillOrSign,
1644
1833
  mayFillByHand,
1645
1834
  takesInput: (field) => !field.readOnly && mayFillByHand(field),
1646
1835
  assertMayFill: (field, operation) => ctx.assertAllowedField("fill", field, operation),
@@ -1680,6 +1869,76 @@ function createFormattedTexts(ctx, fields) {
1680
1869
  };
1681
1870
  }
1682
1871
  //#endregion
1872
+ //#region src/services/groups.ts
1873
+ /**
1874
+ * The form's groups as people see them. A field's group is an id in the PDF
1875
+ * (`groupId`); who the group is and the color its fields show in are the
1876
+ * app's, told to this document with `setGroups()`, and never written into the
1877
+ * PDF. Every group shows in a color: its own when the app gives one, else one
1878
+ * of eight by its place in the list, so no two of the first eight share one.
1879
+ * How strongly it shows is the `fields.tint` setting; at `0` no field shows
1880
+ * its group at all.
1881
+ */
1882
+ /**
1883
+ * The colors of the groups the app gives none: the first group in the list
1884
+ * gets the first, and the ninth the first again.
1885
+ */
1886
+ const GROUP_COLORS = Object.freeze([
1887
+ "#ea580c",
1888
+ "#16a34a",
1889
+ "#9333ea",
1890
+ "#2563eb",
1891
+ "#db2777",
1892
+ "#0d9488",
1893
+ "#ca8a04",
1894
+ "#65a30d"
1895
+ ]);
1896
+ const MODIFY$1 = "doc.forms.modify";
1897
+ const NO_LOOKS = /* @__PURE__ */ new Map();
1898
+ function createGroups(ctx, fields, events) {
1899
+ /** The ids of the groups the form's fields are in, in the fields' order, as one key. */
1900
+ const used = () => {
1901
+ const ids = /* @__PURE__ */ new Set();
1902
+ for (const field of fields.view().snapshot?.fields ?? []) if (field.groupId !== null) ids.add(field.groupId);
1903
+ return JSON.stringify([...ids]);
1904
+ };
1905
+ const list = (0, _embedpdf_core.memo)(() => [ctx.state.get().groups, used()], (named, ids) => {
1906
+ const known = new Set(named.map((group) => group.id));
1907
+ const others = JSON.parse(ids).filter((id) => !known.has(id)).map((id) => ({
1908
+ id,
1909
+ label: null,
1910
+ color: null
1911
+ }));
1912
+ return Object.freeze([...named, ...others].map((group, place) => Object.freeze({
1913
+ id: group.id,
1914
+ label: group.label,
1915
+ color: group.color ?? GROUP_COLORS[place % GROUP_COLORS.length]
1916
+ })));
1917
+ });
1918
+ const looks = (0, _embedpdf_core.memo)(() => [list(), ctx.settings().get().fields.tint], (groups, strength) => groups.length === 0 ? NO_LOOKS : new Map(groups.map((group) => [group.id, Object.freeze({
1919
+ label: group.label,
1920
+ accent: strength > 0 ? Object.freeze({
1921
+ color: group.color,
1922
+ strength
1923
+ }) : null
1924
+ })])));
1925
+ ctx.state.onChange(({ previous, next }) => {
1926
+ if (previous.groups !== next.groups) events.groupsChanged.emit({ groups: list() });
1927
+ });
1928
+ const maySetGroup = (groupId) => ctx.doc.security.allowsField("set-group", { groupId });
1929
+ return {
1930
+ list,
1931
+ lookOf: (groupId) => groupId === null ? null : looks().get(groupId) ?? null,
1932
+ maySet: (groupId) => ctx.allows(MODIFY$1) && maySetGroup(groupId),
1933
+ assertMaySet: (groupId, operation) => {
1934
+ ctx.assertAllowed(MODIFY$1, operation);
1935
+ if (maySetGroup(groupId)) return;
1936
+ const permission = `fields:set-group:group=${groupId}`;
1937
+ throw new _embedpdf_core.PluginError("permission-denied", "form", `${operation} requires ${permission}`, { permission });
1938
+ }
1939
+ };
1940
+ }
1941
+ //#endregion
1683
1942
  //#region src/services/looks.ts
1684
1943
  /**
1685
1944
  * What a shown widget looks like now: the engine's picture, or the painter's
@@ -1946,6 +2205,41 @@ function resolveSiblings(ctx) {
1946
2205
  };
1947
2206
  }
1948
2207
  //#endregion
2208
+ //#region src/services/tab-order.ts
2209
+ /**
2210
+ * The order Tab visits the widgets in: every widget that shows, page by page in the document's
2211
+ * order, each page by its own tab order (the engine's `tabOrderOf()`). The cursor goes this way
2212
+ * (`write/focus.ts`), and so do the arrow keys round a radio group's buttons, so a button's
2213
+ * place among its group's is its place in this order.
2214
+ */
2215
+ function createTabOrder(ctx, fields) {
2216
+ const rows = (0, _embedpdf_core.memo)(() => [fields.view(), ctx.document()?.pages], (index, pages) => (0, _embedpdf_engine_core_runtime.tabOrderOf)((index.snapshot?.widgets ?? []).filter(shownOnScreen), pages ?? []));
2217
+ const groupPositions = (0, _embedpdf_core.memo)(() => [fields.view(), rows()], (index, ordered) => {
2218
+ const buttons = /* @__PURE__ */ new Map();
2219
+ for (const row of ordered) {
2220
+ const widget = widgetObjectOf(row.ref);
2221
+ const field = fieldForWidget(index, widget);
2222
+ if (field?.kind !== "radio") continue;
2223
+ const key = fieldKeyOf(field);
2224
+ const group = buttons.get(key);
2225
+ if (group) group.push(widget);
2226
+ else buttons.set(key, [widget]);
2227
+ }
2228
+ const positions = /* @__PURE__ */ new Map();
2229
+ for (const group of buttons.values()) group.forEach((widget, at) => {
2230
+ positions.set(widget, {
2231
+ position: at + 1,
2232
+ size: group.length
2233
+ });
2234
+ });
2235
+ return positions;
2236
+ });
2237
+ return {
2238
+ rows,
2239
+ groupPositionOf: (widget) => groupPositions().get(widget) ?? null
2240
+ };
2241
+ }
2242
+ //#endregion
1949
2243
  //#region src/services/index.ts
1950
2244
  function createServices(ctx) {
1951
2245
  const siblings = resolveSiblings(ctx);
@@ -1956,8 +2250,10 @@ function createServices(ctx) {
1956
2250
  return {
1957
2251
  fields,
1958
2252
  rights: createFillRights(ctx, fields),
2253
+ groups: createGroups(ctx, fields, events),
1959
2254
  events,
1960
2255
  cursor: createCursor(ctx, fields, events),
2256
+ tabOrder: createTabOrder(ctx, fields),
1961
2257
  siblings,
1962
2258
  scripting: createScriptingSeam(ctx, siblings),
1963
2259
  design,
@@ -2397,7 +2693,7 @@ function exportValueFor(field) {
2397
2693
  }
2398
2694
  const MODIFY = "doc.forms.modify";
2399
2695
  const SCRIPT = "doc.forms.script";
2400
- function createFieldWrites(ctx, { fields, enqueue }) {
2696
+ function createFieldWrites(ctx, { fields, enqueue, groups }) {
2401
2697
  const numbers = createObjectNumbers(ctx);
2402
2698
  /** Refuse up front without `doc.forms.modify`, and without `doc.forms.script` when it writes scripts. */
2403
2699
  const allow = (operation, scripts = false) => {
@@ -2426,6 +2722,7 @@ function createFieldWrites(ctx, { fields, enqueue }) {
2426
2722
  };
2427
2723
  const create = async (draft, options) => {
2428
2724
  allow("form.create", (0, _embedpdf_engine_core_runtime.draftWritesScripts)(draft));
2725
+ if (typeof draft.groupId === "string") groups.assertMaySet(draft.groupId, "form.create");
2429
2726
  const count = 1 + (draft.widgets?.length ?? 0);
2430
2727
  const [objectNumber, ...widgetObjectNumbers] = numbers.takeNow(count) ?? await numbers.take(count);
2431
2728
  const change = stage("create", {
@@ -2447,7 +2744,7 @@ function createFieldWrites(ctx, { fields, enqueue }) {
2447
2744
  if (!page) throw new _embedpdf_core.PluginError("invalid-input", "form", "the field shows on no page: give `page` and `rect`");
2448
2745
  const size = ctx.getPage(page)?.size;
2449
2746
  const onPage = rows.filter((row) => row.page.objectNumber === page.objectNumber);
2450
- const rect = placement.rect ?? placement.box ?? (size && onPage.length > 0 ? nextInLine(onPage.map((row) => row.box), size) : void 0);
2747
+ const rect = placement.rect ?? placement.box ?? (size && onPage.length > 0 ? nextInLine(onPage.map((row) => row.rect), size) : void 0);
2451
2748
  if (!rect) throw new _embedpdf_core.PluginError("invalid-input", "form", "no widget of the field on that page: give `rect`");
2452
2749
  const exportValue = placement.exportValue ?? exportValueFor(field);
2453
2750
  const split = isMerged(field);
@@ -2553,6 +2850,33 @@ function createFieldWrites(ctx, { fields, enqueue }) {
2553
2850
  }
2554
2851
  return duplicateResultOf(items, copy.copies, copy.dropped);
2555
2852
  };
2853
+ const moveToGroup = async (refs, groupId, options) => {
2854
+ allow("form.moveToGroup");
2855
+ if (groupId !== null) groups.assertMaySet(groupId, "form.moveToGroup");
2856
+ const index = fields.view();
2857
+ const moved = refs.map((ref) => {
2858
+ const field = fieldByRef(index, ref);
2859
+ if (!field) throw new _embedpdf_core.PluginError("not-found", "form", "no form field has this ref");
2860
+ return field;
2861
+ });
2862
+ const moving = /* @__PURE__ */ new Map();
2863
+ for (const field of moved) if (field.groupId !== groupId) moving.set(fieldKeyOf(field), field);
2864
+ if (moving.size === 0) return { fields: moved };
2865
+ const change = stageAll("update", [...moving.values()].map((field) => ({
2866
+ type: "forms.update",
2867
+ field: field.ref,
2868
+ patch: { groupId }
2869
+ })));
2870
+ let items;
2871
+ try {
2872
+ items = (await ctx.cancellable(options?.signal, change.result)).items;
2873
+ } catch (error) {
2874
+ throw (0, _embedpdf_core.toPluginError)("form", error);
2875
+ }
2876
+ const answered = /* @__PURE__ */ new Map();
2877
+ for (const item of items) if (item.type === "forms.update") answered.set(fieldKeyOf(item.field), item.field);
2878
+ return { fields: moved.map((field) => answered.get(fieldKeyOf(field)) ?? field) };
2879
+ };
2556
2880
  return {
2557
2881
  copyOps,
2558
2882
  api: {
@@ -2560,8 +2884,10 @@ function createFieldWrites(ctx, { fields, enqueue }) {
2560
2884
  addWidget,
2561
2885
  duplicate,
2562
2886
  duplicateWidgets,
2887
+ moveToGroup,
2563
2888
  update: async (ref, patch, options) => {
2564
2889
  allow("form.update", (0, _embedpdf_engine_core_runtime.writesScripts)(patch.actions));
2890
+ if (typeof patch.groupId === "string" && patch.groupId !== fieldByRef(fields.view(), ref)?.groupId) groups.assertMaySet(patch.groupId, "form.update");
2565
2891
  const change = stage("update", {
2566
2892
  type: "forms.update",
2567
2893
  field: ref,
@@ -2932,20 +3258,29 @@ function failedFill(result) {
2932
3258
  /**
2933
3259
  * Moving the cursor between fields: `focus()`, `focusNext()` (what Tab does), the arrow keys in a
2934
3260
  * radio group, and the field the cursor is in. This area decides where the cursor goes: which
2935
- * field, which of its boxes, in Tab's order (the engine's `tabOrderOf()`); the cursor service
3261
+ * field, which of its boxes, in Tab's order (`services/tab-order.ts`); the cursor service
2936
3262
  * (`services/cursor.ts`) brings the box into view and hands it to its control.
3263
+ *
3264
+ * A stop is a box of a field the user may fill in. The cursor passes over one whose control
3265
+ * takes no cursor (`cursor.goTo` declines it): a signature field with nothing to sign it. Stops
3266
+ * are tried in the order Tab comes to them, so a move asks only the ones it reaches.
3267
+ *
3268
+ * A radio group is one stop on each page it shows on, where its first button comes in Tab's
3269
+ * order. The button that takes the cursor may come later in that order, with other fields
3270
+ * before it. From any of its buttons the cursor goes on from the group's stop, so Tab takes
3271
+ * what comes after the group and Shift+Tab what comes before it, each field once.
2937
3272
  */
3273
+ const NO_STOPS = /* @__PURE__ */ new Set();
2938
3274
  /** A radio button as its field lists it: whether it's the checked one, and the value it picks. */
2939
3275
  const radioButtonOf = (field, widget) => field.kind === "radio" ? field.widgets.find((candidate) => candidate.objectNumber === widget) ?? null : null;
2940
- function createFocus(ctx, { fields, rights, events, cursor }, fill) {
3276
+ function createFocus(ctx, { fields, rights, events, cursor, tabOrder }, fill) {
2941
3277
  /** Every box that shows, in Tab's order, and the ones Tab stops at. */
2942
3278
  const order = (0, _embedpdf_core.memo)(() => [
2943
3279
  fields.view(),
2944
- ctx.document()?.pages,
3280
+ tabOrder.rows(),
2945
3281
  rights.key(),
2946
3282
  ctx.settings().get().fillable
2947
- ], (index, pages) => {
2948
- const rows = (0, _embedpdf_engine_core_runtime.tabOrderOf)((index.snapshot?.widgets ?? []).filter(shownOnScreen), pages ?? []);
3283
+ ], (index, rows) => {
2949
3284
  const position = /* @__PURE__ */ new Map();
2950
3285
  const stops = [];
2951
3286
  const groups = /* @__PURE__ */ new Set();
@@ -2986,30 +3321,56 @@ function createFocus(ctx, { fields, rights, events, cursor }, fill) {
2986
3321
  const index = fields.view();
2987
3322
  const field = fieldByRef(index, ref);
2988
3323
  if (!field || !rights.takesInput(field)) return false;
2989
- let row;
3324
+ const select = options.select ?? false;
2990
3325
  if (options.widget) {
2991
3326
  const widget = widgetObjectOf(options.widget);
2992
3327
  if (fieldForWidget(index, widget) !== field) return false;
2993
- row = order().rows.find((candidate) => widgetObjectOf(candidate.ref) === widget);
2994
- } else {
2995
- const stop = order().stops.find((candidate) => candidate.field === field);
2996
- row = stop && boxAt(stop, false);
3328
+ const row = order().rows.find((candidate) => widgetObjectOf(candidate.ref) === widget);
3329
+ return row ? cursor.goTo(row, select) === "taken" : false;
3330
+ }
3331
+ for (const stop of order().stops) {
3332
+ if (stop.field !== field) continue;
3333
+ const move = cursor.goTo(boxAt(stop, false), select);
3334
+ if (move !== "declined") return move === "taken";
2997
3335
  }
2998
- return row ? cursor.goTo(row, options.select ?? false) : false;
3336
+ return false;
2999
3337
  };
3000
- const focusNext = (options = {}) => {
3338
+ /**
3339
+ * Move the cursor to the next stop after a box (`from`; `null`: from the start), as Tab does:
3340
+ * the first one on the way that takes the cursor. A radio button's place is its group's stop.
3341
+ * `passed` are the stops this move already asked for and that came in holding nothing to focus.
3342
+ */
3343
+ const step = (from, how, passed = NO_STOPS) => {
3344
+ const { backward, empty, wrap } = how;
3001
3345
  const index = fields.view();
3002
3346
  const { position, stops } = order();
3003
- const backward = options.backward ?? false;
3004
- const fromField = options.from ? fieldByRef(index, options.from) : null;
3005
- const from = options.from ? fromField?.widgets.map(({ objectNumber }) => objectNumber).find((w) => position.has(w)) ?? null : cursor.focused()?.widget ?? cursor.last();
3006
- const at = from === null ? null : position.get(from) ?? null;
3007
3347
  const field = from === null ? null : fieldForWidget(index, from);
3008
3348
  const page = from === null ? null : widgetRowOf(index, from)?.page.objectNumber;
3009
- const candidates = stops.filter((stop) => (!options.empty || isEmpty(stop.field)) && !(stop.field === field && field.kind === "radio" && stop.row.page.objectNumber === page));
3010
- const ahead = candidates.filter((stop) => at === null ? true : backward ? stop.at < at : stop.at > at);
3011
- const next = (backward ? ahead.at(-1) : ahead[0]) ?? (options.wrap ? backward ? candidates.at(-1) : candidates[0] : void 0);
3012
- return next ? cursor.goTo(boxAt(next, backward), true) : false;
3349
+ const group = field?.kind === "radio" ? stops.find((stop) => stop.field === field && stop.row.page.objectNumber === page) : void 0;
3350
+ const own = from === null ? void 0 : position.get(from);
3351
+ const at = own === void 0 ? null : group?.at ?? own;
3352
+ const candidates = stops.filter((stop) => (!empty || isEmpty(stop.field)) && stop !== group && !passed.has(widgetObjectOf(stop.row.ref)));
3353
+ const isAhead = (stop) => at === null ? true : backward ? stop.at < at : stop.at > at;
3354
+ const ahead = candidates.filter(isAhead);
3355
+ const round = wrap ? candidates.filter((stop) => !isAhead(stop)) : [];
3356
+ const way = backward ? [...ahead.reverse(), ...round.reverse()] : [...ahead, ...round];
3357
+ for (const stop of way) {
3358
+ const here = widgetObjectOf(stop.row.ref);
3359
+ const onward = () => void step(here, how, /* @__PURE__ */ new Set([...passed, here]));
3360
+ const move = cursor.goTo(boxAt(stop, backward), true, onward);
3361
+ if (move !== "declined") return move === "taken";
3362
+ }
3363
+ return false;
3364
+ };
3365
+ const focusNext = (options = {}) => {
3366
+ const { position } = order();
3367
+ const fromField = options.from ? fieldByRef(fields.view(), options.from) : null;
3368
+ const from = options.from ? fromField?.widgets.map(({ objectNumber }) => objectNumber).find((w) => position.has(w)) ?? null : cursor.focused()?.widget ?? cursor.last();
3369
+ return step(from, {
3370
+ backward: options.backward ?? false,
3371
+ empty: options.empty ?? false,
3372
+ wrap: options.wrap ?? false
3373
+ });
3013
3374
  };
3014
3375
  const moveInGroup = (ref, backward) => {
3015
3376
  const widget = widgetObjectOf(ref);
@@ -3019,7 +3380,7 @@ function createFocus(ctx, { fields, rights, events, cursor }, fill) {
3019
3380
  const here = buttons.findIndex((row) => widgetObjectOf(row.ref) === widget);
3020
3381
  if (here < 0 || buttons.length < 2) return false;
3021
3382
  const next = buttons[(here + (backward ? buttons.length - 1 : 1)) % buttons.length];
3022
- if (!cursor.goTo(next, false)) return false;
3383
+ if (cursor.goTo(next, false) !== "taken") return false;
3023
3384
  const button = radioButtonOf(field, widgetObjectOf(next.ref));
3024
3385
  if (button) {
3025
3386
  const activate = () => void fill.activateWidget(next.ref).catch(() => {});
@@ -3037,6 +3398,35 @@ function createFocus(ctx, { fields, rights, events, cursor }, fill) {
3037
3398
  } };
3038
3399
  }
3039
3400
  //#endregion
3401
+ //#region src/write/groups.ts
3402
+ /** The app's list as the state holds it: each id once (the first entry of an id is the group). */
3403
+ function namedGroupsOf(groups) {
3404
+ const byId = /* @__PURE__ */ new Map();
3405
+ for (const group of groups) {
3406
+ if (byId.has(group.id)) continue;
3407
+ byId.set(group.id, Object.freeze({
3408
+ id: group.id,
3409
+ label: group.label ?? null,
3410
+ color: group.color ?? null
3411
+ }));
3412
+ }
3413
+ return Object.freeze([...byId.values()]);
3414
+ }
3415
+ function createGroupWrites(ctx, { groups }) {
3416
+ return { api: {
3417
+ listGroups: groups.list,
3418
+ setGroups: (list) => {
3419
+ ctx.state.update(setGroups, namedGroupsOf(list));
3420
+ },
3421
+ getDesignGroup: () => ctx.state.get().designGroup,
3422
+ setDesignGroup: (groupId) => {
3423
+ if (groupId !== null) groups.assertMaySet(groupId, "form.setDesignGroup");
3424
+ ctx.state.update(setDesignGroup, groupId);
3425
+ },
3426
+ canSetGroup: groups.maySet
3427
+ } };
3428
+ }
3429
+ //#endregion
3040
3430
  //#region src/write/interchange.ts
3041
3431
  function createInterchange(ctx, services) {
3042
3432
  const { enqueue, siblings } = services;
@@ -3095,13 +3485,18 @@ function createInterchange(ctx, services) {
3095
3485
  * change as the rest of it. While the tool fills, nothing is lent, and the
3096
3486
  * form layer draws and fills every widget. A widget of no size is never lent:
3097
3487
  * nobody can see it, so nobody should be able to select it by hand.
3488
+ *
3489
+ * Each lent widget carries its field's group's color as its accent,
3490
+ * `fields.tint` strong, so the annotation layer shows whose field it is.
3098
3491
  */
3099
3492
  const objectNumberOf = (ref) => ref.kind === "objectNumber" ? ref.objectNumber : -1;
3100
- function createWidgetLender(ctx, { fields, design, pictures, looks }, copyOps) {
3493
+ function createWidgetLender(ctx, { fields, design, pictures, looks, groups }, copyOps) {
3101
3494
  const records = (0, _embedpdf_core.memo)(() => [
3102
3495
  design.lending(),
3103
3496
  fields.get().snapshot,
3104
- fields.view().snapshot
3497
+ fields.view().snapshot,
3498
+ groups.list(),
3499
+ ctx.settings().get().fields.tint
3105
3500
  ], (lending, confirmed, shown) => lending && confirmed && shown ? {
3106
3501
  confirmed: confirmed.widgets.filter(hasArea),
3107
3502
  shown: shown.widgets.filter(hasArea)
@@ -3185,6 +3580,10 @@ function createWidgetLender(ctx, { fields, design, pictures, looks }, copyOps) {
3185
3580
  getPictureVersion: pictures.versionOf,
3186
3581
  renderAppearances: pictures.render,
3187
3582
  isPending: looks.isPending,
3583
+ accentOf: (record) => {
3584
+ const field = fieldForWidget(fields.view(), objectNumberOf(record.ref));
3585
+ return groups.lookOf(field?.groupId ?? null)?.accent ?? null;
3586
+ },
3188
3587
  painter: (record) => record.subtype === "widget" ? looks.painterOf(record) : null
3189
3588
  };
3190
3589
  }
@@ -3622,6 +4021,7 @@ function createFormController(ctx) {
3622
4021
  const typing = createTyping(ctx, services, values.setText);
3623
4022
  const resets = createResetWrites(ctx, services, fills);
3624
4023
  const design = createFieldWrites(ctx, services);
4024
+ const groups = createGroupWrites(ctx, services);
3625
4025
  const interchange = createInterchange(ctx, services);
3626
4026
  const activation = createActivation(ctx, services, fills);
3627
4027
  const scripts = createScriptEffects(ctx, services, fills);
@@ -3638,6 +4038,7 @@ function createFormController(ctx) {
3638
4038
  typing.api,
3639
4039
  resets.api,
3640
4040
  design.api,
4041
+ groups.api,
3641
4042
  interchange.api,
3642
4043
  activation.api,
3643
4044
  scripts.api,
@@ -3656,7 +4057,9 @@ function createFormController(ctx) {
3656
4057
  onFieldUpdated: events.fieldUpdated.on,
3657
4058
  onFieldDeleted: events.fieldDeleted.on,
3658
4059
  onValidationRejected: events.validationRejected.on,
3659
- onResynced: events.resynced.on
4060
+ onResynced: events.resynced.on,
4061
+ onDesignGroupChanged: events.designGroupChanged.on,
4062
+ onGroupsChanged: events.groupsChanged.on
3660
4063
  }
3661
4064
  ]);
3662
4065
  return {
@@ -3676,7 +4079,8 @@ function createFormController(ctx) {
3676
4079
  * the annotation plugin present, the form lends it the widgets, which its
3677
4080
  * tools then select, move, restyle and delete. The render plugin draws the
3678
4081
  * widgets' pictures in both modes. With the fonts plugin, a text field in a
3679
- * font of its own is edited in that font's program. `config` is the settings the app
4082
+ * font of its own is edited in that font's program. With the Stage, `focus()` and
4083
+ * `focusNext()` bring the box they go to into view. `config` is the settings the app
3680
4084
  * registers, over {@link FORM_DEFAULTS}.
3681
4085
  */
3682
4086
  const formPlugin = (config) => (0, _embedpdf_core.definePlugin)({
@@ -3688,7 +4092,8 @@ const formPlugin = (config) => (0, _embedpdf_core.definePlugin)({
3688
4092
  _embedpdf_plugin_annotation_contract.AnnotationToken,
3689
4093
  _embedpdf_plugin_actions_contract.ActionsToken,
3690
4094
  _embedpdf_plugin_render_contract.RenderToken,
3691
- _embedpdf_plugin_fonts_contract.FontsToken
4095
+ _embedpdf_plugin_fonts_contract.FontsToken,
4096
+ _embedpdf_plugin_stage_contract.StageToken
3692
4097
  ],
3693
4098
  state: initialFormModel,
3694
4099
  settings: {
@@ -3706,20 +4111,27 @@ const formPlugin = (config) => (0, _embedpdf_core.definePlugin)({
3706
4111
  * field changes.
3707
4112
  */
3708
4113
  const NO_FIELDS = Object.freeze([]);
4114
+ const NO_GROUPS = Object.freeze([]);
3709
4115
  const formState = (0, _embedpdf_core.defineState)(require_contract.FormToken, {
3710
4116
  read: (form) => ({
3711
4117
  fields: form.list(),
3712
4118
  status: form.getStatus(),
3713
4119
  formKind: form.getFormKind(),
3714
4120
  selectedField: form.getSelectedField(),
3715
- focusedField: form.getFocusedField()
4121
+ focusedField: form.getFocusedField(),
4122
+ selectedFields: form.listSelectedFields(),
4123
+ groups: form.listGroups(),
4124
+ designGroup: form.getDesignGroup()
3716
4125
  }),
3717
4126
  empty: {
3718
4127
  fields: NO_FIELDS,
3719
4128
  status: "idle",
3720
4129
  formKind: "none",
3721
4130
  selectedField: null,
3722
- focusedField: null
4131
+ focusedField: null,
4132
+ selectedFields: NO_FIELDS,
4133
+ groups: NO_GROUPS,
4134
+ designGroup: null
3723
4135
  }
3724
4136
  });
3725
4137
  //#endregion