@folijs/react 0.3.0 → 0.5.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,41 +1,71 @@
1
1
  import {
2
2
  type Alignment,
3
+ acceptAllChanges,
4
+ acceptChange,
5
+ addComment,
3
6
  alignAt,
4
7
  type Command,
5
8
  canOutdent,
6
9
  changeIndent,
7
10
  colorAt,
11
+ deleteColumns,
12
+ deleteRows,
13
+ deleteTable,
8
14
  type Editor,
9
15
  type EditorState,
10
16
  fontFamilyAt,
11
17
  fontSizeAt,
18
+ insertColumn,
12
19
  insertPageBreak,
20
+ insertPicture,
21
+ insertRow,
22
+ insertTable,
23
+ isHeaderRow,
13
24
  isSafeHref,
14
25
  lineSpacingAt,
15
26
  linkAt,
16
27
  listKindAt,
28
+ mergeCells,
29
+ nextChange,
17
30
  normalizeHref,
18
31
  openLinkEditor,
19
32
  paragraphStyleAt,
20
33
  paragraphStyles,
34
+ previousChange,
35
+ type ReviewView,
21
36
  redo,
22
37
  redoDepth,
38
+ rejectAllChanges,
39
+ rejectChange,
23
40
  removeLink,
24
41
  requestsLinkEditor,
42
+ selectedPicture,
25
43
  setAlign,
44
+ setCellShading,
26
45
  setFontFamily,
27
46
  setFontSize,
28
47
  setHighlight,
29
48
  setLineSpacing,
30
49
  setLink,
31
50
  setParagraphStyle,
51
+ setPictureAlt,
52
+ setPictureSize,
53
+ setReviewView,
54
+ setTableStyle,
32
55
  setTextColor,
56
+ setTrackChanges,
57
+ splitCell,
58
+ tableStyleAt,
59
+ tableStyles,
60
+ toggleHeaderRow,
33
61
  toggleList,
34
62
  toggleMark,
63
+ trackState,
35
64
  undo,
36
65
  undoDepth,
37
66
  wordContext,
38
67
  } from "@folijs/core";
68
+ import { type EditorViewOptions, EMU_PER_PX, measureImageFile, textWidthEmu } from "@folijs/view";
39
69
  import {
40
70
  type FormEvent,
41
71
  Fragment,
@@ -44,6 +74,7 @@ import {
44
74
  type ReactNode,
45
75
  useEffect,
46
76
  useId,
77
+ useMemo,
47
78
  useRef,
48
79
  useState,
49
80
  } from "react";
@@ -64,6 +95,16 @@ export interface FoliToolbarProps {
64
95
  onClickCommand?: (() => void) | undefined;
65
96
  /** Accessible name of the toolbar (default "Formatting"). */
66
97
  label?: string | undefined;
98
+ /**
99
+ * Show "New comment": only where a comments pane (`FoliComments`) lets the comment be written
100
+ * (`FoliEditor` passes it). Default false.
101
+ */
102
+ comments?: boolean | undefined;
103
+ /**
104
+ * Where an inserted picture's image file goes (`EditorViewOptions.upload`): with it, "Picture"
105
+ * inserts one from a file; without it, it only edits a selected picture.
106
+ */
107
+ upload?: EditorViewOptions["upload"] | undefined;
67
108
  className?: string | undefined;
68
109
  }
69
110
 
@@ -93,6 +134,10 @@ interface Item {
93
134
  value: (state: EditorState) => string | null;
94
135
  pick: (color: string | null) => Command;
95
136
  };
137
+ /** An action menu button (the table menu): its commands, in order. */
138
+ actions?: readonly Action[];
139
+ /** A button opening a dialog (the picture's). */
140
+ dialog?: "picture";
96
141
  /** A drop-down list (a `select`): its options, the current value, and what picking runs. */
97
142
  select?: {
98
143
  options: (state: EditorState) => readonly { value: string; label: string }[];
@@ -101,6 +146,16 @@ interface Item {
101
146
  };
102
147
  }
103
148
 
149
+ /** A command in an action menu (a menuitem, or a menuitemcheckbox when it has `checked`). */
150
+ interface Action {
151
+ key: string;
152
+ label: string;
153
+ /** The command it runs; `insertTable` opens the dialog that asks for the size instead. */
154
+ command: Command;
155
+ dialog?: "insertTable";
156
+ checked?: (state: EditorState) => boolean;
157
+ }
158
+
104
159
  interface ColorOption {
105
160
  name: string;
106
161
  /** Lowercase `#rrggbb`; null removes the color. */
@@ -130,6 +185,48 @@ const HIGHLIGHTS: readonly ColorOption[] = [
130
185
  { name: "Gray", color: "#c0c0c0" },
131
186
  ];
132
187
 
188
+ /** Cell shadings: light fills that keep text readable. */
189
+ const SHADINGS: readonly ColorOption[] = [
190
+ { name: "None", color: null },
191
+ { name: "Light gray", color: "#d9d9d9" },
192
+ { name: "Light blue", color: "#deeaf6" },
193
+ { name: "Light green", color: "#e2efd9" },
194
+ { name: "Light yellow", color: "#fff2cc" },
195
+ { name: "Light orange", color: "#fbe4d5" },
196
+ ];
197
+
198
+ /** The cell around the selection's start, if any (cheap: the start's ancestors). */
199
+ function cellAt(state: EditorState) {
200
+ const { $from } = state.selection;
201
+ for (let d = $from.depth; d > 0; d--)
202
+ if ($from.node(d).type.name === "tableCell") return $from.node(d);
203
+ // A cell selection starts before its first cell.
204
+ const after = $from.nodeAfter;
205
+ return after?.type.name === "tableCell" ? after : null;
206
+ }
207
+ const inTable = (state: EditorState) => cellAt(state) !== null;
208
+ /** Table and cell properties change only when not tracking (Foli does not record them yet). */
209
+ const canFormatTable = (state: EditorState) => inTable(state) && trackState(state)?.on !== true;
210
+
211
+ const TABLE_ACTIONS: readonly Action[] = [
212
+ { key: "insertTable", label: "Insert table…", command: insertTable(1, 1), dialog: "insertTable" },
213
+ { key: "rowAbove", label: "Insert row above", command: insertRow(-1) },
214
+ { key: "rowBelow", label: "Insert row below", command: insertRow(1) },
215
+ { key: "columnLeft", label: "Insert column left", command: insertColumn(-1) },
216
+ { key: "columnRight", label: "Insert column right", command: insertColumn(1) },
217
+ { key: "deleteRows", label: "Delete rows", command: deleteRows },
218
+ { key: "deleteColumns", label: "Delete columns", command: deleteColumns },
219
+ { key: "deleteTable", label: "Delete table", command: deleteTable },
220
+ { key: "mergeCells", label: "Merge cells", command: mergeCells },
221
+ { key: "splitCell", label: "Split cell", command: splitCell },
222
+ {
223
+ key: "headerRow",
224
+ label: "Repeat as header row",
225
+ command: toggleHeaderRow,
226
+ checked: isHeaderRow,
227
+ },
228
+ ];
229
+
133
230
  /** Whether the selection holds a textblock (a caret's own block first; else it walks the range). */
134
231
  function hasTextblock(state: EditorState): boolean {
135
232
  if (state.selection.$from.parent.isTextblock) return true;
@@ -186,6 +283,11 @@ const FONTS = [
186
283
  ];
187
284
  const SIZES = [8, 9, 10, 10.5, 11, 12, 14, 16, 18, 20, 22, 24, 26, 28, 36, 48, 72];
188
285
  const LINE_SPACINGS = [1, 1.15, 1.5, 2, 2.5, 3];
286
+ const REVIEW_VIEWS = [
287
+ { value: "markup", label: "All markup" },
288
+ { value: "simple", label: "Simple markup" },
289
+ { value: "final", label: "No markup" },
290
+ ];
189
291
 
190
292
  /** Word's controls. */
191
293
  const GROUPS: Item[][] = [
@@ -351,6 +453,78 @@ const GROUPS: Item[][] = [
351
453
  command: () => changeIndent(1),
352
454
  },
353
455
  ],
456
+ [
457
+ {
458
+ key: "newComment",
459
+ label: "New comment on the selection",
460
+ text: "New comment",
461
+ enabled: (state) => wordContext(state) !== null && hasTextblock(state),
462
+ command: () => addComment(""),
463
+ },
464
+ {
465
+ key: "trackChanges",
466
+ label: "Track changes",
467
+ text: "Track changes",
468
+ pressed: (state) => trackState(state)?.on === true,
469
+ enabled: (state) => trackState(state) !== null,
470
+ command: (state) => setTrackChanges(!trackState(state)?.on),
471
+ },
472
+ {
473
+ key: "reviewView",
474
+ label: "Show changes as",
475
+ text: "Show",
476
+ enabled: (state) => trackState(state) !== null,
477
+ select: {
478
+ options: () => REVIEW_VIEWS,
479
+ value: (state) => trackState(state)?.view ?? "markup",
480
+ pick: (view) => setReviewView(view as ReviewView),
481
+ },
482
+ },
483
+ // Enabled while tracking can be used: whether there is a change to go to or resolve would
484
+ // walk the whole document after every transaction.
485
+ {
486
+ key: "previousChange",
487
+ label: "Previous change",
488
+ text: "Previous change",
489
+ enabled: (state) => trackState(state) !== null,
490
+ command: () => previousChange,
491
+ },
492
+ {
493
+ key: "nextChange",
494
+ label: "Next change",
495
+ text: "Next change",
496
+ enabled: (state) => trackState(state) !== null,
497
+ command: () => nextChange,
498
+ },
499
+ {
500
+ key: "acceptChange",
501
+ label: "Accept the change here, or the changes selected",
502
+ text: "Accept",
503
+ enabled: (state) => trackState(state) !== null,
504
+ command: () => acceptChange,
505
+ },
506
+ {
507
+ key: "rejectChange",
508
+ label: "Reject the change here, or the changes selected",
509
+ text: "Reject",
510
+ enabled: (state) => trackState(state) !== null,
511
+ command: () => rejectChange,
512
+ },
513
+ {
514
+ key: "acceptAll",
515
+ label: "Accept all changes",
516
+ text: "Accept all",
517
+ enabled: (state) => trackState(state) !== null,
518
+ command: () => acceptAllChanges(),
519
+ },
520
+ {
521
+ key: "rejectAll",
522
+ label: "Reject all changes",
523
+ text: "Reject all",
524
+ enabled: (state) => trackState(state) !== null,
525
+ command: () => rejectAllChanges(),
526
+ },
527
+ ],
354
528
  [
355
529
  {
356
530
  key: "undo",
@@ -367,10 +541,58 @@ const GROUPS: Item[][] = [
367
541
  command: () => redo,
368
542
  },
369
543
  ],
370
- [{ key: "pageBreak", label: "Page break", text: "Page break", command: () => insertPageBreak }],
544
+ [
545
+ {
546
+ key: "table",
547
+ label: "Table",
548
+ text: "Table",
549
+ enabled: (state) => wordContext(state) !== null && "table" in state.schema.nodes,
550
+ actions: TABLE_ACTIONS,
551
+ },
552
+ {
553
+ key: "tableStyle",
554
+ label: "Table style",
555
+ text: "Table style",
556
+ enabled: canFormatTable,
557
+ select: {
558
+ options: (state) => tableStyles(state).map((name) => ({ value: name, label: name })),
559
+ value: (state) => (inTable(state) ? (tableStyleAt(state) ?? "") : null),
560
+ pick: (name) => setTableStyle(name),
561
+ },
562
+ },
563
+ {
564
+ key: "cellShading",
565
+ label: "Cell shading",
566
+ text: "Shading",
567
+ enabled: canFormatTable,
568
+ menu: {
569
+ options: SHADINGS,
570
+ value: (state) => {
571
+ const fill = (cellAt(state)?.attrs.shading as { fill?: string } | null)?.fill;
572
+ return fill && fill.toLowerCase() !== "auto" ? `#${fill.toLowerCase()}` : null;
573
+ },
574
+ pick: (color) => setCellShading(color ? color.slice(1).toUpperCase() : null),
575
+ },
576
+ },
577
+ ],
578
+ [
579
+ {
580
+ key: "picture",
581
+ label: "Insert a picture, or edit the selected one",
582
+ text: "Picture…",
583
+ enabled: (state) =>
584
+ wordContext(state) !== null && (selectedPicture(state) !== null || hasTextblock(state)),
585
+ // With a picture selected the dialog edits it.
586
+ dialog: "picture",
587
+ },
588
+ { key: "pageBreak", label: "Page break", text: "Page break", command: () => insertPageBreak },
589
+ ],
371
590
  ];
372
591
 
373
592
  const ITEMS = GROUPS.flat();
593
+ /** Without "New comment": where no comments pane lets a comment be written. */
594
+ const GROUPS_NO_COMMENT = GROUPS.map((group) => group.filter((i) => i.key !== "newComment"));
595
+ const ITEMS_NO_COMMENT = GROUPS_NO_COMMENT.flat();
374
596
 
375
597
  interface LinkDialogState {
376
598
  /** The link at the selection when the dialog opened ("" for none). */
@@ -404,14 +626,19 @@ const statesOf =
404
626
  items.map((item) => ({
405
627
  pressed: item.pressed?.(state, editor),
406
628
  enabled: item.enabled?.(state) ?? true,
407
- value: item.menu?.value(state) ?? item.select?.value(state),
629
+ value:
630
+ item.menu?.value(state) ??
631
+ item.select?.value(state) ??
632
+ (item.dialog ? (selectedPicture(state) ? "edit" : "insert") : undefined),
408
633
  }));
409
634
  const selectStates = statesOf(ITEMS);
635
+ const selectStatesNoComment = statesOf(ITEMS_NO_COMMENT);
410
636
 
411
637
  /**
412
638
  * Word's formatting controls for an editor: paragraph style, font and size boxes, marks, link (a
413
639
  * dialog, also on Mod-K in the document), text color and highlight menus, alignment and line
414
- * spacing, lists (bulleted, numbered, decrease and increase indent), undo, redo, page break.
640
+ * spacing, lists (bulleted, numbered, decrease and increase indent), undo, redo, tables (a Table
641
+ * menu with an insert table dialog, a table style box, a cell shading menu), page break.
415
642
  * One tab stop (arrow keys, Home and End move between buttons); toggles carry
416
643
  * `aria-pressed`; a button whose command cannot run now is `aria-disabled` (still focusable).
417
644
  * Clicks leave the focus and selection in the document.
@@ -422,11 +649,16 @@ export function FoliToolbar({
422
649
  onClickCommand,
423
650
  label = "Formatting",
424
651
  className,
652
+ comments = false,
653
+ upload,
425
654
  }: FoliToolbarProps) {
426
655
  const editor = useEditorOrContext(given, "FoliToolbar");
427
- const groups = GROUPS;
428
- const items = ITEMS;
429
- const states = useEditorState(selectStates, { editor, isEqual: sameStates });
656
+ const groups = comments ? GROUPS : GROUPS_NO_COMMENT;
657
+ const items = comments ? ITEMS : ITEMS_NO_COMMENT;
658
+ const states = useEditorState(comments ? selectStates : selectStatesNoComment, {
659
+ editor,
660
+ isEqual: sameStates,
661
+ });
430
662
  const [active, setActive] = useState(0);
431
663
  const buttons = useRef<(HTMLButtonElement | HTMLSelectElement | null)[]>([]);
432
664
  // Whether a select box was last used with the pointer (its pick then goes back to the document).
@@ -440,7 +672,20 @@ export function FoliToolbar({
440
672
  const run = (index: number, event: MouseEvent) => {
441
673
  const item = items[index];
442
674
  if (!item || disabled || !states[index]?.enabled) return;
443
- if (item.menu) {
675
+ if (item.dialog === "picture") {
676
+ const selected = selectedPicture(editor.state);
677
+ // Inserting needs the app's upload; editing a selected picture does not.
678
+ if (!selected && !upload) return;
679
+ setDialog(null);
680
+ setTableDialog(null);
681
+ setPictureDialog({
682
+ pos: selected?.pos ?? null,
683
+ selection: editor.state.selection,
684
+ restore: buttons.current[index] ?? null,
685
+ });
686
+ return;
687
+ }
688
+ if (item.menu || item.actions) {
444
689
  if (menu !== item.key) {
445
690
  setMenu(item.key);
446
691
  return;
@@ -467,6 +712,25 @@ export function FoliToolbar({
467
712
  editor.subscribe((state, transactions) => {
468
713
  if (disabled) return;
469
714
  if (!transactions.some(requestsLinkEditor)) {
715
+ // The picture dialog too: what it edits or inserts at may have gone (another
716
+ // document, set with no transaction, included).
717
+ setPictureDialog((current) =>
718
+ current &&
719
+ (!transactions.length ||
720
+ transactions.some((tr) => tr.docChanged) ||
721
+ !state.selection.eq(current.selection))
722
+ ? null
723
+ : current,
724
+ );
725
+ // The insert table dialog is for the caret it opened on, as the link dialog is.
726
+ setTableDialog((current) =>
727
+ current &&
728
+ (!transactions.length ||
729
+ transactions.some((tr) => tr.docChanged) ||
730
+ !state.selection.eq(current.selection))
731
+ ? null
732
+ : current,
733
+ );
470
734
  setDialog((current) =>
471
735
  current &&
472
736
  (transactions.some((tr) => tr.docChanged) || !state.selection.eq(current.selection))
@@ -476,6 +740,8 @@ export function FoliToolbar({
476
740
  return;
477
741
  }
478
742
  const active = typeof document === "undefined" ? null : document.activeElement;
743
+ setTableDialog(null);
744
+ setPictureDialog(null);
479
745
  setDialog((current) =>
480
746
  current
481
747
  ? { ...current, request: current.request + 1 }
@@ -497,6 +763,24 @@ export function FoliToolbar({
497
763
  dialog?.restore?.focus();
498
764
  setDialog(null);
499
765
  };
766
+ // The insert table dialog (from the table menu): the focus goes back to the menu's button.
767
+ const [tableDialog, setTableDialog] = useState<{
768
+ restore: HTMLElement | null;
769
+ selection: EditorState["selection"];
770
+ request: number;
771
+ } | null>(null);
772
+ useEffect(() => {
773
+ if (disabled) setTableDialog(null);
774
+ }, [disabled]);
775
+ // The picture dialog: inserts at (or edits the picture at `pos`) the selection it opened on.
776
+ const [pictureDialog, setPictureDialog] = useState<{
777
+ pos: number | null;
778
+ selection: EditorState["selection"];
779
+ restore: HTMLElement | null;
780
+ } | null>(null);
781
+ useEffect(() => {
782
+ if (disabled) setPictureDialog(null);
783
+ }, [disabled]);
500
784
 
501
785
  const onKeyDown = (event: KeyboardEvent) => {
502
786
  // Alt+Left (back) and other shortcuts are the browser's.
@@ -530,7 +814,11 @@ export function FoliToolbar({
530
814
  {group.map((item) => {
531
815
  const i = index++;
532
816
  const state = states[i];
533
- const off = disabled || !state?.enabled;
817
+ // Inserting a picture needs the app's upload; editing a selected one does not.
818
+ const off =
819
+ disabled ||
820
+ !state?.enabled ||
821
+ (item.dialog === "picture" && state?.value === "insert" && !upload);
534
822
  if (item.select) {
535
823
  const { select } = item;
536
824
  const value = state?.value ?? "";
@@ -588,8 +876,10 @@ export function FoliToolbar({
588
876
  aria-label={item.symbol ? item.label : undefined}
589
877
  title={item.label}
590
878
  aria-pressed={item.pressed ? Boolean(state?.pressed) : undefined}
591
- aria-haspopup={item.menu ? "menu" : undefined}
592
- aria-expanded={item.menu ? menu === item.key : undefined}
879
+ aria-haspopup={
880
+ item.menu || item.actions ? "menu" : item.dialog ? "dialog" : undefined
881
+ }
882
+ aria-expanded={item.menu || item.actions ? menu === item.key : undefined}
593
883
  aria-disabled={off || undefined}
594
884
  tabIndex={i === active ? 0 : -1}
595
885
  // Keep the focus (and the selection) in the document on click.
@@ -598,7 +888,7 @@ export function FoliToolbar({
598
888
  onClick={(event) => run(i, event)}
599
889
  onKeyDown={(event) => {
600
890
  // ArrowDown opens a menu (the WAI-ARIA menu button pattern).
601
- if (!item.menu || off || event.key !== "ArrowDown") return;
891
+ if (!(item.menu || item.actions) || off || event.key !== "ArrowDown") return;
602
892
  event.preventDefault();
603
893
  setMenu(item.key);
604
894
  }}
@@ -613,6 +903,40 @@ export function FoliToolbar({
613
903
  )}
614
904
  </button>
615
905
  );
906
+ if (item.actions) {
907
+ const { actions } = item;
908
+ return (
909
+ <span key={item.key} className="foli-toolbar-menu">
910
+ {button}
911
+ {menu === item.key && !disabled && (
912
+ <ActionMenu
913
+ label={item.label}
914
+ actions={actions}
915
+ state={editor.state}
916
+ onPick={(action, pointer) => {
917
+ setMenu(null);
918
+ if (action.dialog) {
919
+ setDialog(null);
920
+ setTableDialog((current) => ({
921
+ restore: buttons.current[i] ?? null,
922
+ selection: editor.state.selection,
923
+ request: (current?.request ?? -1) + 1,
924
+ }));
925
+ return;
926
+ }
927
+ editor.run(action.command);
928
+ if (pointer) onClickCommand?.();
929
+ else buttons.current[i]?.focus();
930
+ }}
931
+ onClose={(refocus) => {
932
+ setMenu(null);
933
+ if (refocus) buttons.current[i]?.focus();
934
+ }}
935
+ />
936
+ )}
937
+ </span>
938
+ );
939
+ }
616
940
  const options = item.menu?.options;
617
941
  if (!options || !item.menu) return button;
618
942
  const { pick } = item.menu;
@@ -642,6 +966,31 @@ export function FoliToolbar({
642
966
  </Fragment>
643
967
  ))}
644
968
  </div>
969
+ {pictureDialog && !disabled && (
970
+ <PictureDialog
971
+ editor={editor}
972
+ pos={pictureDialog.pos}
973
+ upload={upload}
974
+ onClose={(done) => {
975
+ const { restore } = pictureDialog;
976
+ setPictureDialog(null);
977
+ if (done && onClickCommand) onClickCommand();
978
+ else restore?.focus();
979
+ }}
980
+ />
981
+ )}
982
+ {tableDialog && !disabled && (
983
+ <InsertTableDialog
984
+ editor={editor}
985
+ request={tableDialog.request}
986
+ onClose={(inserted) => {
987
+ const { restore } = tableDialog;
988
+ setTableDialog(null);
989
+ if (inserted && onClickCommand) onClickCommand();
990
+ else restore?.focus();
991
+ }}
992
+ />
993
+ )}
645
994
  {dialog && !disabled && (
646
995
  <LinkDialog
647
996
  editor={editor}
@@ -832,3 +1181,477 @@ function LinkDialog({
832
1181
  </div>
833
1182
  );
834
1183
  }
1184
+
1185
+ /**
1186
+ * An action menu (WAI-ARIA menu: menuitems, a menuitemcheckbox for a toggle): the first item
1187
+ * focused on open; arrow keys, Home and End move; Enter or Space (or a click) runs an item;
1188
+ * Escape closes it back to its button, Tab closes it and moves on; leaving it closes it. An item
1189
+ * that cannot apply here is `aria-disabled` (still focusable, as in the toolbar).
1190
+ */
1191
+ function ActionMenu({
1192
+ label,
1193
+ actions,
1194
+ state,
1195
+ onPick,
1196
+ onClose,
1197
+ }: {
1198
+ label: string;
1199
+ actions: readonly Action[];
1200
+ state: EditorState;
1201
+ onPick: (action: Action, pointer: boolean) => void;
1202
+ onClose: (refocus: boolean) => void;
1203
+ }) {
1204
+ const items = useRef<(HTMLButtonElement | null)[]>([]);
1205
+ // Dry runs, once per opening (not after every transaction).
1206
+ // biome-ignore lint/correctness/useExhaustiveDependencies: the actions are a constant list.
1207
+ const enabled = useMemo(() => actions.map((action) => action.command(state)), [state]);
1208
+ // biome-ignore lint/correctness/useExhaustiveDependencies: focus once, on open.
1209
+ useEffect(() => {
1210
+ items.current[0]?.focus();
1211
+ }, []);
1212
+
1213
+ const onKeyDown = (event: KeyboardEvent) => {
1214
+ const count = actions.length;
1215
+ const at = items.current.indexOf(event.target as HTMLButtonElement);
1216
+ const moves: Record<string, number> = {
1217
+ ArrowDown: (at + 1) % count,
1218
+ ArrowUp: (at - 1 + count) % count,
1219
+ Home: 0,
1220
+ End: count - 1,
1221
+ };
1222
+ const next = moves[event.key];
1223
+ event.stopPropagation();
1224
+ if (next !== undefined) {
1225
+ event.preventDefault();
1226
+ items.current[next]?.focus();
1227
+ } else if (event.key === "Escape") {
1228
+ event.preventDefault();
1229
+ onClose(true);
1230
+ } else if (event.key === "Tab") onClose(true);
1231
+ };
1232
+
1233
+ return (
1234
+ <div
1235
+ role="menu"
1236
+ aria-label={label}
1237
+ className="foli-menu"
1238
+ onKeyDown={onKeyDown}
1239
+ onBlur={(event) => {
1240
+ if (!event.currentTarget.contains(event.relatedTarget as Node | null)) onClose(false);
1241
+ }}
1242
+ >
1243
+ {actions.map((action, i) => {
1244
+ const props = {
1245
+ ref: (element: HTMLButtonElement | null) => {
1246
+ items.current[i] = element;
1247
+ },
1248
+ type: "button" as const,
1249
+ "aria-disabled": enabled[i] ? undefined : true,
1250
+ tabIndex: -1,
1251
+ className: "foli-menu-item",
1252
+ onMouseDown: (event: MouseEvent) => event.preventDefault(),
1253
+ onClick: (event: MouseEvent) => {
1254
+ if (enabled[i]) onPick(action, event.detail > 0);
1255
+ },
1256
+ };
1257
+ return action.checked ? (
1258
+ <button
1259
+ key={action.key}
1260
+ {...props}
1261
+ role="menuitemcheckbox"
1262
+ aria-checked={action.checked(state)}
1263
+ >
1264
+ {action.label}
1265
+ </button>
1266
+ ) : (
1267
+ <button key={action.key} {...props} role="menuitem">
1268
+ {action.label}
1269
+ </button>
1270
+ );
1271
+ })}
1272
+ </div>
1273
+ );
1274
+ }
1275
+
1276
+ /** Word's limits for a new table. */
1277
+ const MAX_TABLE_ROWS = 1000;
1278
+ const MAX_TABLE_COLUMNS = 63;
1279
+
1280
+ /**
1281
+ * The insert table dialog: rows and columns (whole numbers within Word's limits; an invalid one
1282
+ * is marked and announced), Insert and Cancel; Escape cancels.
1283
+ */
1284
+ function InsertTableDialog({
1285
+ editor,
1286
+ request,
1287
+ onClose,
1288
+ }: {
1289
+ editor: Editor;
1290
+ /** Counts the open requests: each one focuses the first field. */
1291
+ request: number;
1292
+ /** `inserted`: a table was inserted (the focus may go to the document). */
1293
+ onClose: (inserted: boolean) => void;
1294
+ }) {
1295
+ const [rows, setRows] = useState("2");
1296
+ const [columns, setColumns] = useState("3");
1297
+ // What is wrong: a field out of range, or the place (the caret is not in a paragraph).
1298
+ const [error, setError] = useState<"rows" | "columns" | "place" | null>(null);
1299
+ const rowsField = useRef<HTMLInputElement>(null);
1300
+ const columnsField = useRef<HTMLInputElement>(null);
1301
+ const id = useId();
1302
+ // biome-ignore lint/correctness/useExhaustiveDependencies: each request focuses the field again.
1303
+ useEffect(() => {
1304
+ rowsField.current?.focus();
1305
+ rowsField.current?.select();
1306
+ }, [request]);
1307
+
1308
+ const parse = (value: string, max: number) => {
1309
+ const n = Number(value);
1310
+ return Number.isInteger(n) && n >= 1 && n <= max ? n : null;
1311
+ };
1312
+ const insert = (event: FormEvent) => {
1313
+ event.preventDefault();
1314
+ const r = parse(rows, MAX_TABLE_ROWS);
1315
+ const c = parse(columns, MAX_TABLE_COLUMNS);
1316
+ const wrong = r === null ? "rows" : c === null ? "columns" : null;
1317
+ if (!wrong && editor.run(insertTable(r as number, c as number))) {
1318
+ onClose(true);
1319
+ return;
1320
+ }
1321
+ setError(wrong ?? "place");
1322
+ (wrong === "columns" ? columnsField : rowsField).current?.focus();
1323
+ };
1324
+ const messages = {
1325
+ rows: `Enter a number of rows from 1 to ${MAX_TABLE_ROWS}.`,
1326
+ columns: `Enter a number of columns from 1 to ${MAX_TABLE_COLUMNS}.`,
1327
+ place: "A table cannot be inserted here: put the caret in a paragraph.",
1328
+ };
1329
+ const field = (
1330
+ name: "rows" | "columns",
1331
+ label: string,
1332
+ value: string,
1333
+ set: (value: string) => void,
1334
+ max: number,
1335
+ ref: typeof rowsField,
1336
+ ) => (
1337
+ <>
1338
+ <label htmlFor={`${id}-${name}`}>{label}</label>
1339
+ <input
1340
+ ref={ref}
1341
+ id={`${id}-${name}`}
1342
+ type="number"
1343
+ min={1}
1344
+ max={max}
1345
+ step={1}
1346
+ value={value}
1347
+ aria-invalid={error === name || undefined}
1348
+ aria-describedby={error === name ? `${id}-error` : undefined}
1349
+ onChange={(event) => {
1350
+ set(event.target.value);
1351
+ setError(null);
1352
+ }}
1353
+ />
1354
+ </>
1355
+ );
1356
+
1357
+ return (
1358
+ <div
1359
+ role="dialog"
1360
+ aria-label="Insert table"
1361
+ className="foli-link-dialog foli-table-dialog"
1362
+ onKeyDown={(event) => {
1363
+ if (event.key !== "Escape") return;
1364
+ event.preventDefault();
1365
+ onClose(false);
1366
+ }}
1367
+ >
1368
+ <form onSubmit={insert} noValidate>
1369
+ {field("rows", "Rows", rows, setRows, MAX_TABLE_ROWS, rowsField)}
1370
+ {field("columns", "Columns", columns, setColumns, MAX_TABLE_COLUMNS, columnsField)}
1371
+ <button type="submit">Insert</button>
1372
+ <button type="button" onClick={() => onClose(false)}>
1373
+ Cancel
1374
+ </button>
1375
+ {error && (
1376
+ <p id={`${id}-error`} className="foli-link-error" role="alert">
1377
+ {messages[error]}
1378
+ </p>
1379
+ )}
1380
+ </form>
1381
+ </div>
1382
+ );
1383
+ }
1384
+
1385
+ /** The largest picture side the schema takes, in px (2^31 - 1 EMU). */
1386
+ const MAX_PICTURE_PX = Math.floor(2_147_483_647 / EMU_PER_PX);
1387
+
1388
+ /**
1389
+ * The picture dialog. Inserting (`pos` null): an image file, its alt text (required unless the
1390
+ * picture is marked decorative), Insert and Cancel; the file goes through `upload`, the picture
1391
+ * in at the file's natural size no wider than the page's text. Editing the picture at `pos`:
1392
+ * its alt text, decorative, and its width and height in px (proportions kept unless unchecked;
1393
+ * not while tracking changes), Apply and Cancel. Escape cancels; a field that is wrong is marked
1394
+ * and announced.
1395
+ */
1396
+ function PictureDialog({
1397
+ editor,
1398
+ pos,
1399
+ upload,
1400
+ onClose,
1401
+ }: {
1402
+ editor: Editor;
1403
+ pos: number | null;
1404
+ upload: EditorViewOptions["upload"] | undefined;
1405
+ /** `done`: a picture was inserted or changed (the focus may go to the document). */
1406
+ onClose: (done: boolean) => void;
1407
+ }) {
1408
+ const picture = pos === null ? null : editor.state.doc.nodeAt(pos);
1409
+ const attrs = picture?.attrs ?? {};
1410
+ const px = (emu: unknown) => String(Math.round(Number(emu) / EMU_PER_PX));
1411
+ const [file, setFile] = useState<File | null>(null);
1412
+ const [alt, setAlt] = useState(String(attrs.alt ?? ""));
1413
+ const [decorative, setDecorative] = useState(attrs.decorative === true);
1414
+ const [width, setWidth] = useState(picture ? px(attrs.width) : "");
1415
+ const [height, setHeight] = useState(picture ? px(attrs.height) : "");
1416
+ const [keep, setKeep] = useState(true);
1417
+ const [error, setError] = useState<"file" | "alt" | "size" | "failed" | null>(null);
1418
+ const [busy, setBusy] = useState(false);
1419
+ const fileField = useRef<HTMLInputElement>(null);
1420
+ const altField = useRef<HTMLInputElement>(null);
1421
+ const decorativeField = useRef<HTMLInputElement>(null);
1422
+ const widthField = useRef<HTMLInputElement>(null);
1423
+ const id = useId();
1424
+ const tracking = trackState(editor.state)?.on === true;
1425
+ const ratio = picture ? Number(attrs.height) / Number(attrs.width) : 1;
1426
+ // The first field that can take the focus (a decorative picture's alt text cannot).
1427
+ // biome-ignore lint/correctness/useExhaustiveDependencies: focus once, on open.
1428
+ useEffect(() => {
1429
+ (pos === null
1430
+ ? fileField.current
1431
+ : decorative
1432
+ ? decorativeField.current
1433
+ : altField.current
1434
+ )?.focus();
1435
+ }, []);
1436
+ // A dialog closed while an upload runs: what the upload finds then is not inserted. Set in
1437
+ // the effect too: StrictMode runs effects twice (setup, cleanup, setup).
1438
+ const open = useRef(true);
1439
+ useEffect(() => {
1440
+ open.current = true;
1441
+ return () => {
1442
+ open.current = false;
1443
+ };
1444
+ }, []);
1445
+
1446
+ const messages = {
1447
+ file: "Choose an image file.",
1448
+ alt: "Describe the picture, or mark it as decorative.",
1449
+ size: `Enter a width and height in pixels, from 1 to ${MAX_PICTURE_PX}.`,
1450
+ failed: "The picture could not be inserted: the file could not be read or uploaded here.",
1451
+ };
1452
+ const invalid = (field: string) => (error === field ? true : undefined);
1453
+ const described = (field: string) => (error === field ? `${id}-error` : undefined);
1454
+ /** Marks `field` wrong and puts the focus on it. */
1455
+ const fail = (field: NonNullable<typeof error>) => {
1456
+ setError(field);
1457
+ const target = {
1458
+ file: fileField,
1459
+ alt: altField,
1460
+ size: widthField,
1461
+ failed: fileField,
1462
+ }[field].current;
1463
+ target?.focus();
1464
+ };
1465
+
1466
+ const submit = async (event: FormEvent) => {
1467
+ event.preventDefault();
1468
+ if (busy) return;
1469
+ if (!decorative && !alt.trim()) {
1470
+ fail("alt");
1471
+ return;
1472
+ }
1473
+ if (pos !== null) {
1474
+ // The picture is gone (the dialog closes on a change; this is a guard).
1475
+ if (!picture) {
1476
+ onClose(false);
1477
+ return;
1478
+ }
1479
+ const w = Math.round(Number(width));
1480
+ const h = Math.round(Number(height));
1481
+ const sizeChanged = w !== Number(px(attrs.width)) || h !== Number(px(attrs.height));
1482
+ const valid = (n: number) => Number.isFinite(n) && n >= 1 && n <= MAX_PICTURE_PX;
1483
+ if (sizeChanged && !tracking && !(valid(w) && valid(h))) {
1484
+ fail("size");
1485
+ return;
1486
+ }
1487
+ editor.run(setPictureAlt(pos, alt, decorative));
1488
+ if (sizeChanged && !tracking)
1489
+ editor.run(setPictureSize(pos, Math.round(w * EMU_PER_PX), Math.round(h * EMU_PER_PX)));
1490
+ onClose(true);
1491
+ return;
1492
+ }
1493
+ if (!file || !upload || !file.type.startsWith("image/")) {
1494
+ fail("file");
1495
+ return;
1496
+ }
1497
+ setBusy(true);
1498
+ try {
1499
+ const size = await measureImageFile(file, document);
1500
+ const answer = size ? await upload(file) : null;
1501
+ const src = typeof answer === "string" ? answer : answer?.src;
1502
+ if (!open.current) return;
1503
+ if (!size || !src) throw new Error("no image");
1504
+ const scale = Math.min(1, textWidthEmu(editor.state) / (size.width * EMU_PER_PX));
1505
+ const type = /^data:([^;,]+)/i.exec(src)?.[1]?.toLowerCase() ?? file.type;
1506
+ const done = editor.run(
1507
+ insertPicture({
1508
+ contentType: type,
1509
+ ...(src.startsWith("data:") ? { data: src } : { url: src }),
1510
+ width: Math.max(1, Math.round(size.width * EMU_PER_PX * scale)),
1511
+ height: Math.max(1, Math.round(size.height * EMU_PER_PX * scale)),
1512
+ ...(decorative ? { decorative: true } : { alt }),
1513
+ }),
1514
+ );
1515
+ if (!done) throw new Error("not inserted");
1516
+ onClose(true);
1517
+ } catch {
1518
+ if (!open.current) return;
1519
+ setBusy(false);
1520
+ fail("failed");
1521
+ }
1522
+ };
1523
+
1524
+ const changeWidth = (value: string) => {
1525
+ setWidth(value);
1526
+ setError(null);
1527
+ if (keep && Number(value) > 0)
1528
+ setHeight(String(Math.max(1, Math.round(Number(value) * ratio))));
1529
+ };
1530
+ const changeHeight = (value: string) => {
1531
+ setHeight(value);
1532
+ setError(null);
1533
+ if (keep && Number(value) > 0) setWidth(String(Math.max(1, Math.round(Number(value) / ratio))));
1534
+ };
1535
+ const sizeNote = tracking ? `${id}-tracking` : undefined;
1536
+ const sizeDescribed = [described("size"), sizeNote].filter(Boolean).join(" ") || undefined;
1537
+
1538
+ return (
1539
+ <div
1540
+ role="dialog"
1541
+ aria-label={pos === null ? "Insert picture" : "Edit picture"}
1542
+ className="foli-link-dialog foli-picture-dialog"
1543
+ aria-busy={busy || undefined}
1544
+ onKeyDown={(event) => {
1545
+ if (event.key !== "Escape") return;
1546
+ event.preventDefault();
1547
+ onClose(false);
1548
+ }}
1549
+ >
1550
+ <form onSubmit={submit} noValidate>
1551
+ {pos === null && (
1552
+ <>
1553
+ <label htmlFor={`${id}-file`}>Image</label>
1554
+ <input
1555
+ ref={fileField}
1556
+ id={`${id}-file`}
1557
+ type="file"
1558
+ accept="image/*"
1559
+ required
1560
+ aria-invalid={invalid("file")}
1561
+ aria-describedby={described("file")}
1562
+ onChange={(event) => {
1563
+ setFile(event.target.files?.[0] ?? null);
1564
+ setError(null);
1565
+ }}
1566
+ />
1567
+ </>
1568
+ )}
1569
+ <label htmlFor={`${id}-alt`}>Alt text</label>
1570
+ <input
1571
+ ref={altField}
1572
+ id={`${id}-alt`}
1573
+ type="text"
1574
+ maxLength={65_535}
1575
+ value={decorative ? "" : alt}
1576
+ disabled={decorative}
1577
+ required={!decorative}
1578
+ aria-invalid={invalid("alt")}
1579
+ aria-describedby={described("alt")}
1580
+ onChange={(event) => {
1581
+ setAlt(event.target.value);
1582
+ setError(null);
1583
+ }}
1584
+ />
1585
+ <label>
1586
+ <input
1587
+ ref={decorativeField}
1588
+ type="checkbox"
1589
+ checked={decorative}
1590
+ onChange={(event) => {
1591
+ setDecorative(event.target.checked);
1592
+ setError(null);
1593
+ }}
1594
+ />
1595
+ Decorative (no alt text)
1596
+ </label>
1597
+ {pos !== null && (
1598
+ <>
1599
+ <label htmlFor={`${id}-width`}>Width (px)</label>
1600
+ <input
1601
+ ref={widthField}
1602
+ id={`${id}-width`}
1603
+ type="number"
1604
+ min={1}
1605
+ max={MAX_PICTURE_PX}
1606
+ step={1}
1607
+ value={width}
1608
+ disabled={tracking}
1609
+ aria-invalid={invalid("size")}
1610
+ aria-describedby={sizeDescribed}
1611
+ onChange={(event) => changeWidth(event.target.value)}
1612
+ />
1613
+ <label htmlFor={`${id}-height`}>Height (px)</label>
1614
+ <input
1615
+ id={`${id}-height`}
1616
+ type="number"
1617
+ min={1}
1618
+ max={MAX_PICTURE_PX}
1619
+ step={1}
1620
+ value={height}
1621
+ disabled={tracking}
1622
+ aria-invalid={invalid("size")}
1623
+ aria-describedby={sizeDescribed}
1624
+ onChange={(event) => changeHeight(event.target.value)}
1625
+ />
1626
+ <label>
1627
+ <input
1628
+ type="checkbox"
1629
+ checked={keep}
1630
+ disabled={tracking}
1631
+ aria-describedby={sizeNote}
1632
+ onChange={(event) => setKeep(event.target.checked)}
1633
+ />
1634
+ Keep proportions
1635
+ </label>
1636
+ {tracking && <p id={sizeNote}>The size does not change while changes are tracked.</p>}
1637
+ </>
1638
+ )}
1639
+ {/* Not `disabled` while uploading: the focus stays on it (Escape still cancels). */}
1640
+ <button type="submit" aria-disabled={busy || undefined}>
1641
+ {pos === null ? "Insert" : "Apply"}
1642
+ </button>
1643
+ <button type="button" onClick={() => onClose(false)}>
1644
+ Cancel
1645
+ </button>
1646
+ <p role="status" className="foli-picture-status">
1647
+ {busy ? "Inserting the picture…" : ""}
1648
+ </p>
1649
+ {error && (
1650
+ <p id={`${id}-error`} className="foli-link-error" role="alert">
1651
+ {messages[error]}
1652
+ </p>
1653
+ )}
1654
+ </form>
1655
+ </div>
1656
+ );
1657
+ }