@tristan2828/ui-foundation 4.124.2 → 4.126.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.
Files changed (69) hide show
  1. package/README.md +1 -1
  2. package/conventions/docs/add-an-entity.md +42 -21
  3. package/conventions/docs/cell-patterns.md +80 -39
  4. package/dist/api/transport/index.js +10 -1
  5. package/dist/components/app/edit-caret.d.ts +25 -0
  6. package/dist/components/app/edit-caret.js +118 -0
  7. package/dist/components/app/edit-in-place-store.d.ts +43 -4
  8. package/dist/components/app/edit-in-place-store.js +169 -19
  9. package/dist/components/app/editable-value.js +164 -22
  10. package/dist/components/app/entity-form.js +4 -0
  11. package/dist/components/app/entity-view.js +1 -1
  12. package/dist/components/app/form-leave-guard.js +7 -1
  13. package/dist/components/app/milkdown-editor.d.ts +1 -0
  14. package/dist/components/app/milkdown-editor.js +224 -63
  15. package/dist/components/app/prose-look.d.ts +1 -1
  16. package/dist/components/app/prose-look.js +3 -1
  17. package/dist/components/app/rich-text-autolink.d.ts +6 -0
  18. package/dist/components/app/rich-text-autolink.js +79 -0
  19. package/dist/components/app/rich-text-edges.d.ts +8 -0
  20. package/dist/components/app/rich-text-edges.js +144 -0
  21. package/dist/components/app/rich-text-editor.d.ts +15 -2
  22. package/dist/components/app/rich-text-editor.js +16 -4
  23. package/dist/components/app/rich-text-empty-paragraph.d.ts +14 -6
  24. package/dist/components/app/rich-text-empty-paragraph.js +19 -8
  25. package/dist/components/app/rich-text-formats.js +88 -15
  26. package/dist/components/app/rich-text-full-screen.d.ts +2 -0
  27. package/dist/components/app/rich-text-full-screen.js +78 -0
  28. package/dist/components/app/rich-text-highlight-menu.d.ts +3 -1
  29. package/dist/components/app/rich-text-highlight-menu.js +3 -2
  30. package/dist/components/app/rich-text-input-rules.d.ts +7 -0
  31. package/dist/components/app/rich-text-input-rules.js +83 -0
  32. package/dist/components/app/rich-text-keyboard-bar.d.ts +24 -0
  33. package/dist/components/app/rich-text-keyboard-bar.js +214 -0
  34. package/dist/components/app/rich-text-node-views.js +2 -1
  35. package/dist/components/app/rich-text-paste.d.ts +43 -0
  36. package/dist/components/app/rich-text-paste.js +355 -0
  37. package/dist/components/app/rich-text-shortcuts.d.ts +5 -1
  38. package/dist/components/app/rich-text-shortcuts.js +132 -2
  39. package/dist/components/app/rich-text-slash-menu.js +47 -9
  40. package/dist/components/app/rich-text-slash.d.ts +7 -0
  41. package/dist/components/app/rich-text-slash.js +27 -14
  42. package/dist/components/app/rich-text-table-grips.d.ts +8 -6
  43. package/dist/components/app/rich-text-table-grips.js +11 -12
  44. package/dist/components/app/rich-text-tasks.d.ts +8 -0
  45. package/dist/components/app/rich-text-tasks.js +20 -0
  46. package/dist/components/app/rich-text-toolbar.d.ts +5 -1
  47. package/dist/components/app/rich-text-toolbar.js +13 -5
  48. package/dist/components/app/rich-text-touch.d.ts +2 -0
  49. package/dist/components/app/rich-text-touch.js +18 -0
  50. package/dist/components/app/rich-text-widgets.js +1 -1
  51. package/dist/hooks/table-url-changes.d.ts +4 -0
  52. package/dist/hooks/table-url-changes.js +13 -0
  53. package/dist/hooks/use-table-url-state.js +14 -8
  54. package/dist/index.d.ts +1 -0
  55. package/dist/index.js +3 -0
  56. package/dist/lib/markdown-merge.d.ts +26 -0
  57. package/dist/lib/markdown-merge.js +112 -17
  58. package/dist/lib/page-leaving.d.ts +8 -0
  59. package/dist/lib/page-leaving.js +30 -0
  60. package/dist/lib/pending-edits.d.ts +14 -0
  61. package/dist/lib/pending-edits.js +51 -0
  62. package/dist/mocks/e2e-hooks.js +10 -0
  63. package/dist/mocks/override.d.ts +8 -0
  64. package/dist/mocks/start-worker.d.ts +24 -0
  65. package/dist/mocks/start-worker.js +120 -3
  66. package/dist/testing/index.d.ts +84 -5
  67. package/dist/testing/index.js +177 -10
  68. package/package.json +1 -1
  69. package/styles/index.css +7 -0
@@ -1,12 +1,16 @@
1
- // The slash menu's logic: "/" typed at the start of a top-level paragraph
2
- // (or one in a callout) opens it, what's typed after the "/" filters it,
3
- // and picking an item turns the paragraph into that block, the "/…" gone.
4
- // The menu itself: rich-text-slash-menu.tsx; its keys and ARIA:
5
- // milkdown-editor.tsx.
1
+ // The slash menu's logic: "/" typed at the start of a line of text opens
2
+ // it, what's typed after the "/" filters it, and picking an item turns the
3
+ // line into that block, the "/…" gone. The menu itself:
4
+ // rich-text-slash-menu.tsx; its keys and ARIA: milkdown-editor.tsx.
5
+ //
6
+ // Any line of text (4.126, the RichTextEditor review's F18): a top-level
7
+ // one or a heading, a list item's, a quote's or a callout's, a table
8
+ // cell's. The menu lists only what can be made there: in a cell, the
9
+ // highlights (a cell holds one line), not a heading or a list.
6
10
  //
7
11
  // Only a "/" typed there opens it: one already in the text (a path,
8
- // `/usr/bin`) never does, and neither does a "/" mid-line or inside a
9
- // list, a quote or a code block.
12
+ // `/usr/bin`) never does, and neither does a "/" mid-line or in a code
13
+ // block.
10
14
  import { Plugin, PluginKey } from '@milkdown/kit/prose/state';
11
15
  import { FileTextIcon, ImageIcon } from 'lucide-react';
12
16
  import { CALLOUT_VARIANTS, FORMAT_GROUPS, HIGHLIGHT_VARIANTS, TOGGLE_HEADING_VARIANTS } from './rich-text-format-items.js';
@@ -14,12 +18,10 @@ import { toggleFormat } from './rich-text-formats.js';
14
18
  const slashKey = new PluginKey('rich-text-slash');
15
19
  // Longer than any item's name: past it, the person is writing, not picking.
16
20
  const MAX_QUERY = 24;
17
- // A top-level paragraph's start, or one's in a callout (where picking a
18
- // kind of callout changes the callout's): where a "/" opens the menu.
21
+ // A line of text's start, but a code block's: where a "/" opens the menu.
19
22
  function atParagraphStart(state, pos) {
20
23
  const $pos = state.doc.resolve(pos);
21
- const placed = $pos.depth === 1 || ($pos.depth === 2 && $pos.node(1).type.name === 'callout');
22
- return placed && $pos.parent.type.name === 'paragraph' && $pos.parentOffset === 0;
24
+ return $pos.parent.isTextblock && !$pos.parent.type.spec.code && $pos.parentOffset === 0;
23
25
  }
24
26
  // The menu's span, if the "/" at `from` still opens it: the caret after it
25
27
  // in the same paragraph, nothing selected, and what follows the "/" plain
@@ -118,21 +120,32 @@ const IMAGE_KEYWORDS = ['image', 'picture', 'photo', 'img', 'upload'];
118
120
  // it's the only item that leaves the editor (a title box, then the app).
119
121
  const PAGE_ITEM = { id: 'page', label: 'Page', icon: FileTextIcon };
120
122
  const PAGE_KEYWORDS = ['page', 'subpage', 'child', 'link', 'new'];
123
+ // Whether picking `id` would do anything where the menu is: its command
124
+ // run, with the "/…" gone, and its transaction dropped.
125
+ function appliesAt(place) {
126
+ const state = place.state.apply(place.state.tr.delete(place.span.from, place.span.to));
127
+ return (id) => toggleFormat(state, () => { }, id);
128
+ }
121
129
  /**
122
130
  * The blocks matching what's typed after the "/": in the name, or the
123
131
  * start of a keyword. With `image`, an image too; with `page`, the new page.
132
+ * With `at`, only the blocks that can be made there.
124
133
  */
125
134
  export function slashItems(query, options = {}) {
126
135
  const typed = query.trim().toLowerCase();
127
136
  const page = options.page && (!typed || 'page'.includes(typed) || PAGE_KEYWORDS.some((word) => word.startsWith(typed))) ? [PAGE_ITEM] : [];
128
137
  const image = options.image && (!typed || IMAGE_KEYWORDS.some((word) => word.startsWith(typed))) ? [IMAGE_ITEM] : [];
129
- if (!typed)
130
- return [...BLOCKS, ...image, ...page];
138
+ const applies = options.at ? appliesAt(options.at) : () => true;
139
+ if (!typed) {
140
+ // Where no block can go (a table cell), the highlights, which can.
141
+ const here = BLOCKS.filter((item) => applies(item.id));
142
+ return [...(here.length ? here : HIGHLIGHT_VARIANTS.filter((item) => applies(item.id))), ...image, ...page];
143
+ }
131
144
  const blocks = [...BLOCKS];
132
145
  blocks.splice(BLOCKS.findIndex((item) => item.id === 'callout') + 1, 0, ...CALLOUT_VARIANTS);
133
146
  blocks.push(...HIGHLIGHT_VARIANTS);
134
147
  const matches = [
135
- ...blocks.filter((item) => item.label.toLowerCase().includes(typed) || KEYWORDS[item.id].some((word) => word.startsWith(typed))),
148
+ ...blocks.filter((item) => (item.label.toLowerCase().includes(typed) || KEYWORDS[item.id].some((word) => word.startsWith(typed))) && applies(item.id)),
136
149
  ...image,
137
150
  ];
138
151
  // "/page" puts the page first: it's what was asked for by name.
@@ -1,4 +1,3 @@
1
- import { type EditorState } from '@milkdown/kit/prose/state';
2
1
  import type { EditorView } from '@milkdown/kit/prose/view';
3
2
  import { type HighlightColor } from '../../lib/markdown-highlight.js';
4
3
  import { type TableAction, type TableColorScope } from './rich-text-table.js';
@@ -11,16 +10,19 @@ export type TableCell = {
11
10
  export declare const TABLE_MENU_EVENT = "rich-text-table-menu";
12
11
  export interface TableGripsProps {
13
12
  view: EditorView;
14
- /** The editor's state, so the grips follow each change. */
15
- state: EditorState | null;
13
+ /**
14
+ * The cell the caret is in when it's in this table and the text has
15
+ * focus, else null: all the grips draw from the editor's state, so a
16
+ * key that doesn't move it re-renders nothing (F6). What a menu offers
17
+ * is read from `view`'s state as it opens.
18
+ */
19
+ caret: TableCell | null;
16
20
  getPos: () => number | undefined;
17
21
  /** The node view's frame (the grips' layer is positioned in it), its scroll box and its table. */
18
22
  frame: HTMLElement;
19
23
  box: HTMLElement;
20
24
  table: HTMLTableElement;
21
25
  readOnly: boolean;
22
- /** Whether focus is in the field: the caret's cell has grips only then. */
23
- focused: boolean;
24
26
  /** Runs a table action on a cell (the caret put there first), focus back in the text. */
25
27
  onAction: (cell: TableCell, action: TableAction) => void;
26
28
  /** Colours a cell, its row or its column (null: no colour). */
@@ -32,4 +34,4 @@ export interface TableGripsProps {
32
34
  /** The editable element, where focus goes when a menu closes. */
33
35
  text: () => HTMLElement | null;
34
36
  }
35
- export declare function TableGrips({ view, state, getPos, frame, box, table, readOnly, focused, onAction, onColor, onWidth, onPreviewWidth, text }: TableGripsProps): import("react").JSX.Element | null;
37
+ export declare function TableGrips({ view, caret, getPos, frame, box, table, readOnly, onAction, onColor, onWidth, onPreviewWidth, text }: TableGripsProps): import("react").JSX.Element | null;
@@ -22,14 +22,13 @@ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-run
22
22
  // focus back to the text with the caret in that cell.
23
23
  import { useEffect, useLayoutEffect, useRef, useState } from 'react';
24
24
  import { TextSelection } from '@milkdown/kit/prose/state';
25
- import { selectedRect, TableMap } from '@milkdown/kit/prose/tables';
25
+ import { TableMap } from '@milkdown/kit/prose/tables';
26
26
  import { AlignCenterIcon, AlignLeftIcon, AlignRightIcon, ArrowDownAZIcon, ArrowDownIcon, ArrowLeftIcon, ArrowRightIcon, ArrowUpIcon, ArrowUpZAIcon, BetweenHorizontalEndIcon, BetweenHorizontalStartIcon, BetweenVerticalEndIcon, BetweenVerticalStartIcon, ChevronsLeftRightIcon, ChevronsRightLeftIcon, Columns3Icon, GripHorizontalIcon, GripVerticalIcon, MoveHorizontalIcon, PanelLeftIcon, Trash2Icon, } from 'lucide-react';
27
27
  import { cn } from 'cn';
28
28
  import { DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuSeparator, DropdownMenuTrigger, } from '../ui/dropdown-menu.js';
29
29
  import { useIsMobile } from '../../hooks/use-mobile.js';
30
30
  import { HIGHLIGHT_COLORS } from '../../lib/markdown-highlight.js';
31
31
  import { catchColumnWidth, clampColumnWidth, MAX_COLUMN_WIDTH, MIN_COLUMN_WIDTH } from '../../lib/markdown-table-widths.js';
32
- import { tableAt } from './rich-text-formats.js';
33
32
  import { cellColorAt, columnAlignment, columnWidthAt, headerColumnOn, tableHasWidths, tableActionEnabled, tableColorEnabled, } from './rich-text-table.js';
34
33
  /** The event the editor sends a table's frame to open the caret's cell menu (Shift+F10). */
35
34
  export const TABLE_MENU_EVENT = 'rich-text-table-menu';
@@ -102,7 +101,7 @@ function edgeAt(table, box, x, y) {
102
101
  });
103
102
  return best;
104
103
  }
105
- export function TableGrips({ view, state, getPos, frame, box, table, readOnly, focused, onAction, onColor, onWidth, onPreviewWidth, text }) {
104
+ export function TableGrips({ view, caret, getPos, frame, box, table, readOnly, onAction, onColor, onWidth, onPreviewWidth, text }) {
106
105
  const [hover, setHover] = useState(null);
107
106
  const [open, setOpen] = useState(null);
108
107
  const [target, setTarget] = useState(null);
@@ -117,12 +116,6 @@ export function TableGrips({ view, state, getPos, frame, box, table, readOnly, f
117
116
  const edgeHandle = useRef(null);
118
117
  const phone = useIsMobile();
119
118
  const tablePos = getPos();
120
- // The caret's cell, when it's in this table.
121
- let caret = null;
122
- if (focused && state && tablePos !== undefined && tableAt(state)?.pos === tablePos) {
123
- const { top, left } = selectedRect(state);
124
- caret = { row: top, column: left };
125
- }
126
119
  // The caret's cell for the keyboard's menu, read by a listener set up once.
127
120
  const caretRef = useRef(caret);
128
121
  useLayoutEffect(() => {
@@ -200,7 +193,10 @@ export function TableGrips({ view, state, getPos, frame, box, table, readOnly, f
200
193
  const middle = head.left + head.width / 2;
201
194
  columnButton.hidden = middle < scroll.left || middle > scroll.right;
202
195
  columnButton.style.left = `${middle - origin.left}px`;
203
- columnButton.style.top = `${head.top - origin.top}px`;
196
+ // A touch screen's column grip sits a little higher, so its 40px
197
+ // square takes less of the header cell (the frame has room above).
198
+ const lift = window.matchMedia('(pointer: coarse)').matches ? 6 : 0;
199
+ columnButton.style.top = `${head.top - origin.top - lift}px`;
204
200
  rowButton.hidden = false;
205
201
  rowButton.style.left = `${scroll.left - origin.left}px`;
206
202
  rowButton.style.top = `${line.top - origin.top + line.height / 2}px`;
@@ -226,8 +222,9 @@ export function TableGrips({ view, state, getPos, frame, box, table, readOnly, f
226
222
  handle.style.top = `${area.top - origin.top}px`;
227
223
  handle.style.height = `${area.height}px`;
228
224
  });
229
- if (readOnly || tablePos === undefined || !state)
225
+ if (readOnly || tablePos === undefined)
230
226
  return null;
227
+ const state = view.state;
231
228
  const at = (cell) => (cell ? stateAt(state, tablePos, cell) : null);
232
229
  const menuCell = open ? target : active;
233
230
  const there = at(menuCell);
@@ -325,6 +322,8 @@ export function TableGrips({ view, state, getPos, frame, box, table, readOnly, f
325
322
  }, children: ALIGNMENTS.map(({ value, label, icon: Icon }) => (_jsxs(DropdownMenuRadioItem, { value: value, closeOnClick: true, children: [_jsx(Icon, { "aria-hidden": "true" }), label] }, value))) })] }), _jsx(DropdownMenuSeparator, {}), _jsx(DropdownMenuGroup, { children: items(SORT_ITEMS) }), menuCell?.column === 0 && (_jsxs(_Fragment, { children: [_jsx(DropdownMenuSeparator, {}), _jsxs(DropdownMenuCheckboxItem, { checked: there ? headerColumnOn(there) : false, disabled: !enabled('headerColumn'), onCheckedChange: () => run('headerColumn'), closeOnClick: true, children: [_jsx(PanelLeftIcon, { "aria-hidden": "true" }), "Header Column"] })] })), withColor && there && tableColorEnabled(there, 'column') && (_jsxs(_Fragment, { children: [_jsx(DropdownMenuSeparator, {}), colorGroup('column', 'Colour Column')] })), _jsx(DropdownMenuSeparator, {}), _jsxs(DropdownMenuItem, { onClick: () => run('deleteTable'), children: [_jsx(Trash2Icon, { "aria-hidden": "true" }), "Delete Table"] })] }));
326
323
  const rowColor = there && tableColorEnabled(there, 'row');
327
324
  const finalFocus = () => text() ?? true;
328
- const grip = 'pointer-events-auto absolute flex items-center justify-center rounded-sm border border-border bg-muted text-muted-foreground shadow-xs outline-none hover:bg-primary hover:text-primary-foreground data-popup-open:bg-primary data-popup-open:text-primary-foreground';
325
+ const grip = 'pointer-events-auto absolute flex items-center justify-center rounded-sm border border-border bg-muted text-muted-foreground shadow-xs outline-none hover:bg-primary hover:text-primary-foreground data-popup-open:bg-primary data-popup-open:text-primary-foreground ' +
326
+ // On a touch screen, an invisible 40px square round each takes the tap (review F11).
327
+ "pointer-coarse:before:absolute pointer-coarse:before:top-1/2 pointer-coarse:before:left-1/2 pointer-coarse:before:size-10 pointer-coarse:before:-translate-1/2 pointer-coarse:before:content-['']";
329
328
  return (_jsxs(_Fragment, { children: [!phone && (_jsxs("div", { ref: edgeHandle, hidden: true, "aria-hidden": "true", "data-slot": "rich-text-table-column-edge", className: "pointer-events-auto absolute z-10 flex w-3 -translate-x-1/2 cursor-col-resize touch-none justify-center", onPointerDown: startDrag, onDoubleClick: () => edge !== null && onWidth(edge, null), children: [_jsx("span", { className: "h-full w-0.5 bg-primary" }), drag && (_jsx("span", { "data-slot": "rich-text-table-column-size", className: "absolute bottom-full mb-1 rounded-sm bg-primary px-1.5 font-mono text-xs whitespace-nowrap text-primary-foreground tabular-nums", children: drag.label }))] })), _jsxs(DropdownMenu, { open: open === 'column' || open === 'cell', onOpenChange: openMenu('column'), children: [_jsx(DropdownMenuTrigger, { tabIndex: -1, "aria-label": menuCell ? `Column: ${columnName(menuCell.column)}` : 'Column', ref: columnGrip, "data-slot": "rich-text-table-column-grip", className: cn(grip, 'h-3.5 w-6 -translate-x-1/2 -translate-y-1/2'), children: _jsx(GripHorizontalIcon, { "aria-hidden": "true", className: "size-3" }) }), _jsx(DropdownMenuContent, { className: "w-56", "data-rich-text-menu": "", finalFocus: finalFocus, children: open === 'cell' ? (_jsxs(_Fragment, { children: [menuCell && menuCell.row > 0 && (_jsxs(_Fragment, { children: [colorGroup('cell', 'Cell Colour'), _jsx(DropdownMenuSeparator, {})] })), _jsxs(DropdownMenuGroup, { children: [_jsx(DropdownMenuLabel, { children: "Row" }), items(ROW_ITEMS)] }), _jsx(DropdownMenuSeparator, {}), columnItems(false, menuCell ? `Column: ${columnName(menuCell.column)}` : 'Column')] })) : (columnItems(true)) })] }), _jsxs(DropdownMenu, { open: open === 'row', onOpenChange: openMenu('row'), children: [_jsx(DropdownMenuTrigger, { tabIndex: -1, "aria-label": menuCell ? (menuCell.row === 0 ? 'Header Row' : `Row ${menuCell.row}`) : 'Row', ref: rowGrip, "data-slot": "rich-text-table-row-grip", className: cn(grip, 'h-6 w-3.5 -translate-x-1/2 -translate-y-1/2'), children: _jsx(GripVerticalIcon, { "aria-hidden": "true", className: "size-3" }) }), _jsxs(DropdownMenuContent, { className: "w-56", "data-rich-text-menu": "", finalFocus: finalFocus, children: [_jsx(DropdownMenuGroup, { children: items(ROW_ITEMS) }), rowColor && (_jsxs(_Fragment, { children: [_jsx(DropdownMenuSeparator, {}), colorGroup('row', 'Colour Row')] }))] })] })] }));
330
329
  }
@@ -6,3 +6,11 @@ export declare const taskInputRule: import("@milkdown/utils").$InputRule;
6
6
  * included), for the editor's own Enter.
7
7
  */
8
8
  export declare function splitTaskItem(state: EditorState, dispatch: (tr: Transaction) => void): boolean;
9
+ /**
10
+ * A task item's box in its hit area (review F11): the box as drawn, in a
11
+ * label whose invisible 40px square, on a touch screen, takes the tap
12
+ * (a press on a label is its checkbox's), and the item's row 40px tall
13
+ * there, so two items' squares never overlap. A laptop is unchanged.
14
+ */
15
+ export declare const TASK_ROW = "pointer-coarse:min-h-10 pointer-coarse:py-2";
16
+ export declare function taskBoxHit(box: HTMLInputElement): HTMLLabelElement;
@@ -70,3 +70,23 @@ export function splitTaskItem(state, dispatch) {
70
70
  dispatch(tr.scrollIntoView());
71
71
  return true;
72
72
  }
73
+ /**
74
+ * A task item's box in its hit area (review F11): the box as drawn, in a
75
+ * label whose invisible 40px square, on a touch screen, takes the tap
76
+ * (a press on a label is its checkbox's), and the item's row 40px tall
77
+ * there, so two items' squares never overlap. A laptop is unchanged.
78
+ */
79
+ export const TASK_ROW = 'pointer-coarse:min-h-10 pointer-coarse:py-2';
80
+ export function taskBoxHit(box) {
81
+ const hit = document.createElement('label');
82
+ hit.contentEditable = 'false';
83
+ hit.dataset.slot = 'task-box';
84
+ hit.className =
85
+ 'relative flex shrink-0 pointer-coarse:before:absolute pointer-coarse:before:top-1/2 pointer-coarse:before:left-1/2 pointer-coarse:before:size-10 pointer-coarse:before:-translate-1/2 pointer-coarse:before:content-[""]';
86
+ // Over the square, so a press on the box itself is the box's.
87
+ box.className = 'relative z-10 mt-1 size-4 accent-primary';
88
+ // A press keeps the caret where it is, as on the box itself.
89
+ hit.addEventListener('mousedown', (event) => event.preventDefault());
90
+ hit.append(box);
91
+ return hit;
92
+ }
@@ -6,6 +6,8 @@ declare const SETS: {
6
6
  all: FormatItem[][];
7
7
  tools: FormatItem[][];
8
8
  selection: FormatItem[][];
9
+ keyboard: FormatItem[][];
10
+ keyboardWords: FormatItem[][];
9
11
  };
10
12
  export type FormatButtonsProps = {
11
13
  /** Every format, or the ones for selected words. */
@@ -25,8 +27,10 @@ export type FormatButtonsProps = {
25
27
  fullScreen?: boolean;
26
28
  /** The editable element, for the Highlight menu to give focus back to. */
27
29
  text?: () => HTMLElement | null;
30
+ /** 40px buttons, for a touch screen (the keyboard bar's). */
31
+ touch?: boolean;
28
32
  };
29
- export declare function FormatButtons({ formats, state, readOnly, onFormat, onPage, onImage, onFullScreen, fullScreen, text }: FormatButtonsProps): import("react").JSX.Element;
33
+ export declare function FormatButtons({ formats, state, readOnly, onFormat, onPage, onImage, onFullScreen, fullScreen, text, touch }: FormatButtonsProps): import("react").JSX.Element;
30
34
  export interface RichTextToolbarProps {
31
35
  /** The editor's state now, to show which formats are on. Null until it's made. */
32
36
  state: EditorState | null;
@@ -17,6 +17,7 @@ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-run
17
17
  // showing: rich-text-floating-toolbar.tsx).
18
18
  import { Fragment, useEffect, useRef, useState } from 'react';
19
19
  import { FileTextIcon, ImageIcon, Maximize2Icon, Minimize2Icon } from 'lucide-react';
20
+ import { cn } from 'cn';
20
21
  import { Button } from '../ui/button.js';
21
22
  import { Separator } from '../ui/separator.js';
22
23
  import { Toggle } from '../ui/toggle.js';
@@ -33,6 +34,11 @@ const SETS = {
33
34
  // Outdent and Indent, for a field with no bar above the text (rich-text-tools-bar.tsx).
34
35
  tools: [[FORMAT_ITEMS.get('outdent'), FORMAT_ITEMS.get('indent')]],
35
36
  selection: [SELECTION.slice(0, 5), SELECTION.slice(5)].map((ids) => ids.map((id) => FORMAT_ITEMS.get(id))),
37
+ // The row pinned above a phone's keyboard (rich-text-keyboard-bar.tsx):
38
+ // what's used while typing a list, and with words selected, their formats
39
+ // first.
40
+ keyboard: [['tasks', 'bullets', 'outdent', 'indent'].map((id) => FORMAT_ITEMS.get(id))],
41
+ keyboardWords: [SELECTION.map((id) => FORMAT_ITEMS.get(id)), ['tasks', 'bullets'].map((id) => FORMAT_ITEMS.get(id))],
36
42
  };
37
43
  // A touch screen or a narrow one: where the keyboard has no Tab, so the
38
44
  // toolbar carries Indent and Outdent for list items.
@@ -51,7 +57,7 @@ function useCompact() {
51
57
  // A toolbar's row of buttons: one tab stop, the last one used (ARIA's
52
58
  // toolbar pattern); the arrow keys, Home and End move along the row. The
53
59
  // toolbar's element (`role="toolbar"`, its name) is the caller's.
54
- export function FormatButtons({ formats, state, readOnly, onFormat, onPage, onImage, onFullScreen, fullScreen = false, text = () => null }) {
60
+ export function FormatButtons({ formats, state, readOnly, onFormat, onPage, onImage, onFullScreen, fullScreen = false, text = () => null, touch = false }) {
55
61
  const apple = isApple();
56
62
  const compact = useCompact();
57
63
  const groups = SETS[formats].map((group) => group.filter((item) => compact || !item.touch)).filter((group) => group.length > 0);
@@ -60,6 +66,8 @@ export function FormatButtons({ formats, state, readOnly, onFormat, onPage, onIm
60
66
  const pageIndex = onPage ? items.length : -1;
61
67
  const imageIndex = onImage ? items.length + (onPage ? 1 : 0) : -1;
62
68
  const fullScreenIndex = onFullScreen ? items.length + (onPage ? 1 : 0) + (onImage ? 1 : 0) : -1;
69
+ // A touch screen's 40px buttons; a laptop's 28px.
70
+ const sized = touch ? 'size-10 min-w-10 [&_svg]:size-5' : undefined;
63
71
  const count = items.length + (onPage ? 1 : 0) + (onImage ? 1 : 0) + (onFullScreen ? 1 : 0);
64
72
  const buttons = useRef([]);
65
73
  // The one button Tab reaches: the last one used.
@@ -82,12 +90,12 @@ export function FormatButtons({ formats, state, readOnly, onFormat, onPage, onIm
82
90
  event.preventDefault();
83
91
  action();
84
92
  };
85
- return (_jsxs(TooltipProvider, { delay: 400, children: [groups.map((group, groupIndex) => (_jsxs(Fragment, { children: [groupIndex > 0 && _jsx(Separator, { orientation: "vertical", className: "mx-1 h-5 self-center" }), group.map((item) => {
93
+ return (_jsxs(TooltipProvider, { delay: 400, children: [groups.map((group, groupIndex) => (_jsxs(Fragment, { children: [groupIndex > 0 && _jsx(Separator, { orientation: "vertical", className: cn('mx-1 h-5 self-center', touch && 'h-6 data-vertical:self-center') }), group.map((item) => {
86
94
  const index = items.indexOf(item);
87
95
  if (item.id === 'highlight')
88
96
  return (_jsx(RichTextHighlightMenu, { ref: (element) => {
89
97
  buttons.current[index] = element;
90
- }, state: state, readOnly: readOnly, tabIndex: index === current ? 0 : -1, onFocus: () => setCurrent(index), onKeyDown: onKeyDown, onFormat: onFormat, text: text }, item.id));
98
+ }, state: state, readOnly: readOnly, tabIndex: index === current ? 0 : -1, onFocus: () => setCurrent(index), onKeyDown: onKeyDown, onFormat: onFormat, text: text, className: touch ? 'h-10 min-w-10' : undefined }, item.id));
91
99
  const Icon = item.icon;
92
100
  const tip = [
93
101
  item.label,
@@ -99,12 +107,12 @@ export function FormatButtons({ formats, state, readOnly, onFormat, onPage, onIm
99
107
  if (item.action)
100
108
  return (_jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { render: _jsx(Button, { ref: (element) => {
101
109
  buttons.current[index] = element;
102
- }, variant: "ghost", size: "icon-sm", "aria-label": item.label,
110
+ }, variant: "ghost", size: "icon-sm", className: sized, "aria-label": item.label,
103
111
  // A table goes in only outside one.
104
112
  disabled: readOnly || (item.id === 'table' && state !== null && formatOn(state, 'table')), tabIndex: index === current ? 0 : -1, onMouseDown: (event) => event.preventDefault(), onFocus: () => setCurrent(index), onKeyDown: onKeyDown, onClick: () => onFormat(item.id) }), children: _jsx(Icon, {}) }), _jsx(TooltipContent, { children: tip })] }, item.id));
105
113
  return (_jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { render: _jsx(Toggle, { ref: (element) => {
106
114
  buttons.current[index] = element;
107
- }, size: "icon-sm", "aria-label": item.label, "aria-keyshortcuts": item.keys ? ariaKeys(item.keys, apple) : undefined, pressed: state ? formatOn(state, item.id) : false, disabled: readOnly, tabIndex: index === current ? 0 : -1, className: "aria-pressed:bg-muted aria-pressed:text-foreground",
115
+ }, size: "icon-sm", "aria-label": item.label, "aria-keyshortcuts": item.keys ? ariaKeys(item.keys, apple) : undefined, pressed: state ? formatOn(state, item.id) : false, disabled: readOnly, tabIndex: index === current ? 0 : -1, className: cn('aria-pressed:bg-muted aria-pressed:text-foreground', sized),
108
116
  // A mouse press keeps focus, and the selection, in the text.
109
117
  onMouseDown: (event) => event.preventDefault(), onFocus: () => setCurrent(index), onKeyDown: onKeyDown, onPressedChange: () => onFormat(item.id) }), children: _jsx(Icon, {}) }), _jsx(TooltipContent, { children: tip })] }, item.id));
110
118
  })] }, groupIndex))), onPage && (_jsxs(_Fragment, { children: [_jsx(Separator, { orientation: "vertical", className: "mx-1 h-5 self-center" }), _jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { render: _jsx(Button, { ref: (element) => {
@@ -0,0 +1,2 @@
1
+ /** Whether the pointer is a finger: where the editor's toolbar is the keyboard bar. */
2
+ export declare function useCoarsePointer(): boolean;
@@ -0,0 +1,18 @@
1
+ // Whether the editor is on a touch screen (review F11): where its toolbar
2
+ // is the bar pinned to the keyboard (rich-text-keyboard-bar.tsx), the
3
+ // floating bar over selected words gives way to the system's own, and the
4
+ // slash menu is capped to what the keyboard leaves visible.
5
+ import { useEffect, useState } from 'react';
6
+ const COARSE = '(pointer: coarse)';
7
+ /** Whether the pointer is a finger: where the editor's toolbar is the keyboard bar. */
8
+ export function useCoarsePointer() {
9
+ const [coarse, setCoarse] = useState(() => typeof window !== 'undefined' && window.matchMedia(COARSE).matches);
10
+ useEffect(() => {
11
+ const query = window.matchMedia(COARSE);
12
+ const update = () => setCoarse(query.matches);
13
+ update();
14
+ query.addEventListener('change', update);
15
+ return () => query.removeEventListener('change', update);
16
+ }, []);
17
+ return coarse;
18
+ }
@@ -20,7 +20,7 @@ import { CALLOUT_LOOK } from './prose-look.js';
20
20
  export function CalloutKindMenu({ kind, readOnly, onPick, onRemove, text }) {
21
21
  const look = CALLOUT_LOOK[kind];
22
22
  const Icon = look.icon;
23
- return (_jsxs(DropdownMenu, { children: [_jsx(DropdownMenuTrigger, { tabIndex: -1, disabled: readOnly, "aria-label": `${look.label} callout: change its kind`, "data-slot": "rich-text-callout-kind", className: "flex size-5 items-center justify-center rounded-md outline-none hover:bg-foreground/10 focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none", children: _jsx(Icon, { "aria-hidden": "true", className: cn('size-4', look.tint) }) }), _jsxs(DropdownMenuContent, { className: "w-44", finalFocus: () => text() ?? true, children: [_jsx(DropdownMenuRadioGroup, { value: kind, onValueChange: (value) => onPick(value), children: CALLOUT_KINDS.map((one) => {
23
+ return (_jsxs(DropdownMenu, { children: [_jsx(DropdownMenuTrigger, { tabIndex: -1, disabled: readOnly, "aria-label": `${look.label} callout: change its kind`, "data-slot": "rich-text-callout-kind", className: "relative pointer-coarse:before:absolute pointer-coarse:before:top-1/2 pointer-coarse:before:left-1/2 pointer-coarse:before:size-10 pointer-coarse:before:-translate-1/2 pointer-coarse:before:content-[''] flex size-5 items-center justify-center rounded-md outline-none hover:bg-foreground/10 focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none", children: _jsx(Icon, { "aria-hidden": "true", className: cn('size-4', look.tint) }) }), _jsxs(DropdownMenuContent, { className: "w-44", finalFocus: () => text() ?? true, children: [_jsx(DropdownMenuRadioGroup, { value: kind, onValueChange: (value) => onPick(value), children: CALLOUT_KINDS.map((one) => {
24
24
  const OneIcon = CALLOUT_LOOK[one].icon;
25
25
  return (_jsxs(DropdownMenuRadioItem, { value: one, closeOnClick: true, children: [_jsx(OneIcon, { "aria-hidden": "true", className: CALLOUT_LOOK[one].tint }), CALLOUT_LOOK[one].label] }, one));
26
26
  }) }), _jsx(DropdownMenuSeparator, {}), _jsx(DropdownMenuItem, { onClick: onRemove, children: "Remove Callout" })] })] }));
@@ -36,6 +36,10 @@ export type TableView<F extends string, M extends string> = {
36
36
  };
37
37
  export declare function serializeSort(next: Sort): string | null;
38
38
  export declare function applyUrlChanges(previous: URLSearchParams, changes: UrlChanges): URLSearchParams;
39
+ export declare function paramsToUpdate(rendered: URLSearchParams, renderedPath: string, addressBar: {
40
+ pathname: string;
41
+ search: string;
42
+ } | undefined): URLSearchParams;
39
43
  export declare function viewToUrlChanges<F extends string, M extends string>(filterNames: readonly F[], multiFilterNames: readonly M[], view: TableView<F, M>, asDefault?: boolean): UrlChanges;
40
44
  /**
41
45
  * The query parameter that says "no view, no filters" on a list with a
@@ -18,6 +18,19 @@ export function applyUrlChanges(previous, changes) {
18
18
  }
19
19
  return next;
20
20
  }
21
+ // The query string an update builds on: the address bar's, not the one
22
+ // the hook last rendered with. Two updates before the next render (two
23
+ // setters in one handler, or another part of the page writing its own
24
+ // param in the same tick) would otherwise each start from the rendered
25
+ // params, and the last would undo the others. react-router writes the
26
+ // address bar as it navigates, synchronously for a route with nothing to
27
+ // load, so it's always the latest. Only when it's this router's address,
28
+ // though: under a memory router (a fixture, a test) the address bar is
29
+ // someone else's, its path isn't the rendered one, and the rendered params
30
+ // are what there is.
31
+ export function paramsToUpdate(rendered, renderedPath, addressBar) {
32
+ return addressBar !== undefined && addressBar.pathname === renderedPath ? new URLSearchParams(addressBar.search) : rendered;
33
+ }
21
34
  // A view is "this combination and nothing else": every filter and the sort
22
35
  // are set, and any the view doesn't name are cleared. Merging over the
23
36
  // current state instead would let a leftover filter silently show something
@@ -1,6 +1,6 @@
1
1
  import { useCallback, useSyncExternalStore } from 'react';
2
- import { useSearchParams } from 'react-router';
3
- import { activeViewOf, applyUrlChanges, filterChanges, readFilterState, ruleFilterNames, serializeSort, viewToUrlChanges, } from './table-url-changes.js';
2
+ import { useHref, useLocation, useSearchParams } from 'react-router';
3
+ import { activeViewOf, applyUrlChanges, filterChanges, paramsToUpdate, readFilterState, ruleFilterNames, serializeSort, viewToUrlChanges, } from './table-url-changes.js';
4
4
  import { browserStore } from './use-table-layout.js';
5
5
  const DEFAULT_PAGE_SIZES = [25, 50, 100];
6
6
  // A table's page, sort and filters, kept in the URL query string
@@ -44,6 +44,8 @@ const DEFAULT_PAGE_SIZES = [25, 50, 100];
44
44
  // Every setter is one update(), and must stay one: see setFilters.
45
45
  export function useTableUrlState(filterNames, multiFilterNames = [], views = {}, { groupStorageKey, pageSizes = DEFAULT_PAGE_SIZES, defaultPageSize = 50, pageSizeStorageKey, defaultView, } = {}) {
46
46
  const [params, setParams] = useSearchParams();
47
+ // This router's address, as the address bar spells it (basename included).
48
+ const renderedPath = useHref({ pathname: useLocation().pathname });
47
49
  const rememberedPageSize = useRemembered(pageSizeStorageKey);
48
50
  const pageSize = resolvePageSize(pageSizes, params.get('size'), rememberedPageSize, defaultPageSize);
49
51
  const rememberedGrouping = useRemembered(groupStorageKey);
@@ -72,8 +74,12 @@ export function useTableUrlState(filterNames, multiFilterNames = [], views = {},
72
74
  const ruleNames = ruleFilterNames(views);
73
75
  // The reader changing filters by hand: see filterChanges.
74
76
  const changeFilters = (changes) => update({ ...keptSort, ...filterChanges(state, changes, ruleNames, fallback !== undefined) });
77
+ // From the address bar, not setParams' `previous`: react-router hands
78
+ // that the params of the last render, so a second update before the
79
+ // next render undid the first. See paramsToUpdate.
75
80
  function update(changes) {
76
- setParams((previous) => applyUrlChanges(previous, changes), { replace: true });
81
+ const addressBar = typeof window === 'undefined' ? undefined : window.location;
82
+ setParams(applyUrlChanges(paramsToUpdate(params, renderedPath, addressBar), changes), { replace: true });
77
83
  }
78
84
  return {
79
85
  page,
@@ -98,11 +104,11 @@ export function useTableUrlState(filterNames, multiFilterNames = [], views = {},
98
104
  setSorting: (next) => update({ sort: serializeSort(next) ?? (fallback?.sort && state.atDefault ? 'none' : null), page: null }),
99
105
  setFilter: (name, value) => changeFilters({ [name]: value }),
100
106
  // Several filters in one call — for any user action that changes more
101
- // than one (both ends of a date range, "clear filters"). Two setters in
102
- // the same tick lose all but the last: react-router hands each
103
- // setSearchParams updater the params from the last render, not the
104
- // ones the previous updater produced. Single-value filters take a
105
- // string ('' clears), multi-value ones a list ([] clears).
107
+ // than one (both ends of a date range, "clear filters"). One call is
108
+ // still the rule: two setters in the same tick both land in a browser
109
+ // router (update() reads the address bar), but under a memory router
110
+ // all but the last are lost. Single-value filters take a string ('' clears),
111
+ // multi-value ones a list ([] clears).
106
112
  setFilters: (changes) => changeFilters(changes),
107
113
  setMultiFilter: (name, values) => changeFilters({ [name]: values }),
108
114
  // Replaces the whole filter + sort state at once — a saved view. See
package/dist/index.d.ts CHANGED
@@ -69,6 +69,7 @@ export { MultiReference } from './components/app/multi-reference.js';
69
69
  export { ListEditor } from './components/app/list-editor.js';
70
70
  export { PasswordInput } from './components/app/password-input.js';
71
71
  export { RichTextEditor, type RichTextEditorProps } from './components/app/rich-text-editor.js';
72
+ export { flushPendingEdits, hasPendingEdits } from './lib/pending-edits.js';
72
73
  export { RouteErrorBoundary } from './components/app/route-error-boundary.js';
73
74
  export { PillFilter, type PillFilterOption, type PillFilterProps } from './components/app/pill-filter.js';
74
75
  export { SecondaryFilters, type ActiveFilter, type SecondaryFiltersProps } from './components/app/secondary-filters.js';
package/dist/index.js CHANGED
@@ -75,6 +75,9 @@ export { MultiReference } from './components/app/multi-reference.js';
75
75
  export { ListEditor } from './components/app/list-editor.js';
76
76
  export { PasswordInput } from './components/app/password-input.js';
77
77
  export { RichTextEditor } from './components/app/rich-text-editor.js';
78
+ // Typing a RichTextEditor holds back until a pause, reported now: call it
79
+ // before reading a rich-text field's value to save it in your own form.
80
+ export { flushPendingEdits, hasPendingEdits } from './lib/pending-edits.js';
78
81
  export { RouteErrorBoundary } from './components/app/route-error-boundary.js';
79
82
  export { PillFilter } from './components/app/pill-filter.js';
80
83
  export { SecondaryFilters } from './components/app/secondary-filters.js';
@@ -1,3 +1,28 @@
1
+ type MdNode = {
2
+ type: string;
3
+ position?: {
4
+ start: {
5
+ offset?: number;
6
+ };
7
+ end: {
8
+ offset?: number;
9
+ };
10
+ };
11
+ children?: MdNode[];
12
+ [key: string]: unknown;
13
+ };
14
+ declare function parse(markdown: string): MdNode;
15
+ declare function meaning(node: unknown, definitions: Map<string, MdNode>): unknown;
16
+ declare function content(node: MdNode, definitions: Map<string, MdNode>): string;
17
+ export declare const mergeParts: {
18
+ parse: typeof parse;
19
+ meaning: typeof meaning;
20
+ content: typeof content;
21
+ };
22
+ /** How many texts mergeMarkdown has parsed, for tests/markdown-merge-budget.test.ts. */
23
+ export declare const mergeStats: {
24
+ parses: number;
25
+ };
1
26
  export declare class MarkdownMergeError extends Error {
2
27
  constructor();
3
28
  }
@@ -17,3 +42,4 @@ export declare function markdownStyle(markdown: string): {
17
42
  bullet: '-' | '*' | '+';
18
43
  rule: '-' | '*' | '_';
19
44
  };
45
+ export {};