@embedpdf/plugin-form 3.2.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,8 +630,22 @@ function fieldsWithChangedValues(previous, next) {
584
630
  });
585
631
  }
586
632
  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;
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
+ });
639
+ /**
640
+ * Whether a widget's box has an area. One of no size is how a PDF keeps a field that shows
641
+ * nowhere: the field of a document timestamp, an invisible signature.
642
+ */
643
+ const hasArea = (row) => row.rect.width > 0 && row.rect.height > 0;
644
+ /**
645
+ * Whether a widget shows on screen: its `hidden` and `noView` flags hide it, and a box of no
646
+ * size has nothing to show. What doesn't show gets no control, and Tab doesn't stop at it.
647
+ */
648
+ const shownOnScreen = (row) => !row.hidden && !row.noView && hasArea(row);
589
649
  /** The widgets one page shows, from the form's widget rows. */
590
650
  function pageWidgetsOf(index, pageObjectNumber) {
591
651
  const widgets = {};
@@ -593,7 +653,8 @@ function pageWidgetsOf(index, pageObjectNumber) {
593
653
  if (row.page.objectNumber !== pageObjectNumber || row.ref.kind !== "objectNumber") continue;
594
654
  if (!shownOnScreen(row)) continue;
595
655
  widgets[row.ref.objectNumber] = {
596
- box: row.rect,
656
+ ref: row.ref,
657
+ ...placeOf(row),
597
658
  look: {
598
659
  border: row.color ?? null,
599
660
  borderWidth: row.strokeWidth ?? 1,
@@ -619,7 +680,7 @@ function shownWidgetsOf(index, pageObjectNumber, lookOf = () => AT_REST) {
619
680
  if (row.page.objectNumber !== pageObjectNumber || !shownOnScreen(row)) continue;
620
681
  shown.push({
621
682
  ref: row.ref,
622
- rect: row.rect,
683
+ ...placeOf(row),
623
684
  appearanceState: row.appearanceState,
624
685
  ...lookOf(row)
625
686
  });
@@ -631,24 +692,48 @@ function widgetRowOf(index, annotObjectNumber) {
631
692
  return position === void 0 ? null : index.snapshot?.widgets[position] ?? null;
632
693
  }
633
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;
634
- /** 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. */
635
696
  function widgetAt(index, widgets, point) {
636
697
  if (!widgets) return null;
637
698
  let best = null;
638
- for (const [key, { box }] of Object.entries(widgets)) {
639
- if (!boxContains(box, point)) continue;
699
+ for (const [key, { box, rotation, rect }] of Object.entries(widgets)) {
700
+ if (!boxContains(rect, point)) continue;
640
701
  const annotObjectNumber = Number(key);
641
702
  const field = fieldForWidget(index, annotObjectNumber);
642
703
  if (!field) continue;
643
- 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 = {
644
705
  annotObjectNumber,
645
706
  field,
646
- box
707
+ box,
708
+ rotation,
709
+ rect
647
710
  };
648
711
  }
649
712
  return best;
650
713
  }
651
- 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
+ }
652
737
  //#endregion
653
738
  //#region src/read/fields.ts
654
739
  /**
@@ -657,6 +742,7 @@ const initialFormModel = () => ({ focused: null });
657
742
  * required-field check.
658
743
  */
659
744
  const NO_FIELDS$1 = Object.freeze([]);
745
+ const NO_SELECTED_FIELDS = Object.freeze([]);
660
746
  const NOTHING_SELECTED = Object.freeze([]);
661
747
  /** A widget address as the annotation object number the field index is keyed by. */
662
748
  const widgetObjectOf = (widget) => "kind" in widget ? widget.kind === "objectNumber" ? widget.objectNumber : 0 : widget.objectNumber;
@@ -770,6 +856,16 @@ function createFieldReads(ctx, { fields, rights, siblings }) {
770
856
  }
771
857
  return found;
772
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
+ });
773
869
  return { api: {
774
870
  getSnapshot: () => fields.view().snapshot,
775
871
  getStatus: fields.getStatus,
@@ -782,6 +878,7 @@ function createFieldReads(ctx, { fields, rights, siblings }) {
782
878
  list,
783
879
  getValue: (ref) => valueByKey(canonicalKey(fields.view(), ref)),
784
880
  getSelectedField,
881
+ listSelectedFields,
785
882
  validate,
786
883
  exportValues
787
884
  } };
@@ -791,7 +888,9 @@ function createFieldReads(ctx, { fields, rights, siblings }) {
791
888
  /**
792
889
  * A field's settings, described for a settings panel the way an annotation
793
890
  * kind describes its look: which settings the field's kind has, how each is
794
- * 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.
795
894
  */
796
895
  /** What every field has. */
797
896
  const COMMON = [
@@ -916,6 +1015,21 @@ function familySettings(field) {
916
1015
  default: return [];
917
1016
  }
918
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
+ }
919
1033
  /** Each setting's value, as the field holds it. */
920
1034
  function valuesOf(field, settings) {
921
1035
  const held = field;
@@ -925,10 +1039,14 @@ function valuesOf(field, settings) {
925
1039
  else values[key] = held[key] ?? null;
926
1040
  return values;
927
1041
  }
928
- function createFieldSettings({ fields }) {
929
- 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) => {
930
1044
  if (!field) return null;
931
- const properties = [...COMMON, ...familySettings(field)];
1045
+ const properties = [
1046
+ ...COMMON,
1047
+ ...groupSetting(field, listed, groups.maySet),
1048
+ ...familySettings(field)
1049
+ ];
932
1050
  return {
933
1051
  properties,
934
1052
  values: valuesOf(field, properties)
@@ -938,21 +1056,43 @@ function createFieldSettings({ fields }) {
938
1056
  }
939
1057
  //#endregion
940
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");
941
1068
  /**
942
- * Project one widget of a field into a fill control; `fillable`: the user may
943
- * fill the field in (a signature field: sign it). Null for kinds with no
944
- * 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.
945
1075
  */
946
- 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;
947
1079
  const base = {
948
- key: fieldKeyOf(field),
1080
+ key,
949
1081
  fieldRef: field.ref,
950
1082
  annotObjectNumber,
951
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,
952
1090
  box: widget.box,
1091
+ rotation: widget.rotation,
1092
+ rect: widget.rect,
953
1093
  look: widget.look,
954
1094
  disabled: field.readOnly || !fillable,
955
- label: field.alternateName ?? field.name
1095
+ label: ownedLabel(field.alternateName ?? field.name, owner)
956
1096
  };
957
1097
  switch (field.kind) {
958
1098
  case "text": return {
@@ -976,12 +1116,15 @@ function projectWidget(field, annotObjectNumber, widget, fillable) {
976
1116
  }
977
1117
  case "radio": {
978
1118
  const toggle = field.widgets.find((candidate) => candidate.objectNumber === annotObjectNumber);
1119
+ const exportValue = toggle && "exportValue" in toggle ? toggle.exportValue : "";
979
1120
  return {
980
1121
  ...base,
1122
+ label: ownedLabel(radioLabel(field.alternateName ?? field.name, exportValue), owner),
981
1123
  control: "toggle",
982
1124
  kind: "radio",
983
1125
  checked: toggle && "checked" in toggle ? toggle.checked : false,
984
- exportValue: toggle && "exportValue" in toggle ? toggle.exportValue : ""
1126
+ exportValue,
1127
+ inGroup
985
1128
  };
986
1129
  }
987
1130
  case "combobox": return {
@@ -1015,19 +1158,22 @@ function projectWidget(field, annotObjectNumber, widget, fillable) {
1015
1158
  }
1016
1159
  }
1017
1160
  /**
1018
- * Project one page's widgets into fill controls, each disabled when the user
1019
- * may not fill its field in, or sign it (`mayFill`). Widgets whose page has not loaded (or
1020
- * that are direct objects with no join key) are skipped; the projection runs
1021
- * 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.
1022
1168
  */
1023
- function fillItems(index, pageObjectNumber, widgets, mayFill) {
1169
+ function fillItems(index, pageObjectNumber, widgets, mayFillByHand, mayFill, groupPositionOf = () => null, groupLookOf = () => null) {
1024
1170
  if (!index.snapshot || !widgets) return [];
1025
1171
  const items = [];
1026
1172
  for (const field of index.snapshot.fields) for (const widget of field.widgets) {
1027
1173
  if (widget.page?.objectNumber !== pageObjectNumber) continue;
1028
1174
  const placed = widgets[widget.objectNumber];
1029
1175
  if (!placed) continue;
1030
- 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));
1031
1177
  if (item) items.push(item);
1032
1178
  }
1033
1179
  return items;
@@ -1042,7 +1188,7 @@ function fillItems(index, pageObjectNumber, widgets, mayFill) {
1042
1188
  */
1043
1189
  const NO_WIDGETS = Object.freeze([]);
1044
1190
  const NOTHING_SHOWN$1 = Object.freeze([]);
1045
- function createWidgetReads(ctx, { fields, rights, looks, pictures }) {
1191
+ function createWidgetReads(ctx, { fields, rights, looks, pictures, design, siblings, cursor, tabOrder, groups }) {
1046
1192
  /** Every page's widgets come with the form: one read for the document. */
1047
1193
  const loadWidgets = (_page) => fields.settled();
1048
1194
  const widgetsOn = (0, _embedpdf_core.memoByKey)((pageObjectNumber) => [fields.view()], (pageObjectNumber, index) => pageWidgetsOf(index, pageObjectNumber));
@@ -1056,8 +1202,11 @@ function createWidgetReads(ctx, { fields, rights, looks, pictures }) {
1056
1202
  fields.view(),
1057
1203
  widgetsOn(pageObjectNumber),
1058
1204
  rights.key(),
1059
- ctx.settings().get().fillable
1060
- ], (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));
1061
1210
  /** The page's content box (`{0, 0, width, height}`), for page-bound placement. */
1062
1211
  const getPageBox = (page) => {
1063
1212
  const size = ctx.getPage(page)?.size;
@@ -1068,6 +1217,19 @@ function createWidgetReads(ctx, { fields, rights, looks, pictures }) {
1068
1217
  height: size.height
1069
1218
  } : null;
1070
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
+ };
1071
1233
  return {
1072
1234
  getPageBox,
1073
1235
  api: {
@@ -1086,7 +1248,9 @@ function createWidgetReads(ctx, { fields, rights, looks, pictures }) {
1086
1248
  getWidgetFontCss: looks.getWidgetFontCss,
1087
1249
  ensureLoaded: loadWidgets,
1088
1250
  getWidgetAt,
1089
- getPageBox
1251
+ getPageBox,
1252
+ getWidgetAnchor,
1253
+ isWidgetFocused: (widget) => cursor.focused()?.widget === widgetObjectOf(widget)
1090
1254
  }
1091
1255
  };
1092
1256
  }
@@ -1509,6 +1673,10 @@ function createFieldsMirror(ctx, events) {
1509
1673
  //#region src/services/cursor.ts
1510
1674
  /** How long a box asked for keeps its claim on the cursor while its page comes in. */
1511
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;
1512
1680
  function createCursor(ctx, fields, events) {
1513
1681
  const targets = /* @__PURE__ */ new Map();
1514
1682
  let pending = null;
@@ -1530,8 +1698,29 @@ function createCursor(ctx, fields, events) {
1530
1698
  };
1531
1699
  const clearPending = () => {
1532
1700
  pending?.expire();
1701
+ pending?.settle?.();
1533
1702
  pending = null;
1534
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
+ };
1535
1724
  return {
1536
1725
  focused: () => ctx.state.get().focused,
1537
1726
  last: () => last,
@@ -1555,34 +1744,34 @@ function createCursor(ctx, fields, events) {
1555
1744
  });
1556
1745
  }
1557
1746
  },
1558
- goTo(row, select) {
1747
+ goTo(row, select, onward) {
1559
1748
  const widget = widgetObjectOf(row.ref);
1749
+ const shown = targets.get(widget);
1750
+ if (shown && !takes(shown)) return "declined";
1560
1751
  const stage = ctx.tryGet(_embedpdf_plugin_stage_contract.StageToken);
1561
1752
  stage?.reveal(row.page, { rect: row.rect });
1562
1753
  clearPending();
1563
1754
  const target = targets.get(widget);
1564
- if (target) {
1565
- target.focus({ select });
1566
- return true;
1567
- }
1568
- if (!stage) return false;
1569
- pending = {
1755
+ if (target && enter(target, select)) return "taken";
1756
+ if (target && target === shown) return "declined";
1757
+ if (!stage) return "unreachable";
1758
+ const waiting = {
1570
1759
  widget,
1571
1760
  select,
1761
+ onward: onward ?? null,
1572
1762
  expire: ctx.clock.after(PENDING_MS, () => {
1573
- if (pending?.widget === widget) pending = null;
1574
- })
1763
+ if (pending === waiting) clearPending();
1764
+ }),
1765
+ settle: null
1575
1766
  };
1576
- return true;
1767
+ pending = waiting;
1768
+ if (target) settleLater(waiting);
1769
+ return "taken";
1577
1770
  },
1578
1771
  attach(widgetRef, target) {
1579
1772
  const widget = widgetObjectOf(widgetRef);
1580
1773
  targets.set(widget, target);
1581
- if (pending?.widget === widget) {
1582
- const { select } = pending;
1583
- clearPending();
1584
- target.focus({ select });
1585
- }
1774
+ if (pending?.widget === widget) arrive(pending, target);
1586
1775
  return () => {
1587
1776
  if (targets.get(widget) === target) targets.delete(widget);
1588
1777
  };
@@ -1604,15 +1793,21 @@ function createDesign(ctx, siblings) {
1604
1793
  //#endregion
1605
1794
  //#region src/services/events.ts
1606
1795
  function createEvents(ctx) {
1607
- return {
1796
+ const events = {
1608
1797
  valueChanged: ctx.events.source(),
1609
1798
  fieldCreated: ctx.events.source(),
1610
1799
  fieldUpdated: ctx.events.source(),
1611
1800
  fieldDeleted: ctx.events.source(),
1612
1801
  validationRejected: ctx.events.source(),
1613
1802
  resynced: ctx.events.source(),
1614
- focusChanged: ctx.events.source()
1803
+ focusChanged: ctx.events.source(),
1804
+ designGroupChanged: ctx.events.source(),
1805
+ groupsChanged: ctx.events.source()
1615
1806
  };
1807
+ ctx.state.onChange(({ previous, next }) => {
1808
+ if (previous.designGroup !== next.designGroup) events.designGroupChanged.emit({ groupId: next.designGroup });
1809
+ });
1810
+ return events;
1616
1811
  }
1617
1812
  //#endregion
1618
1813
  //#region src/services/fill-rights.ts
@@ -1627,12 +1822,14 @@ const isFillableByHand = (fillable, kind) => typeof fillable === "boolean" ? fil
1627
1822
  function createFillRights(ctx, fields) {
1628
1823
  const mayFill = (field) => ctx.allowsField("fill", field);
1629
1824
  const maySign = (field) => ctx.allowsField("sign", field);
1630
- 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);
1631
1827
  /** The form's groups, `null` (no group) among them. */
1632
1828
  const groups = (0, _embedpdf_core.memo)(() => [fields.view()], (index) => [...new Set((index.snapshot?.fields ?? []).map((field) => field.groupId))]);
1633
1829
  return {
1634
1830
  mayFill,
1635
1831
  maySign,
1832
+ mayFillOrSign,
1636
1833
  mayFillByHand,
1637
1834
  takesInput: (field) => !field.readOnly && mayFillByHand(field),
1638
1835
  assertMayFill: (field, operation) => ctx.assertAllowedField("fill", field, operation),
@@ -1672,6 +1869,76 @@ function createFormattedTexts(ctx, fields) {
1672
1869
  };
1673
1870
  }
1674
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
1675
1942
  //#region src/services/looks.ts
1676
1943
  /**
1677
1944
  * What a shown widget looks like now: the engine's picture, or the painter's
@@ -1938,6 +2205,41 @@ function resolveSiblings(ctx) {
1938
2205
  };
1939
2206
  }
1940
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
1941
2243
  //#region src/services/index.ts
1942
2244
  function createServices(ctx) {
1943
2245
  const siblings = resolveSiblings(ctx);
@@ -1948,8 +2250,10 @@ function createServices(ctx) {
1948
2250
  return {
1949
2251
  fields,
1950
2252
  rights: createFillRights(ctx, fields),
2253
+ groups: createGroups(ctx, fields, events),
1951
2254
  events,
1952
2255
  cursor: createCursor(ctx, fields, events),
2256
+ tabOrder: createTabOrder(ctx, fields),
1953
2257
  siblings,
1954
2258
  scripting: createScriptingSeam(ctx, siblings),
1955
2259
  design,
@@ -2389,7 +2693,7 @@ function exportValueFor(field) {
2389
2693
  }
2390
2694
  const MODIFY = "doc.forms.modify";
2391
2695
  const SCRIPT = "doc.forms.script";
2392
- function createFieldWrites(ctx, { fields, enqueue }) {
2696
+ function createFieldWrites(ctx, { fields, enqueue, groups }) {
2393
2697
  const numbers = createObjectNumbers(ctx);
2394
2698
  /** Refuse up front without `doc.forms.modify`, and without `doc.forms.script` when it writes scripts. */
2395
2699
  const allow = (operation, scripts = false) => {
@@ -2418,6 +2722,7 @@ function createFieldWrites(ctx, { fields, enqueue }) {
2418
2722
  };
2419
2723
  const create = async (draft, options) => {
2420
2724
  allow("form.create", (0, _embedpdf_engine_core_runtime.draftWritesScripts)(draft));
2725
+ if (typeof draft.groupId === "string") groups.assertMaySet(draft.groupId, "form.create");
2421
2726
  const count = 1 + (draft.widgets?.length ?? 0);
2422
2727
  const [objectNumber, ...widgetObjectNumbers] = numbers.takeNow(count) ?? await numbers.take(count);
2423
2728
  const change = stage("create", {
@@ -2439,7 +2744,7 @@ function createFieldWrites(ctx, { fields, enqueue }) {
2439
2744
  if (!page) throw new _embedpdf_core.PluginError("invalid-input", "form", "the field shows on no page: give `page` and `rect`");
2440
2745
  const size = ctx.getPage(page)?.size;
2441
2746
  const onPage = rows.filter((row) => row.page.objectNumber === page.objectNumber);
2442
- 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);
2443
2748
  if (!rect) throw new _embedpdf_core.PluginError("invalid-input", "form", "no widget of the field on that page: give `rect`");
2444
2749
  const exportValue = placement.exportValue ?? exportValueFor(field);
2445
2750
  const split = isMerged(field);
@@ -2545,6 +2850,33 @@ function createFieldWrites(ctx, { fields, enqueue }) {
2545
2850
  }
2546
2851
  return duplicateResultOf(items, copy.copies, copy.dropped);
2547
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
+ };
2548
2880
  return {
2549
2881
  copyOps,
2550
2882
  api: {
@@ -2552,8 +2884,10 @@ function createFieldWrites(ctx, { fields, enqueue }) {
2552
2884
  addWidget,
2553
2885
  duplicate,
2554
2886
  duplicateWidgets,
2887
+ moveToGroup,
2555
2888
  update: async (ref, patch, options) => {
2556
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");
2557
2891
  const change = stage("update", {
2558
2892
  type: "forms.update",
2559
2893
  field: ref,
@@ -2924,20 +3258,29 @@ function failedFill(result) {
2924
3258
  /**
2925
3259
  * Moving the cursor between fields: `focus()`, `focusNext()` (what Tab does), the arrow keys in a
2926
3260
  * radio group, and the field the cursor is in. This area decides where the cursor goes: which
2927
- * 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
2928
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.
2929
3272
  */
3273
+ const NO_STOPS = /* @__PURE__ */ new Set();
2930
3274
  /** A radio button as its field lists it: whether it's the checked one, and the value it picks. */
2931
3275
  const radioButtonOf = (field, widget) => field.kind === "radio" ? field.widgets.find((candidate) => candidate.objectNumber === widget) ?? null : null;
2932
- function createFocus(ctx, { fields, rights, events, cursor }, fill) {
3276
+ function createFocus(ctx, { fields, rights, events, cursor, tabOrder }, fill) {
2933
3277
  /** Every box that shows, in Tab's order, and the ones Tab stops at. */
2934
3278
  const order = (0, _embedpdf_core.memo)(() => [
2935
3279
  fields.view(),
2936
- ctx.document()?.pages,
3280
+ tabOrder.rows(),
2937
3281
  rights.key(),
2938
3282
  ctx.settings().get().fillable
2939
- ], (index, pages) => {
2940
- const rows = (0, _embedpdf_engine_core_runtime.tabOrderOf)((index.snapshot?.widgets ?? []).filter(shownOnScreen), pages ?? []);
3283
+ ], (index, rows) => {
2941
3284
  const position = /* @__PURE__ */ new Map();
2942
3285
  const stops = [];
2943
3286
  const groups = /* @__PURE__ */ new Set();
@@ -2978,30 +3321,56 @@ function createFocus(ctx, { fields, rights, events, cursor }, fill) {
2978
3321
  const index = fields.view();
2979
3322
  const field = fieldByRef(index, ref);
2980
3323
  if (!field || !rights.takesInput(field)) return false;
2981
- let row;
3324
+ const select = options.select ?? false;
2982
3325
  if (options.widget) {
2983
3326
  const widget = widgetObjectOf(options.widget);
2984
3327
  if (fieldForWidget(index, widget) !== field) return false;
2985
- row = order().rows.find((candidate) => widgetObjectOf(candidate.ref) === widget);
2986
- } else {
2987
- const stop = order().stops.find((candidate) => candidate.field === field);
2988
- 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";
2989
3335
  }
2990
- return row ? cursor.goTo(row, options.select ?? false) : false;
3336
+ return false;
2991
3337
  };
2992
- 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;
2993
3345
  const index = fields.view();
2994
3346
  const { position, stops } = order();
2995
- const backward = options.backward ?? false;
2996
- const fromField = options.from ? fieldByRef(index, options.from) : null;
2997
- const from = options.from ? fromField?.widgets.map(({ objectNumber }) => objectNumber).find((w) => position.has(w)) ?? null : cursor.focused()?.widget ?? cursor.last();
2998
- const at = from === null ? null : position.get(from) ?? null;
2999
3347
  const field = from === null ? null : fieldForWidget(index, from);
3000
3348
  const page = from === null ? null : widgetRowOf(index, from)?.page.objectNumber;
3001
- const candidates = stops.filter((stop) => (!options.empty || isEmpty(stop.field)) && !(stop.field === field && field.kind === "radio" && stop.row.page.objectNumber === page));
3002
- const ahead = candidates.filter((stop) => at === null ? true : backward ? stop.at < at : stop.at > at);
3003
- const next = (backward ? ahead.at(-1) : ahead[0]) ?? (options.wrap ? backward ? candidates.at(-1) : candidates[0] : void 0);
3004
- 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
+ });
3005
3374
  };
3006
3375
  const moveInGroup = (ref, backward) => {
3007
3376
  const widget = widgetObjectOf(ref);
@@ -3011,7 +3380,7 @@ function createFocus(ctx, { fields, rights, events, cursor }, fill) {
3011
3380
  const here = buttons.findIndex((row) => widgetObjectOf(row.ref) === widget);
3012
3381
  if (here < 0 || buttons.length < 2) return false;
3013
3382
  const next = buttons[(here + (backward ? buttons.length - 1 : 1)) % buttons.length];
3014
- if (!cursor.goTo(next, false)) return false;
3383
+ if (cursor.goTo(next, false) !== "taken") return false;
3015
3384
  const button = radioButtonOf(field, widgetObjectOf(next.ref));
3016
3385
  if (button) {
3017
3386
  const activate = () => void fill.activateWidget(next.ref).catch(() => {});
@@ -3029,6 +3398,35 @@ function createFocus(ctx, { fields, rights, events, cursor }, fill) {
3029
3398
  } };
3030
3399
  }
3031
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
3032
3430
  //#region src/write/interchange.ts
3033
3431
  function createInterchange(ctx, services) {
3034
3432
  const { enqueue, siblings } = services;
@@ -3085,17 +3483,23 @@ function createInterchange(ctx, services) {
3085
3483
  * its records and edits them with its tools: select, move, resize, restyle,
3086
3484
  * reorder, delete. Each edit comes back here as the form's ops, in the same
3087
3485
  * change as the rest of it. While the tool fills, nothing is lent, and the
3088
- * form layer draws and fills every widget.
3486
+ * form layer draws and fills every widget. A widget of no size is never lent:
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.
3089
3491
  */
3090
3492
  const objectNumberOf = (ref) => ref.kind === "objectNumber" ? ref.objectNumber : -1;
3091
- function createWidgetLender(ctx, { fields, design, pictures, looks }, copyOps) {
3493
+ function createWidgetLender(ctx, { fields, design, pictures, looks, groups }, copyOps) {
3092
3494
  const records = (0, _embedpdf_core.memo)(() => [
3093
3495
  design.lending(),
3094
3496
  fields.get().snapshot,
3095
- fields.view().snapshot
3497
+ fields.view().snapshot,
3498
+ groups.list(),
3499
+ ctx.settings().get().fields.tint
3096
3500
  ], (lending, confirmed, shown) => lending && confirmed && shown ? {
3097
- confirmed: confirmed.widgets,
3098
- shown: shown.widgets
3501
+ confirmed: confirmed.widgets.filter(hasArea),
3502
+ shown: shown.widgets.filter(hasArea)
3099
3503
  } : null);
3100
3504
  /**
3101
3505
  * Deleted widgets, as the form's ops: a widget leaves its field
@@ -3176,6 +3580,10 @@ function createWidgetLender(ctx, { fields, design, pictures, looks }, copyOps) {
3176
3580
  getPictureVersion: pictures.versionOf,
3177
3581
  renderAppearances: pictures.render,
3178
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
+ },
3179
3587
  painter: (record) => record.subtype === "widget" ? looks.painterOf(record) : null
3180
3588
  };
3181
3589
  }
@@ -3613,6 +4021,7 @@ function createFormController(ctx) {
3613
4021
  const typing = createTyping(ctx, services, values.setText);
3614
4022
  const resets = createResetWrites(ctx, services, fills);
3615
4023
  const design = createFieldWrites(ctx, services);
4024
+ const groups = createGroupWrites(ctx, services);
3616
4025
  const interchange = createInterchange(ctx, services);
3617
4026
  const activation = createActivation(ctx, services, fills);
3618
4027
  const scripts = createScriptEffects(ctx, services, fills);
@@ -3629,6 +4038,7 @@ function createFormController(ctx) {
3629
4038
  typing.api,
3630
4039
  resets.api,
3631
4040
  design.api,
4041
+ groups.api,
3632
4042
  interchange.api,
3633
4043
  activation.api,
3634
4044
  scripts.api,
@@ -3647,7 +4057,9 @@ function createFormController(ctx) {
3647
4057
  onFieldUpdated: events.fieldUpdated.on,
3648
4058
  onFieldDeleted: events.fieldDeleted.on,
3649
4059
  onValidationRejected: events.validationRejected.on,
3650
- onResynced: events.resynced.on
4060
+ onResynced: events.resynced.on,
4061
+ onDesignGroupChanged: events.designGroupChanged.on,
4062
+ onGroupsChanged: events.groupsChanged.on
3651
4063
  }
3652
4064
  ]);
3653
4065
  return {
@@ -3667,7 +4079,8 @@ function createFormController(ctx) {
3667
4079
  * the annotation plugin present, the form lends it the widgets, which its
3668
4080
  * tools then select, move, restyle and delete. The render plugin draws the
3669
4081
  * widgets' pictures in both modes. With the fonts plugin, a text field in a
3670
- * 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
3671
4084
  * registers, over {@link FORM_DEFAULTS}.
3672
4085
  */
3673
4086
  const formPlugin = (config) => (0, _embedpdf_core.definePlugin)({
@@ -3679,7 +4092,8 @@ const formPlugin = (config) => (0, _embedpdf_core.definePlugin)({
3679
4092
  _embedpdf_plugin_annotation_contract.AnnotationToken,
3680
4093
  _embedpdf_plugin_actions_contract.ActionsToken,
3681
4094
  _embedpdf_plugin_render_contract.RenderToken,
3682
- _embedpdf_plugin_fonts_contract.FontsToken
4095
+ _embedpdf_plugin_fonts_contract.FontsToken,
4096
+ _embedpdf_plugin_stage_contract.StageToken
3683
4097
  ],
3684
4098
  state: initialFormModel,
3685
4099
  settings: {
@@ -3697,20 +4111,27 @@ const formPlugin = (config) => (0, _embedpdf_core.definePlugin)({
3697
4111
  * field changes.
3698
4112
  */
3699
4113
  const NO_FIELDS = Object.freeze([]);
4114
+ const NO_GROUPS = Object.freeze([]);
3700
4115
  const formState = (0, _embedpdf_core.defineState)(require_contract.FormToken, {
3701
4116
  read: (form) => ({
3702
4117
  fields: form.list(),
3703
4118
  status: form.getStatus(),
3704
4119
  formKind: form.getFormKind(),
3705
4120
  selectedField: form.getSelectedField(),
3706
- focusedField: form.getFocusedField()
4121
+ focusedField: form.getFocusedField(),
4122
+ selectedFields: form.listSelectedFields(),
4123
+ groups: form.listGroups(),
4124
+ designGroup: form.getDesignGroup()
3707
4125
  }),
3708
4126
  empty: {
3709
4127
  fields: NO_FIELDS,
3710
4128
  status: "idle",
3711
4129
  formKind: "none",
3712
4130
  selectedField: null,
3713
- focusedField: null
4131
+ focusedField: null,
4132
+ selectedFields: NO_FIELDS,
4133
+ groups: NO_GROUPS,
4134
+ designGroup: null
3714
4135
  }
3715
4136
  });
3716
4137
  //#endregion