@tristan2828/ui-foundation 4.125.0 → 4.127.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 (94) hide show
  1. package/README.md +1 -1
  2. package/conventions/docs/add-an-entity.md +140 -35
  3. package/conventions/docs/cell-patterns.md +144 -56
  4. package/conventions/docs/design-language.md +45 -13
  5. package/dist/api/contracts.d.ts +8 -1
  6. package/dist/api/gateway/errors.js +4 -0
  7. package/dist/api/schema.d.ts +9 -0
  8. package/dist/api/transport/index.js +10 -1
  9. package/dist/components/app/data-table-tools.d.ts +12 -0
  10. package/dist/components/app/data-table-tools.js +2 -2
  11. package/dist/components/app/data-table.d.ts +2 -1
  12. package/dist/components/app/data-table.js +1 -1
  13. package/dist/components/app/edit-caret.d.ts +25 -0
  14. package/dist/components/app/edit-caret.js +118 -0
  15. package/dist/components/app/edit-in-place-presets.d.ts +51 -1
  16. package/dist/components/app/edit-in-place-presets.js +30 -0
  17. package/dist/components/app/edit-in-place-store.d.ts +70 -4
  18. package/dist/components/app/edit-in-place-store.js +219 -21
  19. package/dist/components/app/edit-in-place.d.ts +11 -0
  20. package/dist/components/app/editable-value.js +202 -25
  21. package/dist/components/app/entity-form.js +4 -0
  22. package/dist/components/app/entity-view.js +5 -1
  23. package/dist/components/app/equal-items.d.ts +32 -6
  24. package/dist/components/app/equal-items.js +59 -8
  25. package/dist/components/app/error-state.js +1 -0
  26. package/dist/components/app/form-leave-guard.js +7 -1
  27. package/dist/components/app/milkdown-editor.d.ts +1 -0
  28. package/dist/components/app/milkdown-editor.js +226 -64
  29. package/dist/components/app/pill-filter.d.ts +16 -0
  30. package/dist/components/app/pill-filter.js +22 -1
  31. package/dist/components/app/prose-look.d.ts +1 -1
  32. package/dist/components/app/prose-look.js +3 -1
  33. package/dist/components/app/rating-input.d.ts +22 -0
  34. package/dist/components/app/rating-input.js +65 -0
  35. package/dist/components/app/rating-score.d.ts +2 -1
  36. package/dist/components/app/rating-score.js +2 -6
  37. package/dist/components/app/rich-text-autolink.d.ts +6 -0
  38. package/dist/components/app/rich-text-autolink.js +79 -0
  39. package/dist/components/app/rich-text-edges.d.ts +8 -0
  40. package/dist/components/app/rich-text-edges.js +144 -0
  41. package/dist/components/app/rich-text-editor.d.ts +19 -4
  42. package/dist/components/app/rich-text-editor.js +19 -6
  43. package/dist/components/app/rich-text-empty-paragraph.d.ts +14 -6
  44. package/dist/components/app/rich-text-empty-paragraph.js +19 -8
  45. package/dist/components/app/rich-text-formats.js +88 -15
  46. package/dist/components/app/rich-text-full-screen.d.ts +2 -0
  47. package/dist/components/app/rich-text-full-screen.js +78 -0
  48. package/dist/components/app/rich-text-highlight-menu.d.ts +3 -1
  49. package/dist/components/app/rich-text-highlight-menu.js +3 -2
  50. package/dist/components/app/rich-text-input-rules.d.ts +7 -0
  51. package/dist/components/app/rich-text-input-rules.js +83 -0
  52. package/dist/components/app/rich-text-keyboard-bar.d.ts +24 -0
  53. package/dist/components/app/rich-text-keyboard-bar.js +215 -0
  54. package/dist/components/app/rich-text-node-views.js +2 -1
  55. package/dist/components/app/rich-text-paste.d.ts +43 -0
  56. package/dist/components/app/rich-text-paste.js +355 -0
  57. package/dist/components/app/rich-text-shortcuts.d.ts +5 -1
  58. package/dist/components/app/rich-text-shortcuts.js +132 -2
  59. package/dist/components/app/rich-text-slash-menu.js +47 -9
  60. package/dist/components/app/rich-text-slash.d.ts +7 -0
  61. package/dist/components/app/rich-text-slash.js +27 -14
  62. package/dist/components/app/rich-text-table-grips.d.ts +8 -6
  63. package/dist/components/app/rich-text-table-grips.js +11 -12
  64. package/dist/components/app/rich-text-tasks.d.ts +8 -0
  65. package/dist/components/app/rich-text-tasks.js +20 -0
  66. package/dist/components/app/rich-text-toolbar.d.ts +5 -1
  67. package/dist/components/app/rich-text-toolbar.js +14 -6
  68. package/dist/components/app/rich-text-tools-bar.d.ts +3 -1
  69. package/dist/components/app/rich-text-tools-bar.js +2 -2
  70. package/dist/components/app/rich-text-touch.d.ts +2 -0
  71. package/dist/components/app/rich-text-touch.js +18 -0
  72. package/dist/components/app/rich-text-widgets.js +1 -1
  73. package/dist/hooks/table-url-changes.d.ts +4 -0
  74. package/dist/hooks/table-url-changes.js +13 -0
  75. package/dist/hooks/use-record-update.d.ts +13 -1
  76. package/dist/hooks/use-record-update.js +17 -3
  77. package/dist/hooks/use-table-url-state.js +14 -8
  78. package/dist/index.d.ts +5 -2
  79. package/dist/index.js +8 -0
  80. package/dist/lib/markdown-merge.d.ts +38 -0
  81. package/dist/lib/markdown-merge.js +202 -17
  82. package/dist/lib/page-leaving.d.ts +8 -0
  83. package/dist/lib/page-leaving.js +30 -0
  84. package/dist/lib/pending-edits.d.ts +14 -0
  85. package/dist/lib/pending-edits.js +51 -0
  86. package/dist/lib/rating-glyphs.d.ts +3 -0
  87. package/dist/lib/rating-glyphs.js +7 -0
  88. package/dist/mocks/e2e-hooks.js +10 -0
  89. package/dist/mocks/override.d.ts +8 -0
  90. package/dist/testing/index.d.ts +40 -2
  91. package/dist/testing/index.js +101 -7
  92. package/openapi/foundation.yaml +12 -0
  93. package/package.json +1 -1
  94. package/styles/index.css +7 -0
@@ -27,13 +27,20 @@ export declare function slashPlugin(): Plugin<SlashState>;
27
27
  export type SlashItem = Omit<FormatItem, 'id'> & {
28
28
  id: FormatId | 'image' | 'page';
29
29
  };
30
+ /** Where the menu is open, for `slashItems` to leave out what can't be made there. */
31
+ export type SlashPlace = {
32
+ state: EditorState;
33
+ span: SlashQuery;
34
+ };
30
35
  /**
31
36
  * The blocks matching what's typed after the "/": in the name, or the
32
37
  * start of a keyword. With `image`, an image too; with `page`, the new page.
38
+ * With `at`, only the blocks that can be made there.
33
39
  */
34
40
  export declare function slashItems(query: string, options?: {
35
41
  page?: boolean;
36
42
  image?: boolean;
43
+ at?: SlashPlace;
37
44
  }): SlashItem[];
38
45
  /** Picks the image item: the "/…" goes and the menu closes, the caret where it was, for the picked images. */
39
46
  export declare function clearSlash(view: EditorView, span: SlashQuery): void;
@@ -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,17 +107,17 @@ 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) => {
111
119
  buttons.current[pageIndex] = element;
112
- }, variant: "ghost", size: "icon-sm", "aria-label": "Turn Into Page", disabled: readOnly, tabIndex: pageIndex === current ? 0 : -1, onMouseDown: (event) => event.preventDefault(), onFocus: () => setCurrent(pageIndex), onKeyDown: onKeyDown, onClick: onPage }), children: _jsx(FileTextIcon, {}) }), _jsx(TooltipContent, { children: "Turn Into Page \u00B7 a new page named for the words, linked here" })] })] })), onImage && (_jsxs(_Fragment, { children: [_jsx(Separator, { orientation: "vertical", className: "mx-1 h-5 self-center" }), _jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { render: _jsx(Button, { ref: (element) => {
120
+ }, variant: "ghost", size: "icon-sm", "aria-label": "Turn Into Page", disabled: readOnly, tabIndex: pageIndex === current ? 0 : -1, onMouseDown: (event) => event.preventDefault(), onFocus: () => setCurrent(pageIndex), onKeyDown: onKeyDown, onClick: onPage }), children: _jsx(FileTextIcon, {}) }), _jsx(TooltipContent, { children: "Turn Into Page \u00B7 a new page named for the words, linked here" })] })] })), onImage && (_jsxs(_Fragment, { children: [(items.length > 0 || onPage) && _jsx(Separator, { orientation: "vertical", className: "mx-1 h-5 self-center" }), _jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { render: _jsx(Button, { ref: (element) => {
113
121
  buttons.current[imageIndex] = element;
114
122
  }, variant: "ghost", size: "icon-sm", "aria-label": "Image", disabled: readOnly, tabIndex: imageIndex === current ? 0 : -1, onMouseDown: (event) => event.preventDefault(), onFocus: () => setCurrent(imageIndex), onKeyDown: onKeyDown, onClick: onImage }), children: _jsx(ImageIcon, {}) }), _jsx(TooltipContent, { children: "Image \u00B7 or paste or drop one" })] })] })), onFullScreen && (_jsxs(_Fragment, { children: [_jsx(Separator, { orientation: "vertical", className: "mx-1 h-5 self-center" }), _jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { render: _jsx(Toggle, { ref: (element) => {
115
123
  buttons.current[fullScreenIndex] = element;
@@ -8,6 +8,8 @@ export interface RichTextToolsBarProps {
8
8
  /** The editable element's id, for `aria-controls`. */
9
9
  controls: string;
10
10
  onFormat: (id: FormatId) => void;
11
+ /** The Image button pressed: pick images to upload. No button without it (the editor has no `upload`). */
12
+ onImage?: () => void;
11
13
  onFullScreen: () => void;
12
14
  /** Esc: focus back to the text. */
13
15
  onReturn: () => void;
@@ -15,4 +17,4 @@ export interface RichTextToolsBarProps {
15
17
  onBlur: (event: FocusEvent) => void;
16
18
  ref?: Ref<HTMLDivElement>;
17
19
  }
18
- export declare function RichTextToolsBar({ state, readOnly, fullScreen, controls, onFormat, onFullScreen, onReturn, onBlur, ref }: RichTextToolsBarProps): import("react").JSX.Element;
20
+ export declare function RichTextToolsBar({ state, readOnly, fullScreen, controls, onFormat, onImage, onFullScreen, onReturn, onBlur, ref }: RichTextToolsBarProps): import("react").JSX.Element;
@@ -1,7 +1,7 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
2
  import { cn } from 'cn';
3
3
  import { FormatButtons } from './rich-text-toolbar.js';
4
- export function RichTextToolsBar({ state, readOnly, fullScreen, controls, onFormat, onFullScreen, onReturn, onBlur, ref }) {
4
+ export function RichTextToolsBar({ state, readOnly, fullScreen, controls, onFormat, onImage, onFullScreen, onReturn, onBlur, ref }) {
5
5
  const onKeyDown = (event) => {
6
6
  // Full screen's Esc is the field's (milkdown-editor.tsx); otherwise it
7
7
  // gives focus back to the text.
@@ -13,5 +13,5 @@ export function RichTextToolsBar({ state, readOnly, fullScreen, controls, onForm
13
13
  };
14
14
  return (_jsx("div", { ref: ref, role: "toolbar", "aria-label": "Editor tools", "aria-controls": controls, "data-slot": "rich-text-tools-bar", className: cn('absolute right-0 z-40 flex items-center gap-0.5 rounded-lg bg-popover p-1 text-popover-foreground shadow-md ring-1 ring-foreground/10',
15
15
  // Above the field, or inside its corner once it fills the window.
16
- fullScreen ? 'top-2 right-2' : 'bottom-full mb-1'), onKeyDown: onKeyDown, onBlur: onBlur, children: _jsx(FormatButtons, { formats: "tools", state: state, readOnly: readOnly, onFormat: onFormat, onFullScreen: onFullScreen, fullScreen: fullScreen }) }));
16
+ fullScreen ? 'top-2 right-2' : 'bottom-full mb-1'), onKeyDown: onKeyDown, onBlur: onBlur, children: _jsx(FormatButtons, { formats: "tools", state: state, readOnly: readOnly, onFormat: onFormat, onImage: onImage, onFullScreen: onFullScreen, fullScreen: fullScreen }) }));
17
17
  }
@@ -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
@@ -21,6 +21,18 @@ export type RecordUpdateOptions<TRecord extends {
21
21
  listsKey: QueryKey;
22
22
  /** The gateway's PATCH: sends `update`, resolves with the saved record, rejects with an `AppError`. */
23
23
  update: (id: TRecord['id'], update: TUpdate) => Promise<TRecord>;
24
+ /**
25
+ * Adds the version the change was built on to what's sent, when the
26
+ * record has one: `(update, widget) => ({ ...update, baseUpdatedAt:
27
+ * widget.updatedAt })`. `record` is the server's latest record this tab
28
+ * knows (in a burst of saves, the one the previous save returned), so a
29
+ * save never conflicts with this tab's own. The server answers 409 when
30
+ * the record's version is no longer that one (AppError kind `conflict`):
31
+ * the record is refetched, and nothing was written. Leave it out and no
32
+ * version is sent (docs/foundation/add-an-entity.md "Saves that don't
33
+ * overwrite").
34
+ */
35
+ withVersion?: (update: TUpdate, record: TRecord) => TUpdate;
24
36
  /** What a refusal's toast calls the record: "Couldn't update <name>: <reason>". */
25
37
  name: (record: TRecord) => string;
26
38
  /**
@@ -63,7 +75,7 @@ export declare function refusalReason(error: AppError, sent?: object): string;
63
75
  */
64
76
  export declare function recordUpdateMutationOptions<TRecord extends {
65
77
  id: RecordId;
66
- }, TUpdate extends Partial<TRecord>>(queryClient: QueryClient, { id, detailKey, listsKey, update, name, optimistic, toastOnError, onSuccess, onError, onSettled, }: RecordUpdateOptions<TRecord, TUpdate>): MutationOptions<TRecord, AppError, RecordChange<TRecord, TUpdate>, {
78
+ }, TUpdate extends Partial<TRecord>>(queryClient: QueryClient, { id, detailKey, listsKey, update, name, withVersion, optimistic, toastOnError, onSuccess, onError, onSettled, }: RecordUpdateOptions<TRecord, TUpdate>): MutationOptions<TRecord, AppError, RecordChange<TRecord, TUpdate>, {
67
79
  entry: Entry<TRecord, TUpdate>;
68
80
  }>;
69
81
  /**
@@ -26,6 +26,14 @@
26
26
  // function change has nothing to build on and is refused like any other
27
27
  // refusal. Both warn in the console, naming the keys searched.
28
28
  //
29
+ // - **A version check, when the record has one** (`withVersion`). Each
30
+ // request carries the version of the record it was built on (its
31
+ // `updatedAt`), and the server answers 409 when another writer saved
32
+ // since: nothing is written, the save rejects with an AppError of kind
33
+ // `conflict`, and the record is fetched again so the screen shows what
34
+ // the other writer saved. Without `withVersion` nothing is sent and
35
+ // nothing is checked, as before.
36
+ //
29
37
  // Editing in place uses the same save with `optimistic: false` and
30
38
  // `toastOnError: false`: nothing changes on screen until the server
31
39
  // agrees, and a refusal comes back to the field (`mutateAsync` rejects)
@@ -69,7 +77,7 @@ export function refusalReason(error, sent) {
69
77
  * The mutation options behind `useRecordUpdate`, for a given QueryClient.
70
78
  * Exported for tests and for code outside React; screens use the hook.
71
79
  */
72
- export function recordUpdateMutationOptions(queryClient, { id, detailKey, listsKey, update, name, optimistic = true, toastOnError = true, onSuccess, onError, onSettled, }) {
80
+ export function recordUpdateMutationOptions(queryClient, { id, detailKey, listsKey, update, name, withVersion, optimistic = true, toastOnError = true, onSuccess, onError, onSettled, }) {
73
81
  const key = hashKey(detailKey);
74
82
  const lists = { queryKey: listsKey };
75
83
  const map = recordStates(queryClient);
@@ -110,8 +118,10 @@ export function recordUpdateMutationOptions(queryClient, { id, detailKey, listsK
110
118
  scope: { id: `record-update:${key}` },
111
119
  mutationFn: (change) => {
112
120
  const confirmed = map.get(key)?.confirmed ?? cached();
113
- if (confirmed)
114
- return update(id, resolve(change, confirmed));
121
+ if (confirmed) {
122
+ const built = resolve(change, confirmed);
123
+ return update(id, withVersion ? withVersion(built, confirmed) : built);
124
+ }
115
125
  // The screen holds the record somewhere these keys don't reach (a
116
126
  // query gathering a related list's records, say). An object change
117
127
  // needs no current record, so it's still sent; a function change
@@ -147,6 +157,10 @@ export function recordUpdateMutationOptions(queryClient, { id, detailKey, listsK
147
157
  const record = state.confirmed;
148
158
  const sent = record ? resolve(change, record) : typeof change === 'function' ? undefined : change;
149
159
  settle(state, context.entry);
160
+ // Another writer saved since: show what they saved (the detail;
161
+ // the lists refetch once the last save settles, in settle).
162
+ if (error.kind === 'conflict')
163
+ void queryClient.invalidateQueries({ queryKey: detailKey });
150
164
  if (toastOnError)
151
165
  toast.error(`Couldn't update ${record ? name(record) : 'this record'}: ${refusalReason(error, sent)}`);
152
166
  }
@@ -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