@folijs/react 0.6.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,6 @@
1
- import { type Editor } from "@folijs/core";
1
+ import { type Command, type Editor, type EditorState } from "@folijs/core";
2
2
  import { type EditorViewOptions } from "@folijs/view";
3
+ import { type ReactNode } from "react";
3
4
  export interface FoliToolbarProps {
4
5
  /** Default: the editor of the nearest `FoliEditorProvider`. */
5
6
  editor?: Editor | undefined;
@@ -25,16 +26,90 @@ export interface FoliToolbarProps {
25
26
  * inserts one from a file; without it, it only edits a selected picture.
26
27
  */
27
28
  upload?: EditorViewOptions["upload"] | undefined;
29
+ /**
30
+ * The items, in groups (a separator between groups), in place of `defaultToolbarItems`: the
31
+ * built-in ones from `toolbarItems`, and the app's own. "New comment" shows only with
32
+ * `comments`; an empty group is left out.
33
+ */
34
+ items?: readonly (readonly ToolbarItem[])[] | undefined;
28
35
  className?: string | undefined;
29
36
  }
37
+ /** What every toolbar item has. */
38
+ interface ToolbarItemBase {
39
+ /** Unique in the toolbar; also its class, `foli-toolbar-<key>`. */
40
+ readonly key: string;
41
+ /** What it does: the tooltip, and the accessible name when an `icon` stands for the text. */
42
+ readonly label: string;
43
+ /** Visible text, which is then the accessible name (default `label`). */
44
+ readonly text?: string | undefined;
45
+ /** Shown instead of the text (a symbol or an SVG): `label` is then the accessible name. */
46
+ readonly icon?: ReactNode | undefined;
47
+ /**
48
+ * Whether it can be used now. Default: a button's dry run of its `command` (`editor.can`); for
49
+ * a menu, whether it has entries. Runs after every transaction: keep it cheap.
50
+ */
51
+ readonly enabled?: ((state: EditorState, editor: Editor) => boolean) | undefined;
52
+ }
53
+ /** A toolbar button that runs a command. */
54
+ export interface ToolbarButton extends ToolbarItemBase {
55
+ /**
56
+ * What a press runs, on the editor of the header, footer or note open on its page, else the
57
+ * body's (as the built-in buttons do).
58
+ */
59
+ readonly command: Command;
60
+ /** A toggle: whether it shows as pressed (`aria-pressed`). Runs after every transaction. */
61
+ readonly pressed?: ((state: EditorState, editor: Editor) => boolean) | undefined;
62
+ readonly actions?: undefined;
63
+ }
64
+ /** A toolbar menu button: a WAI-ARIA menu of its `actions`. */
65
+ export interface ToolbarMenu extends ToolbarItemBase {
66
+ /**
67
+ * Its entries, in order, or a function of the body's editor making them (as the built-in
68
+ * menus do). Each entry is dry-run when the menu opens; without entries the button is disabled.
69
+ */
70
+ readonly actions: readonly ToolbarAction[] | ((editor: Editor) => readonly ToolbarAction[]);
71
+ readonly command?: undefined;
72
+ readonly pressed?: undefined;
73
+ }
74
+ /**
75
+ * A toolbar item, built-in (`toolbarItems`) or the app's own: a button running a command, or a
76
+ * menu button. The toolbar keeps one tab stop for all its items (arrow keys, Home and End move
77
+ * between them), gives toggles `aria-pressed` and an item that cannot apply now `aria-disabled`
78
+ * (still focusable), and leaves the focus and selection in the document on click.
79
+ */
80
+ export type ToolbarItem = ToolbarButton | ToolbarMenu;
81
+ /** An entry of a toolbar menu (a `menuitem`, or a `menuitemcheckbox` when it has `checked`). */
82
+ export interface ToolbarAction {
83
+ /** Unique in its menu. */
84
+ readonly key: string;
85
+ readonly label: string;
86
+ /** What it runs; a dry run when the menu opens decides whether it is enabled. */
87
+ readonly command: Command;
88
+ /** A checkable entry: whether it is checked (with the same arguments as `pressed`). */
89
+ readonly checked?: ((state: EditorState, editor: Editor) => boolean) | undefined;
90
+ }
91
+ /** The names of the built-in items in `toolbarItems`. */
92
+ export type ToolbarItemName = "style" | "font" | "size" | "bold" | "italic" | "underline" | "strike" | "link" | "textColor" | "highlight" | "alignStart" | "alignCenter" | "alignEnd" | "alignJustify" | "lineSpacing" | "bulletList" | "orderedList" | "outdent" | "indent" | "newComment" | "trackChanges" | "reviewView" | "previousChange" | "nextChange" | "acceptChange" | "rejectChange" | "acceptAll" | "rejectAll" | "undo" | "redo" | "table" | "tableStyle" | "cellShading" | "picture" | "pageBreak" | "section" | "headerFooter" | "fields" | "navigate" | "notes" | "controls";
93
+ /** The built-in menu buttons of `actions` (the color menus and boxes are buttons to an app). */
94
+ type ToolbarMenuName = "table" | "section" | "headerFooter" | "fields" | "navigate" | "notes" | "controls";
95
+ /**
96
+ * The built-in items by name, to place in `FoliToolbarProps.items` (an item's `key` is its name,
97
+ * except the alignments: `align-start`, `align-center`, `align-end`, `align-justify`). A copy
98
+ * with another `label` or `icon` keeps what the built-in does.
99
+ */
100
+ export declare const toolbarItems: { readonly [Name in ToolbarItemName]: Name extends ToolbarMenuName ? ToolbarMenu : ToolbarButton; };
101
+ /** The default toolbar: groups of `toolbarItems`, a separator between groups. */
102
+ export declare const defaultToolbarItems: readonly (readonly ToolbarItem[])[];
30
103
  /**
31
- * Word's formatting controls for an editor: paragraph style, font and size boxes, marks, link (a
32
- * dialog, also on Mod-K in the document), text color and highlight menus, alignment and line
33
- * spacing, lists (bulleted, numbered, decrease and increase indent), undo, redo, tables (a Table
34
- * menu with an insert table dialog, a table style box, a cell shading menu), page break.
104
+ * Word's formatting controls for an editor (`defaultToolbarItems`, or `items`): paragraph
105
+ * style, font and size boxes, marks, link (a dialog, also on Mod-K in the document), text color
106
+ * and highlight menus, alignment and line spacing, lists (bulleted, numbered, decrease and
107
+ * increase indent), undo, redo, tables (a Table menu with an insert table dialog, a table style
108
+ * box, a cell shading menu), page break.
35
109
  * One tab stop (arrow keys, Home and End move between buttons); toggles carry
36
110
  * `aria-pressed`; a button whose command cannot run now is `aria-disabled` (still focusable).
37
111
  * Clicks leave the focus and selection in the document.
38
112
  */
39
- export declare function FoliToolbar({ editor: given, disabled, onClickCommand, label, className, comments, upload, }: FoliToolbarProps): import("react").JSX.Element;
113
+ export declare function FoliToolbar({ editor: given, disabled, onClickCommand, label, className, comments, upload, items: itemGroups, }: FoliToolbarProps): import("react").JSX.Element;
114
+ export {};
40
115
  //# sourceMappingURL=FoliToolbar.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"FoliToolbar.d.ts","sourceRoot":"","sources":["../src/FoliTo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;AAChG,KAAK,eAAe,GAChB,OAAO,GACP,SAAS,GACT,cAAc,GACd,QAAQ,GACR,UAAU,GACV,OAAO,GACP,UAAU,CAAC;AAEf;;;;GAIG;AACH,eAAO,MAAM,YAAY,EAET,EACd,QAAQ,EAAE,IAAI,IAAI,eAAe,GAAG,IAAI,SAAS,eAAe,GAAG,WAAW,GAAG,aAAa,GAC/F,CAAC;AAEF,iFAAiF;AACjF,eAAO,MAAM,mBAAmB,EAAwB,SAAS,CAAC,SAAS,WAAW,EAAE,CAAC,EAAE,CAAC;AA0D5F;;;;;;;;;GASG;AACH,wBAAgB,WAAW,CAAC,EAC1B,MAAM,EAAE,KAAK,EACb,QAAgB,EAChB,cAAc,EACd,KAAoB,EACpB,SAAS,EACT,QAAgB,EAChB,MAAM,EACN,KAAK,EAAE,UAAU,GAClB,EAAE,gBAAgB,+BAwgBlB"}
@@ -1,8 +1,9 @@
1
1
  import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { acceptAllChanges, acceptChange, addComment, addRepeatingItem, alignAt, canOutdent, changeIndent, colorAt, controlAt, controlProperties, convertNotes, crossReferenceTargets, deleteColumns, deleteRows, deleteTable, documentSections, fieldCodesShown, fieldsIn, fontFamilyAt, fontSizeAt, insertColumn, insertColumnBreak, insertControl, insertCrossReference, insertDate, insertNote, insertPageBreak, insertPageNumber, insertPicture, insertRow, insertSectionBreak, insertTable, insertTableOfContents, isHeaderRow, isSafeHref, lineSpacingAt, linkAt, listKindAt, mergeCells, nextChange, normalizeHref, noteAtSelection, noteProperties, openLinkEditor, paragraphStyleAt, paragraphStyles, previousChange, redo, redoDepth, rejectAllChanges, rejectChange, removeLink, removeSectionBreak, requestsLinkEditor, sectionAt, selectedPicture, setAlign, setCellShading, setControlProperties, setDifferentEvenPages, setDifferentFirstPage, setFontFamily, setFontSize, setHighlight, setLineSpacing, setLink, setNoteProperties, setParagraphStyle, setPictureAlt, setPictureSize, setReviewView, setSectionSetup, setStoryLinked, setTableStyle, setTextColor, setTrackChanges, splitCell, tableStyleAt, tableStyles, toggleFieldCodes, toggleHeaderRow, toggleList, toggleMark, trackState, undo, undoDepth, updateFields, wordContext, } from "@folijs/core";
2
+ import { acceptAllChanges, acceptChange, addComment, addRepeatingItem, alignAt, canOutdent, changeIndent, colorAt, controlAt, controlProperties, convertNotes, crossReferenceTargets, deleteColumns, deleteRows, deleteTable, documentSections, fieldCodesShown, fieldsIn, fontFamilyAt, fontSizeAt, insertColumn, insertColumnBreak, insertControl, insertCrossReference, insertDate, insertNote, insertPageBreak, insertPageNumber, insertPicture, insertRow, insertSectionBreak, insertTable, insertTableOfContents, isHeaderRow, isSafeHref, lineSpacingAt, linkAt, listKindAt, mergeCells, nextChange, normalizeHref, noteAtSelection, noteProperties, openLinkEditor, paragraphStyleAt, paragraphStyles, previousChange, redo, redoDepth, rejectAllChanges, rejectChange, removeLink, removeSectionBreak, requestsLinkEditor, sectionAt, selectedPicture, setAlign, setCellShading, setControlProperties, setDifferentEvenPages, setDifferentFirstPage, setFontFamily, setFontSize, setHighlight, setLineSpacing, setLink, setNoteProperties, setParagraphStyle, setPictureAlt, setPictureSize, setReviewView, setSectionSetup, setStoryLinked, setTableStyle, setTextColor, setTrackChanges, splitCell, tableStyleAt, tableStyles, toggleFieldCodes, toggleHeaderRow, toggleList, toggleMark, trackState, undo, undoDepth, updateFields, } from "@folijs/core";
3
+ import { wordContext } from "@folijs/core/internal";
3
4
  import { EMU_PER_PX, measureImageFile, textWidthEmu } from "@folijs/view";
4
5
  import { Fragment, useEffect, useId, useMemo, useRef, useState, } from "react";
5
- import { useActiveEditor, useEditorOrContext, useEditorState } from "./editor.js";
6
+ import { development, sameItems, useActiveEditor, useEditorOrContext, useEditorState, } from "./editor.js";
6
7
  /**
7
8
  * The palettes (fixed: a document should not need a color picker). Text colors keep at least
8
9
  * 4.5:1 contrast on white; highlights keep dark text readable.
@@ -336,23 +337,23 @@ function hasTextblock(state) {
336
337
  }
337
338
  /** Four bars, like the alignment they stand for (x and width per bar). */
338
339
  const alignIcon = (bars) => (_jsx("svg", { viewBox: "0 0 16 16", width: "16", height: "16", "aria-hidden": "true", focusable: "false", children: bars.map(([x, width], i) => (_jsx("rect", { x: x, y: 2.5 + i * 3.5, width: width, height: "1.5", fill: "currentColor" }, i))) }));
340
+ /** A paragraph takes every mark and a page break: no need for a dry run after each change. */
341
+ const always = () => true;
339
342
  const align = (value, label, bars) => ({
340
343
  key: `align-${value}`,
341
344
  label,
342
- text: label,
343
- symbol: true,
344
345
  icon: alignIcon(bars),
345
346
  pressed: (state) => alignAt(state) === value,
346
347
  enabled: hasTextblock,
347
- command: () => setAlign(value),
348
+ command: setAlign(value),
348
349
  });
349
- const mark = (key, label, text) => ({
350
+ const mark = (key, label, icon) => ({
350
351
  key,
351
352
  label,
352
- text,
353
- symbol: true,
353
+ icon,
354
354
  pressed: (_state, editor) => editor.isMarkActive(key),
355
- command: () => toggleMark(key),
355
+ enabled: always,
356
+ command: toggleMark(key),
356
357
  });
357
358
  const capitalized = (name) => name.charAt(0).toUpperCase() + name.slice(1);
358
359
  /** The fonts the font box offers (with the document's theme fonts, and the one shown now). */
@@ -431,13 +432,12 @@ const GROUPS = [
431
432
  pressed: (state) => linkAt(state) !== null,
432
433
  enabled: (state) => openLinkEditor(state),
433
434
  // Asks for the link dialog, as Mod-K does: the toolbar listens for that request.
434
- command: () => openLinkEditor,
435
+ command: openLinkEditor,
435
436
  },
436
437
  {
437
438
  key: "textColor",
438
439
  label: "Text color",
439
- text: "A",
440
- symbol: true,
440
+ icon: "A",
441
441
  enabled: hasTextblock,
442
442
  menu: {
443
443
  options: TEXT_COLORS,
@@ -448,8 +448,7 @@ const GROUPS = [
448
448
  {
449
449
  key: "highlight",
450
450
  label: "Highlight",
451
- text: "H",
452
- symbol: true,
451
+ icon: "H",
453
452
  enabled: hasTextblock,
454
453
  menu: {
455
454
  options: HIGHLIGHTS,
@@ -502,37 +501,33 @@ const GROUPS = [
502
501
  {
503
502
  key: "bulletList",
504
503
  label: "Bulleted list",
505
- text: "•",
506
- symbol: true,
504
+ icon: "•",
507
505
  pressed: (state) => listKindAt(state) === "bulletList",
508
506
  enabled: hasTextblock,
509
- command: () => toggleList("bulletList"),
507
+ command: toggleList("bulletList"),
510
508
  },
511
509
  {
512
510
  key: "orderedList",
513
511
  label: "Numbered list",
514
512
  // A symbol, not "1.": visible text that is not part of the name fails WCAG 2.5.3.
515
- text: "№",
516
- symbol: true,
513
+ icon: "№",
517
514
  pressed: (state) => listKindAt(state) === "orderedList",
518
515
  enabled: hasTextblock,
519
- command: () => toggleList("orderedList"),
516
+ command: toggleList("orderedList"),
520
517
  },
521
518
  {
522
519
  key: "outdent",
523
520
  label: "Decrease indent",
524
- text: "⇤",
525
- symbol: true,
521
+ icon: "⇤",
526
522
  enabled: canOutdent,
527
- command: () => changeIndent(-1),
523
+ command: changeIndent(-1),
528
524
  },
529
525
  {
530
526
  key: "indent",
531
527
  label: "Increase indent",
532
- text: "⇥",
533
- symbol: true,
528
+ icon: "⇥",
534
529
  enabled: hasTextblock,
535
- command: () => changeIndent(1),
530
+ command: changeIndent(1),
536
531
  },
537
532
  ],
538
533
  [
@@ -541,7 +536,7 @@ const GROUPS = [
541
536
  label: "New comment on the selection",
542
537
  text: "New comment",
543
538
  enabled: (state) => wordContext(state) !== null && hasTextblock(state),
544
- command: () => addComment(""),
539
+ command: addComment(""),
545
540
  },
546
541
  {
547
542
  key: "trackChanges",
@@ -549,7 +544,7 @@ const GROUPS = [
549
544
  text: "Track changes",
550
545
  pressed: (state) => trackState(state)?.on === true,
551
546
  enabled: (state) => trackState(state) !== null,
552
- command: (state) => setTrackChanges(!trackState(state)?.on),
547
+ command: (state, dispatch) => setTrackChanges(!trackState(state)?.on)(state, dispatch),
553
548
  },
554
549
  {
555
550
  key: "reviewView",
@@ -569,42 +564,42 @@ const GROUPS = [
569
564
  label: "Previous change",
570
565
  text: "Previous change",
571
566
  enabled: (state) => trackState(state) !== null,
572
- command: () => previousChange,
567
+ command: previousChange,
573
568
  },
574
569
  {
575
570
  key: "nextChange",
576
571
  label: "Next change",
577
572
  text: "Next change",
578
573
  enabled: (state) => trackState(state) !== null,
579
- command: () => nextChange,
574
+ command: nextChange,
580
575
  },
581
576
  {
582
577
  key: "acceptChange",
583
578
  label: "Accept the change here, or the changes selected",
584
579
  text: "Accept",
585
580
  enabled: (state) => trackState(state) !== null,
586
- command: () => acceptChange,
581
+ command: acceptChange,
587
582
  },
588
583
  {
589
584
  key: "rejectChange",
590
585
  label: "Reject the change here, or the changes selected",
591
586
  text: "Reject",
592
587
  enabled: (state) => trackState(state) !== null,
593
- command: () => rejectChange,
588
+ command: rejectChange,
594
589
  },
595
590
  {
596
591
  key: "acceptAll",
597
592
  label: "Accept all changes",
598
593
  text: "Accept all",
599
594
  enabled: (state) => trackState(state) !== null,
600
- command: () => acceptAllChanges(),
595
+ command: acceptAllChanges(),
601
596
  },
602
597
  {
603
598
  key: "rejectAll",
604
599
  label: "Reject all changes",
605
600
  text: "Reject all",
606
601
  enabled: (state) => trackState(state) !== null,
607
- command: () => rejectAllChanges(),
602
+ command: rejectAllChanges(),
608
603
  },
609
604
  ],
610
605
  [
@@ -613,14 +608,14 @@ const GROUPS = [
613
608
  label: "Undo",
614
609
  text: "Undo",
615
610
  enabled: (state) => undoDepth(state) > 0,
616
- command: () => undo,
611
+ command: undo,
617
612
  },
618
613
  {
619
614
  key: "redo",
620
615
  label: "Redo",
621
616
  text: "Redo",
622
617
  enabled: (state) => redoDepth(state) > 0,
623
- command: () => redo,
618
+ command: redo,
624
619
  },
625
620
  ],
626
621
  [
@@ -666,7 +661,13 @@ const GROUPS = [
666
661
  // With a picture selected the dialog edits it.
667
662
  dialog: "picture",
668
663
  },
669
- { key: "pageBreak", label: "Page break", text: "Page break", command: () => insertPageBreak },
664
+ {
665
+ key: "pageBreak",
666
+ label: "Page break",
667
+ text: "Page break",
668
+ enabled: always,
669
+ command: insertPageBreak,
670
+ },
670
671
  {
671
672
  key: "section",
672
673
  label: "Section",
@@ -711,44 +712,73 @@ const GROUPS = [
711
712
  },
712
713
  ],
713
714
  ];
714
- const ITEMS = GROUPS.flat();
715
- /** Without "New comment": where no comments pane lets a comment be written. */
716
- const GROUPS_NO_COMMENT = GROUPS.map((group) => group.filter((i) => i.key !== "newComment"));
717
- const ITEMS_NO_COMMENT = GROUPS_NO_COMMENT.flat();
715
+ /**
716
+ * The built-in items by name, to place in `FoliToolbarProps.items` (an item's `key` is its name,
717
+ * except the alignments: `align-start`, `align-center`, `align-end`, `align-justify`). A copy
718
+ * with another `label` or `icon` keeps what the built-in does.
719
+ */
720
+ export const toolbarItems = Object.fromEntries(GROUPS.flat().map((item) => [item.key.replace(/-(\w)/, (_, c) => c.toUpperCase()), item]));
721
+ /** The default toolbar: groups of `toolbarItems`, a separator between groups. */
722
+ export const defaultToolbarItems = GROUPS;
718
723
  const sameStates = (a, b) => a.length === b.length &&
719
724
  a.every((item, i) => item.pressed === b[i]?.pressed &&
720
725
  item.enabled === b[i]?.enabled &&
721
726
  item.value === b[i]?.value);
722
- /** Runs after every transaction: O(selection), no transactions built. */
723
- const statesOf = (items) => (state, editor) => items.map((item) => ({
727
+ /**
728
+ * Runs after every transaction: the built-ins' checks are O(selection), no transactions built;
729
+ * an app's item without `enabled` gets a dry run of its command.
730
+ */
731
+ const statesOf = (items, body) => (state, editor) => items.map((item) => ({
724
732
  pressed: item.pressed?.(state, editor),
725
- enabled: item.enabled?.(state) ?? true,
733
+ enabled: item.enabled
734
+ ? item.enabled(state, editor)
735
+ : item.actions
736
+ ? actionsOf(item, body).length > 0
737
+ : !item.command || editor.can(item.command),
726
738
  value: item.menu?.value(state) ??
727
739
  item.select?.value(state) ??
728
740
  (item.dialog ? (selectedPicture(state) ? "edit" : "insert") : undefined),
729
741
  }));
730
- const selectStates = statesOf(ITEMS);
731
- const selectStatesNoComment = statesOf(ITEMS_NO_COMMENT);
742
+ /** A menu button's entries (made from the body's editor when a function). */
743
+ const actionsOf = (item, body) => typeof item.actions === "function" ? item.actions(body) : (item.actions ?? []);
744
+ /** The same groups of the same items (an inline `items` array is not a change). */
745
+ const sameGroups = (a, b) => a === b || (!!a && !!b && a.length === b.length && a.every((group, i) => sameItems(group, b[i])));
732
746
  /**
733
- * Word's formatting controls for an editor: paragraph style, font and size boxes, marks, link (a
734
- * dialog, also on Mod-K in the document), text color and highlight menus, alignment and line
735
- * spacing, lists (bulleted, numbered, decrease and increase indent), undo, redo, tables (a Table
736
- * menu with an insert table dialog, a table style box, a cell shading menu), page break.
747
+ * Word's formatting controls for an editor (`defaultToolbarItems`, or `items`): paragraph
748
+ * style, font and size boxes, marks, link (a dialog, also on Mod-K in the document), text color
749
+ * and highlight menus, alignment and line spacing, lists (bulleted, numbered, decrease and
750
+ * increase indent), undo, redo, tables (a Table menu with an insert table dialog, a table style
751
+ * box, a cell shading menu), page break.
737
752
  * One tab stop (arrow keys, Home and End move between buttons); toggles carry
738
753
  * `aria-pressed`; a button whose command cannot run now is `aria-disabled` (still focusable).
739
754
  * Clicks leave the focus and selection in the document.
740
755
  */
741
- export function FoliToolbar({ editor: given, disabled = false, onClickCommand, label = "Formatting", className, comments = false, upload, }) {
756
+ export function FoliToolbar({ editor: given, disabled = false, onClickCommand, label = "Formatting", className, comments = false, upload, items: itemGroups, }) {
742
757
  const body = useEditorOrContext(given, "FoliToolbar");
743
758
  // A story open on its page takes the formatting commands; the body otherwise.
744
759
  const editor = useActiveEditor(body);
745
- const groups = comments ? GROUPS : GROUPS_NO_COMMENT;
746
- const items = comments ? ITEMS : ITEMS_NO_COMMENT;
747
- const states = useEditorState(comments ? selectStates : selectStatesNoComment, {
748
- editor,
749
- isEqual: sameStates,
750
- });
751
- const [active, setActive] = useState(0);
760
+ // Without "New comment" where no comments pane lets a comment be written.
761
+ const lastGroups = useRef(itemGroups);
762
+ if (!sameGroups(lastGroups.current, itemGroups))
763
+ lastGroups.current = itemGroups;
764
+ const stableGroups = lastGroups.current;
765
+ const { groups, items, selectStates } = useMemo(() => {
766
+ const groups = (stableGroups ?? GROUPS)
767
+ .map((group) => group.filter((item) => comments || item.key !== "newComment"))
768
+ .filter((group) => group.length > 0);
769
+ const items = groups.flat();
770
+ if (development()) {
771
+ const keys = items.map((item) => item.key);
772
+ const twice = keys.find((key, i) => keys.indexOf(key) !== i);
773
+ if (twice !== undefined)
774
+ console.warn(`FoliToolbar: two items have the key "${twice}"; each needs its own`);
775
+ }
776
+ return { groups, items, selectStates: statesOf(items, body) };
777
+ }, [stableGroups, comments, body]);
778
+ const states = useEditorState(selectStates, { editor, isEqual: sameStates });
779
+ const [focused, setActive] = useState(0);
780
+ // The tab stop stays on the toolbar when items are taken away.
781
+ const active = focused < items.length ? focused : 0;
752
782
  const buttons = useRef([]);
753
783
  // Whether a select box was last used with the pointer (its pick then goes back to the document).
754
784
  const pointer = useRef(false);
@@ -776,6 +806,8 @@ export function FoliToolbar({ editor: given, disabled = false, onClickCommand, l
776
806
  });
777
807
  return;
778
808
  }
809
+ if (item.actions && !actionsOf(item, body).length)
810
+ return;
779
811
  if (item.menu || item.actions) {
780
812
  if (menu !== item.key) {
781
813
  setMenu(item.key);
@@ -791,7 +823,7 @@ export function FoliToolbar({ editor: given, disabled = false, onClickCommand, l
791
823
  }
792
824
  if (!item.command)
793
825
  return;
794
- editor.run(item.command(editor.state));
826
+ editor.run(item.command);
795
827
  // `detail` counts pointer clicks; Enter and Space on a button give 0.
796
828
  if (event.detail > 0)
797
829
  onClickCommand?.();
@@ -933,9 +965,11 @@ export function FoliToolbar({ editor: given, disabled = false, onClickCommand, l
933
965
  const i = index++;
934
966
  const state = states[i];
935
967
  // Inserting a picture needs the app's upload; editing a selected one does not.
968
+ // A menu without entries cannot open, whatever its `enabled` says.
936
969
  const off = disabled ||
937
970
  !state?.enabled ||
938
- (item.dialog === "picture" && state?.value === "insert" && !upload);
971
+ (item.dialog === "picture" && state?.value === "insert" && !upload) ||
972
+ (item.actions !== undefined && actionsOf(item, body).length === 0);
939
973
  if (item.select) {
940
974
  const { select } = item;
941
975
  const value = state?.value ?? "";
@@ -959,7 +993,7 @@ export function FoliToolbar({ editor: given, disabled = false, onClickCommand, l
959
993
  }
960
994
  const button = (_jsxs("button", { ref: (element) => {
961
995
  buttons.current[i] = element;
962
- }, type: "button", className: `foli-toolbar-button foli-toolbar-${item.key}`, "aria-label": item.symbol ? item.label : undefined, title: item.label, "aria-pressed": item.pressed ? Boolean(state?.pressed) : undefined, "aria-haspopup": item.menu || item.actions ? "menu" : item.dialog ? "dialog" : undefined, "aria-expanded": item.menu || item.actions ? menu === item.key : undefined, "aria-disabled": off || undefined, tabIndex: i === active ? 0 : -1,
996
+ }, type: "button", className: `foli-toolbar-button foli-toolbar-${item.key}`, "aria-label": item.icon !== undefined ? item.label : undefined, title: item.label, "aria-pressed": item.pressed ? Boolean(state?.pressed) : undefined, "aria-haspopup": item.menu || item.actions ? "menu" : item.dialog ? "dialog" : undefined, "aria-expanded": item.menu || item.actions ? menu === item.key : undefined, "aria-disabled": off || undefined, tabIndex: i === active ? 0 : -1,
963
997
  // Keep the focus (and the selection) in the document on click.
964
998
  onMouseDown: (event) => event.preventDefault(), onFocus: () => setActive(i), onClick: (event) => run(i, event), onKeyDown: (event) => {
965
999
  // ArrowDown opens a menu (the WAI-ARIA menu button pattern).
@@ -967,10 +1001,10 @@ export function FoliToolbar({ editor: given, disabled = false, onClickCommand, l
967
1001
  return;
968
1002
  event.preventDefault();
969
1003
  setMenu(item.key);
970
- }, children: [item.icon ?? item.text, item.menu && (_jsx("span", { className: "foli-toolbar-swatch", "aria-hidden": "true", style: { background: state?.value ?? "transparent" } }))] }, item.key));
1004
+ }, children: [item.icon ?? item.text ?? item.label, item.menu && (_jsx("span", { className: "foli-toolbar-swatch", "aria-hidden": "true", style: { background: state?.value ?? "transparent" } }))] }, item.key));
971
1005
  if (item.actions) {
972
- const actions = typeof item.actions === "function" ? item.actions(body) : item.actions;
973
- return (_jsxs("span", { className: "foli-toolbar-menu", children: [button, menu === item.key && !disabled && (_jsx(ActionMenu, { label: item.label, actions: actions, state: editor.state, onPick: (action, pointer) => {
1006
+ const actions = actionsOf(item, body);
1007
+ return (_jsxs("span", { className: "foli-toolbar-menu", children: [button, menu === item.key && !disabled && actions.length > 0 && (_jsx(ActionMenu, { label: item.label, actions: actions, editor: editor, state: editor.state, onPick: (action, pointer) => {
974
1008
  setMenu(null);
975
1009
  if (action.dialog === "noteOptions") {
976
1010
  setDialog(null);
@@ -1185,7 +1219,7 @@ function LinkDialog({ editor, href, request, onClose, }) {
1185
1219
  * Escape closes it back to its button, Tab closes it and moves on; leaving it closes it. An item
1186
1220
  * that cannot apply here is `aria-disabled` (still focusable, as in the toolbar).
1187
1221
  */
1188
- function ActionMenu({ label, actions, state, onPick, onClose, }) {
1222
+ function ActionMenu({ label, actions, editor, state, onPick, onClose, }) {
1189
1223
  const items = useRef([]);
1190
1224
  // Dry runs, once per opening (not after every transaction).
1191
1225
  // biome-ignore lint/correctness/useExhaustiveDependencies: the actions are a constant list.
@@ -1234,7 +1268,7 @@ function ActionMenu({ label, actions, state, onPick, onClose, }) {
1234
1268
  onPick(action, event.detail > 0);
1235
1269
  },
1236
1270
  };
1237
- return action.checked ? (_jsx("button", { ...props, role: "menuitemcheckbox", "aria-checked": action.checked(state), children: action.label }, action.key)) : (_jsx("button", { ...props, role: "menuitem", children: action.label }, action.key));
1271
+ return action.checked ? (_jsx("button", { ...props, role: "menuitemcheckbox", "aria-checked": action.checked(state, editor), children: action.label }, action.key)) : (_jsx("button", { ...props, role: "menuitem", children: action.label }, action.key));
1238
1272
  }) }));
1239
1273
  }
1240
1274
  /** Word's limits for a new table. */