@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.js CHANGED
@@ -1,4 +1,4 @@
1
- import { i as FormToken, n as FormTransfer, r as toFieldRef, t as FORM_DEFAULTS } from "./contract-Bu3RA2jA.js";
1
+ import { i as FormToken, n as FormTransfer, r as toFieldRef, t as FORM_DEFAULTS } from "./contract-J_QN_Igp.js";
2
2
  import { n as createFormScriptingController, r as scriptError, t as FormScriptingController } from "./controller-BbC8XWpY.js";
3
3
  import { FormToken as FormToken$1 } from "./contract/host.js";
4
4
  import { PluginError, composeApi, definePlugin, defineState, memo, memoByKey, reload, toPluginError, toPluginErrorInfo } from "@embedpdf/core";
@@ -7,11 +7,11 @@ import { AnnotationToken } from "@embedpdf/plugin-annotation/contract";
7
7
  import { FontsToken } from "@embedpdf/plugin-fonts/contract";
8
8
  import { InteractionToken, samplePointOn } from "@embedpdf/plugin-interaction/contract/host";
9
9
  import { RenderToken } from "@embedpdf/plugin-render/contract";
10
+ import { StageToken } from "@embedpdf/plugin-stage/contract";
10
11
  import { annotationKey, draftWritesScripts, fieldAfterReset, fieldAfterValue, fieldValueOf, fieldValueWriteOf, formEffectOps, formFieldAfter, formFieldOfDraft, isStandardFontName, pageRefsEqual, planFormCopies, reorderPart, reorderedList, serializeError, tabOrderOf, toFieldRef as toFieldRef$1, widgetAfterPatch, widgetFlagsOf, widgetPlacementOf, widgetsAfterDisplay, writesScripts } from "@embedpdf/engine-core/runtime";
11
12
  import { ActionsToken as ActionsToken$1 } from "@embedpdf/plugin-actions/contract/host";
12
13
  import { AnnotationToken as AnnotationToken$1 } from "@embedpdf/plugin-annotation/contract/host";
13
- import { gesturePlacement, refOf, widgetAppearanceOf } from "@embedpdf/core-annotation";
14
- import { StageToken } from "@embedpdf/plugin-stage/contract";
14
+ import { gesturePlacement, placedBoxFields, refOf, standingRect, widgetAppearanceOf } from "@embedpdf/core-annotation";
15
15
  import { paints, textEditorLayout, widgetDrawing, widgetScene, widgetText } from "@embedpdf/core-form";
16
16
  import { standardFontCss, standardFontOf } from "@embedpdf/core-fonts";
17
17
  import { RenderToken as RenderToken$1 } from "@embedpdf/plugin-render/contract/host";
@@ -32,6 +32,7 @@ const FORM_TOOLS = [
32
32
  width: 160,
33
33
  height: 24
34
34
  },
35
+ upright: true,
35
36
  defaults: {
36
37
  ...FIELD_CHROME,
37
38
  fontSize: 12
@@ -46,6 +47,7 @@ const FORM_TOOLS = [
46
47
  width: 18,
47
48
  height: 18
48
49
  },
50
+ upright: true,
49
51
  defaults: FIELD_CHROME,
50
52
  cursor: "crosshair"
51
53
  },
@@ -57,6 +59,7 @@ const FORM_TOOLS = [
57
59
  width: 18,
58
60
  height: 18
59
61
  },
62
+ upright: true,
60
63
  defaults: FIELD_CHROME,
61
64
  cursor: "crosshair"
62
65
  },
@@ -68,6 +71,7 @@ const FORM_TOOLS = [
68
71
  width: 140,
69
72
  height: 24
70
73
  },
74
+ upright: true,
71
75
  defaults: {
72
76
  ...FIELD_CHROME,
73
77
  fontSize: 12
@@ -82,6 +86,7 @@ const FORM_TOOLS = [
82
86
  width: 140,
83
87
  height: 72
84
88
  },
89
+ upright: true,
85
90
  defaults: {
86
91
  ...FIELD_CHROME,
87
92
  fontSize: 12
@@ -96,6 +101,7 @@ const FORM_TOOLS = [
96
101
  width: 100,
97
102
  height: 28
98
103
  },
104
+ upright: true,
99
105
  defaults: {
100
106
  ...FIELD_CHROME,
101
107
  interiorColor: "#e5e7eb",
@@ -111,6 +117,7 @@ const FORM_TOOLS = [
111
117
  width: 160,
112
118
  height: 48
113
119
  },
120
+ upright: true,
114
121
  defaults: FIELD_CHROME,
115
122
  cursor: "crosshair"
116
123
  }
@@ -137,12 +144,37 @@ function clampToPage(box, page) {
137
144
  return clamped.width < 1 || clamped.height < 1 ? null : clamped;
138
145
  }
139
146
  /**
147
+ * A placed field's frame and turn, as its widget's placement states them
148
+ * (`placedBoxFields`), kept on the page: the rect the turned frame stands in
149
+ * is cut to the page (`clampToPage`), and the frame follows it. `null` when
150
+ * too little of it is on the page.
151
+ */
152
+ function placedOnPage(placement, page) {
153
+ const { box, rotation } = placedBoxFields(placement);
154
+ const turn = rotation ?? 0;
155
+ const stands = clampToPage(standingRect(box, turn), page);
156
+ if (!stands) return null;
157
+ return {
158
+ box: standingRect(stands, turn),
159
+ ...turn ? { rotation: turn } : {}
160
+ };
161
+ }
162
+ /**
140
163
  * The field a palette tool places: one widget at `widget`, named like
141
- * `text_1`. A radio button stands for `'Choice1'` and a dropdown or a list
142
- * starts with two options, as in Acrobat; rename and change them in a
143
- * settings panel.
164
+ * `text_1`, in `groupId` when the palette places for a group (the form's
165
+ * design group); without one it is in no group. A
166
+ * radio button stands for `'Choice1'` and a dropdown or a list starts with
167
+ * two options, as in Acrobat; rename and change them in a settings panel.
144
168
  */
145
- function toolDraft(tool, name, widget) {
169
+ function toolDraft(tool, name, widget, groupId = null) {
170
+ const draft = kindDraft(tool, name, widget);
171
+ return groupId === null ? draft : {
172
+ ...draft,
173
+ groupId
174
+ };
175
+ }
176
+ /** {@link toolDraft}'s field, as the tool's kind starts one. */
177
+ function kindDraft(tool, name, widget) {
146
178
  switch (tool.fieldKind) {
147
179
  case "radio": return {
148
180
  kind: "radio",
@@ -190,6 +222,12 @@ function toolDraft(tool, name, widget) {
190
222
  * every tool: select the new widget, and keep the tool or go back to the
191
223
  * default one.
192
224
  *
225
+ * An upright tool places the field as the author sees the page: the press's
226
+ * display rotation goes to `gesturePlacement`, and the widget takes the
227
+ * placed frame and its turn (`placedOnPage`), so on a page shown turned the
228
+ * field reads upright. The ghost and the drag's preview make the same call
229
+ * with the same turn.
230
+ *
193
231
  * With the annotation plugin, the tool's ghost shows the field a click
194
232
  * places: this handler's hover puts it where the click would reach it (no
195
233
  * widget or annotation under the pointer claims it) and the user may design
@@ -202,23 +240,25 @@ function toolDraft(tool, name, widget) {
202
240
  */
203
241
  function createPlaceHandler(form, interaction, annotation) {
204
242
  let origin = null;
243
+ /** Whether the tool places upright: the annotation plugin's tool says, else the tool table. */
244
+ const uprightOf = (tool) => annotation?.getResolvedTool(tool.id)?.upright ?? tool.upright;
205
245
  /** Drop the gesture and what it painted: its placement and the tool's ghost. */
206
246
  const endGesture = () => {
207
247
  origin = null;
208
248
  annotation?.clearPlacementPreview();
209
249
  annotation?.clearGhost();
210
250
  };
211
- const place = async (tool, page, box) => {
251
+ const place = async (tool, page, placement) => {
212
252
  const pageBox = form.getPageBox(page);
213
- const rect = pageBox ? clampToPage(box, pageBox) : null;
214
- if (!rect) return;
253
+ const placed = pageBox ? placedOnPage(placement, pageBox) : null;
254
+ if (!placed) return;
215
255
  const look = widgetAppearanceOf(annotation ? annotation.tools.getDefaults(tool.id) : tool.defaults);
216
256
  const name = nextFieldName(tool.fieldKind, new Set(form.list().map((field) => field.name)));
217
257
  const created = form.create(toolDraft(tool, name, {
218
258
  page,
219
- rect,
259
+ ...placed,
220
260
  ...look
221
- }));
261
+ }, form.getDesignGroup()));
222
262
  const field = form.get({
223
263
  kind: "fqn",
224
264
  name
@@ -246,7 +286,8 @@ function createPlaceHandler(form, interaction, annotation) {
246
286
  origin = {
247
287
  page: sample.page.ref,
248
288
  start: sample.page.point,
249
- last: sample.page.point
289
+ last: sample.page.point,
290
+ displayRotation: sample.page.rotation
250
291
  };
251
292
  return true;
252
293
  },
@@ -255,7 +296,7 @@ function createPlaceHandler(form, interaction, annotation) {
255
296
  const point = samplePointOn(sample, origin.page);
256
297
  if (!point) return;
257
298
  origin.last = point;
258
- annotation?.previewPlacement(interaction.getActiveToolId(), origin.page, origin.start, point);
299
+ annotation?.previewPlacement(interaction.getActiveToolId(), origin.page, origin.start, point, origin.displayRotation);
259
300
  },
260
301
  onPointerUp: (sample) => {
261
302
  if (!origin) return;
@@ -264,9 +305,13 @@ function createPlaceHandler(form, interaction, annotation) {
264
305
  const tool = FORM_TOOL_BY_ID.get(interaction.getActiveToolId());
265
306
  if (!tool) return;
266
307
  const end = samplePointOn(sample, gesture.page) ?? gesture.last;
267
- const placement = gesturePlacement("box", gesture.start, end, tool.clickCreate, { pageBox: form.getPageBox(gesture.page) ?? void 0 });
308
+ const placement = gesturePlacement("box", gesture.start, end, tool.clickCreate, {
309
+ pageBox: form.getPageBox(gesture.page) ?? void 0,
310
+ upright: uprightOf(tool),
311
+ displayRotation: gesture.displayRotation
312
+ });
268
313
  if (placement?.kind !== "box") return;
269
- place(tool, gesture.page, placement.rect).catch((error) => {
314
+ place(tool, gesture.page, placement).catch((error) => {
270
315
  globalThis.console?.error("[form] placing the field failed:", error);
271
316
  });
272
317
  },
@@ -301,6 +346,7 @@ function connectForm(ctx, form, lender) {
301
346
  cursor: tool.cursor,
302
347
  enables: [...PLACE_TAGS],
303
348
  clickCreate: tool.clickCreate,
349
+ upright: tool.upright,
304
350
  defaults: tool.defaults,
305
351
  ghost: true
306
352
  }) : interaction.registerTool({
@@ -582,8 +628,22 @@ function fieldsWithChangedValues(previous, next) {
582
628
  });
583
629
  }
584
630
  const valueEntryOf = (field) => "valueEntry" in field ? field.valueEntry : null;
585
- /** Whether a widget shows on screen: its `hidden` and `noView` flags hide it. */
586
- const shownOnScreen = (row) => !row.hidden && !row.noView;
631
+ /** A widget row's place: its frame (its rect, for a row without one), its turn and its rect. */
632
+ const placeOf = (row) => ({
633
+ box: row.box ?? row.rect,
634
+ rotation: row.box ? row.rotation ?? 0 : 0,
635
+ rect: row.rect
636
+ });
637
+ /**
638
+ * Whether a widget's box has an area. One of no size is how a PDF keeps a field that shows
639
+ * nowhere: the field of a document timestamp, an invisible signature.
640
+ */
641
+ const hasArea = (row) => row.rect.width > 0 && row.rect.height > 0;
642
+ /**
643
+ * Whether a widget shows on screen: its `hidden` and `noView` flags hide it, and a box of no
644
+ * size has nothing to show. What doesn't show gets no control, and Tab doesn't stop at it.
645
+ */
646
+ const shownOnScreen = (row) => !row.hidden && !row.noView && hasArea(row);
587
647
  /** The widgets one page shows, from the form's widget rows. */
588
648
  function pageWidgetsOf(index, pageObjectNumber) {
589
649
  const widgets = {};
@@ -591,7 +651,8 @@ function pageWidgetsOf(index, pageObjectNumber) {
591
651
  if (row.page.objectNumber !== pageObjectNumber || row.ref.kind !== "objectNumber") continue;
592
652
  if (!shownOnScreen(row)) continue;
593
653
  widgets[row.ref.objectNumber] = {
594
- box: row.rect,
654
+ ref: row.ref,
655
+ ...placeOf(row),
595
656
  look: {
596
657
  border: row.color ?? null,
597
658
  borderWidth: row.strokeWidth ?? 1,
@@ -617,7 +678,7 @@ function shownWidgetsOf(index, pageObjectNumber, lookOf = () => AT_REST) {
617
678
  if (row.page.objectNumber !== pageObjectNumber || !shownOnScreen(row)) continue;
618
679
  shown.push({
619
680
  ref: row.ref,
620
- rect: row.rect,
681
+ ...placeOf(row),
621
682
  appearanceState: row.appearanceState,
622
683
  ...lookOf(row)
623
684
  });
@@ -629,24 +690,48 @@ function widgetRowOf(index, annotObjectNumber) {
629
690
  return position === void 0 ? null : index.snapshot?.widgets[position] ?? null;
630
691
  }
631
692
  const boxContains = (box, point) => point.x >= box.x && point.x <= box.x + box.width && point.y >= box.y && point.y <= box.y + box.height;
632
- /** The widget under a page-space point; nested widgets resolve to the smallest box. */
693
+ /** The widget under a page-space point; nested widgets resolve to the smallest one. */
633
694
  function widgetAt(index, widgets, point) {
634
695
  if (!widgets) return null;
635
696
  let best = null;
636
- for (const [key, { box }] of Object.entries(widgets)) {
637
- if (!boxContains(box, point)) continue;
697
+ for (const [key, { box, rotation, rect }] of Object.entries(widgets)) {
698
+ if (!boxContains(rect, point)) continue;
638
699
  const annotObjectNumber = Number(key);
639
700
  const field = fieldForWidget(index, annotObjectNumber);
640
701
  if (!field) continue;
641
- if (!best || box.width * box.height < best.box.width * best.box.height) best = {
702
+ if (!best || rect.width * rect.height < best.rect.width * best.rect.height) best = {
642
703
  annotObjectNumber,
643
704
  field,
644
- box
705
+ box,
706
+ rotation,
707
+ rect
645
708
  };
646
709
  }
647
710
  return best;
648
711
  }
649
- const initialFormModel = () => ({ focused: null });
712
+ const NO_NAMED_GROUPS = Object.freeze([]);
713
+ const initialFormModel = () => ({
714
+ focused: null,
715
+ designGroup: null,
716
+ groups: NO_NAMED_GROUPS
717
+ });
718
+ /** Name this document's groups: the whole list. The same list again changes nothing. */
719
+ function setGroups(state, groups) {
720
+ return groups.length === state.groups.length && groups.every((group, at) => {
721
+ const held = state.groups[at];
722
+ return group.id === held.id && group.label === held.label && group.color === held.color;
723
+ }) ? state : {
724
+ ...state,
725
+ groups
726
+ };
727
+ }
728
+ /** Name the group that fields placed with a tool go in; the same group changes nothing. */
729
+ function setDesignGroup(state, groupId) {
730
+ return state.designGroup === groupId ? state : {
731
+ ...state,
732
+ designGroup: groupId
733
+ };
734
+ }
650
735
  //#endregion
651
736
  //#region src/read/fields.ts
652
737
  /**
@@ -655,6 +740,7 @@ const initialFormModel = () => ({ focused: null });
655
740
  * required-field check.
656
741
  */
657
742
  const NO_FIELDS$1 = Object.freeze([]);
743
+ const NO_SELECTED_FIELDS = Object.freeze([]);
658
744
  const NOTHING_SELECTED = Object.freeze([]);
659
745
  /** A widget address as the annotation object number the field index is keyed by. */
660
746
  const widgetObjectOf = (widget) => "kind" in widget ? widget.kind === "objectNumber" ? widget.objectNumber : 0 : widget.objectNumber;
@@ -768,6 +854,16 @@ function createFieldReads(ctx, { fields, rights, siblings }) {
768
854
  }
769
855
  return found;
770
856
  });
857
+ /** Every field with a selected widget, in the selection's order, each once. */
858
+ const listSelectedFields = memo(() => [fields.view(), siblings.annotation()?.selection.getSelected() ?? NOTHING_SELECTED], (index, selected) => {
859
+ const found = /* @__PURE__ */ new Map();
860
+ for (const annotation of selected) {
861
+ if (!annotation.subtype.startsWith("widget")) continue;
862
+ const field = fieldForWidget(index, widgetObjectOf(annotation.ref));
863
+ if (field && !found.has(fieldKeyOf(field))) found.set(fieldKeyOf(field), field);
864
+ }
865
+ return found.size === 0 ? NO_SELECTED_FIELDS : Object.freeze([...found.values()]);
866
+ });
771
867
  return { api: {
772
868
  getSnapshot: () => fields.view().snapshot,
773
869
  getStatus: fields.getStatus,
@@ -780,6 +876,7 @@ function createFieldReads(ctx, { fields, rights, siblings }) {
780
876
  list,
781
877
  getValue: (ref) => valueByKey(canonicalKey(fields.view(), ref)),
782
878
  getSelectedField,
879
+ listSelectedFields,
783
880
  validate,
784
881
  exportValues
785
882
  } };
@@ -789,7 +886,9 @@ function createFieldReads(ctx, { fields, rights, siblings }) {
789
886
  /**
790
887
  * A field's settings, described for a settings panel the way an annotation
791
888
  * kind describes its look: which settings the field's kind has, how each is
792
- * edited, and its value. `update()` writes them.
889
+ * edited, and its value. `update()` writes them. While the document has
890
+ * groups, a field's group is one of them: the choices are the groups the
891
+ * user may put a field in, and the one the field is in.
793
892
  */
794
893
  /** What every field has. */
795
894
  const COMMON = [
@@ -914,6 +1013,21 @@ function familySettings(field) {
914
1013
  default: return [];
915
1014
  }
916
1015
  }
1016
+ /**
1017
+ * Who fills the field in, among the document's groups: the ones the user may put a field in,
1018
+ * and the field's own. Nothing while the document has no groups.
1019
+ */
1020
+ function groupSetting(field, groups, maySet) {
1021
+ if (groups.length === 0) return [];
1022
+ return [{
1023
+ key: "groupId",
1024
+ control: "choice",
1025
+ label: "Filled in by",
1026
+ labelKey: "form.settings.group",
1027
+ options: groups.filter((group) => group.id === field.groupId || maySet(group.id)).map((group) => group.id),
1028
+ free: false
1029
+ }];
1030
+ }
917
1031
  /** Each setting's value, as the field holds it. */
918
1032
  function valuesOf(field, settings) {
919
1033
  const held = field;
@@ -923,10 +1037,14 @@ function valuesOf(field, settings) {
923
1037
  else values[key] = held[key] ?? null;
924
1038
  return values;
925
1039
  }
926
- function createFieldSettings({ fields }) {
927
- const settingsByKey = memoByKey((key) => [fieldByKey(fields.view(), key)], (_key, field) => {
1040
+ function createFieldSettings({ fields, groups }) {
1041
+ const settingsByKey = memoByKey((key) => [fieldByKey(fields.view(), key), groups.list()], (_key, field, listed) => {
928
1042
  if (!field) return null;
929
- const properties = [...COMMON, ...familySettings(field)];
1043
+ const properties = [
1044
+ ...COMMON,
1045
+ ...groupSetting(field, listed, groups.maySet),
1046
+ ...familySettings(field)
1047
+ ];
930
1048
  return {
931
1049
  properties,
932
1050
  values: valuesOf(field, properties)
@@ -936,21 +1054,43 @@ function createFieldSettings({ fields }) {
936
1054
  }
937
1055
  //#endregion
938
1056
  //#region src/read/fill-items.ts
1057
+ /** A radio button's accessible name: its group's, then the option it stands for. */
1058
+ const radioLabel = (group, option) => option === "" ? group : `${group}: ${option}`;
1059
+ /** A box's accessible name, then whose field it is, when the app says who the group is. */
1060
+ const ownedLabel = (name, owner) => owner === null ? name : `${name}, ${owner}`;
939
1061
  /**
940
- * Project one widget of a field into a fill control; `fillable`: the user may
941
- * fill the field in (a signature field: sign it). Null for kinds with no
942
- * fill control.
1062
+ * Whether the field still takes a value: it holds one (a push button doesn't), it isn't
1063
+ * read-only, nor a signed signature.
943
1064
  */
944
- function projectWidget(field, annotObjectNumber, widget, fillable) {
1065
+ const takesValue = (field) => field.kind !== "pushbutton" && !field.readOnly && !(field.kind === "signature" && field.valueEntry.kind !== "none");
1066
+ /**
1067
+ * Project one widget of a field into a fill control. `fillable`: people fill
1068
+ * the field in by hand (a signature field: sign it), which the box is
1069
+ * `disabled` without; `canFill`: the session's permission alone, which the
1070
+ * `fillable` setting doesn't change; `inGroup`: where a radio button comes
1071
+ * among its group's; `group`: how the field's group shows, `null` for a field
1072
+ * in none. Null for kinds with no fill control.
1073
+ */
1074
+ function projectWidget(field, annotObjectNumber, widget, fillable, canFill, inGroup = null, group = null) {
1075
+ const key = fieldKeyOf(field);
1076
+ const owner = group?.label ?? null;
945
1077
  const base = {
946
- key: fieldKeyOf(field),
1078
+ key,
947
1079
  fieldRef: field.ref,
948
1080
  annotObjectNumber,
949
1081
  annotationRef: field.widgets.find((candidate) => candidate.objectNumber === annotObjectNumber)?.ref ?? null,
1082
+ ref: widget.ref,
1083
+ groupId: field.groupId,
1084
+ canFill,
1085
+ required: field.required,
1086
+ empty: isEmpty(field),
1087
+ accent: canFill && takesValue(field) ? group?.accent ?? null : null,
950
1088
  box: widget.box,
1089
+ rotation: widget.rotation,
1090
+ rect: widget.rect,
951
1091
  look: widget.look,
952
1092
  disabled: field.readOnly || !fillable,
953
- label: field.alternateName ?? field.name
1093
+ label: ownedLabel(field.alternateName ?? field.name, owner)
954
1094
  };
955
1095
  switch (field.kind) {
956
1096
  case "text": return {
@@ -974,12 +1114,15 @@ function projectWidget(field, annotObjectNumber, widget, fillable) {
974
1114
  }
975
1115
  case "radio": {
976
1116
  const toggle = field.widgets.find((candidate) => candidate.objectNumber === annotObjectNumber);
1117
+ const exportValue = toggle && "exportValue" in toggle ? toggle.exportValue : "";
977
1118
  return {
978
1119
  ...base,
1120
+ label: ownedLabel(radioLabel(field.alternateName ?? field.name, exportValue), owner),
979
1121
  control: "toggle",
980
1122
  kind: "radio",
981
1123
  checked: toggle && "checked" in toggle ? toggle.checked : false,
982
- exportValue: toggle && "exportValue" in toggle ? toggle.exportValue : ""
1124
+ exportValue,
1125
+ inGroup
983
1126
  };
984
1127
  }
985
1128
  case "combobox": return {
@@ -1013,19 +1156,22 @@ function projectWidget(field, annotObjectNumber, widget, fillable) {
1013
1156
  }
1014
1157
  }
1015
1158
  /**
1016
- * Project one page's widgets into fill controls, each disabled when the user
1017
- * may not fill its field in, or sign it (`mayFill`). Widgets whose page has not loaded (or
1018
- * that are direct objects with no join key) are skipped; the projection runs
1019
- * again when the page's widgets land.
1159
+ * Project one page's widgets into fill controls, each disabled when people
1160
+ * don't fill its field in by hand (`mayFillByHand`), each saying whether the
1161
+ * session may fill it in, or sign it (`mayFill`, its permissions alone), and
1162
+ * each radio button with where it comes in its group (`groupPositionOf`),
1163
+ * and each with how its field's group shows (`groupLookOf`).
1164
+ * Widgets whose page has not loaded (or that are direct objects with no join
1165
+ * key) are skipped; the projection runs again when the page's widgets land.
1020
1166
  */
1021
- function fillItems(index, pageObjectNumber, widgets, mayFill) {
1167
+ function fillItems(index, pageObjectNumber, widgets, mayFillByHand, mayFill, groupPositionOf = () => null, groupLookOf = () => null) {
1022
1168
  if (!index.snapshot || !widgets) return [];
1023
1169
  const items = [];
1024
1170
  for (const field of index.snapshot.fields) for (const widget of field.widgets) {
1025
1171
  if (widget.page?.objectNumber !== pageObjectNumber) continue;
1026
1172
  const placed = widgets[widget.objectNumber];
1027
1173
  if (!placed) continue;
1028
- const item = projectWidget(field, widget.objectNumber, placed, mayFill(field));
1174
+ const item = projectWidget(field, widget.objectNumber, placed, mayFillByHand(field), mayFill(field), groupPositionOf(widget.objectNumber), field.groupId === null ? null : groupLookOf(field.groupId));
1029
1175
  if (item) items.push(item);
1030
1176
  }
1031
1177
  return items;
@@ -1040,7 +1186,7 @@ function fillItems(index, pageObjectNumber, widgets, mayFill) {
1040
1186
  */
1041
1187
  const NO_WIDGETS = Object.freeze([]);
1042
1188
  const NOTHING_SHOWN$1 = Object.freeze([]);
1043
- function createWidgetReads(ctx, { fields, rights, looks, pictures }) {
1189
+ function createWidgetReads(ctx, { fields, rights, looks, pictures, design, siblings, cursor, tabOrder, groups }) {
1044
1190
  /** Every page's widgets come with the form: one read for the document. */
1045
1191
  const loadWidgets = (_page) => fields.settled();
1046
1192
  const widgetsOn = memoByKey((pageObjectNumber) => [fields.view()], (pageObjectNumber, index) => pageWidgetsOf(index, pageObjectNumber));
@@ -1054,8 +1200,11 @@ function createWidgetReads(ctx, { fields, rights, looks, pictures }) {
1054
1200
  fields.view(),
1055
1201
  widgetsOn(pageObjectNumber),
1056
1202
  rights.key(),
1057
- ctx.settings().get().fillable
1058
- ], (pageObjectNumber, index, widgets) => fillItems(index, pageObjectNumber, widgets, rights.mayFillByHand));
1203
+ ctx.settings().get().fillable,
1204
+ tabOrder.rows(),
1205
+ groups.list(),
1206
+ ctx.settings().get().fields.tint
1207
+ ], (pageObjectNumber, index, widgets) => fillItems(index, pageObjectNumber, widgets, rights.mayFillByHand, rights.mayFillOrSign, tabOrder.groupPositionOf, groups.lookOf));
1059
1208
  /** The page's content box (`{0, 0, width, height}`), for page-bound placement. */
1060
1209
  const getPageBox = (page) => {
1061
1210
  const size = ctx.getPage(page)?.size;
@@ -1066,6 +1215,19 @@ function createWidgetReads(ctx, { fields, rights, looks, pictures }) {
1066
1215
  height: size.height
1067
1216
  } : null;
1068
1217
  };
1218
+ const anchors = /* @__PURE__ */ new WeakMap();
1219
+ const getWidgetAnchor = (widget) => {
1220
+ const row = widgetRowOf(fields.view(), widgetObjectOf(widget));
1221
+ if (!row) return null;
1222
+ if (design.lending()) return siblings.annotation()?.getAnnotationAnchor(row.ref) ?? null;
1223
+ if (!shownOnScreen(row)) return null;
1224
+ let anchor = anchors.get(row);
1225
+ if (!anchor) anchors.set(row, anchor = {
1226
+ page: row.page,
1227
+ bounds: row.rect
1228
+ });
1229
+ return anchor;
1230
+ };
1069
1231
  return {
1070
1232
  getPageBox,
1071
1233
  api: {
@@ -1084,7 +1246,9 @@ function createWidgetReads(ctx, { fields, rights, looks, pictures }) {
1084
1246
  getWidgetFontCss: looks.getWidgetFontCss,
1085
1247
  ensureLoaded: loadWidgets,
1086
1248
  getWidgetAt,
1087
- getPageBox
1249
+ getPageBox,
1250
+ getWidgetAnchor,
1251
+ isWidgetFocused: (widget) => cursor.focused()?.widget === widgetObjectOf(widget)
1088
1252
  }
1089
1253
  };
1090
1254
  }
@@ -1507,6 +1671,10 @@ function createFieldsMirror(ctx, events) {
1507
1671
  //#region src/services/cursor.ts
1508
1672
  /** How long a box asked for keeps its claim on the cursor while its page comes in. */
1509
1673
  const PENDING_MS = 2e3;
1674
+ /** Whether a control takes the cursor: every one that doesn't say it takes none. */
1675
+ const takes = (target) => target.takesCursor?.() ?? true;
1676
+ /** Put the cursor in a control. `false` when it takes none: it says so, or nothing in it took it. */
1677
+ const enter = (target, select) => takes(target) && target.focus({ select }) !== false;
1510
1678
  function createCursor(ctx, fields, events) {
1511
1679
  const targets = /* @__PURE__ */ new Map();
1512
1680
  let pending = null;
@@ -1528,8 +1696,29 @@ function createCursor(ctx, fields, events) {
1528
1696
  };
1529
1697
  const clearPending = () => {
1530
1698
  pending?.expire();
1699
+ pending?.settle?.();
1531
1700
  pending = null;
1532
1701
  };
1702
+ /**
1703
+ * A box asked for came in holding nothing to focus. It is given the turn to draw what does (a
1704
+ * control of an app's own may render after its box), and if nothing in it takes the cursor
1705
+ * then, the cursor goes on.
1706
+ */
1707
+ const settleLater = (waiting) => {
1708
+ waiting.settle ?? (waiting.settle = ctx.clock.after(0, () => {
1709
+ waiting.settle = null;
1710
+ if (pending !== waiting) return;
1711
+ const now = targets.get(waiting.widget);
1712
+ if (!now) return;
1713
+ clearPending();
1714
+ if (!enter(now, waiting.select)) waiting.onward?.();
1715
+ }));
1716
+ };
1717
+ /** The box asked for has come in: its control takes the cursor, or gets its turn to. */
1718
+ const arrive = (waiting, target) => {
1719
+ if (!enter(target, waiting.select)) settleLater(waiting);
1720
+ else if (pending === waiting) clearPending();
1721
+ };
1533
1722
  return {
1534
1723
  focused: () => ctx.state.get().focused,
1535
1724
  last: () => last,
@@ -1553,34 +1742,34 @@ function createCursor(ctx, fields, events) {
1553
1742
  });
1554
1743
  }
1555
1744
  },
1556
- goTo(row, select) {
1745
+ goTo(row, select, onward) {
1557
1746
  const widget = widgetObjectOf(row.ref);
1747
+ const shown = targets.get(widget);
1748
+ if (shown && !takes(shown)) return "declined";
1558
1749
  const stage = ctx.tryGet(StageToken);
1559
1750
  stage?.reveal(row.page, { rect: row.rect });
1560
1751
  clearPending();
1561
1752
  const target = targets.get(widget);
1562
- if (target) {
1563
- target.focus({ select });
1564
- return true;
1565
- }
1566
- if (!stage) return false;
1567
- pending = {
1753
+ if (target && enter(target, select)) return "taken";
1754
+ if (target && target === shown) return "declined";
1755
+ if (!stage) return "unreachable";
1756
+ const waiting = {
1568
1757
  widget,
1569
1758
  select,
1759
+ onward: onward ?? null,
1570
1760
  expire: ctx.clock.after(PENDING_MS, () => {
1571
- if (pending?.widget === widget) pending = null;
1572
- })
1761
+ if (pending === waiting) clearPending();
1762
+ }),
1763
+ settle: null
1573
1764
  };
1574
- return true;
1765
+ pending = waiting;
1766
+ if (target) settleLater(waiting);
1767
+ return "taken";
1575
1768
  },
1576
1769
  attach(widgetRef, target) {
1577
1770
  const widget = widgetObjectOf(widgetRef);
1578
1771
  targets.set(widget, target);
1579
- if (pending?.widget === widget) {
1580
- const { select } = pending;
1581
- clearPending();
1582
- target.focus({ select });
1583
- }
1772
+ if (pending?.widget === widget) arrive(pending, target);
1584
1773
  return () => {
1585
1774
  if (targets.get(widget) === target) targets.delete(widget);
1586
1775
  };
@@ -1602,15 +1791,21 @@ function createDesign(ctx, siblings) {
1602
1791
  //#endregion
1603
1792
  //#region src/services/events.ts
1604
1793
  function createEvents(ctx) {
1605
- return {
1794
+ const events = {
1606
1795
  valueChanged: ctx.events.source(),
1607
1796
  fieldCreated: ctx.events.source(),
1608
1797
  fieldUpdated: ctx.events.source(),
1609
1798
  fieldDeleted: ctx.events.source(),
1610
1799
  validationRejected: ctx.events.source(),
1611
1800
  resynced: ctx.events.source(),
1612
- focusChanged: ctx.events.source()
1801
+ focusChanged: ctx.events.source(),
1802
+ designGroupChanged: ctx.events.source(),
1803
+ groupsChanged: ctx.events.source()
1613
1804
  };
1805
+ ctx.state.onChange(({ previous, next }) => {
1806
+ if (previous.designGroup !== next.designGroup) events.designGroupChanged.emit({ groupId: next.designGroup });
1807
+ });
1808
+ return events;
1614
1809
  }
1615
1810
  //#endregion
1616
1811
  //#region src/services/fill-rights.ts
@@ -1625,12 +1820,14 @@ const isFillableByHand = (fillable, kind) => typeof fillable === "boolean" ? fil
1625
1820
  function createFillRights(ctx, fields) {
1626
1821
  const mayFill = (field) => ctx.allowsField("fill", field);
1627
1822
  const maySign = (field) => ctx.allowsField("sign", field);
1628
- const mayFillByHand = (field) => isFillableByHand(ctx.settings().get().fillable, field.kind) && (field.kind === "signature" ? maySign(field) : mayFill(field));
1823
+ const mayFillOrSign = (field) => field.kind === "signature" ? maySign(field) : mayFill(field);
1824
+ const mayFillByHand = (field) => isFillableByHand(ctx.settings().get().fillable, field.kind) && mayFillOrSign(field);
1629
1825
  /** The form's groups, `null` (no group) among them. */
1630
1826
  const groups = memo(() => [fields.view()], (index) => [...new Set((index.snapshot?.fields ?? []).map((field) => field.groupId))]);
1631
1827
  return {
1632
1828
  mayFill,
1633
1829
  maySign,
1830
+ mayFillOrSign,
1634
1831
  mayFillByHand,
1635
1832
  takesInput: (field) => !field.readOnly && mayFillByHand(field),
1636
1833
  assertMayFill: (field, operation) => ctx.assertAllowedField("fill", field, operation),
@@ -1670,6 +1867,76 @@ function createFormattedTexts(ctx, fields) {
1670
1867
  };
1671
1868
  }
1672
1869
  //#endregion
1870
+ //#region src/services/groups.ts
1871
+ /**
1872
+ * The form's groups as people see them. A field's group is an id in the PDF
1873
+ * (`groupId`); who the group is and the color its fields show in are the
1874
+ * app's, told to this document with `setGroups()`, and never written into the
1875
+ * PDF. Every group shows in a color: its own when the app gives one, else one
1876
+ * of eight by its place in the list, so no two of the first eight share one.
1877
+ * How strongly it shows is the `fields.tint` setting; at `0` no field shows
1878
+ * its group at all.
1879
+ */
1880
+ /**
1881
+ * The colors of the groups the app gives none: the first group in the list
1882
+ * gets the first, and the ninth the first again.
1883
+ */
1884
+ const GROUP_COLORS = Object.freeze([
1885
+ "#ea580c",
1886
+ "#16a34a",
1887
+ "#9333ea",
1888
+ "#2563eb",
1889
+ "#db2777",
1890
+ "#0d9488",
1891
+ "#ca8a04",
1892
+ "#65a30d"
1893
+ ]);
1894
+ const MODIFY$1 = "doc.forms.modify";
1895
+ const NO_LOOKS = /* @__PURE__ */ new Map();
1896
+ function createGroups(ctx, fields, events) {
1897
+ /** The ids of the groups the form's fields are in, in the fields' order, as one key. */
1898
+ const used = () => {
1899
+ const ids = /* @__PURE__ */ new Set();
1900
+ for (const field of fields.view().snapshot?.fields ?? []) if (field.groupId !== null) ids.add(field.groupId);
1901
+ return JSON.stringify([...ids]);
1902
+ };
1903
+ const list = memo(() => [ctx.state.get().groups, used()], (named, ids) => {
1904
+ const known = new Set(named.map((group) => group.id));
1905
+ const others = JSON.parse(ids).filter((id) => !known.has(id)).map((id) => ({
1906
+ id,
1907
+ label: null,
1908
+ color: null
1909
+ }));
1910
+ return Object.freeze([...named, ...others].map((group, place) => Object.freeze({
1911
+ id: group.id,
1912
+ label: group.label,
1913
+ color: group.color ?? GROUP_COLORS[place % GROUP_COLORS.length]
1914
+ })));
1915
+ });
1916
+ const looks = memo(() => [list(), ctx.settings().get().fields.tint], (groups, strength) => groups.length === 0 ? NO_LOOKS : new Map(groups.map((group) => [group.id, Object.freeze({
1917
+ label: group.label,
1918
+ accent: strength > 0 ? Object.freeze({
1919
+ color: group.color,
1920
+ strength
1921
+ }) : null
1922
+ })])));
1923
+ ctx.state.onChange(({ previous, next }) => {
1924
+ if (previous.groups !== next.groups) events.groupsChanged.emit({ groups: list() });
1925
+ });
1926
+ const maySetGroup = (groupId) => ctx.doc.security.allowsField("set-group", { groupId });
1927
+ return {
1928
+ list,
1929
+ lookOf: (groupId) => groupId === null ? null : looks().get(groupId) ?? null,
1930
+ maySet: (groupId) => ctx.allows(MODIFY$1) && maySetGroup(groupId),
1931
+ assertMaySet: (groupId, operation) => {
1932
+ ctx.assertAllowed(MODIFY$1, operation);
1933
+ if (maySetGroup(groupId)) return;
1934
+ const permission = `fields:set-group:group=${groupId}`;
1935
+ throw new PluginError("permission-denied", "form", `${operation} requires ${permission}`, { permission });
1936
+ }
1937
+ };
1938
+ }
1939
+ //#endregion
1673
1940
  //#region src/services/looks.ts
1674
1941
  /**
1675
1942
  * What a shown widget looks like now: the engine's picture, or the painter's
@@ -1936,6 +2203,41 @@ function resolveSiblings(ctx) {
1936
2203
  };
1937
2204
  }
1938
2205
  //#endregion
2206
+ //#region src/services/tab-order.ts
2207
+ /**
2208
+ * The order Tab visits the widgets in: every widget that shows, page by page in the document's
2209
+ * order, each page by its own tab order (the engine's `tabOrderOf()`). The cursor goes this way
2210
+ * (`write/focus.ts`), and so do the arrow keys round a radio group's buttons, so a button's
2211
+ * place among its group's is its place in this order.
2212
+ */
2213
+ function createTabOrder(ctx, fields) {
2214
+ const rows = memo(() => [fields.view(), ctx.document()?.pages], (index, pages) => tabOrderOf((index.snapshot?.widgets ?? []).filter(shownOnScreen), pages ?? []));
2215
+ const groupPositions = memo(() => [fields.view(), rows()], (index, ordered) => {
2216
+ const buttons = /* @__PURE__ */ new Map();
2217
+ for (const row of ordered) {
2218
+ const widget = widgetObjectOf(row.ref);
2219
+ const field = fieldForWidget(index, widget);
2220
+ if (field?.kind !== "radio") continue;
2221
+ const key = fieldKeyOf(field);
2222
+ const group = buttons.get(key);
2223
+ if (group) group.push(widget);
2224
+ else buttons.set(key, [widget]);
2225
+ }
2226
+ const positions = /* @__PURE__ */ new Map();
2227
+ for (const group of buttons.values()) group.forEach((widget, at) => {
2228
+ positions.set(widget, {
2229
+ position: at + 1,
2230
+ size: group.length
2231
+ });
2232
+ });
2233
+ return positions;
2234
+ });
2235
+ return {
2236
+ rows,
2237
+ groupPositionOf: (widget) => groupPositions().get(widget) ?? null
2238
+ };
2239
+ }
2240
+ //#endregion
1939
2241
  //#region src/services/index.ts
1940
2242
  function createServices(ctx) {
1941
2243
  const siblings = resolveSiblings(ctx);
@@ -1946,8 +2248,10 @@ function createServices(ctx) {
1946
2248
  return {
1947
2249
  fields,
1948
2250
  rights: createFillRights(ctx, fields),
2251
+ groups: createGroups(ctx, fields, events),
1949
2252
  events,
1950
2253
  cursor: createCursor(ctx, fields, events),
2254
+ tabOrder: createTabOrder(ctx, fields),
1951
2255
  siblings,
1952
2256
  scripting: createScriptingSeam(ctx, siblings),
1953
2257
  design,
@@ -2387,7 +2691,7 @@ function exportValueFor(field) {
2387
2691
  }
2388
2692
  const MODIFY = "doc.forms.modify";
2389
2693
  const SCRIPT = "doc.forms.script";
2390
- function createFieldWrites(ctx, { fields, enqueue }) {
2694
+ function createFieldWrites(ctx, { fields, enqueue, groups }) {
2391
2695
  const numbers = createObjectNumbers(ctx);
2392
2696
  /** Refuse up front without `doc.forms.modify`, and without `doc.forms.script` when it writes scripts. */
2393
2697
  const allow = (operation, scripts = false) => {
@@ -2416,6 +2720,7 @@ function createFieldWrites(ctx, { fields, enqueue }) {
2416
2720
  };
2417
2721
  const create = async (draft, options) => {
2418
2722
  allow("form.create", draftWritesScripts(draft));
2723
+ if (typeof draft.groupId === "string") groups.assertMaySet(draft.groupId, "form.create");
2419
2724
  const count = 1 + (draft.widgets?.length ?? 0);
2420
2725
  const [objectNumber, ...widgetObjectNumbers] = numbers.takeNow(count) ?? await numbers.take(count);
2421
2726
  const change = stage("create", {
@@ -2437,7 +2742,7 @@ function createFieldWrites(ctx, { fields, enqueue }) {
2437
2742
  if (!page) throw new PluginError("invalid-input", "form", "the field shows on no page: give `page` and `rect`");
2438
2743
  const size = ctx.getPage(page)?.size;
2439
2744
  const onPage = rows.filter((row) => row.page.objectNumber === page.objectNumber);
2440
- const rect = placement.rect ?? placement.box ?? (size && onPage.length > 0 ? nextInLine(onPage.map((row) => row.box), size) : void 0);
2745
+ const rect = placement.rect ?? placement.box ?? (size && onPage.length > 0 ? nextInLine(onPage.map((row) => row.rect), size) : void 0);
2441
2746
  if (!rect) throw new PluginError("invalid-input", "form", "no widget of the field on that page: give `rect`");
2442
2747
  const exportValue = placement.exportValue ?? exportValueFor(field);
2443
2748
  const split = isMerged(field);
@@ -2543,6 +2848,33 @@ function createFieldWrites(ctx, { fields, enqueue }) {
2543
2848
  }
2544
2849
  return duplicateResultOf(items, copy.copies, copy.dropped);
2545
2850
  };
2851
+ const moveToGroup = async (refs, groupId, options) => {
2852
+ allow("form.moveToGroup");
2853
+ if (groupId !== null) groups.assertMaySet(groupId, "form.moveToGroup");
2854
+ const index = fields.view();
2855
+ const moved = refs.map((ref) => {
2856
+ const field = fieldByRef(index, ref);
2857
+ if (!field) throw new PluginError("not-found", "form", "no form field has this ref");
2858
+ return field;
2859
+ });
2860
+ const moving = /* @__PURE__ */ new Map();
2861
+ for (const field of moved) if (field.groupId !== groupId) moving.set(fieldKeyOf(field), field);
2862
+ if (moving.size === 0) return { fields: moved };
2863
+ const change = stageAll("update", [...moving.values()].map((field) => ({
2864
+ type: "forms.update",
2865
+ field: field.ref,
2866
+ patch: { groupId }
2867
+ })));
2868
+ let items;
2869
+ try {
2870
+ items = (await ctx.cancellable(options?.signal, change.result)).items;
2871
+ } catch (error) {
2872
+ throw toPluginError("form", error);
2873
+ }
2874
+ const answered = /* @__PURE__ */ new Map();
2875
+ for (const item of items) if (item.type === "forms.update") answered.set(fieldKeyOf(item.field), item.field);
2876
+ return { fields: moved.map((field) => answered.get(fieldKeyOf(field)) ?? field) };
2877
+ };
2546
2878
  return {
2547
2879
  copyOps,
2548
2880
  api: {
@@ -2550,8 +2882,10 @@ function createFieldWrites(ctx, { fields, enqueue }) {
2550
2882
  addWidget,
2551
2883
  duplicate,
2552
2884
  duplicateWidgets,
2885
+ moveToGroup,
2553
2886
  update: async (ref, patch, options) => {
2554
2887
  allow("form.update", writesScripts(patch.actions));
2888
+ if (typeof patch.groupId === "string" && patch.groupId !== fieldByRef(fields.view(), ref)?.groupId) groups.assertMaySet(patch.groupId, "form.update");
2555
2889
  const change = stage("update", {
2556
2890
  type: "forms.update",
2557
2891
  field: ref,
@@ -2922,20 +3256,29 @@ function failedFill(result) {
2922
3256
  /**
2923
3257
  * Moving the cursor between fields: `focus()`, `focusNext()` (what Tab does), the arrow keys in a
2924
3258
  * radio group, and the field the cursor is in. This area decides where the cursor goes: which
2925
- * field, which of its boxes, in Tab's order (the engine's `tabOrderOf()`); the cursor service
3259
+ * field, which of its boxes, in Tab's order (`services/tab-order.ts`); the cursor service
2926
3260
  * (`services/cursor.ts`) brings the box into view and hands it to its control.
3261
+ *
3262
+ * A stop is a box of a field the user may fill in. The cursor passes over one whose control
3263
+ * takes no cursor (`cursor.goTo` declines it): a signature field with nothing to sign it. Stops
3264
+ * are tried in the order Tab comes to them, so a move asks only the ones it reaches.
3265
+ *
3266
+ * A radio group is one stop on each page it shows on, where its first button comes in Tab's
3267
+ * order. The button that takes the cursor may come later in that order, with other fields
3268
+ * before it. From any of its buttons the cursor goes on from the group's stop, so Tab takes
3269
+ * what comes after the group and Shift+Tab what comes before it, each field once.
2927
3270
  */
3271
+ const NO_STOPS = /* @__PURE__ */ new Set();
2928
3272
  /** A radio button as its field lists it: whether it's the checked one, and the value it picks. */
2929
3273
  const radioButtonOf = (field, widget) => field.kind === "radio" ? field.widgets.find((candidate) => candidate.objectNumber === widget) ?? null : null;
2930
- function createFocus(ctx, { fields, rights, events, cursor }, fill) {
3274
+ function createFocus(ctx, { fields, rights, events, cursor, tabOrder }, fill) {
2931
3275
  /** Every box that shows, in Tab's order, and the ones Tab stops at. */
2932
3276
  const order = memo(() => [
2933
3277
  fields.view(),
2934
- ctx.document()?.pages,
3278
+ tabOrder.rows(),
2935
3279
  rights.key(),
2936
3280
  ctx.settings().get().fillable
2937
- ], (index, pages) => {
2938
- const rows = tabOrderOf((index.snapshot?.widgets ?? []).filter(shownOnScreen), pages ?? []);
3281
+ ], (index, rows) => {
2939
3282
  const position = /* @__PURE__ */ new Map();
2940
3283
  const stops = [];
2941
3284
  const groups = /* @__PURE__ */ new Set();
@@ -2976,30 +3319,56 @@ function createFocus(ctx, { fields, rights, events, cursor }, fill) {
2976
3319
  const index = fields.view();
2977
3320
  const field = fieldByRef(index, ref);
2978
3321
  if (!field || !rights.takesInput(field)) return false;
2979
- let row;
3322
+ const select = options.select ?? false;
2980
3323
  if (options.widget) {
2981
3324
  const widget = widgetObjectOf(options.widget);
2982
3325
  if (fieldForWidget(index, widget) !== field) return false;
2983
- row = order().rows.find((candidate) => widgetObjectOf(candidate.ref) === widget);
2984
- } else {
2985
- const stop = order().stops.find((candidate) => candidate.field === field);
2986
- row = stop && boxAt(stop, false);
3326
+ const row = order().rows.find((candidate) => widgetObjectOf(candidate.ref) === widget);
3327
+ return row ? cursor.goTo(row, select) === "taken" : false;
2987
3328
  }
2988
- return row ? cursor.goTo(row, options.select ?? false) : false;
3329
+ for (const stop of order().stops) {
3330
+ if (stop.field !== field) continue;
3331
+ const move = cursor.goTo(boxAt(stop, false), select);
3332
+ if (move !== "declined") return move === "taken";
3333
+ }
3334
+ return false;
2989
3335
  };
2990
- const focusNext = (options = {}) => {
3336
+ /**
3337
+ * Move the cursor to the next stop after a box (`from`; `null`: from the start), as Tab does:
3338
+ * the first one on the way that takes the cursor. A radio button's place is its group's stop.
3339
+ * `passed` are the stops this move already asked for and that came in holding nothing to focus.
3340
+ */
3341
+ const step = (from, how, passed = NO_STOPS) => {
3342
+ const { backward, empty, wrap } = how;
2991
3343
  const index = fields.view();
2992
3344
  const { position, stops } = order();
2993
- const backward = options.backward ?? false;
2994
- const fromField = options.from ? fieldByRef(index, options.from) : null;
2995
- const from = options.from ? fromField?.widgets.map(({ objectNumber }) => objectNumber).find((w) => position.has(w)) ?? null : cursor.focused()?.widget ?? cursor.last();
2996
- const at = from === null ? null : position.get(from) ?? null;
2997
3345
  const field = from === null ? null : fieldForWidget(index, from);
2998
3346
  const page = from === null ? null : widgetRowOf(index, from)?.page.objectNumber;
2999
- const candidates = stops.filter((stop) => (!options.empty || isEmpty(stop.field)) && !(stop.field === field && field.kind === "radio" && stop.row.page.objectNumber === page));
3000
- const ahead = candidates.filter((stop) => at === null ? true : backward ? stop.at < at : stop.at > at);
3001
- const next = (backward ? ahead.at(-1) : ahead[0]) ?? (options.wrap ? backward ? candidates.at(-1) : candidates[0] : void 0);
3002
- return next ? cursor.goTo(boxAt(next, backward), true) : false;
3347
+ const group = field?.kind === "radio" ? stops.find((stop) => stop.field === field && stop.row.page.objectNumber === page) : void 0;
3348
+ const own = from === null ? void 0 : position.get(from);
3349
+ const at = own === void 0 ? null : group?.at ?? own;
3350
+ const candidates = stops.filter((stop) => (!empty || isEmpty(stop.field)) && stop !== group && !passed.has(widgetObjectOf(stop.row.ref)));
3351
+ const isAhead = (stop) => at === null ? true : backward ? stop.at < at : stop.at > at;
3352
+ const ahead = candidates.filter(isAhead);
3353
+ const round = wrap ? candidates.filter((stop) => !isAhead(stop)) : [];
3354
+ const way = backward ? [...ahead.reverse(), ...round.reverse()] : [...ahead, ...round];
3355
+ for (const stop of way) {
3356
+ const here = widgetObjectOf(stop.row.ref);
3357
+ const onward = () => void step(here, how, /* @__PURE__ */ new Set([...passed, here]));
3358
+ const move = cursor.goTo(boxAt(stop, backward), true, onward);
3359
+ if (move !== "declined") return move === "taken";
3360
+ }
3361
+ return false;
3362
+ };
3363
+ const focusNext = (options = {}) => {
3364
+ const { position } = order();
3365
+ const fromField = options.from ? fieldByRef(fields.view(), options.from) : null;
3366
+ const from = options.from ? fromField?.widgets.map(({ objectNumber }) => objectNumber).find((w) => position.has(w)) ?? null : cursor.focused()?.widget ?? cursor.last();
3367
+ return step(from, {
3368
+ backward: options.backward ?? false,
3369
+ empty: options.empty ?? false,
3370
+ wrap: options.wrap ?? false
3371
+ });
3003
3372
  };
3004
3373
  const moveInGroup = (ref, backward) => {
3005
3374
  const widget = widgetObjectOf(ref);
@@ -3009,7 +3378,7 @@ function createFocus(ctx, { fields, rights, events, cursor }, fill) {
3009
3378
  const here = buttons.findIndex((row) => widgetObjectOf(row.ref) === widget);
3010
3379
  if (here < 0 || buttons.length < 2) return false;
3011
3380
  const next = buttons[(here + (backward ? buttons.length - 1 : 1)) % buttons.length];
3012
- if (!cursor.goTo(next, false)) return false;
3381
+ if (cursor.goTo(next, false) !== "taken") return false;
3013
3382
  const button = radioButtonOf(field, widgetObjectOf(next.ref));
3014
3383
  if (button) {
3015
3384
  const activate = () => void fill.activateWidget(next.ref).catch(() => {});
@@ -3027,6 +3396,35 @@ function createFocus(ctx, { fields, rights, events, cursor }, fill) {
3027
3396
  } };
3028
3397
  }
3029
3398
  //#endregion
3399
+ //#region src/write/groups.ts
3400
+ /** The app's list as the state holds it: each id once (the first entry of an id is the group). */
3401
+ function namedGroupsOf(groups) {
3402
+ const byId = /* @__PURE__ */ new Map();
3403
+ for (const group of groups) {
3404
+ if (byId.has(group.id)) continue;
3405
+ byId.set(group.id, Object.freeze({
3406
+ id: group.id,
3407
+ label: group.label ?? null,
3408
+ color: group.color ?? null
3409
+ }));
3410
+ }
3411
+ return Object.freeze([...byId.values()]);
3412
+ }
3413
+ function createGroupWrites(ctx, { groups }) {
3414
+ return { api: {
3415
+ listGroups: groups.list,
3416
+ setGroups: (list) => {
3417
+ ctx.state.update(setGroups, namedGroupsOf(list));
3418
+ },
3419
+ getDesignGroup: () => ctx.state.get().designGroup,
3420
+ setDesignGroup: (groupId) => {
3421
+ if (groupId !== null) groups.assertMaySet(groupId, "form.setDesignGroup");
3422
+ ctx.state.update(setDesignGroup, groupId);
3423
+ },
3424
+ canSetGroup: groups.maySet
3425
+ } };
3426
+ }
3427
+ //#endregion
3030
3428
  //#region src/write/interchange.ts
3031
3429
  function createInterchange(ctx, services) {
3032
3430
  const { enqueue, siblings } = services;
@@ -3083,17 +3481,23 @@ function createInterchange(ctx, services) {
3083
3481
  * its records and edits them with its tools: select, move, resize, restyle,
3084
3482
  * reorder, delete. Each edit comes back here as the form's ops, in the same
3085
3483
  * change as the rest of it. While the tool fills, nothing is lent, and the
3086
- * form layer draws and fills every widget.
3484
+ * form layer draws and fills every widget. A widget of no size is never lent:
3485
+ * nobody can see it, so nobody should be able to select it by hand.
3486
+ *
3487
+ * Each lent widget carries its field's group's color as its accent,
3488
+ * `fields.tint` strong, so the annotation layer shows whose field it is.
3087
3489
  */
3088
3490
  const objectNumberOf = (ref) => ref.kind === "objectNumber" ? ref.objectNumber : -1;
3089
- function createWidgetLender(ctx, { fields, design, pictures, looks }, copyOps) {
3491
+ function createWidgetLender(ctx, { fields, design, pictures, looks, groups }, copyOps) {
3090
3492
  const records = memo(() => [
3091
3493
  design.lending(),
3092
3494
  fields.get().snapshot,
3093
- fields.view().snapshot
3495
+ fields.view().snapshot,
3496
+ groups.list(),
3497
+ ctx.settings().get().fields.tint
3094
3498
  ], (lending, confirmed, shown) => lending && confirmed && shown ? {
3095
- confirmed: confirmed.widgets,
3096
- shown: shown.widgets
3499
+ confirmed: confirmed.widgets.filter(hasArea),
3500
+ shown: shown.widgets.filter(hasArea)
3097
3501
  } : null);
3098
3502
  /**
3099
3503
  * Deleted widgets, as the form's ops: a widget leaves its field
@@ -3174,6 +3578,10 @@ function createWidgetLender(ctx, { fields, design, pictures, looks }, copyOps) {
3174
3578
  getPictureVersion: pictures.versionOf,
3175
3579
  renderAppearances: pictures.render,
3176
3580
  isPending: looks.isPending,
3581
+ accentOf: (record) => {
3582
+ const field = fieldForWidget(fields.view(), objectNumberOf(record.ref));
3583
+ return groups.lookOf(field?.groupId ?? null)?.accent ?? null;
3584
+ },
3177
3585
  painter: (record) => record.subtype === "widget" ? looks.painterOf(record) : null
3178
3586
  };
3179
3587
  }
@@ -3611,6 +4019,7 @@ function createFormController(ctx) {
3611
4019
  const typing = createTyping(ctx, services, values.setText);
3612
4020
  const resets = createResetWrites(ctx, services, fills);
3613
4021
  const design = createFieldWrites(ctx, services);
4022
+ const groups = createGroupWrites(ctx, services);
3614
4023
  const interchange = createInterchange(ctx, services);
3615
4024
  const activation = createActivation(ctx, services, fills);
3616
4025
  const scripts = createScriptEffects(ctx, services, fills);
@@ -3627,6 +4036,7 @@ function createFormController(ctx) {
3627
4036
  typing.api,
3628
4037
  resets.api,
3629
4038
  design.api,
4039
+ groups.api,
3630
4040
  interchange.api,
3631
4041
  activation.api,
3632
4042
  scripts.api,
@@ -3645,7 +4055,9 @@ function createFormController(ctx) {
3645
4055
  onFieldUpdated: events.fieldUpdated.on,
3646
4056
  onFieldDeleted: events.fieldDeleted.on,
3647
4057
  onValidationRejected: events.validationRejected.on,
3648
- onResynced: events.resynced.on
4058
+ onResynced: events.resynced.on,
4059
+ onDesignGroupChanged: events.designGroupChanged.on,
4060
+ onGroupsChanged: events.groupsChanged.on
3649
4061
  }
3650
4062
  ]);
3651
4063
  return {
@@ -3665,7 +4077,8 @@ function createFormController(ctx) {
3665
4077
  * the annotation plugin present, the form lends it the widgets, which its
3666
4078
  * tools then select, move, restyle and delete. The render plugin draws the
3667
4079
  * widgets' pictures in both modes. With the fonts plugin, a text field in a
3668
- * font of its own is edited in that font's program. `config` is the settings the app
4080
+ * font of its own is edited in that font's program. With the Stage, `focus()` and
4081
+ * `focusNext()` bring the box they go to into view. `config` is the settings the app
3669
4082
  * registers, over {@link FORM_DEFAULTS}.
3670
4083
  */
3671
4084
  const formPlugin = (config) => definePlugin({
@@ -3677,7 +4090,8 @@ const formPlugin = (config) => definePlugin({
3677
4090
  AnnotationToken,
3678
4091
  ActionsToken,
3679
4092
  RenderToken,
3680
- FontsToken
4093
+ FontsToken,
4094
+ StageToken
3681
4095
  ],
3682
4096
  state: initialFormModel,
3683
4097
  settings: {
@@ -3686,20 +4100,35 @@ const formPlugin = (config) => definePlugin({
3686
4100
  },
3687
4101
  create: createFormController
3688
4102
  });
4103
+ //#endregion
4104
+ //#region src/state.ts
4105
+ /**
4106
+ * The form page's State table as code: what `useFormState()` returns, and the
4107
+ * same fields in every other framework. One field's value has its own hook
4108
+ * (`useFormValue(ref)`), so a total in your own UI re-renders only when that
4109
+ * field changes.
4110
+ */
4111
+ const NO_FIELDS = Object.freeze([]);
3689
4112
  const formState = defineState(FormToken, {
3690
4113
  read: (form) => ({
3691
4114
  fields: form.list(),
3692
4115
  status: form.getStatus(),
3693
4116
  formKind: form.getFormKind(),
3694
4117
  selectedField: form.getSelectedField(),
3695
- focusedField: form.getFocusedField()
4118
+ focusedField: form.getFocusedField(),
4119
+ selectedFields: form.listSelectedFields(),
4120
+ groups: form.listGroups(),
4121
+ designGroup: form.getDesignGroup()
3696
4122
  }),
3697
4123
  empty: {
3698
- fields: Object.freeze([]),
4124
+ fields: NO_FIELDS,
3699
4125
  status: "idle",
3700
4126
  formKind: "none",
3701
4127
  selectedField: null,
3702
- focusedField: null
4128
+ focusedField: null,
4129
+ selectedFields: NO_FIELDS,
4130
+ groups: Object.freeze([]),
4131
+ designGroup: null
3703
4132
  }
3704
4133
  });
3705
4134
  //#endregion