@folijs/react 0.5.0 → 1.0.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.
@@ -3,31 +3,54 @@ import {
3
3
  acceptAllChanges,
4
4
  acceptChange,
5
5
  addComment,
6
+ addRepeatingItem,
6
7
  alignAt,
7
8
  type Command,
9
+ type ControlJSON,
8
10
  canOutdent,
9
11
  changeIndent,
10
12
  colorAt,
13
+ controlAt,
14
+ controlProperties,
15
+ convertNotes,
16
+ crossReferenceTargets,
11
17
  deleteColumns,
12
18
  deleteRows,
13
19
  deleteTable,
20
+ documentSections,
14
21
  type Editor,
15
22
  type EditorState,
23
+ type FieldLayout,
24
+ fieldCodesShown,
25
+ fieldsIn,
16
26
  fontFamilyAt,
17
27
  fontSizeAt,
18
28
  insertColumn,
29
+ insertColumnBreak,
30
+ insertControl,
31
+ insertCrossReference,
32
+ insertDate,
33
+ insertNote,
19
34
  insertPageBreak,
35
+ insertPageNumber,
20
36
  insertPicture,
21
37
  insertRow,
38
+ insertSectionBreak,
22
39
  insertTable,
40
+ insertTableOfContents,
23
41
  isHeaderRow,
24
42
  isSafeHref,
25
43
  lineSpacingAt,
26
44
  linkAt,
27
45
  listKindAt,
28
46
  mergeCells,
47
+ type NavigationRequest,
48
+ type NoteKind,
49
+ type NotePropertiesJSON,
29
50
  nextChange,
30
51
  normalizeHref,
52
+ noteAtSelection,
53
+ noteProperties,
31
54
  openLinkEditor,
32
55
  paragraphStyleAt,
33
56
  paragraphStyles,
@@ -38,33 +61,47 @@ import {
38
61
  rejectAllChanges,
39
62
  rejectChange,
40
63
  removeLink,
64
+ removeSectionBreak,
41
65
  requestsLinkEditor,
66
+ type SectionJSON,
67
+ type SectionSetup,
68
+ type StorySide,
69
+ sectionAt,
42
70
  selectedPicture,
43
71
  setAlign,
44
72
  setCellShading,
73
+ setControlProperties,
74
+ setDifferentEvenPages,
75
+ setDifferentFirstPage,
45
76
  setFontFamily,
46
77
  setFontSize,
47
78
  setHighlight,
48
79
  setLineSpacing,
49
80
  setLink,
81
+ setNoteProperties,
50
82
  setParagraphStyle,
51
83
  setPictureAlt,
52
84
  setPictureSize,
53
85
  setReviewView,
86
+ setSectionSetup,
87
+ setStoryLinked,
54
88
  setTableStyle,
55
89
  setTextColor,
56
90
  setTrackChanges,
57
91
  splitCell,
58
92
  tableStyleAt,
59
93
  tableStyles,
94
+ toggleFieldCodes,
60
95
  toggleHeaderRow,
61
96
  toggleList,
62
97
  toggleMark,
63
98
  trackState,
99
+ type UpdateFieldsOptions,
64
100
  undo,
65
101
  undoDepth,
66
- wordContext,
102
+ updateFields,
67
103
  } from "@folijs/core";
104
+ import { wordContext } from "@folijs/core/internal";
68
105
  import { type EditorViewOptions, EMU_PER_PX, measureImageFile, textWidthEmu } from "@folijs/view";
69
106
  import {
70
107
  type FormEvent,
@@ -78,7 +115,13 @@ import {
78
115
  useRef,
79
116
  useState,
80
117
  } from "react";
81
- import { useEditorOrContext, useEditorState } from "./editor.js";
118
+ import {
119
+ development,
120
+ sameItems,
121
+ useActiveEditor,
122
+ useEditorOrContext,
123
+ useEditorState,
124
+ } from "./editor.js";
82
125
 
83
126
  export interface FoliToolbarProps {
84
127
  /** Default: the editor of the nearest `FoliEditorProvider`. */
@@ -105,29 +148,82 @@ export interface FoliToolbarProps {
105
148
  * inserts one from a file; without it, it only edits a selected picture.
106
149
  */
107
150
  upload?: EditorViewOptions["upload"] | undefined;
151
+ /**
152
+ * The items, in groups (a separator between groups), in place of `defaultToolbarItems`: the
153
+ * built-in ones from `toolbarItems`, and the app's own. "New comment" shows only with
154
+ * `comments`; an empty group is left out.
155
+ */
156
+ items?: readonly (readonly ToolbarItem[])[] | undefined;
108
157
  className?: string | undefined;
109
158
  }
110
159
 
111
- interface Item {
112
- key: string;
113
- /** Tooltip: what the button does. */
114
- label: string;
115
- /** Visible text: the accessible name, unless it is a symbol (then the label is). */
116
- text: string;
117
- symbol?: boolean;
118
- /** Shown instead of `text` (a symbol: the label is the name). */
119
- icon?: ReactNode;
120
- /** Whether the button shows as pressed (toggle buttons only). */
121
- pressed?: (state: EditorState, editor: Editor) => boolean;
160
+ /** What every toolbar item has. */
161
+ interface ToolbarItemBase {
162
+ /** Unique in the toolbar; also its class, `foli-toolbar-<key>`. */
163
+ readonly key: string;
164
+ /** What it does: the tooltip, and the accessible name when an `icon` stands for the text. */
165
+ readonly label: string;
166
+ /** Visible text, which is then the accessible name (default `label`). */
167
+ readonly text?: string | undefined;
168
+ /** Shown instead of the text (a symbol or an SVG): `label` is then the accessible name. */
169
+ readonly icon?: ReactNode | undefined;
170
+ /**
171
+ * Whether it can be used now. Default: a button's dry run of its `command` (`editor.can`); for
172
+ * a menu, whether it has entries. Runs after every transaction: keep it cheap.
173
+ */
174
+ readonly enabled?: ((state: EditorState, editor: Editor) => boolean) | undefined;
175
+ }
176
+
177
+ /** A toolbar button that runs a command. */
178
+ export interface ToolbarButton extends ToolbarItemBase {
122
179
  /**
123
- * Whether the command can run now (default: always; a paragraph takes every mark and a page
124
- * break). A cheap check, not a dry
125
- * run: it runs after every transaction, and a dry run builds the whole transaction (for a
126
- * block type over a large selection, quadratic in the number of blocks).
180
+ * What a press runs, on the editor of the header, footer or note open on its page, else the
181
+ * body's (as the built-in buttons do).
127
182
  */
128
- enabled?: (state: EditorState) => boolean;
129
- /** The command a press runs (not for a menu button). */
130
- command?: (state: EditorState) => Command;
183
+ readonly command: Command;
184
+ /** A toggle: whether it shows as pressed (`aria-pressed`). Runs after every transaction. */
185
+ readonly pressed?: ((state: EditorState, editor: Editor) => boolean) | undefined;
186
+ readonly actions?: undefined;
187
+ }
188
+
189
+ /** A toolbar menu button: a WAI-ARIA menu of its `actions`. */
190
+ export interface ToolbarMenu extends ToolbarItemBase {
191
+ /**
192
+ * Its entries, in order, or a function of the body's editor making them (as the built-in
193
+ * menus do). Each entry is dry-run when the menu opens; without entries the button is disabled.
194
+ */
195
+ readonly actions: readonly ToolbarAction[] | ((editor: Editor) => readonly ToolbarAction[]);
196
+ readonly command?: undefined;
197
+ readonly pressed?: undefined;
198
+ }
199
+
200
+ /**
201
+ * A toolbar item, built-in (`toolbarItems`) or the app's own: a button running a command, or a
202
+ * menu button. The toolbar keeps one tab stop for all its items (arrow keys, Home and End move
203
+ * between them), gives toggles `aria-pressed` and an item that cannot apply now `aria-disabled`
204
+ * (still focusable), and leaves the focus and selection in the document on click.
205
+ */
206
+ export type ToolbarItem = ToolbarButton | ToolbarMenu;
207
+
208
+ /** An entry of a toolbar menu (a `menuitem`, or a `menuitemcheckbox` when it has `checked`). */
209
+ export interface ToolbarAction {
210
+ /** Unique in its menu. */
211
+ readonly key: string;
212
+ readonly label: string;
213
+ /** What it runs; a dry run when the menu opens decides whether it is enabled. */
214
+ readonly command: Command;
215
+ /** A checkable entry: whether it is checked (with the same arguments as `pressed`). */
216
+ readonly checked?: ((state: EditorState, editor: Editor) => boolean) | undefined;
217
+ }
218
+
219
+ /**
220
+ * A built-in item: boxes, color menus and dialogs are only the toolbar's own. Each has its own
221
+ * cheap `enabled`, not a dry run: that runs after every transaction, and a dry run builds the
222
+ * whole transaction (for a block type over a large selection, quadratic in the number of blocks).
223
+ */
224
+ interface Item extends ToolbarItemBase {
225
+ command?: Command | undefined;
226
+ pressed?: ((state: EditorState, editor: Editor) => boolean) | undefined;
131
227
  /** A menu button: its options, the current value, and what picking one runs. */
132
228
  menu?: {
133
229
  options: readonly ColorOption[];
@@ -135,7 +231,7 @@ interface Item {
135
231
  pick: (color: string | null) => Command;
136
232
  };
137
233
  /** An action menu button (the table menu): its commands, in order. */
138
- actions?: readonly Action[];
234
+ actions?: readonly Action[] | ((editor: Editor) => readonly Action[]) | undefined;
139
235
  /** A button opening a dialog (the picture's). */
140
236
  dialog?: "picture";
141
237
  /** A drop-down list (a `select`): its options, the current value, and what picking runs. */
@@ -146,14 +242,12 @@ interface Item {
146
242
  };
147
243
  }
148
244
 
149
- /** A command in an action menu (a menuitem, or a menuitemcheckbox when it has `checked`). */
150
- interface Action {
151
- key: string;
152
- label: string;
153
- /** The command it runs; `insertTable` opens the dialog that asks for the size instead. */
154
- command: Command;
155
- dialog?: "insertTable";
156
- checked?: (state: EditorState) => boolean;
245
+ /** A built-in menu's entry: it may open a dialog or move the focus. */
246
+ interface Action extends ToolbarAction {
247
+ /** With `dialog`, `command` says whether it applies: the dialog does the rest. */
248
+ dialog?: "insertTable" | "pageSetup" | "crossReference" | "controlProperties" | "noteOptions";
249
+ /** It takes the focus where it belongs (into a story, or back to the body). */
250
+ movesFocus?: boolean;
157
251
  }
158
252
 
159
253
  interface ColorOption {
@@ -227,6 +321,269 @@ const TABLE_ACTIONS: readonly Action[] = [
227
321
  },
228
322
  ];
229
323
 
324
+ const SECTION_ACTIONS: readonly Action[] = [
325
+ {
326
+ key: "pageSetup",
327
+ label: "Page setup…",
328
+ command: (state) => sectionAt(state) !== null,
329
+ dialog: "pageSetup",
330
+ },
331
+ { key: "breakNext", label: "Section break: next page", command: insertSectionBreak("nextPage") },
332
+ {
333
+ key: "breakContinuous",
334
+ label: "Section break: continuous",
335
+ command: insertSectionBreak("continuous"),
336
+ },
337
+ { key: "breakEven", label: "Section break: even page", command: insertSectionBreak("evenPage") },
338
+ { key: "breakOdd", label: "Section break: odd page", command: insertSectionBreak("oddPage") },
339
+ { key: "removeBreak", label: "Remove section break", command: removeSectionBreak },
340
+ { key: "columnBreak", label: "Column break", command: insertColumnBreak },
341
+ ];
342
+
343
+ /**
344
+ * The header and footer menu: opening them on the caret's page, and, for the one open (else the
345
+ * caret's section), what a section does about them.
346
+ */
347
+ function storyActions(body: Editor): readonly Action[] {
348
+ const open = () => body.storyView?.open ?? null;
349
+ const setup = (state: EditorState) => {
350
+ const index = open()?.section ?? sectionAt(state)?.index ?? 0;
351
+ return documentSections(state)[index]?.setup ?? {};
352
+ };
353
+ const edit =
354
+ (side: StorySide): Command =>
355
+ (_state, dispatch) => {
356
+ const view = body.storyView;
357
+ if (!view) return false;
358
+ if (dispatch) view.edit(side);
359
+ return true;
360
+ };
361
+ const linked = (state: EditorState) => {
362
+ const story = open();
363
+ if (!story) return false;
364
+ if (story.side === "note") return false;
365
+ const references = story.side === "header" ? setup(state).headers : setup(state).footers;
366
+ return !references?.[story.variant];
367
+ };
368
+ const evenPages = (state: EditorState) =>
369
+ wordContext(state)?.envelope.settings?.evenAndOddHeaders === true;
370
+ return [
371
+ { key: "editHeader", label: "Edit header", command: edit("header"), movesFocus: true },
372
+ { key: "editFooter", label: "Edit footer", command: edit("footer"), movesFocus: true },
373
+ {
374
+ key: "closeStory",
375
+ label: "Close header and footer",
376
+ movesFocus: true,
377
+ command: (_state, dispatch) => {
378
+ if (!open()) return false;
379
+ if (dispatch) body.storyView?.close();
380
+ return true;
381
+ },
382
+ },
383
+ {
384
+ key: "firstPage",
385
+ label: "Different first page",
386
+ checked: (state) => setup(state).titlePage === true,
387
+ command: (state, dispatch) =>
388
+ setDifferentFirstPage(setup(state).titlePage !== true, open()?.section)(state, dispatch),
389
+ },
390
+ {
391
+ key: "evenPages",
392
+ label: "Different odd and even pages",
393
+ checked: evenPages,
394
+ command: (state, dispatch) => setDifferentEvenPages(!evenPages(state))(state, dispatch),
395
+ },
396
+ {
397
+ key: "linkPrevious",
398
+ label: "Link to previous",
399
+ checked: linked,
400
+ command: (state, dispatch) => {
401
+ const story = open();
402
+ return story && story.side !== "note"
403
+ ? setStoryLinked(
404
+ story.side,
405
+ story.variant,
406
+ !linked(state),
407
+ story.section,
408
+ )(state, dispatch)
409
+ : false;
410
+ },
411
+ },
412
+ ];
413
+ }
414
+
415
+ /**
416
+ * The notes menu: a new note (the caret goes into it), between a reference and its note, the
417
+ * conversions Word has, and the options dialog.
418
+ */
419
+ function noteActions(body: Editor): readonly Action[] {
420
+ const insert =
421
+ (kind: NoteKind): Command =>
422
+ (state, dispatch) => {
423
+ if (!insertNote(kind)(state)) return false;
424
+ if (dispatch) {
425
+ insertNote(kind)(state, dispatch);
426
+ body.storyView?.editNote();
427
+ }
428
+ return true;
429
+ };
430
+ return [
431
+ { key: "footnote", label: "Insert footnote", command: insert("footnote"), movesFocus: true },
432
+ { key: "endnote", label: "Insert endnote", command: insert("endnote"), movesFocus: true },
433
+ {
434
+ key: "goToNote",
435
+ label: "Go to note or reference",
436
+ movesFocus: true,
437
+ command: (state, dispatch) => {
438
+ const view = body.storyView;
439
+ if (!view) return false;
440
+ if (view.open?.side === "note") {
441
+ if (dispatch) view.toReference();
442
+ return true;
443
+ }
444
+ if (!noteAtSelection(state)) return false;
445
+ if (dispatch) view.editNote();
446
+ return true;
447
+ },
448
+ },
449
+ {
450
+ key: "toEndnotes",
451
+ label: "Convert footnotes to endnotes",
452
+ command: (_state, dispatch) => convertNotes("endnote")(body.state, dispatch && body.dispatch),
453
+ },
454
+ {
455
+ key: "toFootnotes",
456
+ label: "Convert endnotes to footnotes",
457
+ command: (_state, dispatch) =>
458
+ convertNotes("footnote")(body.state, dispatch && body.dispatch),
459
+ },
460
+ {
461
+ key: "noteOptions",
462
+ label: "Note options…",
463
+ dialog: "noteOptions",
464
+ command: (state) => wordContext(state) !== null,
465
+ },
466
+ ];
467
+ }
468
+
469
+ /** The control the selection is in. */
470
+ const selectedControl = (state: EditorState) => {
471
+ const range = controlAt(state.doc, state.selection.from);
472
+ const control = range && controlProperties(state, range.id);
473
+ return range && control ? { id: range.id, control } : null;
474
+ };
475
+
476
+ /** The content controls menu: each kind to insert, then what applies to the one at the caret. */
477
+ const CONTROL_ACTIONS: readonly Action[] = [
478
+ { key: "richText", label: "Rich text", command: insertControl("richText") },
479
+ { key: "plainText", label: "Plain text", command: insertControl("text") },
480
+ { key: "dropDown", label: "Drop-down list", command: insertControl("dropDown") },
481
+ { key: "comboBox", label: "Combo box", command: insertControl("comboBox") },
482
+ { key: "datePicker", label: "Date picker", command: insertControl("date") },
483
+ { key: "checkBox", label: "Check box", command: insertControl("checkbox") },
484
+ { key: "pictureControl", label: "Picture (selected)", command: insertControl("picture") },
485
+ { key: "repeating", label: "Repeating section", command: insertControl("repeating") },
486
+ { key: "repeatingItem", label: "Add repeating item", command: addRepeatingItem() },
487
+ {
488
+ key: "controlProperties",
489
+ label: "Control properties…",
490
+ dialog: "controlProperties",
491
+ command: (state) => selectedControl(state) !== null,
492
+ },
493
+ ];
494
+
495
+ /**
496
+ * The navigation menu: what `FoliNavigation` shows, with Word's keys. Nothing applies without it.
497
+ */
498
+ function navigationActions(body: Editor): readonly Action[] {
499
+ const open =
500
+ (request: NavigationRequest): Command =>
501
+ (_state, dispatch) => {
502
+ if (!body.navigation) return false;
503
+ if (dispatch) body.navigation(request);
504
+ return true;
505
+ };
506
+ const item = (key: NavigationRequest, label: string): Action => ({
507
+ key,
508
+ label,
509
+ command: open(key),
510
+ movesFocus: true,
511
+ });
512
+ return [
513
+ item("find", "Find\u2026"),
514
+ item("replace", "Replace\u2026"),
515
+ item("goTo", "Go to\u2026"),
516
+ item("bookmarks", "Bookmarks\u2026"),
517
+ item("outline", "Outline"),
518
+ ];
519
+ }
520
+
521
+ /**
522
+ * The fields menu: what can be inserted at the selection, updating (the view's pages when there is
523
+ * one) and the codes shown or hidden.
524
+ */
525
+ function fieldActions(body: Editor): readonly Action[] {
526
+ const layout = () => body.storyView?.fieldLayout ?? null;
527
+ const active = () => {
528
+ const open = body.storyView?.open;
529
+ return (open && body.story(open.id)) || body;
530
+ };
531
+ const update = (editor: Editor, options: UpdateFieldsOptions) =>
532
+ body.storyView ? body.storyView.updateFields(options, editor) : updateFields(editor, options);
533
+ return [
534
+ {
535
+ key: "pageNumber",
536
+ label: "Page number",
537
+ command: (state, dispatch) => insertPageNumber({ layout: layout() })(state, dispatch),
538
+ },
539
+ { key: "date", label: "Date", command: insertDate() },
540
+ {
541
+ key: "crossReference",
542
+ label: "Cross-reference…",
543
+ dialog: "crossReference",
544
+ command: (state) => {
545
+ const { bookmarks, headings } = crossReferenceTargets(state);
546
+ return insertPageBreak(state) && bookmarks.length + headings.length > 0;
547
+ },
548
+ },
549
+ {
550
+ key: "tableOfContents",
551
+ label: "Table of contents",
552
+ command: (state, dispatch) => {
553
+ const done = insertTableOfContents({ layout: layout() })(state, dispatch);
554
+ // Its own lines moved the headings: their page numbers follow, in the same undo step.
555
+ if (done && dispatch)
556
+ update(body, { only: (field) => field.parent?.name === "TOC", continues: true });
557
+ return done;
558
+ },
559
+ },
560
+ {
561
+ key: "updateSelected",
562
+ label: "Update selected fields",
563
+ command: (state, dispatch) => {
564
+ if (!fieldsIn(state.doc).length) return false;
565
+ const { from, to } = state.selection;
566
+ if (dispatch) update(active(), { only: { from, to } });
567
+ return true;
568
+ },
569
+ },
570
+ {
571
+ key: "updateAll",
572
+ label: "Update all fields",
573
+ command: (_state, dispatch) => {
574
+ if (dispatch) update(body, {});
575
+ return true;
576
+ },
577
+ },
578
+ {
579
+ key: "fieldCodes",
580
+ label: "Show field codes",
581
+ checked: fieldCodesShown,
582
+ command: toggleFieldCodes,
583
+ },
584
+ ];
585
+ }
586
+
230
587
  /** Whether the selection holds a textblock (a caret's own block first; else it walks the range). */
231
588
  function hasTextblock(state: EditorState): boolean {
232
589
  if (state.selection.$from.parent.isTextblock) return true;
@@ -248,24 +605,25 @@ const alignIcon = (bars: readonly [number, number][]) => (
248
605
  </svg>
249
606
  );
250
607
 
608
+ /** A paragraph takes every mark and a page break: no need for a dry run after each change. */
609
+ const always = () => true;
610
+
251
611
  const align = (value: Alignment, label: string, bars: readonly [number, number][]): Item => ({
252
612
  key: `align-${value}`,
253
613
  label,
254
- text: label,
255
- symbol: true,
256
614
  icon: alignIcon(bars),
257
615
  pressed: (state) => alignAt(state) === value,
258
616
  enabled: hasTextblock,
259
- command: () => setAlign(value),
617
+ command: setAlign(value),
260
618
  });
261
619
 
262
- const mark = (key: string, label: string, text: string): Item => ({
620
+ const mark = (key: string, label: string, icon: string): Item => ({
263
621
  key,
264
622
  label,
265
- text,
266
- symbol: true,
623
+ icon,
267
624
  pressed: (_state, editor) => editor.isMarkActive(key),
268
- command: () => toggleMark(key),
625
+ enabled: always,
626
+ command: toggleMark(key),
269
627
  });
270
628
 
271
629
  const capitalized = (name: string) => name.charAt(0).toUpperCase() + name.slice(1);
@@ -348,13 +706,12 @@ const GROUPS: Item[][] = [
348
706
  pressed: (state) => linkAt(state) !== null,
349
707
  enabled: (state) => openLinkEditor(state),
350
708
  // Asks for the link dialog, as Mod-K does: the toolbar listens for that request.
351
- command: () => openLinkEditor,
709
+ command: openLinkEditor,
352
710
  },
353
711
  {
354
712
  key: "textColor",
355
713
  label: "Text color",
356
- text: "A",
357
- symbol: true,
714
+ icon: "A",
358
715
  enabled: hasTextblock,
359
716
  menu: {
360
717
  options: TEXT_COLORS,
@@ -365,8 +722,7 @@ const GROUPS: Item[][] = [
365
722
  {
366
723
  key: "highlight",
367
724
  label: "Highlight",
368
- text: "H",
369
- symbol: true,
725
+ icon: "H",
370
726
  enabled: hasTextblock,
371
727
  menu: {
372
728
  options: HIGHLIGHTS,
@@ -420,37 +776,33 @@ const GROUPS: Item[][] = [
420
776
  {
421
777
  key: "bulletList",
422
778
  label: "Bulleted list",
423
- text: "•",
424
- symbol: true,
779
+ icon: "•",
425
780
  pressed: (state) => listKindAt(state) === "bulletList",
426
781
  enabled: hasTextblock,
427
- command: () => toggleList("bulletList"),
782
+ command: toggleList("bulletList"),
428
783
  },
429
784
  {
430
785
  key: "orderedList",
431
786
  label: "Numbered list",
432
787
  // A symbol, not "1.": visible text that is not part of the name fails WCAG 2.5.3.
433
- text: "№",
434
- symbol: true,
788
+ icon: "№",
435
789
  pressed: (state) => listKindAt(state) === "orderedList",
436
790
  enabled: hasTextblock,
437
- command: () => toggleList("orderedList"),
791
+ command: toggleList("orderedList"),
438
792
  },
439
793
  {
440
794
  key: "outdent",
441
795
  label: "Decrease indent",
442
- text: "⇤",
443
- symbol: true,
796
+ icon: "⇤",
444
797
  enabled: canOutdent,
445
- command: () => changeIndent(-1),
798
+ command: changeIndent(-1),
446
799
  },
447
800
  {
448
801
  key: "indent",
449
802
  label: "Increase indent",
450
- text: "⇥",
451
- symbol: true,
803
+ icon: "⇥",
452
804
  enabled: hasTextblock,
453
- command: () => changeIndent(1),
805
+ command: changeIndent(1),
454
806
  },
455
807
  ],
456
808
  [
@@ -459,7 +811,7 @@ const GROUPS: Item[][] = [
459
811
  label: "New comment on the selection",
460
812
  text: "New comment",
461
813
  enabled: (state) => wordContext(state) !== null && hasTextblock(state),
462
- command: () => addComment(""),
814
+ command: addComment(""),
463
815
  },
464
816
  {
465
817
  key: "trackChanges",
@@ -467,7 +819,7 @@ const GROUPS: Item[][] = [
467
819
  text: "Track changes",
468
820
  pressed: (state) => trackState(state)?.on === true,
469
821
  enabled: (state) => trackState(state) !== null,
470
- command: (state) => setTrackChanges(!trackState(state)?.on),
822
+ command: (state, dispatch) => setTrackChanges(!trackState(state)?.on)(state, dispatch),
471
823
  },
472
824
  {
473
825
  key: "reviewView",
@@ -487,42 +839,42 @@ const GROUPS: Item[][] = [
487
839
  label: "Previous change",
488
840
  text: "Previous change",
489
841
  enabled: (state) => trackState(state) !== null,
490
- command: () => previousChange,
842
+ command: previousChange,
491
843
  },
492
844
  {
493
845
  key: "nextChange",
494
846
  label: "Next change",
495
847
  text: "Next change",
496
848
  enabled: (state) => trackState(state) !== null,
497
- command: () => nextChange,
849
+ command: nextChange,
498
850
  },
499
851
  {
500
852
  key: "acceptChange",
501
853
  label: "Accept the change here, or the changes selected",
502
854
  text: "Accept",
503
855
  enabled: (state) => trackState(state) !== null,
504
- command: () => acceptChange,
856
+ command: acceptChange,
505
857
  },
506
858
  {
507
859
  key: "rejectChange",
508
860
  label: "Reject the change here, or the changes selected",
509
861
  text: "Reject",
510
862
  enabled: (state) => trackState(state) !== null,
511
- command: () => rejectChange,
863
+ command: rejectChange,
512
864
  },
513
865
  {
514
866
  key: "acceptAll",
515
867
  label: "Accept all changes",
516
868
  text: "Accept all",
517
869
  enabled: (state) => trackState(state) !== null,
518
- command: () => acceptAllChanges(),
870
+ command: acceptAllChanges(),
519
871
  },
520
872
  {
521
873
  key: "rejectAll",
522
874
  label: "Reject all changes",
523
875
  text: "Reject all",
524
876
  enabled: (state) => trackState(state) !== null,
525
- command: () => rejectAllChanges(),
877
+ command: rejectAllChanges(),
526
878
  },
527
879
  ],
528
880
  [
@@ -531,14 +883,14 @@ const GROUPS: Item[][] = [
531
883
  label: "Undo",
532
884
  text: "Undo",
533
885
  enabled: (state) => undoDepth(state) > 0,
534
- command: () => undo,
886
+ command: undo,
535
887
  },
536
888
  {
537
889
  key: "redo",
538
890
  label: "Redo",
539
891
  text: "Redo",
540
892
  enabled: (state) => redoDepth(state) > 0,
541
- command: () => redo,
893
+ command: redo,
542
894
  },
543
895
  ],
544
896
  [
@@ -585,14 +937,125 @@ const GROUPS: Item[][] = [
585
937
  // With a picture selected the dialog edits it.
586
938
  dialog: "picture",
587
939
  },
588
- { key: "pageBreak", label: "Page break", text: "Page break", command: () => insertPageBreak },
940
+ {
941
+ key: "pageBreak",
942
+ label: "Page break",
943
+ text: "Page break",
944
+ enabled: always,
945
+ command: insertPageBreak,
946
+ },
947
+ {
948
+ key: "section",
949
+ label: "Section",
950
+ text: "Section",
951
+ enabled: (state) => wordContext(state) !== null,
952
+ actions: SECTION_ACTIONS,
953
+ },
954
+ {
955
+ key: "headerFooter",
956
+ label: "Header and footer",
957
+ text: "Header",
958
+ enabled: (state) => wordContext(state) !== null,
959
+ actions: storyActions,
960
+ },
961
+ {
962
+ key: "fields",
963
+ label: "Fields",
964
+ text: "Fields",
965
+ enabled: (state) => wordContext(state) !== null,
966
+ actions: fieldActions,
967
+ },
968
+ {
969
+ key: "navigate",
970
+ label: "Find and go to",
971
+ text: "Navigate",
972
+ enabled: (state) => wordContext(state) !== null,
973
+ actions: navigationActions,
974
+ },
975
+ {
976
+ key: "notes",
977
+ label: "Footnotes and endnotes",
978
+ text: "Notes",
979
+ enabled: (state) => wordContext(state) !== null,
980
+ actions: noteActions,
981
+ },
982
+ {
983
+ key: "controls",
984
+ label: "Content controls",
985
+ text: "Controls",
986
+ enabled: (state) => wordContext(state) !== null,
987
+ actions: CONTROL_ACTIONS,
988
+ },
589
989
  ],
590
990
  ];
591
991
 
592
- const ITEMS = GROUPS.flat();
593
- /** Without "New comment": where no comments pane lets a comment be written. */
594
- const GROUPS_NO_COMMENT = GROUPS.map((group) => group.filter((i) => i.key !== "newComment"));
595
- const ITEMS_NO_COMMENT = GROUPS_NO_COMMENT.flat();
992
+ /** The names of the built-in items in `toolbarItems`. */
993
+ export type ToolbarItemName =
994
+ | "style"
995
+ | "font"
996
+ | "size"
997
+ | "bold"
998
+ | "italic"
999
+ | "underline"
1000
+ | "strike"
1001
+ | "link"
1002
+ | "textColor"
1003
+ | "highlight"
1004
+ | "alignStart"
1005
+ | "alignCenter"
1006
+ | "alignEnd"
1007
+ | "alignJustify"
1008
+ | "lineSpacing"
1009
+ | "bulletList"
1010
+ | "orderedList"
1011
+ | "outdent"
1012
+ | "indent"
1013
+ | "newComment"
1014
+ | "trackChanges"
1015
+ | "reviewView"
1016
+ | "previousChange"
1017
+ | "nextChange"
1018
+ | "acceptChange"
1019
+ | "rejectChange"
1020
+ | "acceptAll"
1021
+ | "rejectAll"
1022
+ | "undo"
1023
+ | "redo"
1024
+ | "table"
1025
+ | "tableStyle"
1026
+ | "cellShading"
1027
+ | "picture"
1028
+ | "pageBreak"
1029
+ | "section"
1030
+ | "headerFooter"
1031
+ | "fields"
1032
+ | "navigate"
1033
+ | "notes"
1034
+ | "controls";
1035
+
1036
+ /** The built-in menu buttons of `actions` (the color menus and boxes are buttons to an app). */
1037
+ type ToolbarMenuName =
1038
+ | "table"
1039
+ | "section"
1040
+ | "headerFooter"
1041
+ | "fields"
1042
+ | "navigate"
1043
+ | "notes"
1044
+ | "controls";
1045
+
1046
+ /**
1047
+ * The built-in items by name, to place in `FoliToolbarProps.items` (an item's `key` is its name,
1048
+ * except the alignments: `align-start`, `align-center`, `align-end`, `align-justify`). A copy
1049
+ * with another `label` or `icon` keeps what the built-in does.
1050
+ */
1051
+ export const toolbarItems = Object.fromEntries(
1052
+ GROUPS.flat().map((item) => [item.key.replace(/-(\w)/, (_, c: string) => c.toUpperCase()), item]),
1053
+ ) as unknown as {
1054
+ readonly [Name in ToolbarItemName]: Name extends ToolbarMenuName ? ToolbarMenu : ToolbarButton;
1055
+ };
1056
+
1057
+ /** The default toolbar: groups of `toolbarItems`, a separator between groups. */
1058
+ export const defaultToolbarItems = GROUPS as unknown as readonly (readonly ToolbarItem[])[];
596
1059
 
597
1060
  interface LinkDialogState {
598
1061
  /** The link at the selection when the dialog opened ("" for none). */
@@ -619,26 +1082,43 @@ const sameStates = (a: ItemState[], b: ItemState[]) =>
619
1082
  item.value === b[i]?.value,
620
1083
  );
621
1084
 
622
- /** Runs after every transaction: O(selection), no transactions built. */
1085
+ /**
1086
+ * Runs after every transaction: the built-ins' checks are O(selection), no transactions built;
1087
+ * an app's item without `enabled` gets a dry run of its command.
1088
+ */
623
1089
  const statesOf =
624
- (items: readonly Item[]) =>
1090
+ (items: readonly Item[], body: Editor) =>
625
1091
  (state: EditorState, editor: Editor): ItemState[] =>
626
1092
  items.map((item) => ({
627
1093
  pressed: item.pressed?.(state, editor),
628
- enabled: item.enabled?.(state) ?? true,
1094
+ enabled: item.enabled
1095
+ ? item.enabled(state, editor)
1096
+ : item.actions
1097
+ ? actionsOf(item, body).length > 0
1098
+ : !item.command || editor.can(item.command),
629
1099
  value:
630
1100
  item.menu?.value(state) ??
631
1101
  item.select?.value(state) ??
632
1102
  (item.dialog ? (selectedPicture(state) ? "edit" : "insert") : undefined),
633
1103
  }));
634
- const selectStates = statesOf(ITEMS);
635
- const selectStatesNoComment = statesOf(ITEMS_NO_COMMENT);
1104
+
1105
+ /** A menu button's entries (made from the body's editor when a function). */
1106
+ const actionsOf = (item: Item, body: Editor): readonly Action[] =>
1107
+ typeof item.actions === "function" ? item.actions(body) : (item.actions ?? []);
1108
+
1109
+ /** The same groups of the same items (an inline `items` array is not a change). */
1110
+ const sameGroups = (
1111
+ a: readonly (readonly ToolbarItem[])[] | undefined,
1112
+ b: readonly (readonly ToolbarItem[])[] | undefined,
1113
+ ) =>
1114
+ a === b || (!!a && !!b && a.length === b.length && a.every((group, i) => sameItems(group, b[i])));
636
1115
 
637
1116
  /**
638
- * Word's formatting controls for an editor: paragraph style, font and size boxes, marks, link (a
639
- * dialog, also on Mod-K in the document), text color and highlight menus, alignment and line
640
- * spacing, lists (bulleted, numbered, decrease and increase indent), undo, redo, tables (a Table
641
- * menu with an insert table dialog, a table style box, a cell shading menu), page break.
1117
+ * Word's formatting controls for an editor (`defaultToolbarItems`, or `items`): paragraph
1118
+ * style, font and size boxes, marks, link (a dialog, also on Mod-K in the document), text color
1119
+ * and highlight menus, alignment and line spacing, lists (bulleted, numbered, decrease and
1120
+ * increase indent), undo, redo, tables (a Table menu with an insert table dialog, a table style
1121
+ * box, a cell shading menu), page break.
642
1122
  * One tab stop (arrow keys, Home and End move between buttons); toggles carry
643
1123
  * `aria-pressed`; a button whose command cannot run now is `aria-disabled` (still focusable).
644
1124
  * Clicks leave the focus and selection in the document.
@@ -651,15 +1131,32 @@ export function FoliToolbar({
651
1131
  className,
652
1132
  comments = false,
653
1133
  upload,
1134
+ items: itemGroups,
654
1135
  }: FoliToolbarProps) {
655
- const editor = useEditorOrContext(given, "FoliToolbar");
656
- const groups = comments ? GROUPS : GROUPS_NO_COMMENT;
657
- const items = comments ? ITEMS : ITEMS_NO_COMMENT;
658
- const states = useEditorState(comments ? selectStates : selectStatesNoComment, {
659
- editor,
660
- isEqual: sameStates,
661
- });
662
- const [active, setActive] = useState(0);
1136
+ const body = useEditorOrContext(given, "FoliToolbar");
1137
+ // A story open on its page takes the formatting commands; the body otherwise.
1138
+ const editor = useActiveEditor(body);
1139
+ // Without "New comment" where no comments pane lets a comment be written.
1140
+ const lastGroups = useRef(itemGroups);
1141
+ if (!sameGroups(lastGroups.current, itemGroups)) lastGroups.current = itemGroups;
1142
+ const stableGroups = lastGroups.current;
1143
+ const { groups, items, selectStates } = useMemo(() => {
1144
+ const groups = ((stableGroups ?? GROUPS) as readonly (readonly Item[])[])
1145
+ .map((group) => group.filter((item) => comments || item.key !== "newComment"))
1146
+ .filter((group) => group.length > 0);
1147
+ const items = groups.flat();
1148
+ if (development()) {
1149
+ const keys = items.map((item) => item.key);
1150
+ const twice = keys.find((key, i) => keys.indexOf(key) !== i);
1151
+ if (twice !== undefined)
1152
+ console.warn(`FoliToolbar: two items have the key "${twice}"; each needs its own`);
1153
+ }
1154
+ return { groups, items, selectStates: statesOf(items, body) };
1155
+ }, [stableGroups, comments, body]);
1156
+ const states = useEditorState(selectStates, { editor, isEqual: sameStates });
1157
+ const [focused, setActive] = useState(0);
1158
+ // The tab stop stays on the toolbar when items are taken away.
1159
+ const active = focused < items.length ? focused : 0;
663
1160
  const buttons = useRef<(HTMLButtonElement | HTMLSelectElement | null)[]>([]);
664
1161
  // Whether a select box was last used with the pointer (its pick then goes back to the document).
665
1162
  const pointer = useRef(false);
@@ -685,6 +1182,7 @@ export function FoliToolbar({
685
1182
  });
686
1183
  return;
687
1184
  }
1185
+ if (item.actions && !actionsOf(item, body).length) return;
688
1186
  if (item.menu || item.actions) {
689
1187
  if (menu !== item.key) {
690
1188
  setMenu(item.key);
@@ -697,7 +1195,7 @@ export function FoliToolbar({
697
1195
  return;
698
1196
  }
699
1197
  if (!item.command) return;
700
- editor.run(item.command(editor.state));
1198
+ editor.run(item.command);
701
1199
  // `detail` counts pointer clicks; Enter and Space on a button give 0.
702
1200
  if (event.detail > 0) onClickCommand?.();
703
1201
  };
@@ -722,6 +1220,38 @@ export function FoliToolbar({
722
1220
  ? null
723
1221
  : current,
724
1222
  );
1223
+ // The cross-reference dialog inserts at the selection it opened on.
1224
+ setReferenceDialog((current) =>
1225
+ current &&
1226
+ (!transactions.length ||
1227
+ transactions.some((tr) => tr.docChanged) ||
1228
+ !state.selection.eq(current.selection))
1229
+ ? null
1230
+ : current,
1231
+ );
1232
+ setNoteDialog((current) =>
1233
+ current && (!transactions.length || transactions.some((tr) => tr.docChanged))
1234
+ ? null
1235
+ : current,
1236
+ );
1237
+ // The control properties dialog is for the control it opened on.
1238
+ setControlDialog((current) =>
1239
+ current &&
1240
+ (!transactions.length ||
1241
+ transactions.some((tr) => tr.docChanged) ||
1242
+ !state.selection.eq(current.selection))
1243
+ ? null
1244
+ : current,
1245
+ );
1246
+ // So is the page setup dialog: its section may have changed.
1247
+ setSetupDialog((current) =>
1248
+ current &&
1249
+ (!transactions.length ||
1250
+ transactions.some((tr) => tr.docChanged) ||
1251
+ !state.selection.eq(current.selection))
1252
+ ? null
1253
+ : current,
1254
+ );
725
1255
  // The insert table dialog is for the caret it opened on, as the link dialog is.
726
1256
  setTableDialog((current) =>
727
1257
  current &&
@@ -742,6 +1272,9 @@ export function FoliToolbar({
742
1272
  const active = typeof document === "undefined" ? null : document.activeElement;
743
1273
  setTableDialog(null);
744
1274
  setPictureDialog(null);
1275
+ setSetupDialog(null);
1276
+ setReferenceDialog(null);
1277
+ setControlDialog(null);
745
1278
  setDialog((current) =>
746
1279
  current
747
1280
  ? { ...current, request: current.request + 1 }
@@ -772,6 +1305,35 @@ export function FoliToolbar({
772
1305
  useEffect(() => {
773
1306
  if (disabled) setTableDialog(null);
774
1307
  }, [disabled]);
1308
+ // The page setup dialog (from the section menu), for the section of the caret it opened on.
1309
+ const [setupDialog, setSetupDialog] = useState<{
1310
+ restore: HTMLElement | null;
1311
+ selection: EditorState["selection"];
1312
+ } | null>(null);
1313
+ useEffect(() => {
1314
+ if (disabled) setSetupDialog(null);
1315
+ }, [disabled]);
1316
+ // The cross-reference dialog (from the fields menu).
1317
+ const [referenceDialog, setReferenceDialog] = useState<{
1318
+ restore: HTMLElement | null;
1319
+ selection: EditorState["selection"];
1320
+ } | null>(null);
1321
+ useEffect(() => {
1322
+ if (disabled) setReferenceDialog(null);
1323
+ }, [disabled]);
1324
+ // The control properties dialog (from the content controls menu).
1325
+ const [controlDialog, setControlDialog] = useState<{
1326
+ restore: HTMLElement | null;
1327
+ selection: EditorState["selection"];
1328
+ } | null>(null);
1329
+ useEffect(() => {
1330
+ if (disabled) setControlDialog(null);
1331
+ }, [disabled]);
1332
+ // The note options dialog (from the notes menu).
1333
+ const [noteDialog, setNoteDialog] = useState<{ restore: HTMLElement | null } | null>(null);
1334
+ useEffect(() => {
1335
+ if (disabled) setNoteDialog(null);
1336
+ }, [disabled]);
775
1337
  // The picture dialog: inserts at (or edits the picture at `pos`) the selection it opened on.
776
1338
  const [pictureDialog, setPictureDialog] = useState<{
777
1339
  pos: number | null;
@@ -815,10 +1377,12 @@ export function FoliToolbar({
815
1377
  const i = index++;
816
1378
  const state = states[i];
817
1379
  // Inserting a picture needs the app's upload; editing a selected one does not.
1380
+ // A menu without entries cannot open, whatever its `enabled` says.
818
1381
  const off =
819
1382
  disabled ||
820
1383
  !state?.enabled ||
821
- (item.dialog === "picture" && state?.value === "insert" && !upload);
1384
+ (item.dialog === "picture" && state?.value === "insert" && !upload) ||
1385
+ (item.actions !== undefined && actionsOf(item, body).length === 0);
822
1386
  if (item.select) {
823
1387
  const { select } = item;
824
1388
  const value = state?.value ?? "";
@@ -873,7 +1437,7 @@ export function FoliToolbar({
873
1437
  type="button"
874
1438
  className={`foli-toolbar-button foli-toolbar-${item.key}`}
875
1439
  // Speech input users say what they see: "H1", "Undo"; symbols get a name.
876
- aria-label={item.symbol ? item.label : undefined}
1440
+ aria-label={item.icon !== undefined ? item.label : undefined}
877
1441
  title={item.label}
878
1442
  aria-pressed={item.pressed ? Boolean(state?.pressed) : undefined}
879
1443
  aria-haspopup={
@@ -893,7 +1457,7 @@ export function FoliToolbar({
893
1457
  setMenu(item.key);
894
1458
  }}
895
1459
  >
896
- {item.icon ?? item.text}
1460
+ {item.icon ?? item.text ?? item.label}
897
1461
  {item.menu && (
898
1462
  <span
899
1463
  className="foli-toolbar-swatch"
@@ -904,19 +1468,60 @@ export function FoliToolbar({
904
1468
  </button>
905
1469
  );
906
1470
  if (item.actions) {
907
- const { actions } = item;
1471
+ const actions = actionsOf(item, body);
908
1472
  return (
909
1473
  <span key={item.key} className="foli-toolbar-menu">
910
1474
  {button}
911
- {menu === item.key && !disabled && (
1475
+ {menu === item.key && !disabled && actions.length > 0 && (
912
1476
  <ActionMenu
913
1477
  label={item.label}
914
1478
  actions={actions}
1479
+ editor={editor}
915
1480
  state={editor.state}
916
1481
  onPick={(action, pointer) => {
917
1482
  setMenu(null);
1483
+ if (action.dialog === "noteOptions") {
1484
+ setDialog(null);
1485
+ setTableDialog(null);
1486
+ setSetupDialog(null);
1487
+ setReferenceDialog(null);
1488
+ setControlDialog(null);
1489
+ setNoteDialog({ restore: buttons.current[i] ?? null });
1490
+ return;
1491
+ }
1492
+ if (action.dialog === "controlProperties") {
1493
+ setDialog(null);
1494
+ setTableDialog(null);
1495
+ setSetupDialog(null);
1496
+ setReferenceDialog(null);
1497
+ setControlDialog({
1498
+ restore: buttons.current[i] ?? null,
1499
+ selection: editor.state.selection,
1500
+ });
1501
+ return;
1502
+ }
1503
+ if (action.dialog === "crossReference") {
1504
+ setDialog(null);
1505
+ setTableDialog(null);
1506
+ setSetupDialog(null);
1507
+ setReferenceDialog({
1508
+ restore: buttons.current[i] ?? null,
1509
+ selection: editor.state.selection,
1510
+ });
1511
+ return;
1512
+ }
1513
+ if (action.dialog === "pageSetup") {
1514
+ setDialog(null);
1515
+ setTableDialog(null);
1516
+ setSetupDialog({
1517
+ restore: buttons.current[i] ?? null,
1518
+ selection: editor.state.selection,
1519
+ });
1520
+ return;
1521
+ }
918
1522
  if (action.dialog) {
919
1523
  setDialog(null);
1524
+ setSetupDialog(null);
920
1525
  setTableDialog((current) => ({
921
1526
  restore: buttons.current[i] ?? null,
922
1527
  selection: editor.state.selection,
@@ -925,6 +1530,7 @@ export function FoliToolbar({
925
1530
  return;
926
1531
  }
927
1532
  editor.run(action.command);
1533
+ if (action.movesFocus) return;
928
1534
  if (pointer) onClickCommand?.();
929
1535
  else buttons.current[i]?.focus();
930
1536
  }}
@@ -979,6 +1585,51 @@ export function FoliToolbar({
979
1585
  }}
980
1586
  />
981
1587
  )}
1588
+ {setupDialog && !disabled && (
1589
+ <PageSetupDialog
1590
+ editor={editor}
1591
+ onClose={(applied) => {
1592
+ const { restore } = setupDialog;
1593
+ setSetupDialog(null);
1594
+ if (applied && onClickCommand) onClickCommand();
1595
+ else restore?.focus();
1596
+ }}
1597
+ />
1598
+ )}
1599
+ {referenceDialog && !disabled && (
1600
+ <CrossReferenceDialog
1601
+ editor={editor}
1602
+ layout={() => body.storyView?.fieldLayout ?? null}
1603
+ onClose={(inserted) => {
1604
+ const { restore } = referenceDialog;
1605
+ setReferenceDialog(null);
1606
+ if (inserted && onClickCommand) onClickCommand();
1607
+ else restore?.focus();
1608
+ }}
1609
+ />
1610
+ )}
1611
+ {noteDialog && !disabled && (
1612
+ <NoteOptionsDialog
1613
+ editor={body}
1614
+ onClose={(applied) => {
1615
+ const { restore } = noteDialog;
1616
+ setNoteDialog(null);
1617
+ if (applied && onClickCommand) onClickCommand();
1618
+ else restore?.focus();
1619
+ }}
1620
+ />
1621
+ )}
1622
+ {controlDialog && !disabled && (
1623
+ <ControlDialog
1624
+ editor={editor}
1625
+ onClose={(applied) => {
1626
+ const { restore } = controlDialog;
1627
+ setControlDialog(null);
1628
+ if (applied && onClickCommand) onClickCommand();
1629
+ else restore?.focus();
1630
+ }}
1631
+ />
1632
+ )}
982
1633
  {tableDialog && !disabled && (
983
1634
  <InsertTableDialog
984
1635
  editor={editor}
@@ -1191,12 +1842,15 @@ function LinkDialog({
1191
1842
  function ActionMenu({
1192
1843
  label,
1193
1844
  actions,
1845
+ editor,
1194
1846
  state,
1195
1847
  onPick,
1196
1848
  onClose,
1197
1849
  }: {
1198
1850
  label: string;
1199
1851
  actions: readonly Action[];
1852
+ /** For `checked`, with `state`. */
1853
+ editor: Editor;
1200
1854
  state: EditorState;
1201
1855
  onPick: (action: Action, pointer: boolean) => void;
1202
1856
  onClose: (refocus: boolean) => void;
@@ -1259,7 +1913,7 @@ function ActionMenu({
1259
1913
  key={action.key}
1260
1914
  {...props}
1261
1915
  role="menuitemcheckbox"
1262
- aria-checked={action.checked(state)}
1916
+ aria-checked={action.checked(state, editor)}
1263
1917
  >
1264
1918
  {action.label}
1265
1919
  </button>
@@ -1382,6 +2036,677 @@ function InsertTableDialog({
1382
2036
  );
1383
2037
  }
1384
2038
 
2039
+ /**
2040
+ * The cross-reference dialog: what to refer to (the document's bookmarks and headings), what to
2041
+ * show of it, whether it links there; Insert and Cancel; Escape cancels.
2042
+ */
2043
+ function CrossReferenceDialog({
2044
+ editor,
2045
+ layout,
2046
+ onClose,
2047
+ }: {
2048
+ editor: Editor;
2049
+ layout: () => FieldLayout | null;
2050
+ onClose: (inserted: boolean) => void;
2051
+ }) {
2052
+ const [{ bookmarks, headings }] = useState(() => crossReferenceTargets(editor.state));
2053
+ const options = [
2054
+ ...headings.map((h) => ({
2055
+ value: `h${h.pos}`,
2056
+ label: `${"\u00a0".repeat((h.level - 1) * 2)}${h.number ? `${h.number} ` : ""}${h.text}`,
2057
+ })),
2058
+ ...bookmarks.map((b) => ({ value: `b${b.name}`, label: `Bookmark: ${b.name}` })),
2059
+ ];
2060
+ const [target, setTarget] = useState(options[0]?.value ?? "");
2061
+ const [show, setShow] = useState<"text" | "page" | "number">("text");
2062
+ const [link, setLink] = useState(true);
2063
+ const [failed, setFailed] = useState(false);
2064
+ const first = useRef<HTMLSelectElement>(null);
2065
+ const id = useId();
2066
+ useEffect(() => {
2067
+ first.current?.focus();
2068
+ }, []);
2069
+ const insert = (event: FormEvent) => {
2070
+ event.preventDefault();
2071
+ const to = target[0] === "h" ? Number(target.slice(1)) : target.slice(1);
2072
+ if (editor.run(insertCrossReference({ to, show, link, layout: layout() }))) onClose(true);
2073
+ else setFailed(true);
2074
+ };
2075
+ return (
2076
+ <div
2077
+ role="dialog"
2078
+ aria-modal="true"
2079
+ aria-label="Insert cross-reference"
2080
+ className="foli-link-dialog foli-table-dialog"
2081
+ onKeyDown={(event) => {
2082
+ if (event.key === "Escape") {
2083
+ event.preventDefault();
2084
+ onClose(false);
2085
+ }
2086
+ if (event.key !== "Tab") return;
2087
+ // Tab goes round inside the dialog.
2088
+ const stops = [
2089
+ ...event.currentTarget.querySelectorAll<HTMLElement>("select, input, button"),
2090
+ ];
2091
+ const at = stops.indexOf(event.target as HTMLElement);
2092
+ const next = (at + (event.shiftKey ? -1 : 1) + stops.length) % stops.length;
2093
+ event.preventDefault();
2094
+ stops[next]?.focus();
2095
+ }}
2096
+ >
2097
+ <form onSubmit={insert} noValidate>
2098
+ <label htmlFor={`${id}-target`}>Refer to</label>
2099
+ <select
2100
+ ref={first}
2101
+ id={`${id}-target`}
2102
+ value={target}
2103
+ onChange={(event) => {
2104
+ setTarget(event.target.value);
2105
+ setFailed(false);
2106
+ }}
2107
+ >
2108
+ {options.map((option) => (
2109
+ <option key={option.value} value={option.value}>
2110
+ {option.label}
2111
+ </option>
2112
+ ))}
2113
+ </select>
2114
+ <label htmlFor={`${id}-show`}>Show</label>
2115
+ <select
2116
+ id={`${id}-show`}
2117
+ value={show}
2118
+ onChange={(event) => setShow(event.target.value as typeof show)}
2119
+ >
2120
+ <option value="text">Its text</option>
2121
+ <option value="page">Its page number</option>
2122
+ <option value="number">Its paragraph number</option>
2123
+ </select>
2124
+ <label>
2125
+ <input
2126
+ type="checkbox"
2127
+ checked={link}
2128
+ onChange={(event) => setLink(event.target.checked)}
2129
+ />
2130
+ Link to it
2131
+ </label>
2132
+ <button type="submit">Insert</button>
2133
+ <button type="button" onClick={() => onClose(false)}>
2134
+ Cancel
2135
+ </button>
2136
+ {failed && (
2137
+ <p className="foli-link-error" role="alert">
2138
+ A cross-reference cannot be inserted here.
2139
+ </p>
2140
+ )}
2141
+ </form>
2142
+ </div>
2143
+ );
2144
+ }
2145
+
2146
+ /** Word's number formats for notes. */
2147
+ const NOTE_FORMATS = [
2148
+ ["decimal", "1, 2, 3"],
2149
+ ["lowerLetter", "a, b, c"],
2150
+ ["upperLetter", "A, B, C"],
2151
+ ["lowerRoman", "i, ii, iii"],
2152
+ ["upperRoman", "I, II, III"],
2153
+ ["chicago", "*, †, ‡"],
2154
+ ] as const;
2155
+
2156
+ /**
2157
+ * How notes are placed and numbered, for the whole document as Word's dialog applies it: where
2158
+ * they go, the number format, where numbers start and when they restart; Escape cancels.
2159
+ */
2160
+ function NoteOptionsDialog({
2161
+ editor,
2162
+ onClose,
2163
+ }: {
2164
+ editor: Editor;
2165
+ onClose: (applied: boolean) => void;
2166
+ }) {
2167
+ const [kind, setKind] = useState<NoteKind>("footnote");
2168
+ const valuesOf = (of: NoteKind) => {
2169
+ const envelope = wordContext(editor.state)?.envelope;
2170
+ const section = sectionAt(editor.state)?.setup;
2171
+ return noteProperties(envelope ?? {}, of, section);
2172
+ };
2173
+ const [values, setValues] = useState(() => valuesOf("footnote"));
2174
+ const [start, setStart] = useState(String(values.start));
2175
+ const first = useRef<HTMLSelectElement>(null);
2176
+ const id = useId();
2177
+ useEffect(() => {
2178
+ first.current?.focus();
2179
+ }, []);
2180
+ const set = (change: Partial<typeof values>) => setValues((v) => ({ ...v, ...change }));
2181
+ const restarts = values.restart !== "continuous";
2182
+ const number = Number(start);
2183
+ const invalid = !restarts && (!Number.isInteger(number) || number < 1 || number > 16383);
2184
+ const apply = (event: FormEvent) => {
2185
+ event.preventDefault();
2186
+ if (invalid) return;
2187
+ const properties: NotePropertiesJSON = {
2188
+ position: values.position,
2189
+ format: values.format,
2190
+ restart: values.restart,
2191
+ start: restarts ? 1 : number,
2192
+ };
2193
+ onClose(editor.run(setNoteProperties(kind, properties)));
2194
+ };
2195
+ return (
2196
+ <div
2197
+ role="dialog"
2198
+ aria-label="Note options"
2199
+ className="foli-link-dialog foli-table-dialog"
2200
+ onKeyDown={(event) => {
2201
+ if (event.key !== "Escape") return;
2202
+ event.preventDefault();
2203
+ onClose(false);
2204
+ }}
2205
+ >
2206
+ <form onSubmit={apply} noValidate>
2207
+ <label htmlFor={`${id}-kind`}>Notes</label>
2208
+ <select
2209
+ ref={first}
2210
+ id={`${id}-kind`}
2211
+ value={kind}
2212
+ onChange={(event) => {
2213
+ const next = event.target.value as NoteKind;
2214
+ const shown = valuesOf(next);
2215
+ setKind(next);
2216
+ setValues(shown);
2217
+ setStart(String(shown.start));
2218
+ }}
2219
+ >
2220
+ <option value="footnote">Footnotes</option>
2221
+ <option value="endnote">Endnotes</option>
2222
+ </select>
2223
+ <label htmlFor={`${id}-position`}>Position</label>
2224
+ <select
2225
+ id={`${id}-position`}
2226
+ value={values.position}
2227
+ onChange={(event) =>
2228
+ set({ position: event.target.value as NonNullable<NotePropertiesJSON["position"]> })
2229
+ }
2230
+ >
2231
+ {kind === "footnote" ? (
2232
+ <>
2233
+ <option value="pageBottom">Bottom of page</option>
2234
+ <option value="beneathText">Below text</option>
2235
+ </>
2236
+ ) : (
2237
+ <>
2238
+ <option value="docEnd">End of document</option>
2239
+ <option value="sectEnd">End of section</option>
2240
+ </>
2241
+ )}
2242
+ </select>
2243
+ <label htmlFor={`${id}-format`}>Number format</label>
2244
+ <select
2245
+ id={`${id}-format`}
2246
+ value={values.format}
2247
+ onChange={(event) => set({ format: event.target.value })}
2248
+ >
2249
+ {NOTE_FORMATS.map(([value, label]) => (
2250
+ <option key={value} value={value}>
2251
+ {label}
2252
+ </option>
2253
+ ))}
2254
+ </select>
2255
+ <label htmlFor={`${id}-start`}>Start at</label>
2256
+ <input
2257
+ id={`${id}-start`}
2258
+ type="number"
2259
+ min={1}
2260
+ value={restarts ? "1" : start}
2261
+ disabled={restarts}
2262
+ aria-invalid={invalid || undefined}
2263
+ onChange={(event) => setStart(event.target.value)}
2264
+ />
2265
+ <label htmlFor={`${id}-restart`}>Numbering</label>
2266
+ <select
2267
+ id={`${id}-restart`}
2268
+ value={values.restart}
2269
+ onChange={(event) =>
2270
+ set({ restart: event.target.value as NonNullable<NotePropertiesJSON["restart"]> })
2271
+ }
2272
+ >
2273
+ <option value="continuous">Continuous</option>
2274
+ <option value="eachSect">Restart each section</option>
2275
+ {kind === "footnote" && <option value="eachPage">Restart each page</option>}
2276
+ </select>
2277
+ <button type="submit">Apply</button>
2278
+ <button type="button" onClick={() => onClose(false)}>
2279
+ Cancel
2280
+ </button>
2281
+ {invalid && (
2282
+ <p className="foli-link-error" role="alert">
2283
+ The start must be a whole number from 1.
2284
+ </p>
2285
+ )}
2286
+ </form>
2287
+ </div>
2288
+ );
2289
+ }
2290
+
2291
+ /** A list's items as the dialog shows them: one a line, `shown | value` where they differ. */
2292
+ const itemsText = (items: ControlJSON["items"]) =>
2293
+ (items ?? [])
2294
+ .map((item) =>
2295
+ item.display === undefined || item.display === item.value
2296
+ ? item.value
2297
+ : `${item.display} | ${item.value}`,
2298
+ )
2299
+ .join("\n");
2300
+
2301
+ function parseItems(text: string): NonNullable<ControlJSON["items"]> {
2302
+ const seen = new Set<string>();
2303
+ return text.split("\n").flatMap((line) => {
2304
+ const [shown = "", value = shown] = line.split("|").map((part) => part.trim());
2305
+ // Word refuses two items of one value.
2306
+ if (!shown || seen.has(value)) return [];
2307
+ seen.add(value);
2308
+ return [{ value, display: shown }];
2309
+ });
2310
+ }
2311
+
2312
+ /**
2313
+ * The properties of the control at the caret: title, tag, locks and what its kind has (list items,
2314
+ * date format, line breaks); OK and Cancel; Escape cancels.
2315
+ */
2316
+ function ControlDialog({
2317
+ editor,
2318
+ onClose,
2319
+ }: {
2320
+ editor: Editor;
2321
+ onClose: (applied: boolean) => void;
2322
+ }) {
2323
+ const [selected] = useState(() => selectedControl(editor.state));
2324
+ const control = selected?.control;
2325
+ const [title, setTitle] = useState(control?.alias ?? "");
2326
+ const [tag, setTag] = useState(control?.tag ?? "");
2327
+ const [noDelete, setNoDelete] = useState(
2328
+ control?.lock === "sdtLocked" || control?.lock === "sdtContentLocked",
2329
+ );
2330
+ const [noEdit, setNoEdit] = useState(
2331
+ control?.lock === "contentLocked" || control?.lock === "sdtContentLocked",
2332
+ );
2333
+ const [items, setItems] = useState(itemsText(control?.items));
2334
+ const [dateFormat, setDateFormat] = useState(control?.dateFormat ?? "d MMMM yyyy");
2335
+ const [multiLine, setMultiLine] = useState(control?.multiLine === true);
2336
+ const first = useRef<HTMLInputElement>(null);
2337
+ const id = useId();
2338
+ useEffect(() => {
2339
+ first.current?.focus();
2340
+ }, []);
2341
+ if (!selected || !control) return null;
2342
+ const { kind } = control;
2343
+ const hasList = kind === "dropDown" || kind === "comboBox";
2344
+ const apply = (event: FormEvent) => {
2345
+ event.preventDefault();
2346
+ const lock = noDelete
2347
+ ? noEdit
2348
+ ? "sdtContentLocked"
2349
+ : "sdtLocked"
2350
+ : noEdit
2351
+ ? "contentLocked"
2352
+ : "unlocked";
2353
+ onClose(
2354
+ editor.run(
2355
+ setControlProperties(selected.id, {
2356
+ title,
2357
+ tag,
2358
+ lock,
2359
+ ...(hasList ? { items: parseItems(items) } : {}),
2360
+ ...(kind === "date" ? { dateFormat } : {}),
2361
+ ...(kind === "text" ? { multiLine } : {}),
2362
+ }),
2363
+ ),
2364
+ );
2365
+ };
2366
+ return (
2367
+ <div
2368
+ role="dialog"
2369
+ aria-label="Content control properties"
2370
+ className="foli-link-dialog foli-table-dialog"
2371
+ onKeyDown={(event) => {
2372
+ if (event.key !== "Escape") return;
2373
+ event.preventDefault();
2374
+ onClose(false);
2375
+ }}
2376
+ >
2377
+ <form onSubmit={apply} noValidate>
2378
+ <label htmlFor={`${id}-title`}>Title</label>
2379
+ <input
2380
+ ref={first}
2381
+ id={`${id}-title`}
2382
+ value={title}
2383
+ onChange={(event) => setTitle(event.target.value)}
2384
+ />
2385
+ <label htmlFor={`${id}-tag`}>Tag</label>
2386
+ <input id={`${id}-tag`} value={tag} onChange={(event) => setTag(event.target.value)} />
2387
+ <label>
2388
+ <input
2389
+ type="checkbox"
2390
+ checked={noDelete}
2391
+ onChange={(event) => setNoDelete(event.target.checked)}
2392
+ />
2393
+ The control cannot be deleted
2394
+ </label>
2395
+ <label>
2396
+ <input
2397
+ type="checkbox"
2398
+ checked={noEdit}
2399
+ onChange={(event) => setNoEdit(event.target.checked)}
2400
+ />
2401
+ The contents cannot be edited
2402
+ </label>
2403
+ {hasList && (
2404
+ <>
2405
+ <label htmlFor={`${id}-items`}>List items, one per line (shown | value)</label>
2406
+ <textarea
2407
+ id={`${id}-items`}
2408
+ rows={4}
2409
+ value={items}
2410
+ onChange={(event) => setItems(event.target.value)}
2411
+ />
2412
+ </>
2413
+ )}
2414
+ {kind === "date" && (
2415
+ <>
2416
+ <label htmlFor={`${id}-format`}>Date format</label>
2417
+ <input
2418
+ id={`${id}-format`}
2419
+ value={dateFormat}
2420
+ onChange={(event) => setDateFormat(event.target.value)}
2421
+ />
2422
+ </>
2423
+ )}
2424
+ {kind === "text" && (
2425
+ <label>
2426
+ <input
2427
+ type="checkbox"
2428
+ checked={multiLine}
2429
+ onChange={(event) => setMultiLine(event.target.checked)}
2430
+ />
2431
+ Allow line breaks
2432
+ </label>
2433
+ )}
2434
+ <button type="submit">OK</button>
2435
+ <button type="button" onClick={() => onClose(false)}>
2436
+ Cancel
2437
+ </button>
2438
+ </form>
2439
+ </div>
2440
+ );
2441
+ }
2442
+
2443
+ const TWIPS_PER_CM = 1440 / 2.54;
2444
+ const MAX_TWIPS = 31_680;
2445
+ /** Word's limit on a section's columns. */
2446
+ const MAX_SECTION_COLUMNS = 45;
2447
+ const toCm = (twips: number) => String(Number((twips / TWIPS_PER_CM).toFixed(2)));
2448
+ /** A length in cm as whole twips (a decimal comma too), or null when it is not one in range. */
2449
+ function toTwips(text: string, min: number): number | null {
2450
+ const value = Number(text.trim().replace(",", "."));
2451
+ const twips = Math.round(value * TWIPS_PER_CM);
2452
+ return text.trim() && Number.isFinite(value) && twips >= min && twips <= MAX_TWIPS ? twips : null;
2453
+ }
2454
+
2455
+ const SECTION_STARTS = [
2456
+ ["nextPage", "Next page"],
2457
+ ["continuous", "Continuous"],
2458
+ ["evenPage", "Even page"],
2459
+ ["oddPage", "Odd page"],
2460
+ ["nextColumn", "Next column"],
2461
+ ] as const;
2462
+ type SetupField =
2463
+ | "width"
2464
+ | "height"
2465
+ | "top"
2466
+ | "bottom"
2467
+ | "left"
2468
+ | "right"
2469
+ | "count"
2470
+ | "space"
2471
+ | "widths";
2472
+ const SETUP_LABELS: Record<SetupField, string> = {
2473
+ width: "Page width (cm)",
2474
+ height: "Page height (cm)",
2475
+ top: "Top margin (cm)",
2476
+ bottom: "Bottom margin (cm)",
2477
+ left: "Left margin (cm)",
2478
+ right: "Right margin (cm)",
2479
+ count: "Columns",
2480
+ space: "Space between columns (cm)",
2481
+ widths: "Set column widths (cm, separated by ;)",
2482
+ };
2483
+
2484
+ /**
2485
+ * The page setup dialog, for the caret's section: how it starts, its page size and orientation,
2486
+ * margins and columns (equal, or set widths; the line between them), in centimetres. Only what
2487
+ * was changed is applied. Apply and Cancel; Escape cancels; a wrong field is marked and announced.
2488
+ */
2489
+ function PageSetupDialog({
2490
+ editor,
2491
+ onClose,
2492
+ }: {
2493
+ editor: Editor;
2494
+ /** `applied`: the setup changed (the focus may go to the document). */
2495
+ onClose: (applied: boolean) => void;
2496
+ }) {
2497
+ const id = useId();
2498
+ const [initial] = useState(() => {
2499
+ const setup = sectionAt(editor.state)?.setup ?? {};
2500
+ const width = setup.pageSize?.width ?? 12_240;
2501
+ const height = setup.pageSize?.height ?? 15_840;
2502
+ const m = setup.margins ?? {};
2503
+ const set = setup.columns?.equalWidth === false ? (setup.columns.widths ?? []) : [];
2504
+ return {
2505
+ start: setup.type ?? "nextPage",
2506
+ orientation: setup.pageSize?.orientation ?? (width > height ? "landscape" : "portrait"),
2507
+ separator: setup.columns?.separator === true,
2508
+ columns: setup.columns,
2509
+ fields: {
2510
+ width: toCm(width),
2511
+ height: toCm(height),
2512
+ top: toCm(Math.abs(m.top ?? 1440)),
2513
+ bottom: toCm(Math.abs(m.bottom ?? 1440)),
2514
+ left: toCm(m.left ?? 1440),
2515
+ right: toCm(m.right ?? 1440),
2516
+ count: String(set.length || (setup.columns?.count ?? 1)),
2517
+ space: toCm(setup.columns?.space ?? 720),
2518
+ widths: set.map((column) => toCm(column.width)).join("; "),
2519
+ } satisfies Record<SetupField, string>,
2520
+ };
2521
+ });
2522
+ const [start, setStart] = useState<string>(initial.start);
2523
+ const [orientation, setOrientation] = useState<string>(initial.orientation);
2524
+ const [separator, setSeparator] = useState(initial.separator);
2525
+ const [fields, setFields] = useState(initial.fields);
2526
+ const [error, setError] = useState<SetupField | "setup" | "mismatch" | null>(null);
2527
+ const first = useRef<HTMLSelectElement>(null);
2528
+ useEffect(() => first.current?.focus(), []);
2529
+
2530
+ const apply = (event: FormEvent) => {
2531
+ event.preventDefault();
2532
+ const wrong = (field: SetupField) => {
2533
+ setError(field);
2534
+ document.getElementById(`${id}-${field}`)?.focus();
2535
+ };
2536
+ const changed = (field: SetupField) => fields[field] !== initial.fields[field];
2537
+ const setup: SectionSetup = {};
2538
+ if (start !== initial.start)
2539
+ setup.type = start === "nextPage" ? undefined : (start as SectionJSON["type"]);
2540
+ const lengths: Partial<Record<SetupField, number>> = {};
2541
+ for (const field of ["width", "height", "top", "bottom", "left", "right"] as const) {
2542
+ if (!changed(field)) continue;
2543
+ const twips = toTwips(fields[field], field === "width" || field === "height" ? 1 : 0);
2544
+ if (twips === null) return wrong(field);
2545
+ lengths[field] = twips;
2546
+ }
2547
+ if (
2548
+ lengths.width !== undefined ||
2549
+ lengths.height !== undefined ||
2550
+ orientation !== initial.orientation
2551
+ )
2552
+ setup.pageSize = {
2553
+ ...(lengths.width !== undefined ? { width: lengths.width } : {}),
2554
+ ...(lengths.height !== undefined ? { height: lengths.height } : {}),
2555
+ orientation: orientation as "portrait" | "landscape",
2556
+ };
2557
+ const margins = {
2558
+ top: lengths.top,
2559
+ bottom: lengths.bottom,
2560
+ left: lengths.left,
2561
+ right: lengths.right,
2562
+ };
2563
+ const given = Object.entries(margins).filter(([, value]) => value !== undefined);
2564
+ if (given.length) setup.margins = Object.fromEntries(given);
2565
+ if (
2566
+ changed("count") ||
2567
+ changed("space") ||
2568
+ changed("widths") ||
2569
+ separator !== initial.separator
2570
+ ) {
2571
+ // What was not changed stays exactly as it is, each column's own space included.
2572
+ const before = initial.columns;
2573
+ const set = before?.equalWidth === false ? (before.widths ?? []) : [];
2574
+ const space = changed("space") ? toTwips(fields.space, 0) : (before?.space ?? 720);
2575
+ if (space === null) return wrong("space");
2576
+ let widths: (number | null)[] = set.map((column) => column.width);
2577
+ if (changed("widths"))
2578
+ widths = fields.widths.trim()
2579
+ ? fields.widths
2580
+ .trim()
2581
+ .split(/[;\s]+/)
2582
+ .map((width) => toTwips(width, 1))
2583
+ : [];
2584
+ if (widths.includes(null)) return wrong("widths");
2585
+ const asked = Number(fields.count);
2586
+ if (widths.length && changed("count") && asked !== widths.length) {
2587
+ setError("mismatch");
2588
+ document.getElementById(`${id}-count`)?.focus();
2589
+ return;
2590
+ }
2591
+ const count = widths.length || asked;
2592
+ if (!Number.isInteger(count) || count < 1 || count > MAX_SECTION_COLUMNS)
2593
+ return wrong("count");
2594
+ const { separator: _line, equalWidth: _equal, widths: _widths, ...rest } = before ?? {};
2595
+ setup.columns = {
2596
+ ...rest,
2597
+ count,
2598
+ ...(changed("space") || before?.space === undefined ? { space } : {}),
2599
+ ...(separator ? { separator } : {}),
2600
+ ...(widths.length
2601
+ ? {
2602
+ equalWidth: false,
2603
+ widths: widths.map((width, i) => {
2604
+ const own = changed("space") ? undefined : set[i]?.space;
2605
+ const gap = own ?? (i < widths.length - 1 ? space : undefined);
2606
+ return { width: width as number, ...(gap === undefined ? {} : { space: gap }) };
2607
+ }),
2608
+ }
2609
+ : {}),
2610
+ };
2611
+ }
2612
+ if (!Object.keys(setup).length) return onClose(false);
2613
+ if (editor.run(setSectionSetup(setup))) return onClose(true);
2614
+ setError("setup");
2615
+ };
2616
+ const setOrientationSwapping = (next: string) => {
2617
+ if (next !== orientation)
2618
+ setFields((current) => ({ ...current, width: current.height, height: current.width }));
2619
+ setOrientation(next);
2620
+ setError(null);
2621
+ };
2622
+ const marked = (name: SetupField) => error === name || (name === "count" && error === "mismatch");
2623
+ const field = (name: SetupField) => (
2624
+ <div key={name} className="foli-setup-field">
2625
+ <label htmlFor={`${id}-${name}`}>{SETUP_LABELS[name]}</label>
2626
+ <input
2627
+ id={`${id}-${name}`}
2628
+ type="text"
2629
+ inputMode={name === "widths" ? "text" : "decimal"}
2630
+ value={fields[name]}
2631
+ aria-invalid={marked(name) || undefined}
2632
+ aria-describedby={marked(name) ? `${id}-error` : undefined}
2633
+ onChange={(event) => {
2634
+ setFields((current) => ({ ...current, [name]: event.target.value }));
2635
+ setError(null);
2636
+ }}
2637
+ />
2638
+ </div>
2639
+ );
2640
+
2641
+ return (
2642
+ <div
2643
+ role="dialog"
2644
+ aria-label="Page setup"
2645
+ className="foli-link-dialog foli-setup-dialog"
2646
+ onKeyDown={(event) => {
2647
+ if (event.key !== "Escape") return;
2648
+ event.preventDefault();
2649
+ onClose(false);
2650
+ }}
2651
+ >
2652
+ <form onSubmit={apply} noValidate>
2653
+ <div className="foli-setup-field">
2654
+ <label htmlFor={`${id}-start`}>Section starts</label>
2655
+ <select
2656
+ ref={first}
2657
+ id={`${id}-start`}
2658
+ value={start}
2659
+ onChange={(event) => setStart(event.target.value)}
2660
+ >
2661
+ {SECTION_STARTS.map(([value, label]) => (
2662
+ <option key={value} value={value}>
2663
+ {label}
2664
+ </option>
2665
+ ))}
2666
+ </select>
2667
+ </div>
2668
+ <div className="foli-setup-field">
2669
+ <label htmlFor={`${id}-orientation`}>Orientation</label>
2670
+ <select
2671
+ id={`${id}-orientation`}
2672
+ value={orientation}
2673
+ onChange={(event) => setOrientationSwapping(event.target.value)}
2674
+ >
2675
+ <option value="portrait">Portrait</option>
2676
+ <option value="landscape">Landscape</option>
2677
+ </select>
2678
+ </div>
2679
+ {(["width", "height", "top", "bottom", "left", "right", "count", "space"] as const).map(
2680
+ field,
2681
+ )}
2682
+ <div className="foli-setup-field foli-setup-check">
2683
+ <input
2684
+ id={`${id}-separator`}
2685
+ type="checkbox"
2686
+ checked={separator}
2687
+ onChange={(event) => setSeparator(event.target.checked)}
2688
+ />
2689
+ <label htmlFor={`${id}-separator`}>Line between columns</label>
2690
+ </div>
2691
+ {field("widths")}
2692
+ <button type="submit">Apply</button>
2693
+ <button type="button" onClick={() => onClose(false)}>
2694
+ Cancel
2695
+ </button>
2696
+ {error && (
2697
+ <p id={`${id}-error`} className="foli-link-error" role="alert">
2698
+ {error === "setup"
2699
+ ? "This setup leaves no room for text, or its columns do not fit the page."
2700
+ : error === "mismatch"
2701
+ ? "The number of columns differs from the set widths: list one width per column, or clear them for equal columns."
2702
+ : `Check this value: ${SETUP_LABELS[error]}.`}
2703
+ </p>
2704
+ )}
2705
+ </form>
2706
+ </div>
2707
+ );
2708
+ }
2709
+
1385
2710
  /** The largest picture side the schema takes, in px (2^31 - 1 EMU). */
1386
2711
  const MAX_PICTURE_PX = Math.floor(2_147_483_647 / EMU_PER_PX);
1387
2712