@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,6 +1,7 @@
1
1
  import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { alignAt, canOutdent, changeIndent, colorAt, fontFamilyAt, fontSizeAt, insertPageBreak, isSafeHref, lineSpacingAt, linkAt, listKindAt, normalizeHref, openLinkEditor, paragraphStyleAt, paragraphStyles, redo, redoDepth, removeLink, requestsLinkEditor, setAlign, setFontFamily, setFontSize, setHighlight, setLineSpacing, setLink, setParagraphStyle, setTextColor, toggleList, toggleMark, undo, undoDepth, wordContext, } from "@folijs/core";
3
- import { Fragment, useEffect, useId, useRef, useState, } from "react";
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";
3
+ import { EMU_PER_PX, measureImageFile, textWidthEmu } from "@folijs/view";
4
+ import { Fragment, useEffect, useId, useMemo, useRef, useState, } from "react";
4
5
  import { useEditorOrContext, useEditorState } from "./editor.js";
5
6
  /**
6
7
  * The palettes (fixed: a document should not need a color picker). Text colors keep at least
@@ -24,6 +25,46 @@ const HIGHLIGHTS = [
24
25
  { name: "Pink", color: "#ff00ff" },
25
26
  { name: "Gray", color: "#c0c0c0" },
26
27
  ];
28
+ /** Cell shadings: light fills that keep text readable. */
29
+ const SHADINGS = [
30
+ { name: "None", color: null },
31
+ { name: "Light gray", color: "#d9d9d9" },
32
+ { name: "Light blue", color: "#deeaf6" },
33
+ { name: "Light green", color: "#e2efd9" },
34
+ { name: "Light yellow", color: "#fff2cc" },
35
+ { name: "Light orange", color: "#fbe4d5" },
36
+ ];
37
+ /** The cell around the selection's start, if any (cheap: the start's ancestors). */
38
+ function cellAt(state) {
39
+ const { $from } = state.selection;
40
+ for (let d = $from.depth; d > 0; d--)
41
+ if ($from.node(d).type.name === "tableCell")
42
+ return $from.node(d);
43
+ // A cell selection starts before its first cell.
44
+ const after = $from.nodeAfter;
45
+ return after?.type.name === "tableCell" ? after : null;
46
+ }
47
+ const inTable = (state) => cellAt(state) !== null;
48
+ /** Table and cell properties change only when not tracking (Foli does not record them yet). */
49
+ const canFormatTable = (state) => inTable(state) && trackState(state)?.on !== true;
50
+ const TABLE_ACTIONS = [
51
+ { key: "insertTable", label: "Insert table…", command: insertTable(1, 1), dialog: "insertTable" },
52
+ { key: "rowAbove", label: "Insert row above", command: insertRow(-1) },
53
+ { key: "rowBelow", label: "Insert row below", command: insertRow(1) },
54
+ { key: "columnLeft", label: "Insert column left", command: insertColumn(-1) },
55
+ { key: "columnRight", label: "Insert column right", command: insertColumn(1) },
56
+ { key: "deleteRows", label: "Delete rows", command: deleteRows },
57
+ { key: "deleteColumns", label: "Delete columns", command: deleteColumns },
58
+ { key: "deleteTable", label: "Delete table", command: deleteTable },
59
+ { key: "mergeCells", label: "Merge cells", command: mergeCells },
60
+ { key: "splitCell", label: "Split cell", command: splitCell },
61
+ {
62
+ key: "headerRow",
63
+ label: "Repeat as header row",
64
+ command: toggleHeaderRow,
65
+ checked: isHeaderRow,
66
+ },
67
+ ];
27
68
  /** Whether the selection holds a textblock (a caret's own block first; else it walks the range). */
28
69
  function hasTextblock(state) {
29
70
  if (state.selection.$from.parent.isTextblock)
@@ -70,6 +111,11 @@ const FONTS = [
70
111
  ];
71
112
  const SIZES = [8, 9, 10, 10.5, 11, 12, 14, 16, 18, 20, 22, 24, 26, 28, 36, 48, 72];
72
113
  const LINE_SPACINGS = [1, 1.15, 1.5, 2, 2.5, 3];
114
+ const REVIEW_VIEWS = [
115
+ { value: "markup", label: "All markup" },
116
+ { value: "simple", label: "Simple markup" },
117
+ { value: "final", label: "No markup" },
118
+ ];
73
119
  /** Word's controls. */
74
120
  const GROUPS = [
75
121
  [
@@ -232,6 +278,78 @@ const GROUPS = [
232
278
  command: () => changeIndent(1),
233
279
  },
234
280
  ],
281
+ [
282
+ {
283
+ key: "newComment",
284
+ label: "New comment on the selection",
285
+ text: "New comment",
286
+ enabled: (state) => wordContext(state) !== null && hasTextblock(state),
287
+ command: () => addComment(""),
288
+ },
289
+ {
290
+ key: "trackChanges",
291
+ label: "Track changes",
292
+ text: "Track changes",
293
+ pressed: (state) => trackState(state)?.on === true,
294
+ enabled: (state) => trackState(state) !== null,
295
+ command: (state) => setTrackChanges(!trackState(state)?.on),
296
+ },
297
+ {
298
+ key: "reviewView",
299
+ label: "Show changes as",
300
+ text: "Show",
301
+ enabled: (state) => trackState(state) !== null,
302
+ select: {
303
+ options: () => REVIEW_VIEWS,
304
+ value: (state) => trackState(state)?.view ?? "markup",
305
+ pick: (view) => setReviewView(view),
306
+ },
307
+ },
308
+ // Enabled while tracking can be used: whether there is a change to go to or resolve would
309
+ // walk the whole document after every transaction.
310
+ {
311
+ key: "previousChange",
312
+ label: "Previous change",
313
+ text: "Previous change",
314
+ enabled: (state) => trackState(state) !== null,
315
+ command: () => previousChange,
316
+ },
317
+ {
318
+ key: "nextChange",
319
+ label: "Next change",
320
+ text: "Next change",
321
+ enabled: (state) => trackState(state) !== null,
322
+ command: () => nextChange,
323
+ },
324
+ {
325
+ key: "acceptChange",
326
+ label: "Accept the change here, or the changes selected",
327
+ text: "Accept",
328
+ enabled: (state) => trackState(state) !== null,
329
+ command: () => acceptChange,
330
+ },
331
+ {
332
+ key: "rejectChange",
333
+ label: "Reject the change here, or the changes selected",
334
+ text: "Reject",
335
+ enabled: (state) => trackState(state) !== null,
336
+ command: () => rejectChange,
337
+ },
338
+ {
339
+ key: "acceptAll",
340
+ label: "Accept all changes",
341
+ text: "Accept all",
342
+ enabled: (state) => trackState(state) !== null,
343
+ command: () => acceptAllChanges(),
344
+ },
345
+ {
346
+ key: "rejectAll",
347
+ label: "Reject all changes",
348
+ text: "Reject all",
349
+ enabled: (state) => trackState(state) !== null,
350
+ command: () => rejectAllChanges(),
351
+ },
352
+ ],
235
353
  [
236
354
  {
237
355
  key: "undo",
@@ -248,9 +366,56 @@ const GROUPS = [
248
366
  command: () => redo,
249
367
  },
250
368
  ],
251
- [{ key: "pageBreak", label: "Page break", text: "Page break", command: () => insertPageBreak }],
369
+ [
370
+ {
371
+ key: "table",
372
+ label: "Table",
373
+ text: "Table",
374
+ enabled: (state) => wordContext(state) !== null && "table" in state.schema.nodes,
375
+ actions: TABLE_ACTIONS,
376
+ },
377
+ {
378
+ key: "tableStyle",
379
+ label: "Table style",
380
+ text: "Table style",
381
+ enabled: canFormatTable,
382
+ select: {
383
+ options: (state) => tableStyles(state).map((name) => ({ value: name, label: name })),
384
+ value: (state) => (inTable(state) ? (tableStyleAt(state) ?? "") : null),
385
+ pick: (name) => setTableStyle(name),
386
+ },
387
+ },
388
+ {
389
+ key: "cellShading",
390
+ label: "Cell shading",
391
+ text: "Shading",
392
+ enabled: canFormatTable,
393
+ menu: {
394
+ options: SHADINGS,
395
+ value: (state) => {
396
+ const fill = cellAt(state)?.attrs.shading?.fill;
397
+ return fill && fill.toLowerCase() !== "auto" ? `#${fill.toLowerCase()}` : null;
398
+ },
399
+ pick: (color) => setCellShading(color ? color.slice(1).toUpperCase() : null),
400
+ },
401
+ },
402
+ ],
403
+ [
404
+ {
405
+ key: "picture",
406
+ label: "Insert a picture, or edit the selected one",
407
+ text: "Picture…",
408
+ enabled: (state) => wordContext(state) !== null && (selectedPicture(state) !== null || hasTextblock(state)),
409
+ // With a picture selected the dialog edits it.
410
+ dialog: "picture",
411
+ },
412
+ { key: "pageBreak", label: "Page break", text: "Page break", command: () => insertPageBreak },
413
+ ],
252
414
  ];
253
415
  const ITEMS = GROUPS.flat();
416
+ /** Without "New comment": where no comments pane lets a comment be written. */
417
+ const GROUPS_NO_COMMENT = GROUPS.map((group) => group.filter((i) => i.key !== "newComment"));
418
+ const ITEMS_NO_COMMENT = GROUPS_NO_COMMENT.flat();
254
419
  const sameStates = (a, b) => a.length === b.length &&
255
420
  a.every((item, i) => item.pressed === b[i]?.pressed &&
256
421
  item.enabled === b[i]?.enabled &&
@@ -259,22 +424,29 @@ const sameStates = (a, b) => a.length === b.length &&
259
424
  const statesOf = (items) => (state, editor) => items.map((item) => ({
260
425
  pressed: item.pressed?.(state, editor),
261
426
  enabled: item.enabled?.(state) ?? true,
262
- value: item.menu?.value(state) ?? item.select?.value(state),
427
+ value: item.menu?.value(state) ??
428
+ item.select?.value(state) ??
429
+ (item.dialog ? (selectedPicture(state) ? "edit" : "insert") : undefined),
263
430
  }));
264
431
  const selectStates = statesOf(ITEMS);
432
+ const selectStatesNoComment = statesOf(ITEMS_NO_COMMENT);
265
433
  /**
266
434
  * Word's formatting controls for an editor: paragraph style, font and size boxes, marks, link (a
267
435
  * dialog, also on Mod-K in the document), text color and highlight menus, alignment and line
268
- * spacing, lists (bulleted, numbered, decrease and increase indent), undo, redo, page break.
436
+ * spacing, lists (bulleted, numbered, decrease and increase indent), undo, redo, tables (a Table
437
+ * menu with an insert table dialog, a table style box, a cell shading menu), page break.
269
438
  * One tab stop (arrow keys, Home and End move between buttons); toggles carry
270
439
  * `aria-pressed`; a button whose command cannot run now is `aria-disabled` (still focusable).
271
440
  * Clicks leave the focus and selection in the document.
272
441
  */
273
- export function FoliToolbar({ editor: given, disabled = false, onClickCommand, label = "Formatting", className, }) {
442
+ export function FoliToolbar({ editor: given, disabled = false, onClickCommand, label = "Formatting", className, comments = false, upload, }) {
274
443
  const editor = useEditorOrContext(given, "FoliToolbar");
275
- const groups = GROUPS;
276
- const items = ITEMS;
277
- const states = useEditorState(selectStates, { editor, isEqual: sameStates });
444
+ const groups = comments ? GROUPS : GROUPS_NO_COMMENT;
445
+ const items = comments ? ITEMS : ITEMS_NO_COMMENT;
446
+ const states = useEditorState(comments ? selectStates : selectStatesNoComment, {
447
+ editor,
448
+ isEqual: sameStates,
449
+ });
278
450
  const [active, setActive] = useState(0);
279
451
  const buttons = useRef([]);
280
452
  // Whether a select box was last used with the pointer (its pick then goes back to the document).
@@ -289,7 +461,21 @@ export function FoliToolbar({ editor: given, disabled = false, onClickCommand, l
289
461
  const item = items[index];
290
462
  if (!item || disabled || !states[index]?.enabled)
291
463
  return;
292
- if (item.menu) {
464
+ if (item.dialog === "picture") {
465
+ const selected = selectedPicture(editor.state);
466
+ // Inserting needs the app's upload; editing a selected picture does not.
467
+ if (!selected && !upload)
468
+ return;
469
+ setDialog(null);
470
+ setTableDialog(null);
471
+ setPictureDialog({
472
+ pos: selected?.pos ?? null,
473
+ selection: editor.state.selection,
474
+ restore: buttons.current[index] ?? null,
475
+ });
476
+ return;
477
+ }
478
+ if (item.menu || item.actions) {
293
479
  if (menu !== item.key) {
294
480
  setMenu(item.key);
295
481
  return;
@@ -318,6 +504,21 @@ export function FoliToolbar({ editor: given, disabled = false, onClickCommand, l
318
504
  if (disabled)
319
505
  return;
320
506
  if (!transactions.some(requestsLinkEditor)) {
507
+ // The picture dialog too: what it edits or inserts at may have gone (another
508
+ // document, set with no transaction, included).
509
+ setPictureDialog((current) => current &&
510
+ (!transactions.length ||
511
+ transactions.some((tr) => tr.docChanged) ||
512
+ !state.selection.eq(current.selection))
513
+ ? null
514
+ : current);
515
+ // The insert table dialog is for the caret it opened on, as the link dialog is.
516
+ setTableDialog((current) => current &&
517
+ (!transactions.length ||
518
+ transactions.some((tr) => tr.docChanged) ||
519
+ !state.selection.eq(current.selection))
520
+ ? null
521
+ : current);
321
522
  setDialog((current) => current &&
322
523
  (transactions.some((tr) => tr.docChanged) || !state.selection.eq(current.selection))
323
524
  ? null
@@ -325,6 +526,8 @@ export function FoliToolbar({ editor: given, disabled = false, onClickCommand, l
325
526
  return;
326
527
  }
327
528
  const active = typeof document === "undefined" ? null : document.activeElement;
529
+ setTableDialog(null);
530
+ setPictureDialog(null);
328
531
  setDialog((current) => current
329
532
  ? { ...current, request: current.request + 1 }
330
533
  : {
@@ -343,6 +546,18 @@ export function FoliToolbar({ editor: given, disabled = false, onClickCommand, l
343
546
  dialog?.restore?.focus();
344
547
  setDialog(null);
345
548
  };
549
+ // The insert table dialog (from the table menu): the focus goes back to the menu's button.
550
+ const [tableDialog, setTableDialog] = useState(null);
551
+ useEffect(() => {
552
+ if (disabled)
553
+ setTableDialog(null);
554
+ }, [disabled]);
555
+ // The picture dialog: inserts at (or edits the picture at `pos`) the selection it opened on.
556
+ const [pictureDialog, setPictureDialog] = useState(null);
557
+ useEffect(() => {
558
+ if (disabled)
559
+ setPictureDialog(null);
560
+ }, [disabled]);
346
561
  const onKeyDown = (event) => {
347
562
  // Alt+Left (back) and other shortcuts are the browser's.
348
563
  if (event.altKey || event.ctrlKey || event.metaKey)
@@ -365,7 +580,10 @@ export function FoliToolbar({ editor: given, disabled = false, onClickCommand, l
365
580
  return (_jsxs(_Fragment, { children: [_jsx("div", { role: "toolbar", "aria-label": label, className: className ? `foli-toolbar ${className}` : "foli-toolbar", onKeyDown: onKeyDown, children: groups.map((group, g) => (_jsxs(Fragment, { children: [g > 0 && _jsx("hr", { className: "foli-toolbar-separator", "aria-orientation": "vertical" }), group.map((item) => {
366
581
  const i = index++;
367
582
  const state = states[i];
368
- const off = disabled || !state?.enabled;
583
+ // Inserting a picture needs the app's upload; editing a selected one does not.
584
+ const off = disabled ||
585
+ !state?.enabled ||
586
+ (item.dialog === "picture" && state?.value === "insert" && !upload);
369
587
  if (item.select) {
370
588
  const { select } = item;
371
589
  const value = state?.value ?? "";
@@ -389,15 +607,39 @@ export function FoliToolbar({ editor: given, disabled = false, onClickCommand, l
389
607
  }
390
608
  const button = (_jsxs("button", { ref: (element) => {
391
609
  buttons.current[i] = element;
392
- }, type: "button", className: `foli-toolbar-button foli-toolbar-${item.key}`, "aria-label": item.symbol ? item.label : undefined, title: item.label, "aria-pressed": item.pressed ? Boolean(state?.pressed) : undefined, "aria-haspopup": item.menu ? "menu" : undefined, "aria-expanded": item.menu ? menu === item.key : undefined, "aria-disabled": off || undefined, tabIndex: i === active ? 0 : -1,
610
+ }, type: "button", className: `foli-toolbar-button foli-toolbar-${item.key}`, "aria-label": item.symbol ? item.label : undefined, title: item.label, "aria-pressed": item.pressed ? Boolean(state?.pressed) : undefined, "aria-haspopup": item.menu || item.actions ? "menu" : item.dialog ? "dialog" : undefined, "aria-expanded": item.menu || item.actions ? menu === item.key : undefined, "aria-disabled": off || undefined, tabIndex: i === active ? 0 : -1,
393
611
  // Keep the focus (and the selection) in the document on click.
394
612
  onMouseDown: (event) => event.preventDefault(), onFocus: () => setActive(i), onClick: (event) => run(i, event), onKeyDown: (event) => {
395
613
  // ArrowDown opens a menu (the WAI-ARIA menu button pattern).
396
- if (!item.menu || off || event.key !== "ArrowDown")
614
+ if (!(item.menu || item.actions) || off || event.key !== "ArrowDown")
397
615
  return;
398
616
  event.preventDefault();
399
617
  setMenu(item.key);
400
618
  }, children: [item.icon ?? item.text, item.menu && (_jsx("span", { className: "foli-toolbar-swatch", "aria-hidden": "true", style: { background: state?.value ?? "transparent" } }))] }, item.key));
619
+ if (item.actions) {
620
+ const { actions } = item;
621
+ return (_jsxs("span", { className: "foli-toolbar-menu", children: [button, menu === item.key && !disabled && (_jsx(ActionMenu, { label: item.label, actions: actions, state: editor.state, onPick: (action, pointer) => {
622
+ setMenu(null);
623
+ if (action.dialog) {
624
+ setDialog(null);
625
+ setTableDialog((current) => ({
626
+ restore: buttons.current[i] ?? null,
627
+ selection: editor.state.selection,
628
+ request: (current?.request ?? -1) + 1,
629
+ }));
630
+ return;
631
+ }
632
+ editor.run(action.command);
633
+ if (pointer)
634
+ onClickCommand?.();
635
+ else
636
+ buttons.current[i]?.focus();
637
+ }, onClose: (refocus) => {
638
+ setMenu(null);
639
+ if (refocus)
640
+ buttons.current[i]?.focus();
641
+ } }))] }, item.key));
642
+ }
401
643
  const options = item.menu?.options;
402
644
  if (!options || !item.menu)
403
645
  return button;
@@ -414,7 +656,21 @@ export function FoliToolbar({ editor: given, disabled = false, onClickCommand, l
414
656
  if (refocus)
415
657
  buttons.current[i]?.focus();
416
658
  } }))] }, item.key));
417
- })] }, group[0]?.key))) }), dialog && !disabled && (_jsx(LinkDialog, { editor: editor, href: dialog.href, request: dialog.request, onClose: closeDialog }))] }));
659
+ })] }, group[0]?.key))) }), pictureDialog && !disabled && (_jsx(PictureDialog, { editor: editor, pos: pictureDialog.pos, upload: upload, onClose: (done) => {
660
+ const { restore } = pictureDialog;
661
+ setPictureDialog(null);
662
+ if (done && onClickCommand)
663
+ onClickCommand();
664
+ else
665
+ restore?.focus();
666
+ } })), tableDialog && !disabled && (_jsx(InsertTableDialog, { editor: editor, request: tableDialog.request, onClose: (inserted) => {
667
+ const { restore } = tableDialog;
668
+ setTableDialog(null);
669
+ if (inserted && onClickCommand)
670
+ onClickCommand();
671
+ else
672
+ restore?.focus();
673
+ } })), dialog && !disabled && (_jsx(LinkDialog, { editor: editor, href: dialog.href, request: dialog.request, onClose: closeDialog }))] }));
418
674
  }
419
675
  /**
420
676
  * A color menu (WAI-ARIA menu with radio items): the current color checked and focused on
@@ -501,4 +757,271 @@ function LinkDialog({ editor, href, request, onClose, }) {
501
757
  setInvalid(false);
502
758
  } }), _jsx("button", { type: "submit", children: "Apply" }), href && (_jsx("button", { type: "button", onClick: remove, children: "Remove link" })), _jsx("button", { type: "button", onClick: onClose, children: "Cancel" }), invalid && (_jsx("p", { id: `${id}-error`, className: "foli-link-error", role: "alert", children: "Enter a web or email address, or a link starting with http, https, mailto or tel." }))] }) }));
503
759
  }
760
+ /**
761
+ * An action menu (WAI-ARIA menu: menuitems, a menuitemcheckbox for a toggle): the first item
762
+ * focused on open; arrow keys, Home and End move; Enter or Space (or a click) runs an item;
763
+ * Escape closes it back to its button, Tab closes it and moves on; leaving it closes it. An item
764
+ * that cannot apply here is `aria-disabled` (still focusable, as in the toolbar).
765
+ */
766
+ function ActionMenu({ label, actions, state, onPick, onClose, }) {
767
+ const items = useRef([]);
768
+ // Dry runs, once per opening (not after every transaction).
769
+ // biome-ignore lint/correctness/useExhaustiveDependencies: the actions are a constant list.
770
+ const enabled = useMemo(() => actions.map((action) => action.command(state)), [state]);
771
+ // biome-ignore lint/correctness/useExhaustiveDependencies: focus once, on open.
772
+ useEffect(() => {
773
+ items.current[0]?.focus();
774
+ }, []);
775
+ const onKeyDown = (event) => {
776
+ const count = actions.length;
777
+ const at = items.current.indexOf(event.target);
778
+ const moves = {
779
+ ArrowDown: (at + 1) % count,
780
+ ArrowUp: (at - 1 + count) % count,
781
+ Home: 0,
782
+ End: count - 1,
783
+ };
784
+ const next = moves[event.key];
785
+ event.stopPropagation();
786
+ if (next !== undefined) {
787
+ event.preventDefault();
788
+ items.current[next]?.focus();
789
+ }
790
+ else if (event.key === "Escape") {
791
+ event.preventDefault();
792
+ onClose(true);
793
+ }
794
+ else if (event.key === "Tab")
795
+ onClose(true);
796
+ };
797
+ return (_jsx("div", { role: "menu", "aria-label": label, className: "foli-menu", onKeyDown: onKeyDown, onBlur: (event) => {
798
+ if (!event.currentTarget.contains(event.relatedTarget))
799
+ onClose(false);
800
+ }, children: actions.map((action, i) => {
801
+ const props = {
802
+ ref: (element) => {
803
+ items.current[i] = element;
804
+ },
805
+ type: "button",
806
+ "aria-disabled": enabled[i] ? undefined : true,
807
+ tabIndex: -1,
808
+ className: "foli-menu-item",
809
+ onMouseDown: (event) => event.preventDefault(),
810
+ onClick: (event) => {
811
+ if (enabled[i])
812
+ onPick(action, event.detail > 0);
813
+ },
814
+ };
815
+ return action.checked ? (_jsx("button", { ...props, role: "menuitemcheckbox", "aria-checked": action.checked(state), children: action.label }, action.key)) : (_jsx("button", { ...props, role: "menuitem", children: action.label }, action.key));
816
+ }) }));
817
+ }
818
+ /** Word's limits for a new table. */
819
+ const MAX_TABLE_ROWS = 1000;
820
+ const MAX_TABLE_COLUMNS = 63;
821
+ /**
822
+ * The insert table dialog: rows and columns (whole numbers within Word's limits; an invalid one
823
+ * is marked and announced), Insert and Cancel; Escape cancels.
824
+ */
825
+ function InsertTableDialog({ editor, request, onClose, }) {
826
+ const [rows, setRows] = useState("2");
827
+ const [columns, setColumns] = useState("3");
828
+ // What is wrong: a field out of range, or the place (the caret is not in a paragraph).
829
+ const [error, setError] = useState(null);
830
+ const rowsField = useRef(null);
831
+ const columnsField = useRef(null);
832
+ const id = useId();
833
+ // biome-ignore lint/correctness/useExhaustiveDependencies: each request focuses the field again.
834
+ useEffect(() => {
835
+ rowsField.current?.focus();
836
+ rowsField.current?.select();
837
+ }, [request]);
838
+ const parse = (value, max) => {
839
+ const n = Number(value);
840
+ return Number.isInteger(n) && n >= 1 && n <= max ? n : null;
841
+ };
842
+ const insert = (event) => {
843
+ event.preventDefault();
844
+ const r = parse(rows, MAX_TABLE_ROWS);
845
+ const c = parse(columns, MAX_TABLE_COLUMNS);
846
+ const wrong = r === null ? "rows" : c === null ? "columns" : null;
847
+ if (!wrong && editor.run(insertTable(r, c))) {
848
+ onClose(true);
849
+ return;
850
+ }
851
+ setError(wrong ?? "place");
852
+ (wrong === "columns" ? columnsField : rowsField).current?.focus();
853
+ };
854
+ const messages = {
855
+ rows: `Enter a number of rows from 1 to ${MAX_TABLE_ROWS}.`,
856
+ columns: `Enter a number of columns from 1 to ${MAX_TABLE_COLUMNS}.`,
857
+ place: "A table cannot be inserted here: put the caret in a paragraph.",
858
+ };
859
+ const field = (name, label, value, set, max, ref) => (_jsxs(_Fragment, { children: [_jsx("label", { htmlFor: `${id}-${name}`, children: label }), _jsx("input", { ref: ref, id: `${id}-${name}`, type: "number", min: 1, max: max, step: 1, value: value, "aria-invalid": error === name || undefined, "aria-describedby": error === name ? `${id}-error` : undefined, onChange: (event) => {
860
+ set(event.target.value);
861
+ setError(null);
862
+ } })] }));
863
+ return (_jsx("div", { role: "dialog", "aria-label": "Insert table", className: "foli-link-dialog foli-table-dialog", onKeyDown: (event) => {
864
+ if (event.key !== "Escape")
865
+ return;
866
+ event.preventDefault();
867
+ onClose(false);
868
+ }, 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
+ }
870
+ /** The largest picture side the schema takes, in px (2^31 - 1 EMU). */
871
+ const MAX_PICTURE_PX = Math.floor(2_147_483_647 / EMU_PER_PX);
872
+ /**
873
+ * The picture dialog. Inserting (`pos` null): an image file, its alt text (required unless the
874
+ * picture is marked decorative), Insert and Cancel; the file goes through `upload`, the picture
875
+ * in at the file's natural size no wider than the page's text. Editing the picture at `pos`:
876
+ * its alt text, decorative, and its width and height in px (proportions kept unless unchecked;
877
+ * not while tracking changes), Apply and Cancel. Escape cancels; a field that is wrong is marked
878
+ * and announced.
879
+ */
880
+ function PictureDialog({ editor, pos, upload, onClose, }) {
881
+ const picture = pos === null ? null : editor.state.doc.nodeAt(pos);
882
+ const attrs = picture?.attrs ?? {};
883
+ const px = (emu) => String(Math.round(Number(emu) / EMU_PER_PX));
884
+ const [file, setFile] = useState(null);
885
+ const [alt, setAlt] = useState(String(attrs.alt ?? ""));
886
+ const [decorative, setDecorative] = useState(attrs.decorative === true);
887
+ const [width, setWidth] = useState(picture ? px(attrs.width) : "");
888
+ const [height, setHeight] = useState(picture ? px(attrs.height) : "");
889
+ const [keep, setKeep] = useState(true);
890
+ const [error, setError] = useState(null);
891
+ const [busy, setBusy] = useState(false);
892
+ const fileField = useRef(null);
893
+ const altField = useRef(null);
894
+ const decorativeField = useRef(null);
895
+ const widthField = useRef(null);
896
+ const id = useId();
897
+ const tracking = trackState(editor.state)?.on === true;
898
+ const ratio = picture ? Number(attrs.height) / Number(attrs.width) : 1;
899
+ // The first field that can take the focus (a decorative picture's alt text cannot).
900
+ // biome-ignore lint/correctness/useExhaustiveDependencies: focus once, on open.
901
+ useEffect(() => {
902
+ (pos === null
903
+ ? fileField.current
904
+ : decorative
905
+ ? decorativeField.current
906
+ : altField.current)?.focus();
907
+ }, []);
908
+ // A dialog closed while an upload runs: what the upload finds then is not inserted. Set in
909
+ // the effect too: StrictMode runs effects twice (setup, cleanup, setup).
910
+ const open = useRef(true);
911
+ useEffect(() => {
912
+ open.current = true;
913
+ return () => {
914
+ open.current = false;
915
+ };
916
+ }, []);
917
+ const messages = {
918
+ file: "Choose an image file.",
919
+ alt: "Describe the picture, or mark it as decorative.",
920
+ size: `Enter a width and height in pixels, from 1 to ${MAX_PICTURE_PX}.`,
921
+ failed: "The picture could not be inserted: the file could not be read or uploaded here.",
922
+ };
923
+ const invalid = (field) => (error === field ? true : undefined);
924
+ const described = (field) => (error === field ? `${id}-error` : undefined);
925
+ /** Marks `field` wrong and puts the focus on it. */
926
+ const fail = (field) => {
927
+ setError(field);
928
+ const target = {
929
+ file: fileField,
930
+ alt: altField,
931
+ size: widthField,
932
+ failed: fileField,
933
+ }[field].current;
934
+ target?.focus();
935
+ };
936
+ const submit = async (event) => {
937
+ event.preventDefault();
938
+ if (busy)
939
+ return;
940
+ if (!decorative && !alt.trim()) {
941
+ fail("alt");
942
+ return;
943
+ }
944
+ if (pos !== null) {
945
+ // The picture is gone (the dialog closes on a change; this is a guard).
946
+ if (!picture) {
947
+ onClose(false);
948
+ return;
949
+ }
950
+ const w = Math.round(Number(width));
951
+ const h = Math.round(Number(height));
952
+ const sizeChanged = w !== Number(px(attrs.width)) || h !== Number(px(attrs.height));
953
+ const valid = (n) => Number.isFinite(n) && n >= 1 && n <= MAX_PICTURE_PX;
954
+ if (sizeChanged && !tracking && !(valid(w) && valid(h))) {
955
+ fail("size");
956
+ return;
957
+ }
958
+ editor.run(setPictureAlt(pos, alt, decorative));
959
+ if (sizeChanged && !tracking)
960
+ editor.run(setPictureSize(pos, Math.round(w * EMU_PER_PX), Math.round(h * EMU_PER_PX)));
961
+ onClose(true);
962
+ return;
963
+ }
964
+ if (!file || !upload || !file.type.startsWith("image/")) {
965
+ fail("file");
966
+ return;
967
+ }
968
+ setBusy(true);
969
+ try {
970
+ const size = await measureImageFile(file, document);
971
+ const answer = size ? await upload(file) : null;
972
+ const src = typeof answer === "string" ? answer : answer?.src;
973
+ if (!open.current)
974
+ return;
975
+ if (!size || !src)
976
+ throw new Error("no image");
977
+ const scale = Math.min(1, textWidthEmu(editor.state) / (size.width * EMU_PER_PX));
978
+ const type = /^data:([^;,]+)/i.exec(src)?.[1]?.toLowerCase() ?? file.type;
979
+ const done = editor.run(insertPicture({
980
+ contentType: type,
981
+ ...(src.startsWith("data:") ? { data: src } : { url: src }),
982
+ width: Math.max(1, Math.round(size.width * EMU_PER_PX * scale)),
983
+ height: Math.max(1, Math.round(size.height * EMU_PER_PX * scale)),
984
+ ...(decorative ? { decorative: true } : { alt }),
985
+ }));
986
+ if (!done)
987
+ throw new Error("not inserted");
988
+ onClose(true);
989
+ }
990
+ catch {
991
+ if (!open.current)
992
+ return;
993
+ setBusy(false);
994
+ fail("failed");
995
+ }
996
+ };
997
+ const changeWidth = (value) => {
998
+ setWidth(value);
999
+ setError(null);
1000
+ if (keep && Number(value) > 0)
1001
+ setHeight(String(Math.max(1, Math.round(Number(value) * ratio))));
1002
+ };
1003
+ const changeHeight = (value) => {
1004
+ setHeight(value);
1005
+ setError(null);
1006
+ if (keep && Number(value) > 0)
1007
+ setWidth(String(Math.max(1, Math.round(Number(value) / ratio))));
1008
+ };
1009
+ const sizeNote = tracking ? `${id}-tracking` : undefined;
1010
+ const sizeDescribed = [described("size"), sizeNote].filter(Boolean).join(" ") || undefined;
1011
+ return (_jsx("div", { role: "dialog", "aria-label": pos === null ? "Insert picture" : "Edit picture", className: "foli-link-dialog foli-picture-dialog", "aria-busy": busy || undefined, onKeyDown: (event) => {
1012
+ if (event.key !== "Escape")
1013
+ return;
1014
+ event.preventDefault();
1015
+ onClose(false);
1016
+ }, children: _jsxs("form", { onSubmit: submit, noValidate: true, children: [pos === null && (_jsxs(_Fragment, { children: [_jsx("label", { htmlFor: `${id}-file`, children: "Image" }), _jsx("input", { ref: fileField, id: `${id}-file`, type: "file", accept: "image/*", required: true, "aria-invalid": invalid("file"), "aria-describedby": described("file"), onChange: (event) => {
1017
+ setFile(event.target.files?.[0] ?? null);
1018
+ setError(null);
1019
+ } })] })), _jsx("label", { htmlFor: `${id}-alt`, children: "Alt text" }), _jsx("input", { ref: altField, id: `${id}-alt`, type: "text", maxLength: 65_535, value: decorative ? "" : alt, disabled: decorative, required: !decorative, "aria-invalid": invalid("alt"), "aria-describedby": described("alt"), onChange: (event) => {
1020
+ setAlt(event.target.value);
1021
+ setError(null);
1022
+ } }), _jsxs("label", { children: [_jsx("input", { ref: decorativeField, type: "checkbox", checked: decorative, onChange: (event) => {
1023
+ setDecorative(event.target.checked);
1024
+ setError(null);
1025
+ } }), "Decorative (no alt text)"] }), pos !== null && (_jsxs(_Fragment, { children: [_jsx("label", { htmlFor: `${id}-width`, children: "Width (px)" }), _jsx("input", { ref: widthField, id: `${id}-width`, type: "number", min: 1, max: MAX_PICTURE_PX, step: 1, value: width, disabled: tracking, "aria-invalid": invalid("size"), "aria-describedby": sizeDescribed, onChange: (event) => changeWidth(event.target.value) }), _jsx("label", { htmlFor: `${id}-height`, children: "Height (px)" }), _jsx("input", { id: `${id}-height`, type: "number", min: 1, max: MAX_PICTURE_PX, step: 1, value: height, disabled: tracking, "aria-invalid": invalid("size"), "aria-describedby": sizeDescribed, onChange: (event) => changeHeight(event.target.value) }), _jsxs("label", { children: [_jsx("input", { type: "checkbox", checked: keep, disabled: tracking, "aria-describedby": sizeNote, onChange: (event) => setKeep(event.target.checked) }), "Keep proportions"] }), tracking && _jsx("p", { id: sizeNote, children: "The size does not change while changes are tracked." })] })), _jsx("button", { type: "submit", "aria-disabled": busy || undefined, children: pos === null ? "Insert" : "Apply" }), _jsx("button", { type: "button", onClick: () => onClose(false), children: "Cancel" }), _jsx("p", { role: "status", className: "foli-picture-status", children: busy ? "Inserting the picture…" : "" }), error && (_jsx("p", { id: `${id}-error`, className: "foli-link-error", role: "alert", children: messages[error] }))] }) }));
1026
+ }
504
1027
  //# sourceMappingURL=FoliToolbar.js.map