@folijs/react 0.4.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.
@@ -8,15 +8,24 @@ import {
8
8
  canOutdent,
9
9
  changeIndent,
10
10
  colorAt,
11
+ deleteColumns,
12
+ deleteRows,
13
+ deleteTable,
11
14
  type Editor,
12
15
  type EditorState,
13
16
  fontFamilyAt,
14
17
  fontSizeAt,
18
+ insertColumn,
15
19
  insertPageBreak,
20
+ insertPicture,
21
+ insertRow,
22
+ insertTable,
23
+ isHeaderRow,
16
24
  isSafeHref,
17
25
  lineSpacingAt,
18
26
  linkAt,
19
27
  listKindAt,
28
+ mergeCells,
20
29
  nextChange,
21
30
  normalizeHref,
22
31
  openLinkEditor,
@@ -30,16 +39,25 @@ import {
30
39
  rejectChange,
31
40
  removeLink,
32
41
  requestsLinkEditor,
42
+ selectedPicture,
33
43
  setAlign,
44
+ setCellShading,
34
45
  setFontFamily,
35
46
  setFontSize,
36
47
  setHighlight,
37
48
  setLineSpacing,
38
49
  setLink,
39
50
  setParagraphStyle,
51
+ setPictureAlt,
52
+ setPictureSize,
40
53
  setReviewView,
54
+ setTableStyle,
41
55
  setTextColor,
42
56
  setTrackChanges,
57
+ splitCell,
58
+ tableStyleAt,
59
+ tableStyles,
60
+ toggleHeaderRow,
43
61
  toggleList,
44
62
  toggleMark,
45
63
  trackState,
@@ -47,6 +65,7 @@ import {
47
65
  undoDepth,
48
66
  wordContext,
49
67
  } from "@folijs/core";
68
+ import { type EditorViewOptions, EMU_PER_PX, measureImageFile, textWidthEmu } from "@folijs/view";
50
69
  import {
51
70
  type FormEvent,
52
71
  Fragment,
@@ -55,6 +74,7 @@ import {
55
74
  type ReactNode,
56
75
  useEffect,
57
76
  useId,
77
+ useMemo,
58
78
  useRef,
59
79
  useState,
60
80
  } from "react";
@@ -80,6 +100,11 @@ export interface FoliToolbarProps {
80
100
  * (`FoliEditor` passes it). Default false.
81
101
  */
82
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;
83
108
  className?: string | undefined;
84
109
  }
85
110
 
@@ -109,6 +134,10 @@ interface Item {
109
134
  value: (state: EditorState) => string | null;
110
135
  pick: (color: string | null) => Command;
111
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";
112
141
  /** A drop-down list (a `select`): its options, the current value, and what picking runs. */
113
142
  select?: {
114
143
  options: (state: EditorState) => readonly { value: string; label: string }[];
@@ -117,6 +146,16 @@ interface Item {
117
146
  };
118
147
  }
119
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
+
120
159
  interface ColorOption {
121
160
  name: string;
122
161
  /** Lowercase `#rrggbb`; null removes the color. */
@@ -146,6 +185,48 @@ const HIGHLIGHTS: readonly ColorOption[] = [
146
185
  { name: "Gray", color: "#c0c0c0" },
147
186
  ];
148
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
+
149
230
  /** Whether the selection holds a textblock (a caret's own block first; else it walks the range). */
150
231
  function hasTextblock(state: EditorState): boolean {
151
232
  if (state.selection.$from.parent.isTextblock) return true;
@@ -460,7 +541,52 @@ const GROUPS: Item[][] = [
460
541
  command: () => redo,
461
542
  },
462
543
  ],
463
- [{ 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
+ ],
464
590
  ];
465
591
 
466
592
  const ITEMS = GROUPS.flat();
@@ -500,7 +626,10 @@ const statesOf =
500
626
  items.map((item) => ({
501
627
  pressed: item.pressed?.(state, editor),
502
628
  enabled: item.enabled?.(state) ?? true,
503
- 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),
504
633
  }));
505
634
  const selectStates = statesOf(ITEMS);
506
635
  const selectStatesNoComment = statesOf(ITEMS_NO_COMMENT);
@@ -508,7 +637,8 @@ const selectStatesNoComment = statesOf(ITEMS_NO_COMMENT);
508
637
  /**
509
638
  * Word's formatting controls for an editor: paragraph style, font and size boxes, marks, link (a
510
639
  * dialog, also on Mod-K in the document), text color and highlight menus, alignment and line
511
- * 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.
512
642
  * One tab stop (arrow keys, Home and End move between buttons); toggles carry
513
643
  * `aria-pressed`; a button whose command cannot run now is `aria-disabled` (still focusable).
514
644
  * Clicks leave the focus and selection in the document.
@@ -520,6 +650,7 @@ export function FoliToolbar({
520
650
  label = "Formatting",
521
651
  className,
522
652
  comments = false,
653
+ upload,
523
654
  }: FoliToolbarProps) {
524
655
  const editor = useEditorOrContext(given, "FoliToolbar");
525
656
  const groups = comments ? GROUPS : GROUPS_NO_COMMENT;
@@ -541,7 +672,20 @@ export function FoliToolbar({
541
672
  const run = (index: number, event: MouseEvent) => {
542
673
  const item = items[index];
543
674
  if (!item || disabled || !states[index]?.enabled) return;
544
- 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) {
545
689
  if (menu !== item.key) {
546
690
  setMenu(item.key);
547
691
  return;
@@ -568,6 +712,25 @@ export function FoliToolbar({
568
712
  editor.subscribe((state, transactions) => {
569
713
  if (disabled) return;
570
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
+ );
571
734
  setDialog((current) =>
572
735
  current &&
573
736
  (transactions.some((tr) => tr.docChanged) || !state.selection.eq(current.selection))
@@ -577,6 +740,8 @@ export function FoliToolbar({
577
740
  return;
578
741
  }
579
742
  const active = typeof document === "undefined" ? null : document.activeElement;
743
+ setTableDialog(null);
744
+ setPictureDialog(null);
580
745
  setDialog((current) =>
581
746
  current
582
747
  ? { ...current, request: current.request + 1 }
@@ -598,6 +763,24 @@ export function FoliToolbar({
598
763
  dialog?.restore?.focus();
599
764
  setDialog(null);
600
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]);
601
784
 
602
785
  const onKeyDown = (event: KeyboardEvent) => {
603
786
  // Alt+Left (back) and other shortcuts are the browser's.
@@ -631,7 +814,11 @@ export function FoliToolbar({
631
814
  {group.map((item) => {
632
815
  const i = index++;
633
816
  const state = states[i];
634
- 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);
635
822
  if (item.select) {
636
823
  const { select } = item;
637
824
  const value = state?.value ?? "";
@@ -689,8 +876,10 @@ export function FoliToolbar({
689
876
  aria-label={item.symbol ? item.label : undefined}
690
877
  title={item.label}
691
878
  aria-pressed={item.pressed ? Boolean(state?.pressed) : undefined}
692
- aria-haspopup={item.menu ? "menu" : undefined}
693
- 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}
694
883
  aria-disabled={off || undefined}
695
884
  tabIndex={i === active ? 0 : -1}
696
885
  // Keep the focus (and the selection) in the document on click.
@@ -699,7 +888,7 @@ export function FoliToolbar({
699
888
  onClick={(event) => run(i, event)}
700
889
  onKeyDown={(event) => {
701
890
  // ArrowDown opens a menu (the WAI-ARIA menu button pattern).
702
- if (!item.menu || off || event.key !== "ArrowDown") return;
891
+ if (!(item.menu || item.actions) || off || event.key !== "ArrowDown") return;
703
892
  event.preventDefault();
704
893
  setMenu(item.key);
705
894
  }}
@@ -714,6 +903,40 @@ export function FoliToolbar({
714
903
  )}
715
904
  </button>
716
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
+ }
717
940
  const options = item.menu?.options;
718
941
  if (!options || !item.menu) return button;
719
942
  const { pick } = item.menu;
@@ -743,6 +966,31 @@ export function FoliToolbar({
743
966
  </Fragment>
744
967
  ))}
745
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
+ )}
746
994
  {dialog && !disabled && (
747
995
  <LinkDialog
748
996
  editor={editor}
@@ -933,3 +1181,477 @@ function LinkDialog({
933
1181
  </div>
934
1182
  );
935
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
+ }