@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.
@@ -1,8 +1,8 @@
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, wordContext, } from "@folijs/core";
3
3
  import { EMU_PER_PX, measureImageFile, textWidthEmu } from "@folijs/view";
4
4
  import { Fragment, useEffect, useId, useMemo, useRef, useState, } from "react";
5
- import { useEditorOrContext, useEditorState } from "./editor.js";
5
+ import { useActiveEditor, useEditorOrContext, useEditorState } from "./editor.js";
6
6
  /**
7
7
  * The palettes (fixed: a document should not need a color picker). Text colors keep at least
8
8
  * 4.5:1 contrast on white; highlights keep dark text readable.
@@ -65,6 +65,263 @@ const TABLE_ACTIONS = [
65
65
  checked: isHeaderRow,
66
66
  },
67
67
  ];
68
+ const SECTION_ACTIONS = [
69
+ {
70
+ key: "pageSetup",
71
+ label: "Page setup…",
72
+ command: (state) => sectionAt(state) !== null,
73
+ dialog: "pageSetup",
74
+ },
75
+ { key: "breakNext", label: "Section break: next page", command: insertSectionBreak("nextPage") },
76
+ {
77
+ key: "breakContinuous",
78
+ label: "Section break: continuous",
79
+ command: insertSectionBreak("continuous"),
80
+ },
81
+ { key: "breakEven", label: "Section break: even page", command: insertSectionBreak("evenPage") },
82
+ { key: "breakOdd", label: "Section break: odd page", command: insertSectionBreak("oddPage") },
83
+ { key: "removeBreak", label: "Remove section break", command: removeSectionBreak },
84
+ { key: "columnBreak", label: "Column break", command: insertColumnBreak },
85
+ ];
86
+ /**
87
+ * The header and footer menu: opening them on the caret's page, and, for the one open (else the
88
+ * caret's section), what a section does about them.
89
+ */
90
+ function storyActions(body) {
91
+ const open = () => body.storyView?.open ?? null;
92
+ const setup = (state) => {
93
+ const index = open()?.section ?? sectionAt(state)?.index ?? 0;
94
+ return documentSections(state)[index]?.setup ?? {};
95
+ };
96
+ const edit = (side) => (_state, dispatch) => {
97
+ const view = body.storyView;
98
+ if (!view)
99
+ return false;
100
+ if (dispatch)
101
+ view.edit(side);
102
+ return true;
103
+ };
104
+ const linked = (state) => {
105
+ const story = open();
106
+ if (!story)
107
+ return false;
108
+ if (story.side === "note")
109
+ return false;
110
+ const references = story.side === "header" ? setup(state).headers : setup(state).footers;
111
+ return !references?.[story.variant];
112
+ };
113
+ const evenPages = (state) => wordContext(state)?.envelope.settings?.evenAndOddHeaders === true;
114
+ return [
115
+ { key: "editHeader", label: "Edit header", command: edit("header"), movesFocus: true },
116
+ { key: "editFooter", label: "Edit footer", command: edit("footer"), movesFocus: true },
117
+ {
118
+ key: "closeStory",
119
+ label: "Close header and footer",
120
+ movesFocus: true,
121
+ command: (_state, dispatch) => {
122
+ if (!open())
123
+ return false;
124
+ if (dispatch)
125
+ body.storyView?.close();
126
+ return true;
127
+ },
128
+ },
129
+ {
130
+ key: "firstPage",
131
+ label: "Different first page",
132
+ checked: (state) => setup(state).titlePage === true,
133
+ command: (state, dispatch) => setDifferentFirstPage(setup(state).titlePage !== true, open()?.section)(state, dispatch),
134
+ },
135
+ {
136
+ key: "evenPages",
137
+ label: "Different odd and even pages",
138
+ checked: evenPages,
139
+ command: (state, dispatch) => setDifferentEvenPages(!evenPages(state))(state, dispatch),
140
+ },
141
+ {
142
+ key: "linkPrevious",
143
+ label: "Link to previous",
144
+ checked: linked,
145
+ command: (state, dispatch) => {
146
+ const story = open();
147
+ return story && story.side !== "note"
148
+ ? setStoryLinked(story.side, story.variant, !linked(state), story.section)(state, dispatch)
149
+ : false;
150
+ },
151
+ },
152
+ ];
153
+ }
154
+ /**
155
+ * The notes menu: a new note (the caret goes into it), between a reference and its note, the
156
+ * conversions Word has, and the options dialog.
157
+ */
158
+ function noteActions(body) {
159
+ const insert = (kind) => (state, dispatch) => {
160
+ if (!insertNote(kind)(state))
161
+ return false;
162
+ if (dispatch) {
163
+ insertNote(kind)(state, dispatch);
164
+ body.storyView?.editNote();
165
+ }
166
+ return true;
167
+ };
168
+ return [
169
+ { key: "footnote", label: "Insert footnote", command: insert("footnote"), movesFocus: true },
170
+ { key: "endnote", label: "Insert endnote", command: insert("endnote"), movesFocus: true },
171
+ {
172
+ key: "goToNote",
173
+ label: "Go to note or reference",
174
+ movesFocus: true,
175
+ command: (state, dispatch) => {
176
+ const view = body.storyView;
177
+ if (!view)
178
+ return false;
179
+ if (view.open?.side === "note") {
180
+ if (dispatch)
181
+ view.toReference();
182
+ return true;
183
+ }
184
+ if (!noteAtSelection(state))
185
+ return false;
186
+ if (dispatch)
187
+ view.editNote();
188
+ return true;
189
+ },
190
+ },
191
+ {
192
+ key: "toEndnotes",
193
+ label: "Convert footnotes to endnotes",
194
+ command: (_state, dispatch) => convertNotes("endnote")(body.state, dispatch && body.dispatch),
195
+ },
196
+ {
197
+ key: "toFootnotes",
198
+ label: "Convert endnotes to footnotes",
199
+ command: (_state, dispatch) => convertNotes("footnote")(body.state, dispatch && body.dispatch),
200
+ },
201
+ {
202
+ key: "noteOptions",
203
+ label: "Note options…",
204
+ dialog: "noteOptions",
205
+ command: (state) => wordContext(state) !== null,
206
+ },
207
+ ];
208
+ }
209
+ /** The control the selection is in. */
210
+ const selectedControl = (state) => {
211
+ const range = controlAt(state.doc, state.selection.from);
212
+ const control = range && controlProperties(state, range.id);
213
+ return range && control ? { id: range.id, control } : null;
214
+ };
215
+ /** The content controls menu: each kind to insert, then what applies to the one at the caret. */
216
+ const CONTROL_ACTIONS = [
217
+ { key: "richText", label: "Rich text", command: insertControl("richText") },
218
+ { key: "plainText", label: "Plain text", command: insertControl("text") },
219
+ { key: "dropDown", label: "Drop-down list", command: insertControl("dropDown") },
220
+ { key: "comboBox", label: "Combo box", command: insertControl("comboBox") },
221
+ { key: "datePicker", label: "Date picker", command: insertControl("date") },
222
+ { key: "checkBox", label: "Check box", command: insertControl("checkbox") },
223
+ { key: "pictureControl", label: "Picture (selected)", command: insertControl("picture") },
224
+ { key: "repeating", label: "Repeating section", command: insertControl("repeating") },
225
+ { key: "repeatingItem", label: "Add repeating item", command: addRepeatingItem() },
226
+ {
227
+ key: "controlProperties",
228
+ label: "Control properties…",
229
+ dialog: "controlProperties",
230
+ command: (state) => selectedControl(state) !== null,
231
+ },
232
+ ];
233
+ /**
234
+ * The navigation menu: what `FoliNavigation` shows, with Word's keys. Nothing applies without it.
235
+ */
236
+ function navigationActions(body) {
237
+ const open = (request) => (_state, dispatch) => {
238
+ if (!body.navigation)
239
+ return false;
240
+ if (dispatch)
241
+ body.navigation(request);
242
+ return true;
243
+ };
244
+ const item = (key, label) => ({
245
+ key,
246
+ label,
247
+ command: open(key),
248
+ movesFocus: true,
249
+ });
250
+ return [
251
+ item("find", "Find\u2026"),
252
+ item("replace", "Replace\u2026"),
253
+ item("goTo", "Go to\u2026"),
254
+ item("bookmarks", "Bookmarks\u2026"),
255
+ item("outline", "Outline"),
256
+ ];
257
+ }
258
+ /**
259
+ * The fields menu: what can be inserted at the selection, updating (the view's pages when there is
260
+ * one) and the codes shown or hidden.
261
+ */
262
+ function fieldActions(body) {
263
+ const layout = () => body.storyView?.fieldLayout ?? null;
264
+ const active = () => {
265
+ const open = body.storyView?.open;
266
+ return (open && body.story(open.id)) || body;
267
+ };
268
+ const update = (editor, options) => body.storyView ? body.storyView.updateFields(options, editor) : updateFields(editor, options);
269
+ return [
270
+ {
271
+ key: "pageNumber",
272
+ label: "Page number",
273
+ command: (state, dispatch) => insertPageNumber({ layout: layout() })(state, dispatch),
274
+ },
275
+ { key: "date", label: "Date", command: insertDate() },
276
+ {
277
+ key: "crossReference",
278
+ label: "Cross-reference…",
279
+ dialog: "crossReference",
280
+ command: (state) => {
281
+ const { bookmarks, headings } = crossReferenceTargets(state);
282
+ return insertPageBreak(state) && bookmarks.length + headings.length > 0;
283
+ },
284
+ },
285
+ {
286
+ key: "tableOfContents",
287
+ label: "Table of contents",
288
+ command: (state, dispatch) => {
289
+ const done = insertTableOfContents({ layout: layout() })(state, dispatch);
290
+ // Its own lines moved the headings: their page numbers follow, in the same undo step.
291
+ if (done && dispatch)
292
+ update(body, { only: (field) => field.parent?.name === "TOC", continues: true });
293
+ return done;
294
+ },
295
+ },
296
+ {
297
+ key: "updateSelected",
298
+ label: "Update selected fields",
299
+ command: (state, dispatch) => {
300
+ if (!fieldsIn(state.doc).length)
301
+ return false;
302
+ const { from, to } = state.selection;
303
+ if (dispatch)
304
+ update(active(), { only: { from, to } });
305
+ return true;
306
+ },
307
+ },
308
+ {
309
+ key: "updateAll",
310
+ label: "Update all fields",
311
+ command: (_state, dispatch) => {
312
+ if (dispatch)
313
+ update(body, {});
314
+ return true;
315
+ },
316
+ },
317
+ {
318
+ key: "fieldCodes",
319
+ label: "Show field codes",
320
+ checked: fieldCodesShown,
321
+ command: toggleFieldCodes,
322
+ },
323
+ ];
324
+ }
68
325
  /** Whether the selection holds a textblock (a caret's own block first; else it walks the range). */
69
326
  function hasTextblock(state) {
70
327
  if (state.selection.$from.parent.isTextblock)
@@ -410,6 +667,48 @@ const GROUPS = [
410
667
  dialog: "picture",
411
668
  },
412
669
  { key: "pageBreak", label: "Page break", text: "Page break", command: () => insertPageBreak },
670
+ {
671
+ key: "section",
672
+ label: "Section",
673
+ text: "Section",
674
+ enabled: (state) => wordContext(state) !== null,
675
+ actions: SECTION_ACTIONS,
676
+ },
677
+ {
678
+ key: "headerFooter",
679
+ label: "Header and footer",
680
+ text: "Header",
681
+ enabled: (state) => wordContext(state) !== null,
682
+ actions: storyActions,
683
+ },
684
+ {
685
+ key: "fields",
686
+ label: "Fields",
687
+ text: "Fields",
688
+ enabled: (state) => wordContext(state) !== null,
689
+ actions: fieldActions,
690
+ },
691
+ {
692
+ key: "navigate",
693
+ label: "Find and go to",
694
+ text: "Navigate",
695
+ enabled: (state) => wordContext(state) !== null,
696
+ actions: navigationActions,
697
+ },
698
+ {
699
+ key: "notes",
700
+ label: "Footnotes and endnotes",
701
+ text: "Notes",
702
+ enabled: (state) => wordContext(state) !== null,
703
+ actions: noteActions,
704
+ },
705
+ {
706
+ key: "controls",
707
+ label: "Content controls",
708
+ text: "Controls",
709
+ enabled: (state) => wordContext(state) !== null,
710
+ actions: CONTROL_ACTIONS,
711
+ },
413
712
  ],
414
713
  ];
415
714
  const ITEMS = GROUPS.flat();
@@ -440,7 +739,9 @@ const selectStatesNoComment = statesOf(ITEMS_NO_COMMENT);
440
739
  * Clicks leave the focus and selection in the document.
441
740
  */
442
741
  export function FoliToolbar({ editor: given, disabled = false, onClickCommand, label = "Formatting", className, comments = false, upload, }) {
443
- const editor = useEditorOrContext(given, "FoliToolbar");
742
+ const body = useEditorOrContext(given, "FoliToolbar");
743
+ // A story open on its page takes the formatting commands; the body otherwise.
744
+ const editor = useActiveEditor(body);
444
745
  const groups = comments ? GROUPS : GROUPS_NO_COMMENT;
445
746
  const items = comments ? ITEMS : ITEMS_NO_COMMENT;
446
747
  const states = useEditorState(comments ? selectStates : selectStatesNoComment, {
@@ -512,6 +813,30 @@ export function FoliToolbar({ editor: given, disabled = false, onClickCommand, l
512
813
  !state.selection.eq(current.selection))
513
814
  ? null
514
815
  : current);
816
+ // The cross-reference dialog inserts at the selection it opened on.
817
+ setReferenceDialog((current) => current &&
818
+ (!transactions.length ||
819
+ transactions.some((tr) => tr.docChanged) ||
820
+ !state.selection.eq(current.selection))
821
+ ? null
822
+ : current);
823
+ setNoteDialog((current) => current && (!transactions.length || transactions.some((tr) => tr.docChanged))
824
+ ? null
825
+ : current);
826
+ // The control properties dialog is for the control it opened on.
827
+ setControlDialog((current) => current &&
828
+ (!transactions.length ||
829
+ transactions.some((tr) => tr.docChanged) ||
830
+ !state.selection.eq(current.selection))
831
+ ? null
832
+ : current);
833
+ // So is the page setup dialog: its section may have changed.
834
+ setSetupDialog((current) => current &&
835
+ (!transactions.length ||
836
+ transactions.some((tr) => tr.docChanged) ||
837
+ !state.selection.eq(current.selection))
838
+ ? null
839
+ : current);
515
840
  // The insert table dialog is for the caret it opened on, as the link dialog is.
516
841
  setTableDialog((current) => current &&
517
842
  (!transactions.length ||
@@ -528,6 +853,9 @@ export function FoliToolbar({ editor: given, disabled = false, onClickCommand, l
528
853
  const active = typeof document === "undefined" ? null : document.activeElement;
529
854
  setTableDialog(null);
530
855
  setPictureDialog(null);
856
+ setSetupDialog(null);
857
+ setReferenceDialog(null);
858
+ setControlDialog(null);
531
859
  setDialog((current) => current
532
860
  ? { ...current, request: current.request + 1 }
533
861
  : {
@@ -552,6 +880,30 @@ export function FoliToolbar({ editor: given, disabled = false, onClickCommand, l
552
880
  if (disabled)
553
881
  setTableDialog(null);
554
882
  }, [disabled]);
883
+ // The page setup dialog (from the section menu), for the section of the caret it opened on.
884
+ const [setupDialog, setSetupDialog] = useState(null);
885
+ useEffect(() => {
886
+ if (disabled)
887
+ setSetupDialog(null);
888
+ }, [disabled]);
889
+ // The cross-reference dialog (from the fields menu).
890
+ const [referenceDialog, setReferenceDialog] = useState(null);
891
+ useEffect(() => {
892
+ if (disabled)
893
+ setReferenceDialog(null);
894
+ }, [disabled]);
895
+ // The control properties dialog (from the content controls menu).
896
+ const [controlDialog, setControlDialog] = useState(null);
897
+ useEffect(() => {
898
+ if (disabled)
899
+ setControlDialog(null);
900
+ }, [disabled]);
901
+ // The note options dialog (from the notes menu).
902
+ const [noteDialog, setNoteDialog] = useState(null);
903
+ useEffect(() => {
904
+ if (disabled)
905
+ setNoteDialog(null);
906
+ }, [disabled]);
555
907
  // The picture dialog: inserts at (or edits the picture at `pos`) the selection it opened on.
556
908
  const [pictureDialog, setPictureDialog] = useState(null);
557
909
  useEffect(() => {
@@ -617,11 +969,51 @@ export function FoliToolbar({ editor: given, disabled = false, onClickCommand, l
617
969
  setMenu(item.key);
618
970
  }, children: [item.icon ?? item.text, item.menu && (_jsx("span", { className: "foli-toolbar-swatch", "aria-hidden": "true", style: { background: state?.value ?? "transparent" } }))] }, item.key));
619
971
  if (item.actions) {
620
- const { actions } = item;
972
+ const actions = typeof item.actions === "function" ? item.actions(body) : item.actions;
621
973
  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) => {
622
974
  setMenu(null);
975
+ if (action.dialog === "noteOptions") {
976
+ setDialog(null);
977
+ setTableDialog(null);
978
+ setSetupDialog(null);
979
+ setReferenceDialog(null);
980
+ setControlDialog(null);
981
+ setNoteDialog({ restore: buttons.current[i] ?? null });
982
+ return;
983
+ }
984
+ if (action.dialog === "controlProperties") {
985
+ setDialog(null);
986
+ setTableDialog(null);
987
+ setSetupDialog(null);
988
+ setReferenceDialog(null);
989
+ setControlDialog({
990
+ restore: buttons.current[i] ?? null,
991
+ selection: editor.state.selection,
992
+ });
993
+ return;
994
+ }
995
+ if (action.dialog === "crossReference") {
996
+ setDialog(null);
997
+ setTableDialog(null);
998
+ setSetupDialog(null);
999
+ setReferenceDialog({
1000
+ restore: buttons.current[i] ?? null,
1001
+ selection: editor.state.selection,
1002
+ });
1003
+ return;
1004
+ }
1005
+ if (action.dialog === "pageSetup") {
1006
+ setDialog(null);
1007
+ setTableDialog(null);
1008
+ setSetupDialog({
1009
+ restore: buttons.current[i] ?? null,
1010
+ selection: editor.state.selection,
1011
+ });
1012
+ return;
1013
+ }
623
1014
  if (action.dialog) {
624
1015
  setDialog(null);
1016
+ setSetupDialog(null);
625
1017
  setTableDialog((current) => ({
626
1018
  restore: buttons.current[i] ?? null,
627
1019
  selection: editor.state.selection,
@@ -630,6 +1022,8 @@ export function FoliToolbar({ editor: given, disabled = false, onClickCommand, l
630
1022
  return;
631
1023
  }
632
1024
  editor.run(action.command);
1025
+ if (action.movesFocus)
1026
+ return;
633
1027
  if (pointer)
634
1028
  onClickCommand?.();
635
1029
  else
@@ -663,6 +1057,34 @@ export function FoliToolbar({ editor: given, disabled = false, onClickCommand, l
663
1057
  onClickCommand();
664
1058
  else
665
1059
  restore?.focus();
1060
+ } })), setupDialog && !disabled && (_jsx(PageSetupDialog, { editor: editor, onClose: (applied) => {
1061
+ const { restore } = setupDialog;
1062
+ setSetupDialog(null);
1063
+ if (applied && onClickCommand)
1064
+ onClickCommand();
1065
+ else
1066
+ restore?.focus();
1067
+ } })), referenceDialog && !disabled && (_jsx(CrossReferenceDialog, { editor: editor, layout: () => body.storyView?.fieldLayout ?? null, onClose: (inserted) => {
1068
+ const { restore } = referenceDialog;
1069
+ setReferenceDialog(null);
1070
+ if (inserted && onClickCommand)
1071
+ onClickCommand();
1072
+ else
1073
+ restore?.focus();
1074
+ } })), noteDialog && !disabled && (_jsx(NoteOptionsDialog, { editor: body, onClose: (applied) => {
1075
+ const { restore } = noteDialog;
1076
+ setNoteDialog(null);
1077
+ if (applied && onClickCommand)
1078
+ onClickCommand();
1079
+ else
1080
+ restore?.focus();
1081
+ } })), controlDialog && !disabled && (_jsx(ControlDialog, { editor: editor, onClose: (applied) => {
1082
+ const { restore } = controlDialog;
1083
+ setControlDialog(null);
1084
+ if (applied && onClickCommand)
1085
+ onClickCommand();
1086
+ else
1087
+ restore?.focus();
666
1088
  } })), tableDialog && !disabled && (_jsx(InsertTableDialog, { editor: editor, request: tableDialog.request, onClose: (inserted) => {
667
1089
  const { restore } = tableDialog;
668
1090
  setTableDialog(null);
@@ -867,6 +1289,355 @@ function InsertTableDialog({ editor, request, onClose, }) {
867
1289
  onClose(false);
868
1290
  }, 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
1291
  }
1292
+ /**
1293
+ * The cross-reference dialog: what to refer to (the document's bookmarks and headings), what to
1294
+ * show of it, whether it links there; Insert and Cancel; Escape cancels.
1295
+ */
1296
+ function CrossReferenceDialog({ editor, layout, onClose, }) {
1297
+ const [{ bookmarks, headings }] = useState(() => crossReferenceTargets(editor.state));
1298
+ const options = [
1299
+ ...headings.map((h) => ({
1300
+ value: `h${h.pos}`,
1301
+ label: `${"\u00a0".repeat((h.level - 1) * 2)}${h.number ? `${h.number} ` : ""}${h.text}`,
1302
+ })),
1303
+ ...bookmarks.map((b) => ({ value: `b${b.name}`, label: `Bookmark: ${b.name}` })),
1304
+ ];
1305
+ const [target, setTarget] = useState(options[0]?.value ?? "");
1306
+ const [show, setShow] = useState("text");
1307
+ const [link, setLink] = useState(true);
1308
+ const [failed, setFailed] = useState(false);
1309
+ const first = useRef(null);
1310
+ const id = useId();
1311
+ useEffect(() => {
1312
+ first.current?.focus();
1313
+ }, []);
1314
+ const insert = (event) => {
1315
+ event.preventDefault();
1316
+ const to = target[0] === "h" ? Number(target.slice(1)) : target.slice(1);
1317
+ if (editor.run(insertCrossReference({ to, show, link, layout: layout() })))
1318
+ onClose(true);
1319
+ else
1320
+ setFailed(true);
1321
+ };
1322
+ return (_jsx("div", { role: "dialog", "aria-modal": "true", "aria-label": "Insert cross-reference", className: "foli-link-dialog foli-table-dialog", onKeyDown: (event) => {
1323
+ if (event.key === "Escape") {
1324
+ event.preventDefault();
1325
+ onClose(false);
1326
+ }
1327
+ if (event.key !== "Tab")
1328
+ return;
1329
+ // Tab goes round inside the dialog.
1330
+ const stops = [
1331
+ ...event.currentTarget.querySelectorAll("select, input, button"),
1332
+ ];
1333
+ const at = stops.indexOf(event.target);
1334
+ const next = (at + (event.shiftKey ? -1 : 1) + stops.length) % stops.length;
1335
+ event.preventDefault();
1336
+ stops[next]?.focus();
1337
+ }, 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) => {
1338
+ setTarget(event.target.value);
1339
+ setFailed(false);
1340
+ }, 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." }))] }) }));
1341
+ }
1342
+ /** Word's number formats for notes. */
1343
+ const NOTE_FORMATS = [
1344
+ ["decimal", "1, 2, 3"],
1345
+ ["lowerLetter", "a, b, c"],
1346
+ ["upperLetter", "A, B, C"],
1347
+ ["lowerRoman", "i, ii, iii"],
1348
+ ["upperRoman", "I, II, III"],
1349
+ ["chicago", "*, †, ‡"],
1350
+ ];
1351
+ /**
1352
+ * How notes are placed and numbered, for the whole document as Word's dialog applies it: where
1353
+ * they go, the number format, where numbers start and when they restart; Escape cancels.
1354
+ */
1355
+ function NoteOptionsDialog({ editor, onClose, }) {
1356
+ const [kind, setKind] = useState("footnote");
1357
+ const valuesOf = (of) => {
1358
+ const envelope = wordContext(editor.state)?.envelope;
1359
+ const section = sectionAt(editor.state)?.setup;
1360
+ return noteProperties(envelope ?? {}, of, section);
1361
+ };
1362
+ const [values, setValues] = useState(() => valuesOf("footnote"));
1363
+ const [start, setStart] = useState(String(values.start));
1364
+ const first = useRef(null);
1365
+ const id = useId();
1366
+ useEffect(() => {
1367
+ first.current?.focus();
1368
+ }, []);
1369
+ const set = (change) => setValues((v) => ({ ...v, ...change }));
1370
+ const restarts = values.restart !== "continuous";
1371
+ const number = Number(start);
1372
+ const invalid = !restarts && (!Number.isInteger(number) || number < 1 || number > 16383);
1373
+ const apply = (event) => {
1374
+ event.preventDefault();
1375
+ if (invalid)
1376
+ return;
1377
+ const properties = {
1378
+ position: values.position,
1379
+ format: values.format,
1380
+ restart: values.restart,
1381
+ start: restarts ? 1 : number,
1382
+ };
1383
+ onClose(editor.run(setNoteProperties(kind, properties)));
1384
+ };
1385
+ return (_jsx("div", { role: "dialog", "aria-label": "Note options", className: "foli-link-dialog foli-table-dialog", onKeyDown: (event) => {
1386
+ if (event.key !== "Escape")
1387
+ return;
1388
+ event.preventDefault();
1389
+ onClose(false);
1390
+ }, 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) => {
1391
+ const next = event.target.value;
1392
+ const shown = valuesOf(next);
1393
+ setKind(next);
1394
+ setValues(shown);
1395
+ setStart(String(shown.start));
1396
+ }, 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." }))] }) }));
1397
+ }
1398
+ /** A list's items as the dialog shows them: one a line, `shown | value` where they differ. */
1399
+ const itemsText = (items) => (items ?? [])
1400
+ .map((item) => item.display === undefined || item.display === item.value
1401
+ ? item.value
1402
+ : `${item.display} | ${item.value}`)
1403
+ .join("\n");
1404
+ function parseItems(text) {
1405
+ const seen = new Set();
1406
+ return text.split("\n").flatMap((line) => {
1407
+ const [shown = "", value = shown] = line.split("|").map((part) => part.trim());
1408
+ // Word refuses two items of one value.
1409
+ if (!shown || seen.has(value))
1410
+ return [];
1411
+ seen.add(value);
1412
+ return [{ value, display: shown }];
1413
+ });
1414
+ }
1415
+ /**
1416
+ * The properties of the control at the caret: title, tag, locks and what its kind has (list items,
1417
+ * date format, line breaks); OK and Cancel; Escape cancels.
1418
+ */
1419
+ function ControlDialog({ editor, onClose, }) {
1420
+ const [selected] = useState(() => selectedControl(editor.state));
1421
+ const control = selected?.control;
1422
+ const [title, setTitle] = useState(control?.alias ?? "");
1423
+ const [tag, setTag] = useState(control?.tag ?? "");
1424
+ const [noDelete, setNoDelete] = useState(control?.lock === "sdtLocked" || control?.lock === "sdtContentLocked");
1425
+ const [noEdit, setNoEdit] = useState(control?.lock === "contentLocked" || control?.lock === "sdtContentLocked");
1426
+ const [items, setItems] = useState(itemsText(control?.items));
1427
+ const [dateFormat, setDateFormat] = useState(control?.dateFormat ?? "d MMMM yyyy");
1428
+ const [multiLine, setMultiLine] = useState(control?.multiLine === true);
1429
+ const first = useRef(null);
1430
+ const id = useId();
1431
+ useEffect(() => {
1432
+ first.current?.focus();
1433
+ }, []);
1434
+ if (!selected || !control)
1435
+ return null;
1436
+ const { kind } = control;
1437
+ const hasList = kind === "dropDown" || kind === "comboBox";
1438
+ const apply = (event) => {
1439
+ event.preventDefault();
1440
+ const lock = noDelete
1441
+ ? noEdit
1442
+ ? "sdtContentLocked"
1443
+ : "sdtLocked"
1444
+ : noEdit
1445
+ ? "contentLocked"
1446
+ : "unlocked";
1447
+ onClose(editor.run(setControlProperties(selected.id, {
1448
+ title,
1449
+ tag,
1450
+ lock,
1451
+ ...(hasList ? { items: parseItems(items) } : {}),
1452
+ ...(kind === "date" ? { dateFormat } : {}),
1453
+ ...(kind === "text" ? { multiLine } : {}),
1454
+ })));
1455
+ };
1456
+ return (_jsx("div", { role: "dialog", "aria-label": "Content control properties", className: "foli-link-dialog foli-table-dialog", onKeyDown: (event) => {
1457
+ if (event.key !== "Escape")
1458
+ return;
1459
+ event.preventDefault();
1460
+ onClose(false);
1461
+ }, 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" })] }) }));
1462
+ }
1463
+ const TWIPS_PER_CM = 1440 / 2.54;
1464
+ const MAX_TWIPS = 31_680;
1465
+ /** Word's limit on a section's columns. */
1466
+ const MAX_SECTION_COLUMNS = 45;
1467
+ const toCm = (twips) => String(Number((twips / TWIPS_PER_CM).toFixed(2)));
1468
+ /** A length in cm as whole twips (a decimal comma too), or null when it is not one in range. */
1469
+ function toTwips(text, min) {
1470
+ const value = Number(text.trim().replace(",", "."));
1471
+ const twips = Math.round(value * TWIPS_PER_CM);
1472
+ return text.trim() && Number.isFinite(value) && twips >= min && twips <= MAX_TWIPS ? twips : null;
1473
+ }
1474
+ const SECTION_STARTS = [
1475
+ ["nextPage", "Next page"],
1476
+ ["continuous", "Continuous"],
1477
+ ["evenPage", "Even page"],
1478
+ ["oddPage", "Odd page"],
1479
+ ["nextColumn", "Next column"],
1480
+ ];
1481
+ const SETUP_LABELS = {
1482
+ width: "Page width (cm)",
1483
+ height: "Page height (cm)",
1484
+ top: "Top margin (cm)",
1485
+ bottom: "Bottom margin (cm)",
1486
+ left: "Left margin (cm)",
1487
+ right: "Right margin (cm)",
1488
+ count: "Columns",
1489
+ space: "Space between columns (cm)",
1490
+ widths: "Set column widths (cm, separated by ;)",
1491
+ };
1492
+ /**
1493
+ * The page setup dialog, for the caret's section: how it starts, its page size and orientation,
1494
+ * margins and columns (equal, or set widths; the line between them), in centimetres. Only what
1495
+ * was changed is applied. Apply and Cancel; Escape cancels; a wrong field is marked and announced.
1496
+ */
1497
+ function PageSetupDialog({ editor, onClose, }) {
1498
+ const id = useId();
1499
+ const [initial] = useState(() => {
1500
+ const setup = sectionAt(editor.state)?.setup ?? {};
1501
+ const width = setup.pageSize?.width ?? 12_240;
1502
+ const height = setup.pageSize?.height ?? 15_840;
1503
+ const m = setup.margins ?? {};
1504
+ const set = setup.columns?.equalWidth === false ? (setup.columns.widths ?? []) : [];
1505
+ return {
1506
+ start: setup.type ?? "nextPage",
1507
+ orientation: setup.pageSize?.orientation ?? (width > height ? "landscape" : "portrait"),
1508
+ separator: setup.columns?.separator === true,
1509
+ columns: setup.columns,
1510
+ fields: {
1511
+ width: toCm(width),
1512
+ height: toCm(height),
1513
+ top: toCm(Math.abs(m.top ?? 1440)),
1514
+ bottom: toCm(Math.abs(m.bottom ?? 1440)),
1515
+ left: toCm(m.left ?? 1440),
1516
+ right: toCm(m.right ?? 1440),
1517
+ count: String(set.length || (setup.columns?.count ?? 1)),
1518
+ space: toCm(setup.columns?.space ?? 720),
1519
+ widths: set.map((column) => toCm(column.width)).join("; "),
1520
+ },
1521
+ };
1522
+ });
1523
+ const [start, setStart] = useState(initial.start);
1524
+ const [orientation, setOrientation] = useState(initial.orientation);
1525
+ const [separator, setSeparator] = useState(initial.separator);
1526
+ const [fields, setFields] = useState(initial.fields);
1527
+ const [error, setError] = useState(null);
1528
+ const first = useRef(null);
1529
+ useEffect(() => first.current?.focus(), []);
1530
+ const apply = (event) => {
1531
+ event.preventDefault();
1532
+ const wrong = (field) => {
1533
+ setError(field);
1534
+ document.getElementById(`${id}-${field}`)?.focus();
1535
+ };
1536
+ const changed = (field) => fields[field] !== initial.fields[field];
1537
+ const setup = {};
1538
+ if (start !== initial.start)
1539
+ setup.type = start === "nextPage" ? undefined : start;
1540
+ const lengths = {};
1541
+ for (const field of ["width", "height", "top", "bottom", "left", "right"]) {
1542
+ if (!changed(field))
1543
+ continue;
1544
+ const twips = toTwips(fields[field], field === "width" || field === "height" ? 1 : 0);
1545
+ if (twips === null)
1546
+ return wrong(field);
1547
+ lengths[field] = twips;
1548
+ }
1549
+ if (lengths.width !== undefined ||
1550
+ lengths.height !== undefined ||
1551
+ orientation !== initial.orientation)
1552
+ setup.pageSize = {
1553
+ ...(lengths.width !== undefined ? { width: lengths.width } : {}),
1554
+ ...(lengths.height !== undefined ? { height: lengths.height } : {}),
1555
+ orientation: orientation,
1556
+ };
1557
+ const margins = {
1558
+ top: lengths.top,
1559
+ bottom: lengths.bottom,
1560
+ left: lengths.left,
1561
+ right: lengths.right,
1562
+ };
1563
+ const given = Object.entries(margins).filter(([, value]) => value !== undefined);
1564
+ if (given.length)
1565
+ setup.margins = Object.fromEntries(given);
1566
+ if (changed("count") ||
1567
+ changed("space") ||
1568
+ changed("widths") ||
1569
+ separator !== initial.separator) {
1570
+ // What was not changed stays exactly as it is, each column's own space included.
1571
+ const before = initial.columns;
1572
+ const set = before?.equalWidth === false ? (before.widths ?? []) : [];
1573
+ const space = changed("space") ? toTwips(fields.space, 0) : (before?.space ?? 720);
1574
+ if (space === null)
1575
+ return wrong("space");
1576
+ let widths = set.map((column) => column.width);
1577
+ if (changed("widths"))
1578
+ widths = fields.widths.trim()
1579
+ ? fields.widths
1580
+ .trim()
1581
+ .split(/[;\s]+/)
1582
+ .map((width) => toTwips(width, 1))
1583
+ : [];
1584
+ if (widths.includes(null))
1585
+ return wrong("widths");
1586
+ const asked = Number(fields.count);
1587
+ if (widths.length && changed("count") && asked !== widths.length) {
1588
+ setError("mismatch");
1589
+ document.getElementById(`${id}-count`)?.focus();
1590
+ return;
1591
+ }
1592
+ const count = widths.length || asked;
1593
+ if (!Number.isInteger(count) || count < 1 || count > MAX_SECTION_COLUMNS)
1594
+ return wrong("count");
1595
+ const { separator: _line, equalWidth: _equal, widths: _widths, ...rest } = before ?? {};
1596
+ setup.columns = {
1597
+ ...rest,
1598
+ count,
1599
+ ...(changed("space") || before?.space === undefined ? { space } : {}),
1600
+ ...(separator ? { separator } : {}),
1601
+ ...(widths.length
1602
+ ? {
1603
+ equalWidth: false,
1604
+ widths: widths.map((width, i) => {
1605
+ const own = changed("space") ? undefined : set[i]?.space;
1606
+ const gap = own ?? (i < widths.length - 1 ? space : undefined);
1607
+ return { width: width, ...(gap === undefined ? {} : { space: gap }) };
1608
+ }),
1609
+ }
1610
+ : {}),
1611
+ };
1612
+ }
1613
+ if (!Object.keys(setup).length)
1614
+ return onClose(false);
1615
+ if (editor.run(setSectionSetup(setup)))
1616
+ return onClose(true);
1617
+ setError("setup");
1618
+ };
1619
+ const setOrientationSwapping = (next) => {
1620
+ if (next !== orientation)
1621
+ setFields((current) => ({ ...current, width: current.height, height: current.width }));
1622
+ setOrientation(next);
1623
+ setError(null);
1624
+ };
1625
+ const marked = (name) => error === name || (name === "count" && error === "mismatch");
1626
+ 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) => {
1627
+ setFields((current) => ({ ...current, [name]: event.target.value }));
1628
+ setError(null);
1629
+ } })] }, name));
1630
+ return (_jsx("div", { role: "dialog", "aria-label": "Page setup", className: "foli-link-dialog foli-setup-dialog", onKeyDown: (event) => {
1631
+ if (event.key !== "Escape")
1632
+ return;
1633
+ event.preventDefault();
1634
+ onClose(false);
1635
+ }, 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"
1636
+ ? "This setup leaves no room for text, or its columns do not fit the page."
1637
+ : error === "mismatch"
1638
+ ? "The number of columns differs from the set widths: list one width per column, or clear them for equal columns."
1639
+ : `Check this value: ${SETUP_LABELS[error]}.` }))] }) }));
1640
+ }
870
1641
  /** The largest picture side the schema takes, in px (2^31 - 1 EMU). */
871
1642
  const MAX_PICTURE_PX = Math.floor(2_147_483_647 / EMU_PER_PX);
872
1643
  /**