@embedpdf/plugin-form 3.3.0 → 3.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.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,6 +628,12 @@ function fieldsWithChangedValues(previous, next) {
582
628
  });
583
629
  }
584
630
  const valueEntryOf = (field) => "valueEntry" in field ? field.valueEntry : null;
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
+ });
585
637
  /**
586
638
  * Whether a widget's box has an area. One of no size is how a PDF keeps a field that shows
587
639
  * nowhere: the field of a document timestamp, an invisible signature.
@@ -599,7 +651,8 @@ function pageWidgetsOf(index, pageObjectNumber) {
599
651
  if (row.page.objectNumber !== pageObjectNumber || row.ref.kind !== "objectNumber") continue;
600
652
  if (!shownOnScreen(row)) continue;
601
653
  widgets[row.ref.objectNumber] = {
602
- box: row.rect,
654
+ ref: row.ref,
655
+ ...placeOf(row),
603
656
  look: {
604
657
  border: row.color ?? null,
605
658
  borderWidth: row.strokeWidth ?? 1,
@@ -625,7 +678,7 @@ function shownWidgetsOf(index, pageObjectNumber, lookOf = () => AT_REST) {
625
678
  if (row.page.objectNumber !== pageObjectNumber || !shownOnScreen(row)) continue;
626
679
  shown.push({
627
680
  ref: row.ref,
628
- rect: row.rect,
681
+ ...placeOf(row),
629
682
  appearanceState: row.appearanceState,
630
683
  ...lookOf(row)
631
684
  });
@@ -637,24 +690,48 @@ function widgetRowOf(index, annotObjectNumber) {
637
690
  return position === void 0 ? null : index.snapshot?.widgets[position] ?? null;
638
691
  }
639
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;
640
- /** 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. */
641
694
  function widgetAt(index, widgets, point) {
642
695
  if (!widgets) return null;
643
696
  let best = null;
644
- for (const [key, { box }] of Object.entries(widgets)) {
645
- if (!boxContains(box, point)) continue;
697
+ for (const [key, { box, rotation, rect }] of Object.entries(widgets)) {
698
+ if (!boxContains(rect, point)) continue;
646
699
  const annotObjectNumber = Number(key);
647
700
  const field = fieldForWidget(index, annotObjectNumber);
648
701
  if (!field) continue;
649
- 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 = {
650
703
  annotObjectNumber,
651
704
  field,
652
- box
705
+ box,
706
+ rotation,
707
+ rect
653
708
  };
654
709
  }
655
710
  return best;
656
711
  }
657
- 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
+ }
658
735
  //#endregion
659
736
  //#region src/read/fields.ts
660
737
  /**
@@ -663,6 +740,7 @@ const initialFormModel = () => ({ focused: null });
663
740
  * required-field check.
664
741
  */
665
742
  const NO_FIELDS$1 = Object.freeze([]);
743
+ const NO_SELECTED_FIELDS = Object.freeze([]);
666
744
  const NOTHING_SELECTED = Object.freeze([]);
667
745
  /** A widget address as the annotation object number the field index is keyed by. */
668
746
  const widgetObjectOf = (widget) => "kind" in widget ? widget.kind === "objectNumber" ? widget.objectNumber : 0 : widget.objectNumber;
@@ -776,6 +854,16 @@ function createFieldReads(ctx, { fields, rights, siblings }) {
776
854
  }
777
855
  return found;
778
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
+ });
779
867
  return { api: {
780
868
  getSnapshot: () => fields.view().snapshot,
781
869
  getStatus: fields.getStatus,
@@ -788,6 +876,7 @@ function createFieldReads(ctx, { fields, rights, siblings }) {
788
876
  list,
789
877
  getValue: (ref) => valueByKey(canonicalKey(fields.view(), ref)),
790
878
  getSelectedField,
879
+ listSelectedFields,
791
880
  validate,
792
881
  exportValues
793
882
  } };
@@ -797,7 +886,9 @@ function createFieldReads(ctx, { fields, rights, siblings }) {
797
886
  /**
798
887
  * A field's settings, described for a settings panel the way an annotation
799
888
  * kind describes its look: which settings the field's kind has, how each is
800
- * 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.
801
892
  */
802
893
  /** What every field has. */
803
894
  const COMMON = [
@@ -922,6 +1013,21 @@ function familySettings(field) {
922
1013
  default: return [];
923
1014
  }
924
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
+ }
925
1031
  /** Each setting's value, as the field holds it. */
926
1032
  function valuesOf(field, settings) {
927
1033
  const held = field;
@@ -931,10 +1037,14 @@ function valuesOf(field, settings) {
931
1037
  else values[key] = held[key] ?? null;
932
1038
  return values;
933
1039
  }
934
- function createFieldSettings({ fields }) {
935
- 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) => {
936
1042
  if (!field) return null;
937
- const properties = [...COMMON, ...familySettings(field)];
1043
+ const properties = [
1044
+ ...COMMON,
1045
+ ...groupSetting(field, listed, groups.maySet),
1046
+ ...familySettings(field)
1047
+ ];
938
1048
  return {
939
1049
  properties,
940
1050
  values: valuesOf(field, properties)
@@ -944,21 +1054,43 @@ function createFieldSettings({ fields }) {
944
1054
  }
945
1055
  //#endregion
946
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}`;
1061
+ /**
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.
1064
+ */
1065
+ const takesValue = (field) => field.kind !== "pushbutton" && !field.readOnly && !(field.kind === "signature" && field.valueEntry.kind !== "none");
947
1066
  /**
948
- * Project one widget of a field into a fill control; `fillable`: the user may
949
- * fill the field in (a signature field: sign it). Null for kinds with no
950
- * fill control.
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.
951
1073
  */
952
- function projectWidget(field, annotObjectNumber, widget, fillable) {
1074
+ function projectWidget(field, annotObjectNumber, widget, fillable, canFill, inGroup = null, group = null) {
1075
+ const key = fieldKeyOf(field);
1076
+ const owner = group?.label ?? null;
953
1077
  const base = {
954
- key: fieldKeyOf(field),
1078
+ key,
955
1079
  fieldRef: field.ref,
956
1080
  annotObjectNumber,
957
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,
958
1088
  box: widget.box,
1089
+ rotation: widget.rotation,
1090
+ rect: widget.rect,
959
1091
  look: widget.look,
960
1092
  disabled: field.readOnly || !fillable,
961
- label: field.alternateName ?? field.name
1093
+ label: ownedLabel(field.alternateName ?? field.name, owner)
962
1094
  };
963
1095
  switch (field.kind) {
964
1096
  case "text": return {
@@ -982,12 +1114,15 @@ function projectWidget(field, annotObjectNumber, widget, fillable) {
982
1114
  }
983
1115
  case "radio": {
984
1116
  const toggle = field.widgets.find((candidate) => candidate.objectNumber === annotObjectNumber);
1117
+ const exportValue = toggle && "exportValue" in toggle ? toggle.exportValue : "";
985
1118
  return {
986
1119
  ...base,
1120
+ label: ownedLabel(radioLabel(field.alternateName ?? field.name, exportValue), owner),
987
1121
  control: "toggle",
988
1122
  kind: "radio",
989
1123
  checked: toggle && "checked" in toggle ? toggle.checked : false,
990
- exportValue: toggle && "exportValue" in toggle ? toggle.exportValue : ""
1124
+ exportValue,
1125
+ inGroup
991
1126
  };
992
1127
  }
993
1128
  case "combobox": return {
@@ -1021,19 +1156,22 @@ function projectWidget(field, annotObjectNumber, widget, fillable) {
1021
1156
  }
1022
1157
  }
1023
1158
  /**
1024
- * Project one page's widgets into fill controls, each disabled when the user
1025
- * may not fill its field in, or sign it (`mayFill`). Widgets whose page has not loaded (or
1026
- * that are direct objects with no join key) are skipped; the projection runs
1027
- * 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.
1028
1166
  */
1029
- function fillItems(index, pageObjectNumber, widgets, mayFill) {
1167
+ function fillItems(index, pageObjectNumber, widgets, mayFillByHand, mayFill, groupPositionOf = () => null, groupLookOf = () => null) {
1030
1168
  if (!index.snapshot || !widgets) return [];
1031
1169
  const items = [];
1032
1170
  for (const field of index.snapshot.fields) for (const widget of field.widgets) {
1033
1171
  if (widget.page?.objectNumber !== pageObjectNumber) continue;
1034
1172
  const placed = widgets[widget.objectNumber];
1035
1173
  if (!placed) continue;
1036
- 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));
1037
1175
  if (item) items.push(item);
1038
1176
  }
1039
1177
  return items;
@@ -1048,7 +1186,7 @@ function fillItems(index, pageObjectNumber, widgets, mayFill) {
1048
1186
  */
1049
1187
  const NO_WIDGETS = Object.freeze([]);
1050
1188
  const NOTHING_SHOWN$1 = Object.freeze([]);
1051
- function createWidgetReads(ctx, { fields, rights, looks, pictures }) {
1189
+ function createWidgetReads(ctx, { fields, rights, looks, pictures, design, siblings, cursor, tabOrder, groups }) {
1052
1190
  /** Every page's widgets come with the form: one read for the document. */
1053
1191
  const loadWidgets = (_page) => fields.settled();
1054
1192
  const widgetsOn = memoByKey((pageObjectNumber) => [fields.view()], (pageObjectNumber, index) => pageWidgetsOf(index, pageObjectNumber));
@@ -1062,8 +1200,11 @@ function createWidgetReads(ctx, { fields, rights, looks, pictures }) {
1062
1200
  fields.view(),
1063
1201
  widgetsOn(pageObjectNumber),
1064
1202
  rights.key(),
1065
- ctx.settings().get().fillable
1066
- ], (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));
1067
1208
  /** The page's content box (`{0, 0, width, height}`), for page-bound placement. */
1068
1209
  const getPageBox = (page) => {
1069
1210
  const size = ctx.getPage(page)?.size;
@@ -1074,6 +1215,19 @@ function createWidgetReads(ctx, { fields, rights, looks, pictures }) {
1074
1215
  height: size.height
1075
1216
  } : null;
1076
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
+ };
1077
1231
  return {
1078
1232
  getPageBox,
1079
1233
  api: {
@@ -1092,7 +1246,9 @@ function createWidgetReads(ctx, { fields, rights, looks, pictures }) {
1092
1246
  getWidgetFontCss: looks.getWidgetFontCss,
1093
1247
  ensureLoaded: loadWidgets,
1094
1248
  getWidgetAt,
1095
- getPageBox
1249
+ getPageBox,
1250
+ getWidgetAnchor,
1251
+ isWidgetFocused: (widget) => cursor.focused()?.widget === widgetObjectOf(widget)
1096
1252
  }
1097
1253
  };
1098
1254
  }
@@ -1515,6 +1671,10 @@ function createFieldsMirror(ctx, events) {
1515
1671
  //#region src/services/cursor.ts
1516
1672
  /** How long a box asked for keeps its claim on the cursor while its page comes in. */
1517
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;
1518
1678
  function createCursor(ctx, fields, events) {
1519
1679
  const targets = /* @__PURE__ */ new Map();
1520
1680
  let pending = null;
@@ -1536,8 +1696,29 @@ function createCursor(ctx, fields, events) {
1536
1696
  };
1537
1697
  const clearPending = () => {
1538
1698
  pending?.expire();
1699
+ pending?.settle?.();
1539
1700
  pending = null;
1540
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
+ };
1541
1722
  return {
1542
1723
  focused: () => ctx.state.get().focused,
1543
1724
  last: () => last,
@@ -1561,34 +1742,34 @@ function createCursor(ctx, fields, events) {
1561
1742
  });
1562
1743
  }
1563
1744
  },
1564
- goTo(row, select) {
1745
+ goTo(row, select, onward) {
1565
1746
  const widget = widgetObjectOf(row.ref);
1747
+ const shown = targets.get(widget);
1748
+ if (shown && !takes(shown)) return "declined";
1566
1749
  const stage = ctx.tryGet(StageToken);
1567
1750
  stage?.reveal(row.page, { rect: row.rect });
1568
1751
  clearPending();
1569
1752
  const target = targets.get(widget);
1570
- if (target) {
1571
- target.focus({ select });
1572
- return true;
1573
- }
1574
- if (!stage) return false;
1575
- pending = {
1753
+ if (target && enter(target, select)) return "taken";
1754
+ if (target && target === shown) return "declined";
1755
+ if (!stage) return "unreachable";
1756
+ const waiting = {
1576
1757
  widget,
1577
1758
  select,
1759
+ onward: onward ?? null,
1578
1760
  expire: ctx.clock.after(PENDING_MS, () => {
1579
- if (pending?.widget === widget) pending = null;
1580
- })
1761
+ if (pending === waiting) clearPending();
1762
+ }),
1763
+ settle: null
1581
1764
  };
1582
- return true;
1765
+ pending = waiting;
1766
+ if (target) settleLater(waiting);
1767
+ return "taken";
1583
1768
  },
1584
1769
  attach(widgetRef, target) {
1585
1770
  const widget = widgetObjectOf(widgetRef);
1586
1771
  targets.set(widget, target);
1587
- if (pending?.widget === widget) {
1588
- const { select } = pending;
1589
- clearPending();
1590
- target.focus({ select });
1591
- }
1772
+ if (pending?.widget === widget) arrive(pending, target);
1592
1773
  return () => {
1593
1774
  if (targets.get(widget) === target) targets.delete(widget);
1594
1775
  };
@@ -1610,15 +1791,21 @@ function createDesign(ctx, siblings) {
1610
1791
  //#endregion
1611
1792
  //#region src/services/events.ts
1612
1793
  function createEvents(ctx) {
1613
- return {
1794
+ const events = {
1614
1795
  valueChanged: ctx.events.source(),
1615
1796
  fieldCreated: ctx.events.source(),
1616
1797
  fieldUpdated: ctx.events.source(),
1617
1798
  fieldDeleted: ctx.events.source(),
1618
1799
  validationRejected: ctx.events.source(),
1619
1800
  resynced: ctx.events.source(),
1620
- focusChanged: ctx.events.source()
1801
+ focusChanged: ctx.events.source(),
1802
+ designGroupChanged: ctx.events.source(),
1803
+ groupsChanged: ctx.events.source()
1621
1804
  };
1805
+ ctx.state.onChange(({ previous, next }) => {
1806
+ if (previous.designGroup !== next.designGroup) events.designGroupChanged.emit({ groupId: next.designGroup });
1807
+ });
1808
+ return events;
1622
1809
  }
1623
1810
  //#endregion
1624
1811
  //#region src/services/fill-rights.ts
@@ -1633,12 +1820,14 @@ const isFillableByHand = (fillable, kind) => typeof fillable === "boolean" ? fil
1633
1820
  function createFillRights(ctx, fields) {
1634
1821
  const mayFill = (field) => ctx.allowsField("fill", field);
1635
1822
  const maySign = (field) => ctx.allowsField("sign", field);
1636
- 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);
1637
1825
  /** The form's groups, `null` (no group) among them. */
1638
1826
  const groups = memo(() => [fields.view()], (index) => [...new Set((index.snapshot?.fields ?? []).map((field) => field.groupId))]);
1639
1827
  return {
1640
1828
  mayFill,
1641
1829
  maySign,
1830
+ mayFillOrSign,
1642
1831
  mayFillByHand,
1643
1832
  takesInput: (field) => !field.readOnly && mayFillByHand(field),
1644
1833
  assertMayFill: (field, operation) => ctx.assertAllowedField("fill", field, operation),
@@ -1678,6 +1867,76 @@ function createFormattedTexts(ctx, fields) {
1678
1867
  };
1679
1868
  }
1680
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
1681
1940
  //#region src/services/looks.ts
1682
1941
  /**
1683
1942
  * What a shown widget looks like now: the engine's picture, or the painter's
@@ -1944,6 +2203,41 @@ function resolveSiblings(ctx) {
1944
2203
  };
1945
2204
  }
1946
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
1947
2241
  //#region src/services/index.ts
1948
2242
  function createServices(ctx) {
1949
2243
  const siblings = resolveSiblings(ctx);
@@ -1954,8 +2248,10 @@ function createServices(ctx) {
1954
2248
  return {
1955
2249
  fields,
1956
2250
  rights: createFillRights(ctx, fields),
2251
+ groups: createGroups(ctx, fields, events),
1957
2252
  events,
1958
2253
  cursor: createCursor(ctx, fields, events),
2254
+ tabOrder: createTabOrder(ctx, fields),
1959
2255
  siblings,
1960
2256
  scripting: createScriptingSeam(ctx, siblings),
1961
2257
  design,
@@ -2395,7 +2691,7 @@ function exportValueFor(field) {
2395
2691
  }
2396
2692
  const MODIFY = "doc.forms.modify";
2397
2693
  const SCRIPT = "doc.forms.script";
2398
- function createFieldWrites(ctx, { fields, enqueue }) {
2694
+ function createFieldWrites(ctx, { fields, enqueue, groups }) {
2399
2695
  const numbers = createObjectNumbers(ctx);
2400
2696
  /** Refuse up front without `doc.forms.modify`, and without `doc.forms.script` when it writes scripts. */
2401
2697
  const allow = (operation, scripts = false) => {
@@ -2424,6 +2720,7 @@ function createFieldWrites(ctx, { fields, enqueue }) {
2424
2720
  };
2425
2721
  const create = async (draft, options) => {
2426
2722
  allow("form.create", draftWritesScripts(draft));
2723
+ if (typeof draft.groupId === "string") groups.assertMaySet(draft.groupId, "form.create");
2427
2724
  const count = 1 + (draft.widgets?.length ?? 0);
2428
2725
  const [objectNumber, ...widgetObjectNumbers] = numbers.takeNow(count) ?? await numbers.take(count);
2429
2726
  const change = stage("create", {
@@ -2445,7 +2742,7 @@ function createFieldWrites(ctx, { fields, enqueue }) {
2445
2742
  if (!page) throw new PluginError("invalid-input", "form", "the field shows on no page: give `page` and `rect`");
2446
2743
  const size = ctx.getPage(page)?.size;
2447
2744
  const onPage = rows.filter((row) => row.page.objectNumber === page.objectNumber);
2448
- 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);
2449
2746
  if (!rect) throw new PluginError("invalid-input", "form", "no widget of the field on that page: give `rect`");
2450
2747
  const exportValue = placement.exportValue ?? exportValueFor(field);
2451
2748
  const split = isMerged(field);
@@ -2551,6 +2848,33 @@ function createFieldWrites(ctx, { fields, enqueue }) {
2551
2848
  }
2552
2849
  return duplicateResultOf(items, copy.copies, copy.dropped);
2553
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
+ };
2554
2878
  return {
2555
2879
  copyOps,
2556
2880
  api: {
@@ -2558,8 +2882,10 @@ function createFieldWrites(ctx, { fields, enqueue }) {
2558
2882
  addWidget,
2559
2883
  duplicate,
2560
2884
  duplicateWidgets,
2885
+ moveToGroup,
2561
2886
  update: async (ref, patch, options) => {
2562
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");
2563
2889
  const change = stage("update", {
2564
2890
  type: "forms.update",
2565
2891
  field: ref,
@@ -2930,20 +3256,29 @@ function failedFill(result) {
2930
3256
  /**
2931
3257
  * Moving the cursor between fields: `focus()`, `focusNext()` (what Tab does), the arrow keys in a
2932
3258
  * radio group, and the field the cursor is in. This area decides where the cursor goes: which
2933
- * 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
2934
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.
2935
3270
  */
3271
+ const NO_STOPS = /* @__PURE__ */ new Set();
2936
3272
  /** A radio button as its field lists it: whether it's the checked one, and the value it picks. */
2937
3273
  const radioButtonOf = (field, widget) => field.kind === "radio" ? field.widgets.find((candidate) => candidate.objectNumber === widget) ?? null : null;
2938
- function createFocus(ctx, { fields, rights, events, cursor }, fill) {
3274
+ function createFocus(ctx, { fields, rights, events, cursor, tabOrder }, fill) {
2939
3275
  /** Every box that shows, in Tab's order, and the ones Tab stops at. */
2940
3276
  const order = memo(() => [
2941
3277
  fields.view(),
2942
- ctx.document()?.pages,
3278
+ tabOrder.rows(),
2943
3279
  rights.key(),
2944
3280
  ctx.settings().get().fillable
2945
- ], (index, pages) => {
2946
- const rows = tabOrderOf((index.snapshot?.widgets ?? []).filter(shownOnScreen), pages ?? []);
3281
+ ], (index, rows) => {
2947
3282
  const position = /* @__PURE__ */ new Map();
2948
3283
  const stops = [];
2949
3284
  const groups = /* @__PURE__ */ new Set();
@@ -2984,30 +3319,56 @@ function createFocus(ctx, { fields, rights, events, cursor }, fill) {
2984
3319
  const index = fields.view();
2985
3320
  const field = fieldByRef(index, ref);
2986
3321
  if (!field || !rights.takesInput(field)) return false;
2987
- let row;
3322
+ const select = options.select ?? false;
2988
3323
  if (options.widget) {
2989
3324
  const widget = widgetObjectOf(options.widget);
2990
3325
  if (fieldForWidget(index, widget) !== field) return false;
2991
- row = order().rows.find((candidate) => widgetObjectOf(candidate.ref) === widget);
2992
- } else {
2993
- const stop = order().stops.find((candidate) => candidate.field === field);
2994
- 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;
3328
+ }
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";
2995
3333
  }
2996
- return row ? cursor.goTo(row, options.select ?? false) : false;
3334
+ return false;
2997
3335
  };
2998
- 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;
2999
3343
  const index = fields.view();
3000
3344
  const { position, stops } = order();
3001
- const backward = options.backward ?? false;
3002
- const fromField = options.from ? fieldByRef(index, options.from) : null;
3003
- const from = options.from ? fromField?.widgets.map(({ objectNumber }) => objectNumber).find((w) => position.has(w)) ?? null : cursor.focused()?.widget ?? cursor.last();
3004
- const at = from === null ? null : position.get(from) ?? null;
3005
3345
  const field = from === null ? null : fieldForWidget(index, from);
3006
3346
  const page = from === null ? null : widgetRowOf(index, from)?.page.objectNumber;
3007
- const candidates = stops.filter((stop) => (!options.empty || isEmpty(stop.field)) && !(stop.field === field && field.kind === "radio" && stop.row.page.objectNumber === page));
3008
- const ahead = candidates.filter((stop) => at === null ? true : backward ? stop.at < at : stop.at > at);
3009
- const next = (backward ? ahead.at(-1) : ahead[0]) ?? (options.wrap ? backward ? candidates.at(-1) : candidates[0] : void 0);
3010
- 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
+ });
3011
3372
  };
3012
3373
  const moveInGroup = (ref, backward) => {
3013
3374
  const widget = widgetObjectOf(ref);
@@ -3017,7 +3378,7 @@ function createFocus(ctx, { fields, rights, events, cursor }, fill) {
3017
3378
  const here = buttons.findIndex((row) => widgetObjectOf(row.ref) === widget);
3018
3379
  if (here < 0 || buttons.length < 2) return false;
3019
3380
  const next = buttons[(here + (backward ? buttons.length - 1 : 1)) % buttons.length];
3020
- if (!cursor.goTo(next, false)) return false;
3381
+ if (cursor.goTo(next, false) !== "taken") return false;
3021
3382
  const button = radioButtonOf(field, widgetObjectOf(next.ref));
3022
3383
  if (button) {
3023
3384
  const activate = () => void fill.activateWidget(next.ref).catch(() => {});
@@ -3035,6 +3396,35 @@ function createFocus(ctx, { fields, rights, events, cursor }, fill) {
3035
3396
  } };
3036
3397
  }
3037
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
3038
3428
  //#region src/write/interchange.ts
3039
3429
  function createInterchange(ctx, services) {
3040
3430
  const { enqueue, siblings } = services;
@@ -3093,13 +3483,18 @@ function createInterchange(ctx, services) {
3093
3483
  * change as the rest of it. While the tool fills, nothing is lent, and the
3094
3484
  * form layer draws and fills every widget. A widget of no size is never lent:
3095
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.
3096
3489
  */
3097
3490
  const objectNumberOf = (ref) => ref.kind === "objectNumber" ? ref.objectNumber : -1;
3098
- function createWidgetLender(ctx, { fields, design, pictures, looks }, copyOps) {
3491
+ function createWidgetLender(ctx, { fields, design, pictures, looks, groups }, copyOps) {
3099
3492
  const records = memo(() => [
3100
3493
  design.lending(),
3101
3494
  fields.get().snapshot,
3102
- fields.view().snapshot
3495
+ fields.view().snapshot,
3496
+ groups.list(),
3497
+ ctx.settings().get().fields.tint
3103
3498
  ], (lending, confirmed, shown) => lending && confirmed && shown ? {
3104
3499
  confirmed: confirmed.widgets.filter(hasArea),
3105
3500
  shown: shown.widgets.filter(hasArea)
@@ -3183,6 +3578,10 @@ function createWidgetLender(ctx, { fields, design, pictures, looks }, copyOps) {
3183
3578
  getPictureVersion: pictures.versionOf,
3184
3579
  renderAppearances: pictures.render,
3185
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
+ },
3186
3585
  painter: (record) => record.subtype === "widget" ? looks.painterOf(record) : null
3187
3586
  };
3188
3587
  }
@@ -3620,6 +4019,7 @@ function createFormController(ctx) {
3620
4019
  const typing = createTyping(ctx, services, values.setText);
3621
4020
  const resets = createResetWrites(ctx, services, fills);
3622
4021
  const design = createFieldWrites(ctx, services);
4022
+ const groups = createGroupWrites(ctx, services);
3623
4023
  const interchange = createInterchange(ctx, services);
3624
4024
  const activation = createActivation(ctx, services, fills);
3625
4025
  const scripts = createScriptEffects(ctx, services, fills);
@@ -3636,6 +4036,7 @@ function createFormController(ctx) {
3636
4036
  typing.api,
3637
4037
  resets.api,
3638
4038
  design.api,
4039
+ groups.api,
3639
4040
  interchange.api,
3640
4041
  activation.api,
3641
4042
  scripts.api,
@@ -3654,7 +4055,9 @@ function createFormController(ctx) {
3654
4055
  onFieldUpdated: events.fieldUpdated.on,
3655
4056
  onFieldDeleted: events.fieldDeleted.on,
3656
4057
  onValidationRejected: events.validationRejected.on,
3657
- onResynced: events.resynced.on
4058
+ onResynced: events.resynced.on,
4059
+ onDesignGroupChanged: events.designGroupChanged.on,
4060
+ onGroupsChanged: events.groupsChanged.on
3658
4061
  }
3659
4062
  ]);
3660
4063
  return {
@@ -3674,7 +4077,8 @@ function createFormController(ctx) {
3674
4077
  * the annotation plugin present, the form lends it the widgets, which its
3675
4078
  * tools then select, move, restyle and delete. The render plugin draws the
3676
4079
  * widgets' pictures in both modes. With the fonts plugin, a text field in a
3677
- * 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
3678
4082
  * registers, over {@link FORM_DEFAULTS}.
3679
4083
  */
3680
4084
  const formPlugin = (config) => definePlugin({
@@ -3686,7 +4090,8 @@ const formPlugin = (config) => definePlugin({
3686
4090
  AnnotationToken,
3687
4091
  ActionsToken,
3688
4092
  RenderToken,
3689
- FontsToken
4093
+ FontsToken,
4094
+ StageToken
3690
4095
  ],
3691
4096
  state: initialFormModel,
3692
4097
  settings: {
@@ -3695,20 +4100,35 @@ const formPlugin = (config) => definePlugin({
3695
4100
  },
3696
4101
  create: createFormController
3697
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([]);
3698
4112
  const formState = defineState(FormToken, {
3699
4113
  read: (form) => ({
3700
4114
  fields: form.list(),
3701
4115
  status: form.getStatus(),
3702
4116
  formKind: form.getFormKind(),
3703
4117
  selectedField: form.getSelectedField(),
3704
- focusedField: form.getFocusedField()
4118
+ focusedField: form.getFocusedField(),
4119
+ selectedFields: form.listSelectedFields(),
4120
+ groups: form.listGroups(),
4121
+ designGroup: form.getDesignGroup()
3705
4122
  }),
3706
4123
  empty: {
3707
- fields: Object.freeze([]),
4124
+ fields: NO_FIELDS,
3708
4125
  status: "idle",
3709
4126
  formKind: "none",
3710
4127
  selectedField: null,
3711
- focusedField: null
4128
+ focusedField: null,
4129
+ selectedFields: NO_FIELDS,
4130
+ groups: Object.freeze([]),
4131
+ designGroup: null
3712
4132
  }
3713
4133
  });
3714
4134
  //#endregion