@folijs/react 0.5.0 → 0.6.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,31 +61,45 @@ 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,
102
+ updateFields,
66
103
  wordContext,
67
104
  } from "@folijs/core";
68
105
  import { type EditorViewOptions, EMU_PER_PX, measureImageFile, textWidthEmu } from "@folijs/view";
@@ -78,7 +115,7 @@ import {
78
115
  useRef,
79
116
  useState,
80
117
  } from "react";
81
- import { useEditorOrContext, useEditorState } from "./editor.js";
118
+ import { useActiveEditor, useEditorOrContext, useEditorState } from "./editor.js";
82
119
 
83
120
  export interface FoliToolbarProps {
84
121
  /** Default: the editor of the nearest `FoliEditorProvider`. */
@@ -135,7 +172,7 @@ interface Item {
135
172
  pick: (color: string | null) => Command;
136
173
  };
137
174
  /** An action menu button (the table menu): its commands, in order. */
138
- actions?: readonly Action[];
175
+ actions?: readonly Action[] | ((editor: Editor) => readonly Action[]);
139
176
  /** A button opening a dialog (the picture's). */
140
177
  dialog?: "picture";
141
178
  /** A drop-down list (a `select`): its options, the current value, and what picking runs. */
@@ -150,10 +187,12 @@ interface Item {
150
187
  interface Action {
151
188
  key: string;
152
189
  label: string;
153
- /** The command it runs; `insertTable` opens the dialog that asks for the size instead. */
190
+ /** The command it runs; with `dialog`, whether it applies: the dialog does the rest. */
154
191
  command: Command;
155
- dialog?: "insertTable";
192
+ dialog?: "insertTable" | "pageSetup" | "crossReference" | "controlProperties" | "noteOptions";
156
193
  checked?: (state: EditorState) => boolean;
194
+ /** It takes the focus where it belongs (into a story, or back to the body). */
195
+ movesFocus?: boolean;
157
196
  }
158
197
 
159
198
  interface ColorOption {
@@ -227,6 +266,269 @@ const TABLE_ACTIONS: readonly Action[] = [
227
266
  },
228
267
  ];
229
268
 
269
+ const SECTION_ACTIONS: readonly Action[] = [
270
+ {
271
+ key: "pageSetup",
272
+ label: "Page setup…",
273
+ command: (state) => sectionAt(state) !== null,
274
+ dialog: "pageSetup",
275
+ },
276
+ { key: "breakNext", label: "Section break: next page", command: insertSectionBreak("nextPage") },
277
+ {
278
+ key: "breakContinuous",
279
+ label: "Section break: continuous",
280
+ command: insertSectionBreak("continuous"),
281
+ },
282
+ { key: "breakEven", label: "Section break: even page", command: insertSectionBreak("evenPage") },
283
+ { key: "breakOdd", label: "Section break: odd page", command: insertSectionBreak("oddPage") },
284
+ { key: "removeBreak", label: "Remove section break", command: removeSectionBreak },
285
+ { key: "columnBreak", label: "Column break", command: insertColumnBreak },
286
+ ];
287
+
288
+ /**
289
+ * The header and footer menu: opening them on the caret's page, and, for the one open (else the
290
+ * caret's section), what a section does about them.
291
+ */
292
+ function storyActions(body: Editor): readonly Action[] {
293
+ const open = () => body.storyView?.open ?? null;
294
+ const setup = (state: EditorState) => {
295
+ const index = open()?.section ?? sectionAt(state)?.index ?? 0;
296
+ return documentSections(state)[index]?.setup ?? {};
297
+ };
298
+ const edit =
299
+ (side: StorySide): Command =>
300
+ (_state, dispatch) => {
301
+ const view = body.storyView;
302
+ if (!view) return false;
303
+ if (dispatch) view.edit(side);
304
+ return true;
305
+ };
306
+ const linked = (state: EditorState) => {
307
+ const story = open();
308
+ if (!story) return false;
309
+ if (story.side === "note") return false;
310
+ const references = story.side === "header" ? setup(state).headers : setup(state).footers;
311
+ return !references?.[story.variant];
312
+ };
313
+ const evenPages = (state: EditorState) =>
314
+ wordContext(state)?.envelope.settings?.evenAndOddHeaders === true;
315
+ return [
316
+ { key: "editHeader", label: "Edit header", command: edit("header"), movesFocus: true },
317
+ { key: "editFooter", label: "Edit footer", command: edit("footer"), movesFocus: true },
318
+ {
319
+ key: "closeStory",
320
+ label: "Close header and footer",
321
+ movesFocus: true,
322
+ command: (_state, dispatch) => {
323
+ if (!open()) return false;
324
+ if (dispatch) body.storyView?.close();
325
+ return true;
326
+ },
327
+ },
328
+ {
329
+ key: "firstPage",
330
+ label: "Different first page",
331
+ checked: (state) => setup(state).titlePage === true,
332
+ command: (state, dispatch) =>
333
+ setDifferentFirstPage(setup(state).titlePage !== true, open()?.section)(state, dispatch),
334
+ },
335
+ {
336
+ key: "evenPages",
337
+ label: "Different odd and even pages",
338
+ checked: evenPages,
339
+ command: (state, dispatch) => setDifferentEvenPages(!evenPages(state))(state, dispatch),
340
+ },
341
+ {
342
+ key: "linkPrevious",
343
+ label: "Link to previous",
344
+ checked: linked,
345
+ command: (state, dispatch) => {
346
+ const story = open();
347
+ return story && story.side !== "note"
348
+ ? setStoryLinked(
349
+ story.side,
350
+ story.variant,
351
+ !linked(state),
352
+ story.section,
353
+ )(state, dispatch)
354
+ : false;
355
+ },
356
+ },
357
+ ];
358
+ }
359
+
360
+ /**
361
+ * The notes menu: a new note (the caret goes into it), between a reference and its note, the
362
+ * conversions Word has, and the options dialog.
363
+ */
364
+ function noteActions(body: Editor): readonly Action[] {
365
+ const insert =
366
+ (kind: NoteKind): Command =>
367
+ (state, dispatch) => {
368
+ if (!insertNote(kind)(state)) return false;
369
+ if (dispatch) {
370
+ insertNote(kind)(state, dispatch);
371
+ body.storyView?.editNote();
372
+ }
373
+ return true;
374
+ };
375
+ return [
376
+ { key: "footnote", label: "Insert footnote", command: insert("footnote"), movesFocus: true },
377
+ { key: "endnote", label: "Insert endnote", command: insert("endnote"), movesFocus: true },
378
+ {
379
+ key: "goToNote",
380
+ label: "Go to note or reference",
381
+ movesFocus: true,
382
+ command: (state, dispatch) => {
383
+ const view = body.storyView;
384
+ if (!view) return false;
385
+ if (view.open?.side === "note") {
386
+ if (dispatch) view.toReference();
387
+ return true;
388
+ }
389
+ if (!noteAtSelection(state)) return false;
390
+ if (dispatch) view.editNote();
391
+ return true;
392
+ },
393
+ },
394
+ {
395
+ key: "toEndnotes",
396
+ label: "Convert footnotes to endnotes",
397
+ command: (_state, dispatch) => convertNotes("endnote")(body.state, dispatch && body.dispatch),
398
+ },
399
+ {
400
+ key: "toFootnotes",
401
+ label: "Convert endnotes to footnotes",
402
+ command: (_state, dispatch) =>
403
+ convertNotes("footnote")(body.state, dispatch && body.dispatch),
404
+ },
405
+ {
406
+ key: "noteOptions",
407
+ label: "Note options…",
408
+ dialog: "noteOptions",
409
+ command: (state) => wordContext(state) !== null,
410
+ },
411
+ ];
412
+ }
413
+
414
+ /** The control the selection is in. */
415
+ const selectedControl = (state: EditorState) => {
416
+ const range = controlAt(state.doc, state.selection.from);
417
+ const control = range && controlProperties(state, range.id);
418
+ return range && control ? { id: range.id, control } : null;
419
+ };
420
+
421
+ /** The content controls menu: each kind to insert, then what applies to the one at the caret. */
422
+ const CONTROL_ACTIONS: readonly Action[] = [
423
+ { key: "richText", label: "Rich text", command: insertControl("richText") },
424
+ { key: "plainText", label: "Plain text", command: insertControl("text") },
425
+ { key: "dropDown", label: "Drop-down list", command: insertControl("dropDown") },
426
+ { key: "comboBox", label: "Combo box", command: insertControl("comboBox") },
427
+ { key: "datePicker", label: "Date picker", command: insertControl("date") },
428
+ { key: "checkBox", label: "Check box", command: insertControl("checkbox") },
429
+ { key: "pictureControl", label: "Picture (selected)", command: insertControl("picture") },
430
+ { key: "repeating", label: "Repeating section", command: insertControl("repeating") },
431
+ { key: "repeatingItem", label: "Add repeating item", command: addRepeatingItem() },
432
+ {
433
+ key: "controlProperties",
434
+ label: "Control properties…",
435
+ dialog: "controlProperties",
436
+ command: (state) => selectedControl(state) !== null,
437
+ },
438
+ ];
439
+
440
+ /**
441
+ * The navigation menu: what `FoliNavigation` shows, with Word's keys. Nothing applies without it.
442
+ */
443
+ function navigationActions(body: Editor): readonly Action[] {
444
+ const open =
445
+ (request: NavigationRequest): Command =>
446
+ (_state, dispatch) => {
447
+ if (!body.navigation) return false;
448
+ if (dispatch) body.navigation(request);
449
+ return true;
450
+ };
451
+ const item = (key: NavigationRequest, label: string): Action => ({
452
+ key,
453
+ label,
454
+ command: open(key),
455
+ movesFocus: true,
456
+ });
457
+ return [
458
+ item("find", "Find\u2026"),
459
+ item("replace", "Replace\u2026"),
460
+ item("goTo", "Go to\u2026"),
461
+ item("bookmarks", "Bookmarks\u2026"),
462
+ item("outline", "Outline"),
463
+ ];
464
+ }
465
+
466
+ /**
467
+ * The fields menu: what can be inserted at the selection, updating (the view's pages when there is
468
+ * one) and the codes shown or hidden.
469
+ */
470
+ function fieldActions(body: Editor): readonly Action[] {
471
+ const layout = () => body.storyView?.fieldLayout ?? null;
472
+ const active = () => {
473
+ const open = body.storyView?.open;
474
+ return (open && body.story(open.id)) || body;
475
+ };
476
+ const update = (editor: Editor, options: UpdateFieldsOptions) =>
477
+ body.storyView ? body.storyView.updateFields(options, editor) : updateFields(editor, options);
478
+ return [
479
+ {
480
+ key: "pageNumber",
481
+ label: "Page number",
482
+ command: (state, dispatch) => insertPageNumber({ layout: layout() })(state, dispatch),
483
+ },
484
+ { key: "date", label: "Date", command: insertDate() },
485
+ {
486
+ key: "crossReference",
487
+ label: "Cross-reference…",
488
+ dialog: "crossReference",
489
+ command: (state) => {
490
+ const { bookmarks, headings } = crossReferenceTargets(state);
491
+ return insertPageBreak(state) && bookmarks.length + headings.length > 0;
492
+ },
493
+ },
494
+ {
495
+ key: "tableOfContents",
496
+ label: "Table of contents",
497
+ command: (state, dispatch) => {
498
+ const done = insertTableOfContents({ layout: layout() })(state, dispatch);
499
+ // Its own lines moved the headings: their page numbers follow, in the same undo step.
500
+ if (done && dispatch)
501
+ update(body, { only: (field) => field.parent?.name === "TOC", continues: true });
502
+ return done;
503
+ },
504
+ },
505
+ {
506
+ key: "updateSelected",
507
+ label: "Update selected fields",
508
+ command: (state, dispatch) => {
509
+ if (!fieldsIn(state.doc).length) return false;
510
+ const { from, to } = state.selection;
511
+ if (dispatch) update(active(), { only: { from, to } });
512
+ return true;
513
+ },
514
+ },
515
+ {
516
+ key: "updateAll",
517
+ label: "Update all fields",
518
+ command: (_state, dispatch) => {
519
+ if (dispatch) update(body, {});
520
+ return true;
521
+ },
522
+ },
523
+ {
524
+ key: "fieldCodes",
525
+ label: "Show field codes",
526
+ checked: fieldCodesShown,
527
+ command: toggleFieldCodes,
528
+ },
529
+ ];
530
+ }
531
+
230
532
  /** Whether the selection holds a textblock (a caret's own block first; else it walks the range). */
231
533
  function hasTextblock(state: EditorState): boolean {
232
534
  if (state.selection.$from.parent.isTextblock) return true;
@@ -586,6 +888,48 @@ const GROUPS: Item[][] = [
586
888
  dialog: "picture",
587
889
  },
588
890
  { key: "pageBreak", label: "Page break", text: "Page break", command: () => insertPageBreak },
891
+ {
892
+ key: "section",
893
+ label: "Section",
894
+ text: "Section",
895
+ enabled: (state) => wordContext(state) !== null,
896
+ actions: SECTION_ACTIONS,
897
+ },
898
+ {
899
+ key: "headerFooter",
900
+ label: "Header and footer",
901
+ text: "Header",
902
+ enabled: (state) => wordContext(state) !== null,
903
+ actions: storyActions,
904
+ },
905
+ {
906
+ key: "fields",
907
+ label: "Fields",
908
+ text: "Fields",
909
+ enabled: (state) => wordContext(state) !== null,
910
+ actions: fieldActions,
911
+ },
912
+ {
913
+ key: "navigate",
914
+ label: "Find and go to",
915
+ text: "Navigate",
916
+ enabled: (state) => wordContext(state) !== null,
917
+ actions: navigationActions,
918
+ },
919
+ {
920
+ key: "notes",
921
+ label: "Footnotes and endnotes",
922
+ text: "Notes",
923
+ enabled: (state) => wordContext(state) !== null,
924
+ actions: noteActions,
925
+ },
926
+ {
927
+ key: "controls",
928
+ label: "Content controls",
929
+ text: "Controls",
930
+ enabled: (state) => wordContext(state) !== null,
931
+ actions: CONTROL_ACTIONS,
932
+ },
589
933
  ],
590
934
  ];
591
935
 
@@ -652,7 +996,9 @@ export function FoliToolbar({
652
996
  comments = false,
653
997
  upload,
654
998
  }: FoliToolbarProps) {
655
- const editor = useEditorOrContext(given, "FoliToolbar");
999
+ const body = useEditorOrContext(given, "FoliToolbar");
1000
+ // A story open on its page takes the formatting commands; the body otherwise.
1001
+ const editor = useActiveEditor(body);
656
1002
  const groups = comments ? GROUPS : GROUPS_NO_COMMENT;
657
1003
  const items = comments ? ITEMS : ITEMS_NO_COMMENT;
658
1004
  const states = useEditorState(comments ? selectStates : selectStatesNoComment, {
@@ -722,6 +1068,38 @@ export function FoliToolbar({
722
1068
  ? null
723
1069
  : current,
724
1070
  );
1071
+ // The cross-reference dialog inserts at the selection it opened on.
1072
+ setReferenceDialog((current) =>
1073
+ current &&
1074
+ (!transactions.length ||
1075
+ transactions.some((tr) => tr.docChanged) ||
1076
+ !state.selection.eq(current.selection))
1077
+ ? null
1078
+ : current,
1079
+ );
1080
+ setNoteDialog((current) =>
1081
+ current && (!transactions.length || transactions.some((tr) => tr.docChanged))
1082
+ ? null
1083
+ : current,
1084
+ );
1085
+ // The control properties dialog is for the control it opened on.
1086
+ setControlDialog((current) =>
1087
+ current &&
1088
+ (!transactions.length ||
1089
+ transactions.some((tr) => tr.docChanged) ||
1090
+ !state.selection.eq(current.selection))
1091
+ ? null
1092
+ : current,
1093
+ );
1094
+ // So is the page setup dialog: its section may have changed.
1095
+ setSetupDialog((current) =>
1096
+ current &&
1097
+ (!transactions.length ||
1098
+ transactions.some((tr) => tr.docChanged) ||
1099
+ !state.selection.eq(current.selection))
1100
+ ? null
1101
+ : current,
1102
+ );
725
1103
  // The insert table dialog is for the caret it opened on, as the link dialog is.
726
1104
  setTableDialog((current) =>
727
1105
  current &&
@@ -742,6 +1120,9 @@ export function FoliToolbar({
742
1120
  const active = typeof document === "undefined" ? null : document.activeElement;
743
1121
  setTableDialog(null);
744
1122
  setPictureDialog(null);
1123
+ setSetupDialog(null);
1124
+ setReferenceDialog(null);
1125
+ setControlDialog(null);
745
1126
  setDialog((current) =>
746
1127
  current
747
1128
  ? { ...current, request: current.request + 1 }
@@ -772,6 +1153,35 @@ export function FoliToolbar({
772
1153
  useEffect(() => {
773
1154
  if (disabled) setTableDialog(null);
774
1155
  }, [disabled]);
1156
+ // The page setup dialog (from the section menu), for the section of the caret it opened on.
1157
+ const [setupDialog, setSetupDialog] = useState<{
1158
+ restore: HTMLElement | null;
1159
+ selection: EditorState["selection"];
1160
+ } | null>(null);
1161
+ useEffect(() => {
1162
+ if (disabled) setSetupDialog(null);
1163
+ }, [disabled]);
1164
+ // The cross-reference dialog (from the fields menu).
1165
+ const [referenceDialog, setReferenceDialog] = useState<{
1166
+ restore: HTMLElement | null;
1167
+ selection: EditorState["selection"];
1168
+ } | null>(null);
1169
+ useEffect(() => {
1170
+ if (disabled) setReferenceDialog(null);
1171
+ }, [disabled]);
1172
+ // The control properties dialog (from the content controls menu).
1173
+ const [controlDialog, setControlDialog] = useState<{
1174
+ restore: HTMLElement | null;
1175
+ selection: EditorState["selection"];
1176
+ } | null>(null);
1177
+ useEffect(() => {
1178
+ if (disabled) setControlDialog(null);
1179
+ }, [disabled]);
1180
+ // The note options dialog (from the notes menu).
1181
+ const [noteDialog, setNoteDialog] = useState<{ restore: HTMLElement | null } | null>(null);
1182
+ useEffect(() => {
1183
+ if (disabled) setNoteDialog(null);
1184
+ }, [disabled]);
775
1185
  // The picture dialog: inserts at (or edits the picture at `pos`) the selection it opened on.
776
1186
  const [pictureDialog, setPictureDialog] = useState<{
777
1187
  pos: number | null;
@@ -904,7 +1314,8 @@ export function FoliToolbar({
904
1314
  </button>
905
1315
  );
906
1316
  if (item.actions) {
907
- const { actions } = item;
1317
+ const actions =
1318
+ typeof item.actions === "function" ? item.actions(body) : item.actions;
908
1319
  return (
909
1320
  <span key={item.key} className="foli-toolbar-menu">
910
1321
  {button}
@@ -915,8 +1326,48 @@ export function FoliToolbar({
915
1326
  state={editor.state}
916
1327
  onPick={(action, pointer) => {
917
1328
  setMenu(null);
1329
+ if (action.dialog === "noteOptions") {
1330
+ setDialog(null);
1331
+ setTableDialog(null);
1332
+ setSetupDialog(null);
1333
+ setReferenceDialog(null);
1334
+ setControlDialog(null);
1335
+ setNoteDialog({ restore: buttons.current[i] ?? null });
1336
+ return;
1337
+ }
1338
+ if (action.dialog === "controlProperties") {
1339
+ setDialog(null);
1340
+ setTableDialog(null);
1341
+ setSetupDialog(null);
1342
+ setReferenceDialog(null);
1343
+ setControlDialog({
1344
+ restore: buttons.current[i] ?? null,
1345
+ selection: editor.state.selection,
1346
+ });
1347
+ return;
1348
+ }
1349
+ if (action.dialog === "crossReference") {
1350
+ setDialog(null);
1351
+ setTableDialog(null);
1352
+ setSetupDialog(null);
1353
+ setReferenceDialog({
1354
+ restore: buttons.current[i] ?? null,
1355
+ selection: editor.state.selection,
1356
+ });
1357
+ return;
1358
+ }
1359
+ if (action.dialog === "pageSetup") {
1360
+ setDialog(null);
1361
+ setTableDialog(null);
1362
+ setSetupDialog({
1363
+ restore: buttons.current[i] ?? null,
1364
+ selection: editor.state.selection,
1365
+ });
1366
+ return;
1367
+ }
918
1368
  if (action.dialog) {
919
1369
  setDialog(null);
1370
+ setSetupDialog(null);
920
1371
  setTableDialog((current) => ({
921
1372
  restore: buttons.current[i] ?? null,
922
1373
  selection: editor.state.selection,
@@ -925,6 +1376,7 @@ export function FoliToolbar({
925
1376
  return;
926
1377
  }
927
1378
  editor.run(action.command);
1379
+ if (action.movesFocus) return;
928
1380
  if (pointer) onClickCommand?.();
929
1381
  else buttons.current[i]?.focus();
930
1382
  }}
@@ -979,6 +1431,51 @@ export function FoliToolbar({
979
1431
  }}
980
1432
  />
981
1433
  )}
1434
+ {setupDialog && !disabled && (
1435
+ <PageSetupDialog
1436
+ editor={editor}
1437
+ onClose={(applied) => {
1438
+ const { restore } = setupDialog;
1439
+ setSetupDialog(null);
1440
+ if (applied && onClickCommand) onClickCommand();
1441
+ else restore?.focus();
1442
+ }}
1443
+ />
1444
+ )}
1445
+ {referenceDialog && !disabled && (
1446
+ <CrossReferenceDialog
1447
+ editor={editor}
1448
+ layout={() => body.storyView?.fieldLayout ?? null}
1449
+ onClose={(inserted) => {
1450
+ const { restore } = referenceDialog;
1451
+ setReferenceDialog(null);
1452
+ if (inserted && onClickCommand) onClickCommand();
1453
+ else restore?.focus();
1454
+ }}
1455
+ />
1456
+ )}
1457
+ {noteDialog && !disabled && (
1458
+ <NoteOptionsDialog
1459
+ editor={body}
1460
+ onClose={(applied) => {
1461
+ const { restore } = noteDialog;
1462
+ setNoteDialog(null);
1463
+ if (applied && onClickCommand) onClickCommand();
1464
+ else restore?.focus();
1465
+ }}
1466
+ />
1467
+ )}
1468
+ {controlDialog && !disabled && (
1469
+ <ControlDialog
1470
+ editor={editor}
1471
+ onClose={(applied) => {
1472
+ const { restore } = controlDialog;
1473
+ setControlDialog(null);
1474
+ if (applied && onClickCommand) onClickCommand();
1475
+ else restore?.focus();
1476
+ }}
1477
+ />
1478
+ )}
982
1479
  {tableDialog && !disabled && (
983
1480
  <InsertTableDialog
984
1481
  editor={editor}
@@ -1382,6 +1879,677 @@ function InsertTableDialog({
1382
1879
  );
1383
1880
  }
1384
1881
 
1882
+ /**
1883
+ * The cross-reference dialog: what to refer to (the document's bookmarks and headings), what to
1884
+ * show of it, whether it links there; Insert and Cancel; Escape cancels.
1885
+ */
1886
+ function CrossReferenceDialog({
1887
+ editor,
1888
+ layout,
1889
+ onClose,
1890
+ }: {
1891
+ editor: Editor;
1892
+ layout: () => FieldLayout | null;
1893
+ onClose: (inserted: boolean) => void;
1894
+ }) {
1895
+ const [{ bookmarks, headings }] = useState(() => crossReferenceTargets(editor.state));
1896
+ const options = [
1897
+ ...headings.map((h) => ({
1898
+ value: `h${h.pos}`,
1899
+ label: `${"\u00a0".repeat((h.level - 1) * 2)}${h.number ? `${h.number} ` : ""}${h.text}`,
1900
+ })),
1901
+ ...bookmarks.map((b) => ({ value: `b${b.name}`, label: `Bookmark: ${b.name}` })),
1902
+ ];
1903
+ const [target, setTarget] = useState(options[0]?.value ?? "");
1904
+ const [show, setShow] = useState<"text" | "page" | "number">("text");
1905
+ const [link, setLink] = useState(true);
1906
+ const [failed, setFailed] = useState(false);
1907
+ const first = useRef<HTMLSelectElement>(null);
1908
+ const id = useId();
1909
+ useEffect(() => {
1910
+ first.current?.focus();
1911
+ }, []);
1912
+ const insert = (event: FormEvent) => {
1913
+ event.preventDefault();
1914
+ const to = target[0] === "h" ? Number(target.slice(1)) : target.slice(1);
1915
+ if (editor.run(insertCrossReference({ to, show, link, layout: layout() }))) onClose(true);
1916
+ else setFailed(true);
1917
+ };
1918
+ return (
1919
+ <div
1920
+ role="dialog"
1921
+ aria-modal="true"
1922
+ aria-label="Insert cross-reference"
1923
+ className="foli-link-dialog foli-table-dialog"
1924
+ onKeyDown={(event) => {
1925
+ if (event.key === "Escape") {
1926
+ event.preventDefault();
1927
+ onClose(false);
1928
+ }
1929
+ if (event.key !== "Tab") return;
1930
+ // Tab goes round inside the dialog.
1931
+ const stops = [
1932
+ ...event.currentTarget.querySelectorAll<HTMLElement>("select, input, button"),
1933
+ ];
1934
+ const at = stops.indexOf(event.target as HTMLElement);
1935
+ const next = (at + (event.shiftKey ? -1 : 1) + stops.length) % stops.length;
1936
+ event.preventDefault();
1937
+ stops[next]?.focus();
1938
+ }}
1939
+ >
1940
+ <form onSubmit={insert} noValidate>
1941
+ <label htmlFor={`${id}-target`}>Refer to</label>
1942
+ <select
1943
+ ref={first}
1944
+ id={`${id}-target`}
1945
+ value={target}
1946
+ onChange={(event) => {
1947
+ setTarget(event.target.value);
1948
+ setFailed(false);
1949
+ }}
1950
+ >
1951
+ {options.map((option) => (
1952
+ <option key={option.value} value={option.value}>
1953
+ {option.label}
1954
+ </option>
1955
+ ))}
1956
+ </select>
1957
+ <label htmlFor={`${id}-show`}>Show</label>
1958
+ <select
1959
+ id={`${id}-show`}
1960
+ value={show}
1961
+ onChange={(event) => setShow(event.target.value as typeof show)}
1962
+ >
1963
+ <option value="text">Its text</option>
1964
+ <option value="page">Its page number</option>
1965
+ <option value="number">Its paragraph number</option>
1966
+ </select>
1967
+ <label>
1968
+ <input
1969
+ type="checkbox"
1970
+ checked={link}
1971
+ onChange={(event) => setLink(event.target.checked)}
1972
+ />
1973
+ Link to it
1974
+ </label>
1975
+ <button type="submit">Insert</button>
1976
+ <button type="button" onClick={() => onClose(false)}>
1977
+ Cancel
1978
+ </button>
1979
+ {failed && (
1980
+ <p className="foli-link-error" role="alert">
1981
+ A cross-reference cannot be inserted here.
1982
+ </p>
1983
+ )}
1984
+ </form>
1985
+ </div>
1986
+ );
1987
+ }
1988
+
1989
+ /** Word's number formats for notes. */
1990
+ const NOTE_FORMATS = [
1991
+ ["decimal", "1, 2, 3"],
1992
+ ["lowerLetter", "a, b, c"],
1993
+ ["upperLetter", "A, B, C"],
1994
+ ["lowerRoman", "i, ii, iii"],
1995
+ ["upperRoman", "I, II, III"],
1996
+ ["chicago", "*, †, ‡"],
1997
+ ] as const;
1998
+
1999
+ /**
2000
+ * How notes are placed and numbered, for the whole document as Word's dialog applies it: where
2001
+ * they go, the number format, where numbers start and when they restart; Escape cancels.
2002
+ */
2003
+ function NoteOptionsDialog({
2004
+ editor,
2005
+ onClose,
2006
+ }: {
2007
+ editor: Editor;
2008
+ onClose: (applied: boolean) => void;
2009
+ }) {
2010
+ const [kind, setKind] = useState<NoteKind>("footnote");
2011
+ const valuesOf = (of: NoteKind) => {
2012
+ const envelope = wordContext(editor.state)?.envelope;
2013
+ const section = sectionAt(editor.state)?.setup;
2014
+ return noteProperties(envelope ?? {}, of, section);
2015
+ };
2016
+ const [values, setValues] = useState(() => valuesOf("footnote"));
2017
+ const [start, setStart] = useState(String(values.start));
2018
+ const first = useRef<HTMLSelectElement>(null);
2019
+ const id = useId();
2020
+ useEffect(() => {
2021
+ first.current?.focus();
2022
+ }, []);
2023
+ const set = (change: Partial<typeof values>) => setValues((v) => ({ ...v, ...change }));
2024
+ const restarts = values.restart !== "continuous";
2025
+ const number = Number(start);
2026
+ const invalid = !restarts && (!Number.isInteger(number) || number < 1 || number > 16383);
2027
+ const apply = (event: FormEvent) => {
2028
+ event.preventDefault();
2029
+ if (invalid) return;
2030
+ const properties: NotePropertiesJSON = {
2031
+ position: values.position,
2032
+ format: values.format,
2033
+ restart: values.restart,
2034
+ start: restarts ? 1 : number,
2035
+ };
2036
+ onClose(editor.run(setNoteProperties(kind, properties)));
2037
+ };
2038
+ return (
2039
+ <div
2040
+ role="dialog"
2041
+ aria-label="Note options"
2042
+ className="foli-link-dialog foli-table-dialog"
2043
+ onKeyDown={(event) => {
2044
+ if (event.key !== "Escape") return;
2045
+ event.preventDefault();
2046
+ onClose(false);
2047
+ }}
2048
+ >
2049
+ <form onSubmit={apply} noValidate>
2050
+ <label htmlFor={`${id}-kind`}>Notes</label>
2051
+ <select
2052
+ ref={first}
2053
+ id={`${id}-kind`}
2054
+ value={kind}
2055
+ onChange={(event) => {
2056
+ const next = event.target.value as NoteKind;
2057
+ const shown = valuesOf(next);
2058
+ setKind(next);
2059
+ setValues(shown);
2060
+ setStart(String(shown.start));
2061
+ }}
2062
+ >
2063
+ <option value="footnote">Footnotes</option>
2064
+ <option value="endnote">Endnotes</option>
2065
+ </select>
2066
+ <label htmlFor={`${id}-position`}>Position</label>
2067
+ <select
2068
+ id={`${id}-position`}
2069
+ value={values.position}
2070
+ onChange={(event) =>
2071
+ set({ position: event.target.value as NonNullable<NotePropertiesJSON["position"]> })
2072
+ }
2073
+ >
2074
+ {kind === "footnote" ? (
2075
+ <>
2076
+ <option value="pageBottom">Bottom of page</option>
2077
+ <option value="beneathText">Below text</option>
2078
+ </>
2079
+ ) : (
2080
+ <>
2081
+ <option value="docEnd">End of document</option>
2082
+ <option value="sectEnd">End of section</option>
2083
+ </>
2084
+ )}
2085
+ </select>
2086
+ <label htmlFor={`${id}-format`}>Number format</label>
2087
+ <select
2088
+ id={`${id}-format`}
2089
+ value={values.format}
2090
+ onChange={(event) => set({ format: event.target.value })}
2091
+ >
2092
+ {NOTE_FORMATS.map(([value, label]) => (
2093
+ <option key={value} value={value}>
2094
+ {label}
2095
+ </option>
2096
+ ))}
2097
+ </select>
2098
+ <label htmlFor={`${id}-start`}>Start at</label>
2099
+ <input
2100
+ id={`${id}-start`}
2101
+ type="number"
2102
+ min={1}
2103
+ value={restarts ? "1" : start}
2104
+ disabled={restarts}
2105
+ aria-invalid={invalid || undefined}
2106
+ onChange={(event) => setStart(event.target.value)}
2107
+ />
2108
+ <label htmlFor={`${id}-restart`}>Numbering</label>
2109
+ <select
2110
+ id={`${id}-restart`}
2111
+ value={values.restart}
2112
+ onChange={(event) =>
2113
+ set({ restart: event.target.value as NonNullable<NotePropertiesJSON["restart"]> })
2114
+ }
2115
+ >
2116
+ <option value="continuous">Continuous</option>
2117
+ <option value="eachSect">Restart each section</option>
2118
+ {kind === "footnote" && <option value="eachPage">Restart each page</option>}
2119
+ </select>
2120
+ <button type="submit">Apply</button>
2121
+ <button type="button" onClick={() => onClose(false)}>
2122
+ Cancel
2123
+ </button>
2124
+ {invalid && (
2125
+ <p className="foli-link-error" role="alert">
2126
+ The start must be a whole number from 1.
2127
+ </p>
2128
+ )}
2129
+ </form>
2130
+ </div>
2131
+ );
2132
+ }
2133
+
2134
+ /** A list's items as the dialog shows them: one a line, `shown | value` where they differ. */
2135
+ const itemsText = (items: ControlJSON["items"]) =>
2136
+ (items ?? [])
2137
+ .map((item) =>
2138
+ item.display === undefined || item.display === item.value
2139
+ ? item.value
2140
+ : `${item.display} | ${item.value}`,
2141
+ )
2142
+ .join("\n");
2143
+
2144
+ function parseItems(text: string): NonNullable<ControlJSON["items"]> {
2145
+ const seen = new Set<string>();
2146
+ return text.split("\n").flatMap((line) => {
2147
+ const [shown = "", value = shown] = line.split("|").map((part) => part.trim());
2148
+ // Word refuses two items of one value.
2149
+ if (!shown || seen.has(value)) return [];
2150
+ seen.add(value);
2151
+ return [{ value, display: shown }];
2152
+ });
2153
+ }
2154
+
2155
+ /**
2156
+ * The properties of the control at the caret: title, tag, locks and what its kind has (list items,
2157
+ * date format, line breaks); OK and Cancel; Escape cancels.
2158
+ */
2159
+ function ControlDialog({
2160
+ editor,
2161
+ onClose,
2162
+ }: {
2163
+ editor: Editor;
2164
+ onClose: (applied: boolean) => void;
2165
+ }) {
2166
+ const [selected] = useState(() => selectedControl(editor.state));
2167
+ const control = selected?.control;
2168
+ const [title, setTitle] = useState(control?.alias ?? "");
2169
+ const [tag, setTag] = useState(control?.tag ?? "");
2170
+ const [noDelete, setNoDelete] = useState(
2171
+ control?.lock === "sdtLocked" || control?.lock === "sdtContentLocked",
2172
+ );
2173
+ const [noEdit, setNoEdit] = useState(
2174
+ control?.lock === "contentLocked" || control?.lock === "sdtContentLocked",
2175
+ );
2176
+ const [items, setItems] = useState(itemsText(control?.items));
2177
+ const [dateFormat, setDateFormat] = useState(control?.dateFormat ?? "d MMMM yyyy");
2178
+ const [multiLine, setMultiLine] = useState(control?.multiLine === true);
2179
+ const first = useRef<HTMLInputElement>(null);
2180
+ const id = useId();
2181
+ useEffect(() => {
2182
+ first.current?.focus();
2183
+ }, []);
2184
+ if (!selected || !control) return null;
2185
+ const { kind } = control;
2186
+ const hasList = kind === "dropDown" || kind === "comboBox";
2187
+ const apply = (event: FormEvent) => {
2188
+ event.preventDefault();
2189
+ const lock = noDelete
2190
+ ? noEdit
2191
+ ? "sdtContentLocked"
2192
+ : "sdtLocked"
2193
+ : noEdit
2194
+ ? "contentLocked"
2195
+ : "unlocked";
2196
+ onClose(
2197
+ editor.run(
2198
+ setControlProperties(selected.id, {
2199
+ title,
2200
+ tag,
2201
+ lock,
2202
+ ...(hasList ? { items: parseItems(items) } : {}),
2203
+ ...(kind === "date" ? { dateFormat } : {}),
2204
+ ...(kind === "text" ? { multiLine } : {}),
2205
+ }),
2206
+ ),
2207
+ );
2208
+ };
2209
+ return (
2210
+ <div
2211
+ role="dialog"
2212
+ aria-label="Content control properties"
2213
+ className="foli-link-dialog foli-table-dialog"
2214
+ onKeyDown={(event) => {
2215
+ if (event.key !== "Escape") return;
2216
+ event.preventDefault();
2217
+ onClose(false);
2218
+ }}
2219
+ >
2220
+ <form onSubmit={apply} noValidate>
2221
+ <label htmlFor={`${id}-title`}>Title</label>
2222
+ <input
2223
+ ref={first}
2224
+ id={`${id}-title`}
2225
+ value={title}
2226
+ onChange={(event) => setTitle(event.target.value)}
2227
+ />
2228
+ <label htmlFor={`${id}-tag`}>Tag</label>
2229
+ <input id={`${id}-tag`} value={tag} onChange={(event) => setTag(event.target.value)} />
2230
+ <label>
2231
+ <input
2232
+ type="checkbox"
2233
+ checked={noDelete}
2234
+ onChange={(event) => setNoDelete(event.target.checked)}
2235
+ />
2236
+ The control cannot be deleted
2237
+ </label>
2238
+ <label>
2239
+ <input
2240
+ type="checkbox"
2241
+ checked={noEdit}
2242
+ onChange={(event) => setNoEdit(event.target.checked)}
2243
+ />
2244
+ The contents cannot be edited
2245
+ </label>
2246
+ {hasList && (
2247
+ <>
2248
+ <label htmlFor={`${id}-items`}>List items, one per line (shown | value)</label>
2249
+ <textarea
2250
+ id={`${id}-items`}
2251
+ rows={4}
2252
+ value={items}
2253
+ onChange={(event) => setItems(event.target.value)}
2254
+ />
2255
+ </>
2256
+ )}
2257
+ {kind === "date" && (
2258
+ <>
2259
+ <label htmlFor={`${id}-format`}>Date format</label>
2260
+ <input
2261
+ id={`${id}-format`}
2262
+ value={dateFormat}
2263
+ onChange={(event) => setDateFormat(event.target.value)}
2264
+ />
2265
+ </>
2266
+ )}
2267
+ {kind === "text" && (
2268
+ <label>
2269
+ <input
2270
+ type="checkbox"
2271
+ checked={multiLine}
2272
+ onChange={(event) => setMultiLine(event.target.checked)}
2273
+ />
2274
+ Allow line breaks
2275
+ </label>
2276
+ )}
2277
+ <button type="submit">OK</button>
2278
+ <button type="button" onClick={() => onClose(false)}>
2279
+ Cancel
2280
+ </button>
2281
+ </form>
2282
+ </div>
2283
+ );
2284
+ }
2285
+
2286
+ const TWIPS_PER_CM = 1440 / 2.54;
2287
+ const MAX_TWIPS = 31_680;
2288
+ /** Word's limit on a section's columns. */
2289
+ const MAX_SECTION_COLUMNS = 45;
2290
+ const toCm = (twips: number) => String(Number((twips / TWIPS_PER_CM).toFixed(2)));
2291
+ /** A length in cm as whole twips (a decimal comma too), or null when it is not one in range. */
2292
+ function toTwips(text: string, min: number): number | null {
2293
+ const value = Number(text.trim().replace(",", "."));
2294
+ const twips = Math.round(value * TWIPS_PER_CM);
2295
+ return text.trim() && Number.isFinite(value) && twips >= min && twips <= MAX_TWIPS ? twips : null;
2296
+ }
2297
+
2298
+ const SECTION_STARTS = [
2299
+ ["nextPage", "Next page"],
2300
+ ["continuous", "Continuous"],
2301
+ ["evenPage", "Even page"],
2302
+ ["oddPage", "Odd page"],
2303
+ ["nextColumn", "Next column"],
2304
+ ] as const;
2305
+ type SetupField =
2306
+ | "width"
2307
+ | "height"
2308
+ | "top"
2309
+ | "bottom"
2310
+ | "left"
2311
+ | "right"
2312
+ | "count"
2313
+ | "space"
2314
+ | "widths";
2315
+ const SETUP_LABELS: Record<SetupField, string> = {
2316
+ width: "Page width (cm)",
2317
+ height: "Page height (cm)",
2318
+ top: "Top margin (cm)",
2319
+ bottom: "Bottom margin (cm)",
2320
+ left: "Left margin (cm)",
2321
+ right: "Right margin (cm)",
2322
+ count: "Columns",
2323
+ space: "Space between columns (cm)",
2324
+ widths: "Set column widths (cm, separated by ;)",
2325
+ };
2326
+
2327
+ /**
2328
+ * The page setup dialog, for the caret's section: how it starts, its page size and orientation,
2329
+ * margins and columns (equal, or set widths; the line between them), in centimetres. Only what
2330
+ * was changed is applied. Apply and Cancel; Escape cancels; a wrong field is marked and announced.
2331
+ */
2332
+ function PageSetupDialog({
2333
+ editor,
2334
+ onClose,
2335
+ }: {
2336
+ editor: Editor;
2337
+ /** `applied`: the setup changed (the focus may go to the document). */
2338
+ onClose: (applied: boolean) => void;
2339
+ }) {
2340
+ const id = useId();
2341
+ const [initial] = useState(() => {
2342
+ const setup = sectionAt(editor.state)?.setup ?? {};
2343
+ const width = setup.pageSize?.width ?? 12_240;
2344
+ const height = setup.pageSize?.height ?? 15_840;
2345
+ const m = setup.margins ?? {};
2346
+ const set = setup.columns?.equalWidth === false ? (setup.columns.widths ?? []) : [];
2347
+ return {
2348
+ start: setup.type ?? "nextPage",
2349
+ orientation: setup.pageSize?.orientation ?? (width > height ? "landscape" : "portrait"),
2350
+ separator: setup.columns?.separator === true,
2351
+ columns: setup.columns,
2352
+ fields: {
2353
+ width: toCm(width),
2354
+ height: toCm(height),
2355
+ top: toCm(Math.abs(m.top ?? 1440)),
2356
+ bottom: toCm(Math.abs(m.bottom ?? 1440)),
2357
+ left: toCm(m.left ?? 1440),
2358
+ right: toCm(m.right ?? 1440),
2359
+ count: String(set.length || (setup.columns?.count ?? 1)),
2360
+ space: toCm(setup.columns?.space ?? 720),
2361
+ widths: set.map((column) => toCm(column.width)).join("; "),
2362
+ } satisfies Record<SetupField, string>,
2363
+ };
2364
+ });
2365
+ const [start, setStart] = useState<string>(initial.start);
2366
+ const [orientation, setOrientation] = useState<string>(initial.orientation);
2367
+ const [separator, setSeparator] = useState(initial.separator);
2368
+ const [fields, setFields] = useState(initial.fields);
2369
+ const [error, setError] = useState<SetupField | "setup" | "mismatch" | null>(null);
2370
+ const first = useRef<HTMLSelectElement>(null);
2371
+ useEffect(() => first.current?.focus(), []);
2372
+
2373
+ const apply = (event: FormEvent) => {
2374
+ event.preventDefault();
2375
+ const wrong = (field: SetupField) => {
2376
+ setError(field);
2377
+ document.getElementById(`${id}-${field}`)?.focus();
2378
+ };
2379
+ const changed = (field: SetupField) => fields[field] !== initial.fields[field];
2380
+ const setup: SectionSetup = {};
2381
+ if (start !== initial.start)
2382
+ setup.type = start === "nextPage" ? undefined : (start as SectionJSON["type"]);
2383
+ const lengths: Partial<Record<SetupField, number>> = {};
2384
+ for (const field of ["width", "height", "top", "bottom", "left", "right"] as const) {
2385
+ if (!changed(field)) continue;
2386
+ const twips = toTwips(fields[field], field === "width" || field === "height" ? 1 : 0);
2387
+ if (twips === null) return wrong(field);
2388
+ lengths[field] = twips;
2389
+ }
2390
+ if (
2391
+ lengths.width !== undefined ||
2392
+ lengths.height !== undefined ||
2393
+ orientation !== initial.orientation
2394
+ )
2395
+ setup.pageSize = {
2396
+ ...(lengths.width !== undefined ? { width: lengths.width } : {}),
2397
+ ...(lengths.height !== undefined ? { height: lengths.height } : {}),
2398
+ orientation: orientation as "portrait" | "landscape",
2399
+ };
2400
+ const margins = {
2401
+ top: lengths.top,
2402
+ bottom: lengths.bottom,
2403
+ left: lengths.left,
2404
+ right: lengths.right,
2405
+ };
2406
+ const given = Object.entries(margins).filter(([, value]) => value !== undefined);
2407
+ if (given.length) setup.margins = Object.fromEntries(given);
2408
+ if (
2409
+ changed("count") ||
2410
+ changed("space") ||
2411
+ changed("widths") ||
2412
+ separator !== initial.separator
2413
+ ) {
2414
+ // What was not changed stays exactly as it is, each column's own space included.
2415
+ const before = initial.columns;
2416
+ const set = before?.equalWidth === false ? (before.widths ?? []) : [];
2417
+ const space = changed("space") ? toTwips(fields.space, 0) : (before?.space ?? 720);
2418
+ if (space === null) return wrong("space");
2419
+ let widths: (number | null)[] = set.map((column) => column.width);
2420
+ if (changed("widths"))
2421
+ widths = fields.widths.trim()
2422
+ ? fields.widths
2423
+ .trim()
2424
+ .split(/[;\s]+/)
2425
+ .map((width) => toTwips(width, 1))
2426
+ : [];
2427
+ if (widths.includes(null)) return wrong("widths");
2428
+ const asked = Number(fields.count);
2429
+ if (widths.length && changed("count") && asked !== widths.length) {
2430
+ setError("mismatch");
2431
+ document.getElementById(`${id}-count`)?.focus();
2432
+ return;
2433
+ }
2434
+ const count = widths.length || asked;
2435
+ if (!Number.isInteger(count) || count < 1 || count > MAX_SECTION_COLUMNS)
2436
+ return wrong("count");
2437
+ const { separator: _line, equalWidth: _equal, widths: _widths, ...rest } = before ?? {};
2438
+ setup.columns = {
2439
+ ...rest,
2440
+ count,
2441
+ ...(changed("space") || before?.space === undefined ? { space } : {}),
2442
+ ...(separator ? { separator } : {}),
2443
+ ...(widths.length
2444
+ ? {
2445
+ equalWidth: false,
2446
+ widths: widths.map((width, i) => {
2447
+ const own = changed("space") ? undefined : set[i]?.space;
2448
+ const gap = own ?? (i < widths.length - 1 ? space : undefined);
2449
+ return { width: width as number, ...(gap === undefined ? {} : { space: gap }) };
2450
+ }),
2451
+ }
2452
+ : {}),
2453
+ };
2454
+ }
2455
+ if (!Object.keys(setup).length) return onClose(false);
2456
+ if (editor.run(setSectionSetup(setup))) return onClose(true);
2457
+ setError("setup");
2458
+ };
2459
+ const setOrientationSwapping = (next: string) => {
2460
+ if (next !== orientation)
2461
+ setFields((current) => ({ ...current, width: current.height, height: current.width }));
2462
+ setOrientation(next);
2463
+ setError(null);
2464
+ };
2465
+ const marked = (name: SetupField) => error === name || (name === "count" && error === "mismatch");
2466
+ const field = (name: SetupField) => (
2467
+ <div key={name} className="foli-setup-field">
2468
+ <label htmlFor={`${id}-${name}`}>{SETUP_LABELS[name]}</label>
2469
+ <input
2470
+ id={`${id}-${name}`}
2471
+ type="text"
2472
+ inputMode={name === "widths" ? "text" : "decimal"}
2473
+ value={fields[name]}
2474
+ aria-invalid={marked(name) || undefined}
2475
+ aria-describedby={marked(name) ? `${id}-error` : undefined}
2476
+ onChange={(event) => {
2477
+ setFields((current) => ({ ...current, [name]: event.target.value }));
2478
+ setError(null);
2479
+ }}
2480
+ />
2481
+ </div>
2482
+ );
2483
+
2484
+ return (
2485
+ <div
2486
+ role="dialog"
2487
+ aria-label="Page setup"
2488
+ className="foli-link-dialog foli-setup-dialog"
2489
+ onKeyDown={(event) => {
2490
+ if (event.key !== "Escape") return;
2491
+ event.preventDefault();
2492
+ onClose(false);
2493
+ }}
2494
+ >
2495
+ <form onSubmit={apply} noValidate>
2496
+ <div className="foli-setup-field">
2497
+ <label htmlFor={`${id}-start`}>Section starts</label>
2498
+ <select
2499
+ ref={first}
2500
+ id={`${id}-start`}
2501
+ value={start}
2502
+ onChange={(event) => setStart(event.target.value)}
2503
+ >
2504
+ {SECTION_STARTS.map(([value, label]) => (
2505
+ <option key={value} value={value}>
2506
+ {label}
2507
+ </option>
2508
+ ))}
2509
+ </select>
2510
+ </div>
2511
+ <div className="foli-setup-field">
2512
+ <label htmlFor={`${id}-orientation`}>Orientation</label>
2513
+ <select
2514
+ id={`${id}-orientation`}
2515
+ value={orientation}
2516
+ onChange={(event) => setOrientationSwapping(event.target.value)}
2517
+ >
2518
+ <option value="portrait">Portrait</option>
2519
+ <option value="landscape">Landscape</option>
2520
+ </select>
2521
+ </div>
2522
+ {(["width", "height", "top", "bottom", "left", "right", "count", "space"] as const).map(
2523
+ field,
2524
+ )}
2525
+ <div className="foli-setup-field foli-setup-check">
2526
+ <input
2527
+ id={`${id}-separator`}
2528
+ type="checkbox"
2529
+ checked={separator}
2530
+ onChange={(event) => setSeparator(event.target.checked)}
2531
+ />
2532
+ <label htmlFor={`${id}-separator`}>Line between columns</label>
2533
+ </div>
2534
+ {field("widths")}
2535
+ <button type="submit">Apply</button>
2536
+ <button type="button" onClick={() => onClose(false)}>
2537
+ Cancel
2538
+ </button>
2539
+ {error && (
2540
+ <p id={`${id}-error`} className="foli-link-error" role="alert">
2541
+ {error === "setup"
2542
+ ? "This setup leaves no room for text, or its columns do not fit the page."
2543
+ : error === "mismatch"
2544
+ ? "The number of columns differs from the set widths: list one width per column, or clear them for equal columns."
2545
+ : `Check this value: ${SETUP_LABELS[error]}.`}
2546
+ </p>
2547
+ )}
2548
+ </form>
2549
+ </div>
2550
+ );
2551
+ }
2552
+
1385
2553
  /** The largest picture side the schema takes, in px (2^31 - 1 EMU). */
1386
2554
  const MAX_PICTURE_PX = Math.floor(2_147_483_647 / EMU_PER_PX);
1387
2555