@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.
@@ -1,8 +1,9 @@
1
1
  import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { acceptAllChanges, acceptChange, addComment, alignAt, canOutdent, changeIndent, colorAt, deleteColumns, deleteRows, deleteTable, fontFamilyAt, fontSizeAt, insertColumn, insertPageBreak, insertPicture, insertRow, insertTable, isHeaderRow, isSafeHref, lineSpacingAt, linkAt, listKindAt, mergeCells, nextChange, normalizeHref, openLinkEditor, paragraphStyleAt, paragraphStyles, previousChange, redo, redoDepth, rejectAllChanges, rejectChange, removeLink, requestsLinkEditor, selectedPicture, setAlign, setCellShading, setFontFamily, setFontSize, setHighlight, setLineSpacing, setLink, setParagraphStyle, setPictureAlt, setPictureSize, setReviewView, setTableStyle, setTextColor, setTrackChanges, splitCell, tableStyleAt, tableStyles, toggleHeaderRow, toggleList, toggleMark, trackState, undo, undoDepth, wordContext, } from "@folijs/core";
2
+ import { acceptAllChanges, acceptChange, addComment, addRepeatingItem, alignAt, canOutdent, changeIndent, colorAt, controlAt, controlProperties, convertNotes, crossReferenceTargets, deleteColumns, deleteRows, deleteTable, documentSections, fieldCodesShown, fieldsIn, fontFamilyAt, fontSizeAt, insertColumn, insertColumnBreak, insertControl, insertCrossReference, insertDate, insertNote, insertPageBreak, insertPageNumber, insertPicture, insertRow, insertSectionBreak, insertTable, insertTableOfContents, isHeaderRow, isSafeHref, lineSpacingAt, linkAt, listKindAt, mergeCells, nextChange, normalizeHref, noteAtSelection, noteProperties, openLinkEditor, paragraphStyleAt, paragraphStyles, previousChange, redo, redoDepth, rejectAllChanges, rejectChange, removeLink, removeSectionBreak, requestsLinkEditor, sectionAt, selectedPicture, setAlign, setCellShading, setControlProperties, setDifferentEvenPages, setDifferentFirstPage, setFontFamily, setFontSize, setHighlight, setLineSpacing, setLink, setNoteProperties, setParagraphStyle, setPictureAlt, setPictureSize, setReviewView, setSectionSetup, setStoryLinked, setTableStyle, setTextColor, setTrackChanges, splitCell, tableStyleAt, tableStyles, toggleFieldCodes, toggleHeaderRow, toggleList, toggleMark, trackState, undo, undoDepth, updateFields, } from "@folijs/core";
3
+ import { wordContext } from "@folijs/core/internal";
3
4
  import { EMU_PER_PX, measureImageFile, textWidthEmu } from "@folijs/view";
4
5
  import { Fragment, useEffect, useId, useMemo, useRef, useState, } from "react";
5
- import { useEditorOrContext, useEditorState } from "./editor.js";
6
+ import { development, sameItems, useActiveEditor, useEditorOrContext, useEditorState, } from "./editor.js";
6
7
  /**
7
8
  * The palettes (fixed: a document should not need a color picker). Text colors keep at least
8
9
  * 4.5:1 contrast on white; highlights keep dark text readable.
@@ -65,6 +66,263 @@ const TABLE_ACTIONS = [
65
66
  checked: isHeaderRow,
66
67
  },
67
68
  ];
69
+ const SECTION_ACTIONS = [
70
+ {
71
+ key: "pageSetup",
72
+ label: "Page setup…",
73
+ command: (state) => sectionAt(state) !== null,
74
+ dialog: "pageSetup",
75
+ },
76
+ { key: "breakNext", label: "Section break: next page", command: insertSectionBreak("nextPage") },
77
+ {
78
+ key: "breakContinuous",
79
+ label: "Section break: continuous",
80
+ command: insertSectionBreak("continuous"),
81
+ },
82
+ { key: "breakEven", label: "Section break: even page", command: insertSectionBreak("evenPage") },
83
+ { key: "breakOdd", label: "Section break: odd page", command: insertSectionBreak("oddPage") },
84
+ { key: "removeBreak", label: "Remove section break", command: removeSectionBreak },
85
+ { key: "columnBreak", label: "Column break", command: insertColumnBreak },
86
+ ];
87
+ /**
88
+ * The header and footer menu: opening them on the caret's page, and, for the one open (else the
89
+ * caret's section), what a section does about them.
90
+ */
91
+ function storyActions(body) {
92
+ const open = () => body.storyView?.open ?? null;
93
+ const setup = (state) => {
94
+ const index = open()?.section ?? sectionAt(state)?.index ?? 0;
95
+ return documentSections(state)[index]?.setup ?? {};
96
+ };
97
+ const edit = (side) => (_state, dispatch) => {
98
+ const view = body.storyView;
99
+ if (!view)
100
+ return false;
101
+ if (dispatch)
102
+ view.edit(side);
103
+ return true;
104
+ };
105
+ const linked = (state) => {
106
+ const story = open();
107
+ if (!story)
108
+ return false;
109
+ if (story.side === "note")
110
+ return false;
111
+ const references = story.side === "header" ? setup(state).headers : setup(state).footers;
112
+ return !references?.[story.variant];
113
+ };
114
+ const evenPages = (state) => wordContext(state)?.envelope.settings?.evenAndOddHeaders === true;
115
+ return [
116
+ { key: "editHeader", label: "Edit header", command: edit("header"), movesFocus: true },
117
+ { key: "editFooter", label: "Edit footer", command: edit("footer"), movesFocus: true },
118
+ {
119
+ key: "closeStory",
120
+ label: "Close header and footer",
121
+ movesFocus: true,
122
+ command: (_state, dispatch) => {
123
+ if (!open())
124
+ return false;
125
+ if (dispatch)
126
+ body.storyView?.close();
127
+ return true;
128
+ },
129
+ },
130
+ {
131
+ key: "firstPage",
132
+ label: "Different first page",
133
+ checked: (state) => setup(state).titlePage === true,
134
+ command: (state, dispatch) => setDifferentFirstPage(setup(state).titlePage !== true, open()?.section)(state, dispatch),
135
+ },
136
+ {
137
+ key: "evenPages",
138
+ label: "Different odd and even pages",
139
+ checked: evenPages,
140
+ command: (state, dispatch) => setDifferentEvenPages(!evenPages(state))(state, dispatch),
141
+ },
142
+ {
143
+ key: "linkPrevious",
144
+ label: "Link to previous",
145
+ checked: linked,
146
+ command: (state, dispatch) => {
147
+ const story = open();
148
+ return story && story.side !== "note"
149
+ ? setStoryLinked(story.side, story.variant, !linked(state), story.section)(state, dispatch)
150
+ : false;
151
+ },
152
+ },
153
+ ];
154
+ }
155
+ /**
156
+ * The notes menu: a new note (the caret goes into it), between a reference and its note, the
157
+ * conversions Word has, and the options dialog.
158
+ */
159
+ function noteActions(body) {
160
+ const insert = (kind) => (state, dispatch) => {
161
+ if (!insertNote(kind)(state))
162
+ return false;
163
+ if (dispatch) {
164
+ insertNote(kind)(state, dispatch);
165
+ body.storyView?.editNote();
166
+ }
167
+ return true;
168
+ };
169
+ return [
170
+ { key: "footnote", label: "Insert footnote", command: insert("footnote"), movesFocus: true },
171
+ { key: "endnote", label: "Insert endnote", command: insert("endnote"), movesFocus: true },
172
+ {
173
+ key: "goToNote",
174
+ label: "Go to note or reference",
175
+ movesFocus: true,
176
+ command: (state, dispatch) => {
177
+ const view = body.storyView;
178
+ if (!view)
179
+ return false;
180
+ if (view.open?.side === "note") {
181
+ if (dispatch)
182
+ view.toReference();
183
+ return true;
184
+ }
185
+ if (!noteAtSelection(state))
186
+ return false;
187
+ if (dispatch)
188
+ view.editNote();
189
+ return true;
190
+ },
191
+ },
192
+ {
193
+ key: "toEndnotes",
194
+ label: "Convert footnotes to endnotes",
195
+ command: (_state, dispatch) => convertNotes("endnote")(body.state, dispatch && body.dispatch),
196
+ },
197
+ {
198
+ key: "toFootnotes",
199
+ label: "Convert endnotes to footnotes",
200
+ command: (_state, dispatch) => convertNotes("footnote")(body.state, dispatch && body.dispatch),
201
+ },
202
+ {
203
+ key: "noteOptions",
204
+ label: "Note options…",
205
+ dialog: "noteOptions",
206
+ command: (state) => wordContext(state) !== null,
207
+ },
208
+ ];
209
+ }
210
+ /** The control the selection is in. */
211
+ const selectedControl = (state) => {
212
+ const range = controlAt(state.doc, state.selection.from);
213
+ const control = range && controlProperties(state, range.id);
214
+ return range && control ? { id: range.id, control } : null;
215
+ };
216
+ /** The content controls menu: each kind to insert, then what applies to the one at the caret. */
217
+ const CONTROL_ACTIONS = [
218
+ { key: "richText", label: "Rich text", command: insertControl("richText") },
219
+ { key: "plainText", label: "Plain text", command: insertControl("text") },
220
+ { key: "dropDown", label: "Drop-down list", command: insertControl("dropDown") },
221
+ { key: "comboBox", label: "Combo box", command: insertControl("comboBox") },
222
+ { key: "datePicker", label: "Date picker", command: insertControl("date") },
223
+ { key: "checkBox", label: "Check box", command: insertControl("checkbox") },
224
+ { key: "pictureControl", label: "Picture (selected)", command: insertControl("picture") },
225
+ { key: "repeating", label: "Repeating section", command: insertControl("repeating") },
226
+ { key: "repeatingItem", label: "Add repeating item", command: addRepeatingItem() },
227
+ {
228
+ key: "controlProperties",
229
+ label: "Control properties…",
230
+ dialog: "controlProperties",
231
+ command: (state) => selectedControl(state) !== null,
232
+ },
233
+ ];
234
+ /**
235
+ * The navigation menu: what `FoliNavigation` shows, with Word's keys. Nothing applies without it.
236
+ */
237
+ function navigationActions(body) {
238
+ const open = (request) => (_state, dispatch) => {
239
+ if (!body.navigation)
240
+ return false;
241
+ if (dispatch)
242
+ body.navigation(request);
243
+ return true;
244
+ };
245
+ const item = (key, label) => ({
246
+ key,
247
+ label,
248
+ command: open(key),
249
+ movesFocus: true,
250
+ });
251
+ return [
252
+ item("find", "Find\u2026"),
253
+ item("replace", "Replace\u2026"),
254
+ item("goTo", "Go to\u2026"),
255
+ item("bookmarks", "Bookmarks\u2026"),
256
+ item("outline", "Outline"),
257
+ ];
258
+ }
259
+ /**
260
+ * The fields menu: what can be inserted at the selection, updating (the view's pages when there is
261
+ * one) and the codes shown or hidden.
262
+ */
263
+ function fieldActions(body) {
264
+ const layout = () => body.storyView?.fieldLayout ?? null;
265
+ const active = () => {
266
+ const open = body.storyView?.open;
267
+ return (open && body.story(open.id)) || body;
268
+ };
269
+ const update = (editor, options) => body.storyView ? body.storyView.updateFields(options, editor) : updateFields(editor, options);
270
+ return [
271
+ {
272
+ key: "pageNumber",
273
+ label: "Page number",
274
+ command: (state, dispatch) => insertPageNumber({ layout: layout() })(state, dispatch),
275
+ },
276
+ { key: "date", label: "Date", command: insertDate() },
277
+ {
278
+ key: "crossReference",
279
+ label: "Cross-reference…",
280
+ dialog: "crossReference",
281
+ command: (state) => {
282
+ const { bookmarks, headings } = crossReferenceTargets(state);
283
+ return insertPageBreak(state) && bookmarks.length + headings.length > 0;
284
+ },
285
+ },
286
+ {
287
+ key: "tableOfContents",
288
+ label: "Table of contents",
289
+ command: (state, dispatch) => {
290
+ const done = insertTableOfContents({ layout: layout() })(state, dispatch);
291
+ // Its own lines moved the headings: their page numbers follow, in the same undo step.
292
+ if (done && dispatch)
293
+ update(body, { only: (field) => field.parent?.name === "TOC", continues: true });
294
+ return done;
295
+ },
296
+ },
297
+ {
298
+ key: "updateSelected",
299
+ label: "Update selected fields",
300
+ command: (state, dispatch) => {
301
+ if (!fieldsIn(state.doc).length)
302
+ return false;
303
+ const { from, to } = state.selection;
304
+ if (dispatch)
305
+ update(active(), { only: { from, to } });
306
+ return true;
307
+ },
308
+ },
309
+ {
310
+ key: "updateAll",
311
+ label: "Update all fields",
312
+ command: (_state, dispatch) => {
313
+ if (dispatch)
314
+ update(body, {});
315
+ return true;
316
+ },
317
+ },
318
+ {
319
+ key: "fieldCodes",
320
+ label: "Show field codes",
321
+ checked: fieldCodesShown,
322
+ command: toggleFieldCodes,
323
+ },
324
+ ];
325
+ }
68
326
  /** Whether the selection holds a textblock (a caret's own block first; else it walks the range). */
69
327
  function hasTextblock(state) {
70
328
  if (state.selection.$from.parent.isTextblock)
@@ -79,23 +337,23 @@ function hasTextblock(state) {
79
337
  }
80
338
  /** Four bars, like the alignment they stand for (x and width per bar). */
81
339
  const alignIcon = (bars) => (_jsx("svg", { viewBox: "0 0 16 16", width: "16", height: "16", "aria-hidden": "true", focusable: "false", children: bars.map(([x, width], i) => (_jsx("rect", { x: x, y: 2.5 + i * 3.5, width: width, height: "1.5", fill: "currentColor" }, i))) }));
340
+ /** A paragraph takes every mark and a page break: no need for a dry run after each change. */
341
+ const always = () => true;
82
342
  const align = (value, label, bars) => ({
83
343
  key: `align-${value}`,
84
344
  label,
85
- text: label,
86
- symbol: true,
87
345
  icon: alignIcon(bars),
88
346
  pressed: (state) => alignAt(state) === value,
89
347
  enabled: hasTextblock,
90
- command: () => setAlign(value),
348
+ command: setAlign(value),
91
349
  });
92
- const mark = (key, label, text) => ({
350
+ const mark = (key, label, icon) => ({
93
351
  key,
94
352
  label,
95
- text,
96
- symbol: true,
353
+ icon,
97
354
  pressed: (_state, editor) => editor.isMarkActive(key),
98
- command: () => toggleMark(key),
355
+ enabled: always,
356
+ command: toggleMark(key),
99
357
  });
100
358
  const capitalized = (name) => name.charAt(0).toUpperCase() + name.slice(1);
101
359
  /** The fonts the font box offers (with the document's theme fonts, and the one shown now). */
@@ -174,13 +432,12 @@ const GROUPS = [
174
432
  pressed: (state) => linkAt(state) !== null,
175
433
  enabled: (state) => openLinkEditor(state),
176
434
  // Asks for the link dialog, as Mod-K does: the toolbar listens for that request.
177
- command: () => openLinkEditor,
435
+ command: openLinkEditor,
178
436
  },
179
437
  {
180
438
  key: "textColor",
181
439
  label: "Text color",
182
- text: "A",
183
- symbol: true,
440
+ icon: "A",
184
441
  enabled: hasTextblock,
185
442
  menu: {
186
443
  options: TEXT_COLORS,
@@ -191,8 +448,7 @@ const GROUPS = [
191
448
  {
192
449
  key: "highlight",
193
450
  label: "Highlight",
194
- text: "H",
195
- symbol: true,
451
+ icon: "H",
196
452
  enabled: hasTextblock,
197
453
  menu: {
198
454
  options: HIGHLIGHTS,
@@ -245,37 +501,33 @@ const GROUPS = [
245
501
  {
246
502
  key: "bulletList",
247
503
  label: "Bulleted list",
248
- text: "•",
249
- symbol: true,
504
+ icon: "•",
250
505
  pressed: (state) => listKindAt(state) === "bulletList",
251
506
  enabled: hasTextblock,
252
- command: () => toggleList("bulletList"),
507
+ command: toggleList("bulletList"),
253
508
  },
254
509
  {
255
510
  key: "orderedList",
256
511
  label: "Numbered list",
257
512
  // A symbol, not "1.": visible text that is not part of the name fails WCAG 2.5.3.
258
- text: "№",
259
- symbol: true,
513
+ icon: "№",
260
514
  pressed: (state) => listKindAt(state) === "orderedList",
261
515
  enabled: hasTextblock,
262
- command: () => toggleList("orderedList"),
516
+ command: toggleList("orderedList"),
263
517
  },
264
518
  {
265
519
  key: "outdent",
266
520
  label: "Decrease indent",
267
- text: "⇤",
268
- symbol: true,
521
+ icon: "⇤",
269
522
  enabled: canOutdent,
270
- command: () => changeIndent(-1),
523
+ command: changeIndent(-1),
271
524
  },
272
525
  {
273
526
  key: "indent",
274
527
  label: "Increase indent",
275
- text: "⇥",
276
- symbol: true,
528
+ icon: "⇥",
277
529
  enabled: hasTextblock,
278
- command: () => changeIndent(1),
530
+ command: changeIndent(1),
279
531
  },
280
532
  ],
281
533
  [
@@ -284,7 +536,7 @@ const GROUPS = [
284
536
  label: "New comment on the selection",
285
537
  text: "New comment",
286
538
  enabled: (state) => wordContext(state) !== null && hasTextblock(state),
287
- command: () => addComment(""),
539
+ command: addComment(""),
288
540
  },
289
541
  {
290
542
  key: "trackChanges",
@@ -292,7 +544,7 @@ const GROUPS = [
292
544
  text: "Track changes",
293
545
  pressed: (state) => trackState(state)?.on === true,
294
546
  enabled: (state) => trackState(state) !== null,
295
- command: (state) => setTrackChanges(!trackState(state)?.on),
547
+ command: (state, dispatch) => setTrackChanges(!trackState(state)?.on)(state, dispatch),
296
548
  },
297
549
  {
298
550
  key: "reviewView",
@@ -312,42 +564,42 @@ const GROUPS = [
312
564
  label: "Previous change",
313
565
  text: "Previous change",
314
566
  enabled: (state) => trackState(state) !== null,
315
- command: () => previousChange,
567
+ command: previousChange,
316
568
  },
317
569
  {
318
570
  key: "nextChange",
319
571
  label: "Next change",
320
572
  text: "Next change",
321
573
  enabled: (state) => trackState(state) !== null,
322
- command: () => nextChange,
574
+ command: nextChange,
323
575
  },
324
576
  {
325
577
  key: "acceptChange",
326
578
  label: "Accept the change here, or the changes selected",
327
579
  text: "Accept",
328
580
  enabled: (state) => trackState(state) !== null,
329
- command: () => acceptChange,
581
+ command: acceptChange,
330
582
  },
331
583
  {
332
584
  key: "rejectChange",
333
585
  label: "Reject the change here, or the changes selected",
334
586
  text: "Reject",
335
587
  enabled: (state) => trackState(state) !== null,
336
- command: () => rejectChange,
588
+ command: rejectChange,
337
589
  },
338
590
  {
339
591
  key: "acceptAll",
340
592
  label: "Accept all changes",
341
593
  text: "Accept all",
342
594
  enabled: (state) => trackState(state) !== null,
343
- command: () => acceptAllChanges(),
595
+ command: acceptAllChanges(),
344
596
  },
345
597
  {
346
598
  key: "rejectAll",
347
599
  label: "Reject all changes",
348
600
  text: "Reject all",
349
601
  enabled: (state) => trackState(state) !== null,
350
- command: () => rejectAllChanges(),
602
+ command: rejectAllChanges(),
351
603
  },
352
604
  ],
353
605
  [
@@ -356,14 +608,14 @@ const GROUPS = [
356
608
  label: "Undo",
357
609
  text: "Undo",
358
610
  enabled: (state) => undoDepth(state) > 0,
359
- command: () => undo,
611
+ command: undo,
360
612
  },
361
613
  {
362
614
  key: "redo",
363
615
  label: "Redo",
364
616
  text: "Redo",
365
617
  enabled: (state) => redoDepth(state) > 0,
366
- command: () => redo,
618
+ command: redo,
367
619
  },
368
620
  ],
369
621
  [
@@ -409,45 +661,124 @@ const GROUPS = [
409
661
  // With a picture selected the dialog edits it.
410
662
  dialog: "picture",
411
663
  },
412
- { key: "pageBreak", label: "Page break", text: "Page break", command: () => insertPageBreak },
664
+ {
665
+ key: "pageBreak",
666
+ label: "Page break",
667
+ text: "Page break",
668
+ enabled: always,
669
+ command: insertPageBreak,
670
+ },
671
+ {
672
+ key: "section",
673
+ label: "Section",
674
+ text: "Section",
675
+ enabled: (state) => wordContext(state) !== null,
676
+ actions: SECTION_ACTIONS,
677
+ },
678
+ {
679
+ key: "headerFooter",
680
+ label: "Header and footer",
681
+ text: "Header",
682
+ enabled: (state) => wordContext(state) !== null,
683
+ actions: storyActions,
684
+ },
685
+ {
686
+ key: "fields",
687
+ label: "Fields",
688
+ text: "Fields",
689
+ enabled: (state) => wordContext(state) !== null,
690
+ actions: fieldActions,
691
+ },
692
+ {
693
+ key: "navigate",
694
+ label: "Find and go to",
695
+ text: "Navigate",
696
+ enabled: (state) => wordContext(state) !== null,
697
+ actions: navigationActions,
698
+ },
699
+ {
700
+ key: "notes",
701
+ label: "Footnotes and endnotes",
702
+ text: "Notes",
703
+ enabled: (state) => wordContext(state) !== null,
704
+ actions: noteActions,
705
+ },
706
+ {
707
+ key: "controls",
708
+ label: "Content controls",
709
+ text: "Controls",
710
+ enabled: (state) => wordContext(state) !== null,
711
+ actions: CONTROL_ACTIONS,
712
+ },
413
713
  ],
414
714
  ];
415
- const ITEMS = GROUPS.flat();
416
- /** Without "New comment": where no comments pane lets a comment be written. */
417
- const GROUPS_NO_COMMENT = GROUPS.map((group) => group.filter((i) => i.key !== "newComment"));
418
- const ITEMS_NO_COMMENT = GROUPS_NO_COMMENT.flat();
715
+ /**
716
+ * The built-in items by name, to place in `FoliToolbarProps.items` (an item's `key` is its name,
717
+ * except the alignments: `align-start`, `align-center`, `align-end`, `align-justify`). A copy
718
+ * with another `label` or `icon` keeps what the built-in does.
719
+ */
720
+ export const toolbarItems = Object.fromEntries(GROUPS.flat().map((item) => [item.key.replace(/-(\w)/, (_, c) => c.toUpperCase()), item]));
721
+ /** The default toolbar: groups of `toolbarItems`, a separator between groups. */
722
+ export const defaultToolbarItems = GROUPS;
419
723
  const sameStates = (a, b) => a.length === b.length &&
420
724
  a.every((item, i) => item.pressed === b[i]?.pressed &&
421
725
  item.enabled === b[i]?.enabled &&
422
726
  item.value === b[i]?.value);
423
- /** Runs after every transaction: O(selection), no transactions built. */
424
- const statesOf = (items) => (state, editor) => items.map((item) => ({
727
+ /**
728
+ * Runs after every transaction: the built-ins' checks are O(selection), no transactions built;
729
+ * an app's item without `enabled` gets a dry run of its command.
730
+ */
731
+ const statesOf = (items, body) => (state, editor) => items.map((item) => ({
425
732
  pressed: item.pressed?.(state, editor),
426
- enabled: item.enabled?.(state) ?? true,
733
+ enabled: item.enabled
734
+ ? item.enabled(state, editor)
735
+ : item.actions
736
+ ? actionsOf(item, body).length > 0
737
+ : !item.command || editor.can(item.command),
427
738
  value: item.menu?.value(state) ??
428
739
  item.select?.value(state) ??
429
740
  (item.dialog ? (selectedPicture(state) ? "edit" : "insert") : undefined),
430
741
  }));
431
- const selectStates = statesOf(ITEMS);
432
- const selectStatesNoComment = statesOf(ITEMS_NO_COMMENT);
742
+ /** A menu button's entries (made from the body's editor when a function). */
743
+ const actionsOf = (item, body) => typeof item.actions === "function" ? item.actions(body) : (item.actions ?? []);
744
+ /** The same groups of the same items (an inline `items` array is not a change). */
745
+ const sameGroups = (a, b) => a === b || (!!a && !!b && a.length === b.length && a.every((group, i) => sameItems(group, b[i])));
433
746
  /**
434
- * Word's formatting controls for an editor: paragraph style, font and size boxes, marks, link (a
435
- * dialog, also on Mod-K in the document), text color and highlight menus, alignment and line
436
- * spacing, lists (bulleted, numbered, decrease and increase indent), undo, redo, tables (a Table
437
- * menu with an insert table dialog, a table style box, a cell shading menu), page break.
747
+ * Word's formatting controls for an editor (`defaultToolbarItems`, or `items`): paragraph
748
+ * style, font and size boxes, marks, link (a dialog, also on Mod-K in the document), text color
749
+ * and highlight menus, alignment and line spacing, lists (bulleted, numbered, decrease and
750
+ * increase indent), undo, redo, tables (a Table menu with an insert table dialog, a table style
751
+ * box, a cell shading menu), page break.
438
752
  * One tab stop (arrow keys, Home and End move between buttons); toggles carry
439
753
  * `aria-pressed`; a button whose command cannot run now is `aria-disabled` (still focusable).
440
754
  * Clicks leave the focus and selection in the document.
441
755
  */
442
- export function FoliToolbar({ editor: given, disabled = false, onClickCommand, label = "Formatting", className, comments = false, upload, }) {
443
- const editor = useEditorOrContext(given, "FoliToolbar");
444
- const groups = comments ? GROUPS : GROUPS_NO_COMMENT;
445
- const items = comments ? ITEMS : ITEMS_NO_COMMENT;
446
- const states = useEditorState(comments ? selectStates : selectStatesNoComment, {
447
- editor,
448
- isEqual: sameStates,
449
- });
450
- const [active, setActive] = useState(0);
756
+ export function FoliToolbar({ editor: given, disabled = false, onClickCommand, label = "Formatting", className, comments = false, upload, items: itemGroups, }) {
757
+ const body = useEditorOrContext(given, "FoliToolbar");
758
+ // A story open on its page takes the formatting commands; the body otherwise.
759
+ const editor = useActiveEditor(body);
760
+ // Without "New comment" where no comments pane lets a comment be written.
761
+ const lastGroups = useRef(itemGroups);
762
+ if (!sameGroups(lastGroups.current, itemGroups))
763
+ lastGroups.current = itemGroups;
764
+ const stableGroups = lastGroups.current;
765
+ const { groups, items, selectStates } = useMemo(() => {
766
+ const groups = (stableGroups ?? GROUPS)
767
+ .map((group) => group.filter((item) => comments || item.key !== "newComment"))
768
+ .filter((group) => group.length > 0);
769
+ const items = groups.flat();
770
+ if (development()) {
771
+ const keys = items.map((item) => item.key);
772
+ const twice = keys.find((key, i) => keys.indexOf(key) !== i);
773
+ if (twice !== undefined)
774
+ console.warn(`FoliToolbar: two items have the key "${twice}"; each needs its own`);
775
+ }
776
+ return { groups, items, selectStates: statesOf(items, body) };
777
+ }, [stableGroups, comments, body]);
778
+ const states = useEditorState(selectStates, { editor, isEqual: sameStates });
779
+ const [focused, setActive] = useState(0);
780
+ // The tab stop stays on the toolbar when items are taken away.
781
+ const active = focused < items.length ? focused : 0;
451
782
  const buttons = useRef([]);
452
783
  // Whether a select box was last used with the pointer (its pick then goes back to the document).
453
784
  const pointer = useRef(false);
@@ -475,6 +806,8 @@ export function FoliToolbar({ editor: given, disabled = false, onClickCommand, l
475
806
  });
476
807
  return;
477
808
  }
809
+ if (item.actions && !actionsOf(item, body).length)
810
+ return;
478
811
  if (item.menu || item.actions) {
479
812
  if (menu !== item.key) {
480
813
  setMenu(item.key);
@@ -490,7 +823,7 @@ export function FoliToolbar({ editor: given, disabled = false, onClickCommand, l
490
823
  }
491
824
  if (!item.command)
492
825
  return;
493
- editor.run(item.command(editor.state));
826
+ editor.run(item.command);
494
827
  // `detail` counts pointer clicks; Enter and Space on a button give 0.
495
828
  if (event.detail > 0)
496
829
  onClickCommand?.();
@@ -512,6 +845,30 @@ export function FoliToolbar({ editor: given, disabled = false, onClickCommand, l
512
845
  !state.selection.eq(current.selection))
513
846
  ? null
514
847
  : current);
848
+ // The cross-reference dialog inserts at the selection it opened on.
849
+ setReferenceDialog((current) => current &&
850
+ (!transactions.length ||
851
+ transactions.some((tr) => tr.docChanged) ||
852
+ !state.selection.eq(current.selection))
853
+ ? null
854
+ : current);
855
+ setNoteDialog((current) => current && (!transactions.length || transactions.some((tr) => tr.docChanged))
856
+ ? null
857
+ : current);
858
+ // The control properties dialog is for the control it opened on.
859
+ setControlDialog((current) => current &&
860
+ (!transactions.length ||
861
+ transactions.some((tr) => tr.docChanged) ||
862
+ !state.selection.eq(current.selection))
863
+ ? null
864
+ : current);
865
+ // So is the page setup dialog: its section may have changed.
866
+ setSetupDialog((current) => current &&
867
+ (!transactions.length ||
868
+ transactions.some((tr) => tr.docChanged) ||
869
+ !state.selection.eq(current.selection))
870
+ ? null
871
+ : current);
515
872
  // The insert table dialog is for the caret it opened on, as the link dialog is.
516
873
  setTableDialog((current) => current &&
517
874
  (!transactions.length ||
@@ -528,6 +885,9 @@ export function FoliToolbar({ editor: given, disabled = false, onClickCommand, l
528
885
  const active = typeof document === "undefined" ? null : document.activeElement;
529
886
  setTableDialog(null);
530
887
  setPictureDialog(null);
888
+ setSetupDialog(null);
889
+ setReferenceDialog(null);
890
+ setControlDialog(null);
531
891
  setDialog((current) => current
532
892
  ? { ...current, request: current.request + 1 }
533
893
  : {
@@ -552,6 +912,30 @@ export function FoliToolbar({ editor: given, disabled = false, onClickCommand, l
552
912
  if (disabled)
553
913
  setTableDialog(null);
554
914
  }, [disabled]);
915
+ // The page setup dialog (from the section menu), for the section of the caret it opened on.
916
+ const [setupDialog, setSetupDialog] = useState(null);
917
+ useEffect(() => {
918
+ if (disabled)
919
+ setSetupDialog(null);
920
+ }, [disabled]);
921
+ // The cross-reference dialog (from the fields menu).
922
+ const [referenceDialog, setReferenceDialog] = useState(null);
923
+ useEffect(() => {
924
+ if (disabled)
925
+ setReferenceDialog(null);
926
+ }, [disabled]);
927
+ // The control properties dialog (from the content controls menu).
928
+ const [controlDialog, setControlDialog] = useState(null);
929
+ useEffect(() => {
930
+ if (disabled)
931
+ setControlDialog(null);
932
+ }, [disabled]);
933
+ // The note options dialog (from the notes menu).
934
+ const [noteDialog, setNoteDialog] = useState(null);
935
+ useEffect(() => {
936
+ if (disabled)
937
+ setNoteDialog(null);
938
+ }, [disabled]);
555
939
  // The picture dialog: inserts at (or edits the picture at `pos`) the selection it opened on.
556
940
  const [pictureDialog, setPictureDialog] = useState(null);
557
941
  useEffect(() => {
@@ -581,9 +965,11 @@ export function FoliToolbar({ editor: given, disabled = false, onClickCommand, l
581
965
  const i = index++;
582
966
  const state = states[i];
583
967
  // Inserting a picture needs the app's upload; editing a selected one does not.
968
+ // A menu without entries cannot open, whatever its `enabled` says.
584
969
  const off = disabled ||
585
970
  !state?.enabled ||
586
- (item.dialog === "picture" && state?.value === "insert" && !upload);
971
+ (item.dialog === "picture" && state?.value === "insert" && !upload) ||
972
+ (item.actions !== undefined && actionsOf(item, body).length === 0);
587
973
  if (item.select) {
588
974
  const { select } = item;
589
975
  const value = state?.value ?? "";
@@ -607,7 +993,7 @@ export function FoliToolbar({ editor: given, disabled = false, onClickCommand, l
607
993
  }
608
994
  const button = (_jsxs("button", { ref: (element) => {
609
995
  buttons.current[i] = element;
610
- }, type: "button", className: `foli-toolbar-button foli-toolbar-${item.key}`, "aria-label": item.symbol ? item.label : undefined, title: item.label, "aria-pressed": item.pressed ? Boolean(state?.pressed) : undefined, "aria-haspopup": item.menu || item.actions ? "menu" : item.dialog ? "dialog" : undefined, "aria-expanded": item.menu || item.actions ? menu === item.key : undefined, "aria-disabled": off || undefined, tabIndex: i === active ? 0 : -1,
996
+ }, type: "button", className: `foli-toolbar-button foli-toolbar-${item.key}`, "aria-label": item.icon !== undefined ? item.label : undefined, title: item.label, "aria-pressed": item.pressed ? Boolean(state?.pressed) : undefined, "aria-haspopup": item.menu || item.actions ? "menu" : item.dialog ? "dialog" : undefined, "aria-expanded": item.menu || item.actions ? menu === item.key : undefined, "aria-disabled": off || undefined, tabIndex: i === active ? 0 : -1,
611
997
  // Keep the focus (and the selection) in the document on click.
612
998
  onMouseDown: (event) => event.preventDefault(), onFocus: () => setActive(i), onClick: (event) => run(i, event), onKeyDown: (event) => {
613
999
  // ArrowDown opens a menu (the WAI-ARIA menu button pattern).
@@ -615,13 +1001,53 @@ export function FoliToolbar({ editor: given, disabled = false, onClickCommand, l
615
1001
  return;
616
1002
  event.preventDefault();
617
1003
  setMenu(item.key);
618
- }, children: [item.icon ?? item.text, item.menu && (_jsx("span", { className: "foli-toolbar-swatch", "aria-hidden": "true", style: { background: state?.value ?? "transparent" } }))] }, item.key));
1004
+ }, children: [item.icon ?? item.text ?? item.label, item.menu && (_jsx("span", { className: "foli-toolbar-swatch", "aria-hidden": "true", style: { background: state?.value ?? "transparent" } }))] }, item.key));
619
1005
  if (item.actions) {
620
- const { actions } = item;
621
- return (_jsxs("span", { className: "foli-toolbar-menu", children: [button, menu === item.key && !disabled && (_jsx(ActionMenu, { label: item.label, actions: actions, state: editor.state, onPick: (action, pointer) => {
1006
+ const actions = actionsOf(item, body);
1007
+ return (_jsxs("span", { className: "foli-toolbar-menu", children: [button, menu === item.key && !disabled && actions.length > 0 && (_jsx(ActionMenu, { label: item.label, actions: actions, editor: editor, state: editor.state, onPick: (action, pointer) => {
622
1008
  setMenu(null);
1009
+ if (action.dialog === "noteOptions") {
1010
+ setDialog(null);
1011
+ setTableDialog(null);
1012
+ setSetupDialog(null);
1013
+ setReferenceDialog(null);
1014
+ setControlDialog(null);
1015
+ setNoteDialog({ restore: buttons.current[i] ?? null });
1016
+ return;
1017
+ }
1018
+ if (action.dialog === "controlProperties") {
1019
+ setDialog(null);
1020
+ setTableDialog(null);
1021
+ setSetupDialog(null);
1022
+ setReferenceDialog(null);
1023
+ setControlDialog({
1024
+ restore: buttons.current[i] ?? null,
1025
+ selection: editor.state.selection,
1026
+ });
1027
+ return;
1028
+ }
1029
+ if (action.dialog === "crossReference") {
1030
+ setDialog(null);
1031
+ setTableDialog(null);
1032
+ setSetupDialog(null);
1033
+ setReferenceDialog({
1034
+ restore: buttons.current[i] ?? null,
1035
+ selection: editor.state.selection,
1036
+ });
1037
+ return;
1038
+ }
1039
+ if (action.dialog === "pageSetup") {
1040
+ setDialog(null);
1041
+ setTableDialog(null);
1042
+ setSetupDialog({
1043
+ restore: buttons.current[i] ?? null,
1044
+ selection: editor.state.selection,
1045
+ });
1046
+ return;
1047
+ }
623
1048
  if (action.dialog) {
624
1049
  setDialog(null);
1050
+ setSetupDialog(null);
625
1051
  setTableDialog((current) => ({
626
1052
  restore: buttons.current[i] ?? null,
627
1053
  selection: editor.state.selection,
@@ -630,6 +1056,8 @@ export function FoliToolbar({ editor: given, disabled = false, onClickCommand, l
630
1056
  return;
631
1057
  }
632
1058
  editor.run(action.command);
1059
+ if (action.movesFocus)
1060
+ return;
633
1061
  if (pointer)
634
1062
  onClickCommand?.();
635
1063
  else
@@ -663,6 +1091,34 @@ export function FoliToolbar({ editor: given, disabled = false, onClickCommand, l
663
1091
  onClickCommand();
664
1092
  else
665
1093
  restore?.focus();
1094
+ } })), setupDialog && !disabled && (_jsx(PageSetupDialog, { editor: editor, onClose: (applied) => {
1095
+ const { restore } = setupDialog;
1096
+ setSetupDialog(null);
1097
+ if (applied && onClickCommand)
1098
+ onClickCommand();
1099
+ else
1100
+ restore?.focus();
1101
+ } })), referenceDialog && !disabled && (_jsx(CrossReferenceDialog, { editor: editor, layout: () => body.storyView?.fieldLayout ?? null, onClose: (inserted) => {
1102
+ const { restore } = referenceDialog;
1103
+ setReferenceDialog(null);
1104
+ if (inserted && onClickCommand)
1105
+ onClickCommand();
1106
+ else
1107
+ restore?.focus();
1108
+ } })), noteDialog && !disabled && (_jsx(NoteOptionsDialog, { editor: body, onClose: (applied) => {
1109
+ const { restore } = noteDialog;
1110
+ setNoteDialog(null);
1111
+ if (applied && onClickCommand)
1112
+ onClickCommand();
1113
+ else
1114
+ restore?.focus();
1115
+ } })), controlDialog && !disabled && (_jsx(ControlDialog, { editor: editor, onClose: (applied) => {
1116
+ const { restore } = controlDialog;
1117
+ setControlDialog(null);
1118
+ if (applied && onClickCommand)
1119
+ onClickCommand();
1120
+ else
1121
+ restore?.focus();
666
1122
  } })), tableDialog && !disabled && (_jsx(InsertTableDialog, { editor: editor, request: tableDialog.request, onClose: (inserted) => {
667
1123
  const { restore } = tableDialog;
668
1124
  setTableDialog(null);
@@ -763,7 +1219,7 @@ function LinkDialog({ editor, href, request, onClose, }) {
763
1219
  * Escape closes it back to its button, Tab closes it and moves on; leaving it closes it. An item
764
1220
  * that cannot apply here is `aria-disabled` (still focusable, as in the toolbar).
765
1221
  */
766
- function ActionMenu({ label, actions, state, onPick, onClose, }) {
1222
+ function ActionMenu({ label, actions, editor, state, onPick, onClose, }) {
767
1223
  const items = useRef([]);
768
1224
  // Dry runs, once per opening (not after every transaction).
769
1225
  // biome-ignore lint/correctness/useExhaustiveDependencies: the actions are a constant list.
@@ -812,7 +1268,7 @@ function ActionMenu({ label, actions, state, onPick, onClose, }) {
812
1268
  onPick(action, event.detail > 0);
813
1269
  },
814
1270
  };
815
- return action.checked ? (_jsx("button", { ...props, role: "menuitemcheckbox", "aria-checked": action.checked(state), children: action.label }, action.key)) : (_jsx("button", { ...props, role: "menuitem", children: action.label }, action.key));
1271
+ return action.checked ? (_jsx("button", { ...props, role: "menuitemcheckbox", "aria-checked": action.checked(state, editor), children: action.label }, action.key)) : (_jsx("button", { ...props, role: "menuitem", children: action.label }, action.key));
816
1272
  }) }));
817
1273
  }
818
1274
  /** Word's limits for a new table. */
@@ -867,6 +1323,355 @@ function InsertTableDialog({ editor, request, onClose, }) {
867
1323
  onClose(false);
868
1324
  }, children: _jsxs("form", { onSubmit: insert, noValidate: true, children: [field("rows", "Rows", rows, setRows, MAX_TABLE_ROWS, rowsField), field("columns", "Columns", columns, setColumns, MAX_TABLE_COLUMNS, columnsField), _jsx("button", { type: "submit", children: "Insert" }), _jsx("button", { type: "button", onClick: () => onClose(false), children: "Cancel" }), error && (_jsx("p", { id: `${id}-error`, className: "foli-link-error", role: "alert", children: messages[error] }))] }) }));
869
1325
  }
1326
+ /**
1327
+ * The cross-reference dialog: what to refer to (the document's bookmarks and headings), what to
1328
+ * show of it, whether it links there; Insert and Cancel; Escape cancels.
1329
+ */
1330
+ function CrossReferenceDialog({ editor, layout, onClose, }) {
1331
+ const [{ bookmarks, headings }] = useState(() => crossReferenceTargets(editor.state));
1332
+ const options = [
1333
+ ...headings.map((h) => ({
1334
+ value: `h${h.pos}`,
1335
+ label: `${"\u00a0".repeat((h.level - 1) * 2)}${h.number ? `${h.number} ` : ""}${h.text}`,
1336
+ })),
1337
+ ...bookmarks.map((b) => ({ value: `b${b.name}`, label: `Bookmark: ${b.name}` })),
1338
+ ];
1339
+ const [target, setTarget] = useState(options[0]?.value ?? "");
1340
+ const [show, setShow] = useState("text");
1341
+ const [link, setLink] = useState(true);
1342
+ const [failed, setFailed] = useState(false);
1343
+ const first = useRef(null);
1344
+ const id = useId();
1345
+ useEffect(() => {
1346
+ first.current?.focus();
1347
+ }, []);
1348
+ const insert = (event) => {
1349
+ event.preventDefault();
1350
+ const to = target[0] === "h" ? Number(target.slice(1)) : target.slice(1);
1351
+ if (editor.run(insertCrossReference({ to, show, link, layout: layout() })))
1352
+ onClose(true);
1353
+ else
1354
+ setFailed(true);
1355
+ };
1356
+ return (_jsx("div", { role: "dialog", "aria-modal": "true", "aria-label": "Insert cross-reference", className: "foli-link-dialog foli-table-dialog", onKeyDown: (event) => {
1357
+ if (event.key === "Escape") {
1358
+ event.preventDefault();
1359
+ onClose(false);
1360
+ }
1361
+ if (event.key !== "Tab")
1362
+ return;
1363
+ // Tab goes round inside the dialog.
1364
+ const stops = [
1365
+ ...event.currentTarget.querySelectorAll("select, input, button"),
1366
+ ];
1367
+ const at = stops.indexOf(event.target);
1368
+ const next = (at + (event.shiftKey ? -1 : 1) + stops.length) % stops.length;
1369
+ event.preventDefault();
1370
+ stops[next]?.focus();
1371
+ }, children: _jsxs("form", { onSubmit: insert, noValidate: true, children: [_jsx("label", { htmlFor: `${id}-target`, children: "Refer to" }), _jsx("select", { ref: first, id: `${id}-target`, value: target, onChange: (event) => {
1372
+ setTarget(event.target.value);
1373
+ setFailed(false);
1374
+ }, children: options.map((option) => (_jsx("option", { value: option.value, children: option.label }, option.value))) }), _jsx("label", { htmlFor: `${id}-show`, children: "Show" }), _jsxs("select", { id: `${id}-show`, value: show, onChange: (event) => setShow(event.target.value), children: [_jsx("option", { value: "text", children: "Its text" }), _jsx("option", { value: "page", children: "Its page number" }), _jsx("option", { value: "number", children: "Its paragraph number" })] }), _jsxs("label", { children: [_jsx("input", { type: "checkbox", checked: link, onChange: (event) => setLink(event.target.checked) }), "Link to it"] }), _jsx("button", { type: "submit", children: "Insert" }), _jsx("button", { type: "button", onClick: () => onClose(false), children: "Cancel" }), failed && (_jsx("p", { className: "foli-link-error", role: "alert", children: "A cross-reference cannot be inserted here." }))] }) }));
1375
+ }
1376
+ /** Word's number formats for notes. */
1377
+ const NOTE_FORMATS = [
1378
+ ["decimal", "1, 2, 3"],
1379
+ ["lowerLetter", "a, b, c"],
1380
+ ["upperLetter", "A, B, C"],
1381
+ ["lowerRoman", "i, ii, iii"],
1382
+ ["upperRoman", "I, II, III"],
1383
+ ["chicago", "*, †, ‡"],
1384
+ ];
1385
+ /**
1386
+ * How notes are placed and numbered, for the whole document as Word's dialog applies it: where
1387
+ * they go, the number format, where numbers start and when they restart; Escape cancels.
1388
+ */
1389
+ function NoteOptionsDialog({ editor, onClose, }) {
1390
+ const [kind, setKind] = useState("footnote");
1391
+ const valuesOf = (of) => {
1392
+ const envelope = wordContext(editor.state)?.envelope;
1393
+ const section = sectionAt(editor.state)?.setup;
1394
+ return noteProperties(envelope ?? {}, of, section);
1395
+ };
1396
+ const [values, setValues] = useState(() => valuesOf("footnote"));
1397
+ const [start, setStart] = useState(String(values.start));
1398
+ const first = useRef(null);
1399
+ const id = useId();
1400
+ useEffect(() => {
1401
+ first.current?.focus();
1402
+ }, []);
1403
+ const set = (change) => setValues((v) => ({ ...v, ...change }));
1404
+ const restarts = values.restart !== "continuous";
1405
+ const number = Number(start);
1406
+ const invalid = !restarts && (!Number.isInteger(number) || number < 1 || number > 16383);
1407
+ const apply = (event) => {
1408
+ event.preventDefault();
1409
+ if (invalid)
1410
+ return;
1411
+ const properties = {
1412
+ position: values.position,
1413
+ format: values.format,
1414
+ restart: values.restart,
1415
+ start: restarts ? 1 : number,
1416
+ };
1417
+ onClose(editor.run(setNoteProperties(kind, properties)));
1418
+ };
1419
+ return (_jsx("div", { role: "dialog", "aria-label": "Note options", className: "foli-link-dialog foli-table-dialog", onKeyDown: (event) => {
1420
+ if (event.key !== "Escape")
1421
+ return;
1422
+ event.preventDefault();
1423
+ onClose(false);
1424
+ }, children: _jsxs("form", { onSubmit: apply, noValidate: true, children: [_jsx("label", { htmlFor: `${id}-kind`, children: "Notes" }), _jsxs("select", { ref: first, id: `${id}-kind`, value: kind, onChange: (event) => {
1425
+ const next = event.target.value;
1426
+ const shown = valuesOf(next);
1427
+ setKind(next);
1428
+ setValues(shown);
1429
+ setStart(String(shown.start));
1430
+ }, children: [_jsx("option", { value: "footnote", children: "Footnotes" }), _jsx("option", { value: "endnote", children: "Endnotes" })] }), _jsx("label", { htmlFor: `${id}-position`, children: "Position" }), _jsx("select", { id: `${id}-position`, value: values.position, onChange: (event) => set({ position: event.target.value }), children: kind === "footnote" ? (_jsxs(_Fragment, { children: [_jsx("option", { value: "pageBottom", children: "Bottom of page" }), _jsx("option", { value: "beneathText", children: "Below text" })] })) : (_jsxs(_Fragment, { children: [_jsx("option", { value: "docEnd", children: "End of document" }), _jsx("option", { value: "sectEnd", children: "End of section" })] })) }), _jsx("label", { htmlFor: `${id}-format`, children: "Number format" }), _jsx("select", { id: `${id}-format`, value: values.format, onChange: (event) => set({ format: event.target.value }), children: NOTE_FORMATS.map(([value, label]) => (_jsx("option", { value: value, children: label }, value))) }), _jsx("label", { htmlFor: `${id}-start`, children: "Start at" }), _jsx("input", { id: `${id}-start`, type: "number", min: 1, value: restarts ? "1" : start, disabled: restarts, "aria-invalid": invalid || undefined, onChange: (event) => setStart(event.target.value) }), _jsx("label", { htmlFor: `${id}-restart`, children: "Numbering" }), _jsxs("select", { id: `${id}-restart`, value: values.restart, onChange: (event) => set({ restart: event.target.value }), children: [_jsx("option", { value: "continuous", children: "Continuous" }), _jsx("option", { value: "eachSect", children: "Restart each section" }), kind === "footnote" && _jsx("option", { value: "eachPage", children: "Restart each page" })] }), _jsx("button", { type: "submit", children: "Apply" }), _jsx("button", { type: "button", onClick: () => onClose(false), children: "Cancel" }), invalid && (_jsx("p", { className: "foli-link-error", role: "alert", children: "The start must be a whole number from 1." }))] }) }));
1431
+ }
1432
+ /** A list's items as the dialog shows them: one a line, `shown | value` where they differ. */
1433
+ const itemsText = (items) => (items ?? [])
1434
+ .map((item) => item.display === undefined || item.display === item.value
1435
+ ? item.value
1436
+ : `${item.display} | ${item.value}`)
1437
+ .join("\n");
1438
+ function parseItems(text) {
1439
+ const seen = new Set();
1440
+ return text.split("\n").flatMap((line) => {
1441
+ const [shown = "", value = shown] = line.split("|").map((part) => part.trim());
1442
+ // Word refuses two items of one value.
1443
+ if (!shown || seen.has(value))
1444
+ return [];
1445
+ seen.add(value);
1446
+ return [{ value, display: shown }];
1447
+ });
1448
+ }
1449
+ /**
1450
+ * The properties of the control at the caret: title, tag, locks and what its kind has (list items,
1451
+ * date format, line breaks); OK and Cancel; Escape cancels.
1452
+ */
1453
+ function ControlDialog({ editor, onClose, }) {
1454
+ const [selected] = useState(() => selectedControl(editor.state));
1455
+ const control = selected?.control;
1456
+ const [title, setTitle] = useState(control?.alias ?? "");
1457
+ const [tag, setTag] = useState(control?.tag ?? "");
1458
+ const [noDelete, setNoDelete] = useState(control?.lock === "sdtLocked" || control?.lock === "sdtContentLocked");
1459
+ const [noEdit, setNoEdit] = useState(control?.lock === "contentLocked" || control?.lock === "sdtContentLocked");
1460
+ const [items, setItems] = useState(itemsText(control?.items));
1461
+ const [dateFormat, setDateFormat] = useState(control?.dateFormat ?? "d MMMM yyyy");
1462
+ const [multiLine, setMultiLine] = useState(control?.multiLine === true);
1463
+ const first = useRef(null);
1464
+ const id = useId();
1465
+ useEffect(() => {
1466
+ first.current?.focus();
1467
+ }, []);
1468
+ if (!selected || !control)
1469
+ return null;
1470
+ const { kind } = control;
1471
+ const hasList = kind === "dropDown" || kind === "comboBox";
1472
+ const apply = (event) => {
1473
+ event.preventDefault();
1474
+ const lock = noDelete
1475
+ ? noEdit
1476
+ ? "sdtContentLocked"
1477
+ : "sdtLocked"
1478
+ : noEdit
1479
+ ? "contentLocked"
1480
+ : "unlocked";
1481
+ onClose(editor.run(setControlProperties(selected.id, {
1482
+ title,
1483
+ tag,
1484
+ lock,
1485
+ ...(hasList ? { items: parseItems(items) } : {}),
1486
+ ...(kind === "date" ? { dateFormat } : {}),
1487
+ ...(kind === "text" ? { multiLine } : {}),
1488
+ })));
1489
+ };
1490
+ return (_jsx("div", { role: "dialog", "aria-label": "Content control properties", className: "foli-link-dialog foli-table-dialog", onKeyDown: (event) => {
1491
+ if (event.key !== "Escape")
1492
+ return;
1493
+ event.preventDefault();
1494
+ onClose(false);
1495
+ }, children: _jsxs("form", { onSubmit: apply, noValidate: true, children: [_jsx("label", { htmlFor: `${id}-title`, children: "Title" }), _jsx("input", { ref: first, id: `${id}-title`, value: title, onChange: (event) => setTitle(event.target.value) }), _jsx("label", { htmlFor: `${id}-tag`, children: "Tag" }), _jsx("input", { id: `${id}-tag`, value: tag, onChange: (event) => setTag(event.target.value) }), _jsxs("label", { children: [_jsx("input", { type: "checkbox", checked: noDelete, onChange: (event) => setNoDelete(event.target.checked) }), "The control cannot be deleted"] }), _jsxs("label", { children: [_jsx("input", { type: "checkbox", checked: noEdit, onChange: (event) => setNoEdit(event.target.checked) }), "The contents cannot be edited"] }), hasList && (_jsxs(_Fragment, { children: [_jsx("label", { htmlFor: `${id}-items`, children: "List items, one per line (shown | value)" }), _jsx("textarea", { id: `${id}-items`, rows: 4, value: items, onChange: (event) => setItems(event.target.value) })] })), kind === "date" && (_jsxs(_Fragment, { children: [_jsx("label", { htmlFor: `${id}-format`, children: "Date format" }), _jsx("input", { id: `${id}-format`, value: dateFormat, onChange: (event) => setDateFormat(event.target.value) })] })), kind === "text" && (_jsxs("label", { children: [_jsx("input", { type: "checkbox", checked: multiLine, onChange: (event) => setMultiLine(event.target.checked) }), "Allow line breaks"] })), _jsx("button", { type: "submit", children: "OK" }), _jsx("button", { type: "button", onClick: () => onClose(false), children: "Cancel" })] }) }));
1496
+ }
1497
+ const TWIPS_PER_CM = 1440 / 2.54;
1498
+ const MAX_TWIPS = 31_680;
1499
+ /** Word's limit on a section's columns. */
1500
+ const MAX_SECTION_COLUMNS = 45;
1501
+ const toCm = (twips) => String(Number((twips / TWIPS_PER_CM).toFixed(2)));
1502
+ /** A length in cm as whole twips (a decimal comma too), or null when it is not one in range. */
1503
+ function toTwips(text, min) {
1504
+ const value = Number(text.trim().replace(",", "."));
1505
+ const twips = Math.round(value * TWIPS_PER_CM);
1506
+ return text.trim() && Number.isFinite(value) && twips >= min && twips <= MAX_TWIPS ? twips : null;
1507
+ }
1508
+ const SECTION_STARTS = [
1509
+ ["nextPage", "Next page"],
1510
+ ["continuous", "Continuous"],
1511
+ ["evenPage", "Even page"],
1512
+ ["oddPage", "Odd page"],
1513
+ ["nextColumn", "Next column"],
1514
+ ];
1515
+ const SETUP_LABELS = {
1516
+ width: "Page width (cm)",
1517
+ height: "Page height (cm)",
1518
+ top: "Top margin (cm)",
1519
+ bottom: "Bottom margin (cm)",
1520
+ left: "Left margin (cm)",
1521
+ right: "Right margin (cm)",
1522
+ count: "Columns",
1523
+ space: "Space between columns (cm)",
1524
+ widths: "Set column widths (cm, separated by ;)",
1525
+ };
1526
+ /**
1527
+ * The page setup dialog, for the caret's section: how it starts, its page size and orientation,
1528
+ * margins and columns (equal, or set widths; the line between them), in centimetres. Only what
1529
+ * was changed is applied. Apply and Cancel; Escape cancels; a wrong field is marked and announced.
1530
+ */
1531
+ function PageSetupDialog({ editor, onClose, }) {
1532
+ const id = useId();
1533
+ const [initial] = useState(() => {
1534
+ const setup = sectionAt(editor.state)?.setup ?? {};
1535
+ const width = setup.pageSize?.width ?? 12_240;
1536
+ const height = setup.pageSize?.height ?? 15_840;
1537
+ const m = setup.margins ?? {};
1538
+ const set = setup.columns?.equalWidth === false ? (setup.columns.widths ?? []) : [];
1539
+ return {
1540
+ start: setup.type ?? "nextPage",
1541
+ orientation: setup.pageSize?.orientation ?? (width > height ? "landscape" : "portrait"),
1542
+ separator: setup.columns?.separator === true,
1543
+ columns: setup.columns,
1544
+ fields: {
1545
+ width: toCm(width),
1546
+ height: toCm(height),
1547
+ top: toCm(Math.abs(m.top ?? 1440)),
1548
+ bottom: toCm(Math.abs(m.bottom ?? 1440)),
1549
+ left: toCm(m.left ?? 1440),
1550
+ right: toCm(m.right ?? 1440),
1551
+ count: String(set.length || (setup.columns?.count ?? 1)),
1552
+ space: toCm(setup.columns?.space ?? 720),
1553
+ widths: set.map((column) => toCm(column.width)).join("; "),
1554
+ },
1555
+ };
1556
+ });
1557
+ const [start, setStart] = useState(initial.start);
1558
+ const [orientation, setOrientation] = useState(initial.orientation);
1559
+ const [separator, setSeparator] = useState(initial.separator);
1560
+ const [fields, setFields] = useState(initial.fields);
1561
+ const [error, setError] = useState(null);
1562
+ const first = useRef(null);
1563
+ useEffect(() => first.current?.focus(), []);
1564
+ const apply = (event) => {
1565
+ event.preventDefault();
1566
+ const wrong = (field) => {
1567
+ setError(field);
1568
+ document.getElementById(`${id}-${field}`)?.focus();
1569
+ };
1570
+ const changed = (field) => fields[field] !== initial.fields[field];
1571
+ const setup = {};
1572
+ if (start !== initial.start)
1573
+ setup.type = start === "nextPage" ? undefined : start;
1574
+ const lengths = {};
1575
+ for (const field of ["width", "height", "top", "bottom", "left", "right"]) {
1576
+ if (!changed(field))
1577
+ continue;
1578
+ const twips = toTwips(fields[field], field === "width" || field === "height" ? 1 : 0);
1579
+ if (twips === null)
1580
+ return wrong(field);
1581
+ lengths[field] = twips;
1582
+ }
1583
+ if (lengths.width !== undefined ||
1584
+ lengths.height !== undefined ||
1585
+ orientation !== initial.orientation)
1586
+ setup.pageSize = {
1587
+ ...(lengths.width !== undefined ? { width: lengths.width } : {}),
1588
+ ...(lengths.height !== undefined ? { height: lengths.height } : {}),
1589
+ orientation: orientation,
1590
+ };
1591
+ const margins = {
1592
+ top: lengths.top,
1593
+ bottom: lengths.bottom,
1594
+ left: lengths.left,
1595
+ right: lengths.right,
1596
+ };
1597
+ const given = Object.entries(margins).filter(([, value]) => value !== undefined);
1598
+ if (given.length)
1599
+ setup.margins = Object.fromEntries(given);
1600
+ if (changed("count") ||
1601
+ changed("space") ||
1602
+ changed("widths") ||
1603
+ separator !== initial.separator) {
1604
+ // What was not changed stays exactly as it is, each column's own space included.
1605
+ const before = initial.columns;
1606
+ const set = before?.equalWidth === false ? (before.widths ?? []) : [];
1607
+ const space = changed("space") ? toTwips(fields.space, 0) : (before?.space ?? 720);
1608
+ if (space === null)
1609
+ return wrong("space");
1610
+ let widths = set.map((column) => column.width);
1611
+ if (changed("widths"))
1612
+ widths = fields.widths.trim()
1613
+ ? fields.widths
1614
+ .trim()
1615
+ .split(/[;\s]+/)
1616
+ .map((width) => toTwips(width, 1))
1617
+ : [];
1618
+ if (widths.includes(null))
1619
+ return wrong("widths");
1620
+ const asked = Number(fields.count);
1621
+ if (widths.length && changed("count") && asked !== widths.length) {
1622
+ setError("mismatch");
1623
+ document.getElementById(`${id}-count`)?.focus();
1624
+ return;
1625
+ }
1626
+ const count = widths.length || asked;
1627
+ if (!Number.isInteger(count) || count < 1 || count > MAX_SECTION_COLUMNS)
1628
+ return wrong("count");
1629
+ const { separator: _line, equalWidth: _equal, widths: _widths, ...rest } = before ?? {};
1630
+ setup.columns = {
1631
+ ...rest,
1632
+ count,
1633
+ ...(changed("space") || before?.space === undefined ? { space } : {}),
1634
+ ...(separator ? { separator } : {}),
1635
+ ...(widths.length
1636
+ ? {
1637
+ equalWidth: false,
1638
+ widths: widths.map((width, i) => {
1639
+ const own = changed("space") ? undefined : set[i]?.space;
1640
+ const gap = own ?? (i < widths.length - 1 ? space : undefined);
1641
+ return { width: width, ...(gap === undefined ? {} : { space: gap }) };
1642
+ }),
1643
+ }
1644
+ : {}),
1645
+ };
1646
+ }
1647
+ if (!Object.keys(setup).length)
1648
+ return onClose(false);
1649
+ if (editor.run(setSectionSetup(setup)))
1650
+ return onClose(true);
1651
+ setError("setup");
1652
+ };
1653
+ const setOrientationSwapping = (next) => {
1654
+ if (next !== orientation)
1655
+ setFields((current) => ({ ...current, width: current.height, height: current.width }));
1656
+ setOrientation(next);
1657
+ setError(null);
1658
+ };
1659
+ const marked = (name) => error === name || (name === "count" && error === "mismatch");
1660
+ const field = (name) => (_jsxs("div", { className: "foli-setup-field", children: [_jsx("label", { htmlFor: `${id}-${name}`, children: SETUP_LABELS[name] }), _jsx("input", { id: `${id}-${name}`, type: "text", inputMode: name === "widths" ? "text" : "decimal", value: fields[name], "aria-invalid": marked(name) || undefined, "aria-describedby": marked(name) ? `${id}-error` : undefined, onChange: (event) => {
1661
+ setFields((current) => ({ ...current, [name]: event.target.value }));
1662
+ setError(null);
1663
+ } })] }, name));
1664
+ return (_jsx("div", { role: "dialog", "aria-label": "Page setup", className: "foli-link-dialog foli-setup-dialog", onKeyDown: (event) => {
1665
+ if (event.key !== "Escape")
1666
+ return;
1667
+ event.preventDefault();
1668
+ onClose(false);
1669
+ }, children: _jsxs("form", { onSubmit: apply, noValidate: true, children: [_jsxs("div", { className: "foli-setup-field", children: [_jsx("label", { htmlFor: `${id}-start`, children: "Section starts" }), _jsx("select", { ref: first, id: `${id}-start`, value: start, onChange: (event) => setStart(event.target.value), children: SECTION_STARTS.map(([value, label]) => (_jsx("option", { value: value, children: label }, value))) })] }), _jsxs("div", { className: "foli-setup-field", children: [_jsx("label", { htmlFor: `${id}-orientation`, children: "Orientation" }), _jsxs("select", { id: `${id}-orientation`, value: orientation, onChange: (event) => setOrientationSwapping(event.target.value), children: [_jsx("option", { value: "portrait", children: "Portrait" }), _jsx("option", { value: "landscape", children: "Landscape" })] })] }), ["width", "height", "top", "bottom", "left", "right", "count", "space"].map(field), _jsxs("div", { className: "foli-setup-field foli-setup-check", children: [_jsx("input", { id: `${id}-separator`, type: "checkbox", checked: separator, onChange: (event) => setSeparator(event.target.checked) }), _jsx("label", { htmlFor: `${id}-separator`, children: "Line between columns" })] }), field("widths"), _jsx("button", { type: "submit", children: "Apply" }), _jsx("button", { type: "button", onClick: () => onClose(false), children: "Cancel" }), error && (_jsx("p", { id: `${id}-error`, className: "foli-link-error", role: "alert", children: error === "setup"
1670
+ ? "This setup leaves no room for text, or its columns do not fit the page."
1671
+ : error === "mismatch"
1672
+ ? "The number of columns differs from the set widths: list one width per column, or clear them for equal columns."
1673
+ : `Check this value: ${SETUP_LABELS[error]}.` }))] }) }));
1674
+ }
870
1675
  /** The largest picture side the schema takes, in px (2^31 - 1 EMU). */
871
1676
  const MAX_PICTURE_PX = Math.floor(2_147_483_647 / EMU_PER_PX);
872
1677
  /**