@tristan2828/ui-foundation 4.152.0 → 4.154.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.
package/README.md CHANGED
@@ -18,7 +18,7 @@ than installing this by hand:
18
18
 
19
19
  | Import | What |
20
20
  |---|---|
21
- | `@tristan2828/ui-foundation` | The composites and what goes with them: `AppShell`, `DataTable`, `EntityView` (with editing in place: `EditableValue`, `editInPlace`, `inPlace`; `EditInPlaceScope` runs it on a page of the app's own), `EntityForm`, `FormDialog`, `RecordDialogRoute`, `Markdown`, `RichTextEditor` (and `preloadRichTextEditor`), `ErrorState`, `FoundationProviders`, `LoginRoute`, `RegisterRoute`; the hooks `useAuth`, `useTableUrlState`, `useRecordUpdate`; `createQueryClient`, `cn`; types `Page`, `AppError`, `QuerySpec`. The full list is the package's type declarations (`dist/index.d.ts`); what each part is for is in the app's `docs/foundation/` |
21
+ | `@tristan2828/ui-foundation` | The composites and what goes with them: `AppShell`, `DataTable`, `EntityView` (with editing in place: `EditableValue`, `editInPlace`, `inPlace`; `EditInPlaceScope` runs it on a page of the app's own), `EntityForm`, `FormDialog`, `RecordDialogRoute`, `Markdown`, `RichTextEditor` (and `preloadRichTextEditor`, `holdKeysForNextEditor`), `ErrorState`, `FoundationProviders`, `LoginRoute`, `RegisterRoute`; the hooks `useAuth`, `useTableUrlState`, `useRecordUpdate`; `createQueryClient`, `cn`; types `Page`, `AppError`, `QuerySpec`. The full list is the package's type declarations (`dist/index.d.ts`); what each part is for is in the app's `docs/foundation/` |
22
22
  | `@tristan2828/ui-foundation/ui/<name>` | shadcn primitives: alert, badge, breadcrumb, button, calendar, card, checkbox, collapsible, combobox, dialog, dropdown-menu, empty, field, input, input-group, label, popover, progress, radio-group, select, separator, sheet, sidebar, skeleton, slider, sonner, spinner, switch, table, tabs, textarea, toggle, toggle-group, tooltip |
23
23
  | `@tristan2828/ui-foundation/gateway` | `safeFetch`, `toAppError`, `networkError`, `proxyAuthError` — for an app's `src/api/gateway/` only |
24
24
  | `@tristan2828/ui-foundation/mocks` | MSW: `authHandlers`, `environmentHandlers`, `clientErrorHandlers`, `pushHandlers`, `resetMockAuth`, `getMockCurrentUser`, `MOCK_USER`, `startMockWorker` (mock mode's boot), `exposeMswForE2E`, among others (`dist/mocks/index.d.ts`) |
@@ -26,26 +26,26 @@
26
26
  - [A variant: a pressed icon inside another value's cell](#a-variant-a-pressed-icon-inside-another-values-cell) · lines 636–715
27
27
  - [16. Title linking to the record's view](#16-title-linking-to-the-records-view) · lines 717–758
28
28
  - [17. Quick action on the view](#17-quick-action-on-the-view) · lines 760–832
29
- - [18. Editable value](#18-editable-value) · lines 834–1661
30
- - [Presets: one line per field](#presets-one-line-per-field) · lines 1233–1305
31
- - [Several fields edited as one](#several-fields-edited-as-one) · lines 1307–1343
32
- - [A link and its label](#a-link-and-its-label) · lines 1345–1369
33
- - [A list of sub-items](#a-list-of-sub-items) · lines 1371–1504
34
- - [On a page of the app's own: `EditInPlaceScope`](#on-a-page-of-the-apps-own-editinplacescope) · lines 1506–1578
35
- - [In a table's rows](#in-a-tables-rows) · lines 1580–1654
36
- - [A table of a few short columns: `width="content"`](#a-table-of-a-few-short-columns-widthcontent) · lines 1656–1661
37
- - [19. Stage circle for an ordered status](#19-stage-circle-for-an-ordered-status) · lines 1663–1729
38
- - [20. Count linking to the related records](#20-count-linking-to-the-related-records) · lines 1731–1785
39
- - [21. Rows grouped under headings, and a pill filter](#21-rows-grouped-under-headings-and-a-pill-filter) · lines 1787–1869
40
- - [22. A highlighted row, and rows that are done](#22-a-highlighted-row-and-rows-that-are-done) · lines 1871–1896
41
- - [28. A list's rows: hover, lines, rows per page](#28-a-lists-rows-hover-lines-rows-per-page) · lines 1898–1931
42
- - [23. A Group menu, and a record read beside the list](#23-a-group-menu-and-a-record-read-beside-the-list) · lines 1933–1984
43
- - [24. A stored colour beside its name](#24-a-stored-colour-beside-its-name) · lines 1986–2060
44
- - [Picking one on a form: `ColorField`](#picking-one-on-a-form-colorfield) · lines 2006–2060
45
- - [25. A list's tools: views, filters, columns, row actions, a phone's rows](#25-a-lists-tools-views-filters-columns-row-actions-a-phones-rows) · lines 2062–2274
46
- - [The framed look, and sibling lists beside the title](#the-framed-look-and-sibling-lists-beside-the-title) · lines 2223–2274
47
- - [26. A record's related list, capped](#26-a-records-related-list-capped) · lines 2276–2310
48
- - [27. A repeat and its next time](#27-a-repeat-and-its-next-time) · lines 2312–2359
29
+ - [18. Editable value](#18-editable-value) · lines 834–1696
30
+ - [Presets: one line per field](#presets-one-line-per-field) · lines 1240–1312
31
+ - [Several fields edited as one](#several-fields-edited-as-one) · lines 1314–1350
32
+ - [A link and its label](#a-link-and-its-label) · lines 1352–1376
33
+ - [A list of sub-items](#a-list-of-sub-items) · lines 1378–1511
34
+ - [On a page of the app's own: `EditInPlaceScope`](#on-a-page-of-the-apps-own-editinplacescope) · lines 1513–1613
35
+ - [In a table's rows](#in-a-tables-rows) · lines 1615–1689
36
+ - [A table of a few short columns: `width="content"`](#a-table-of-a-few-short-columns-widthcontent) · lines 1691–1696
37
+ - [19. Stage circle for an ordered status](#19-stage-circle-for-an-ordered-status) · lines 1698–1764
38
+ - [20. Count linking to the related records](#20-count-linking-to-the-related-records) · lines 1766–1820
39
+ - [21. Rows grouped under headings, and a pill filter](#21-rows-grouped-under-headings-and-a-pill-filter) · lines 1822–1904
40
+ - [22. A highlighted row, and rows that are done](#22-a-highlighted-row-and-rows-that-are-done) · lines 1906–1931
41
+ - [28. A list's rows: hover, lines, rows per page](#28-a-lists-rows-hover-lines-rows-per-page) · lines 1933–1966
42
+ - [23. A Group menu, and a record read beside the list](#23-a-group-menu-and-a-record-read-beside-the-list) · lines 1968–2019
43
+ - [24. A stored colour beside its name](#24-a-stored-colour-beside-its-name) · lines 2021–2095
44
+ - [Picking one on a form: `ColorField`](#picking-one-on-a-form-colorfield) · lines 2041–2095
45
+ - [25. A list's tools: views, filters, columns, row actions, a phone's rows](#25-a-lists-tools-views-filters-columns-row-actions-a-phones-rows) · lines 2097–2309
46
+ - [The framed look, and sibling lists beside the title](#the-framed-look-and-sibling-lists-beside-the-title) · lines 2258–2309
47
+ - [26. A record's related list, capped](#26-a-records-related-list-capped) · lines 2311–2345
48
+ - [27. A repeat and its next time](#27-a-repeat-and-its-next-time) · lines 2347–2394
49
49
 
50
50
  <!-- /index -->
51
51
 
@@ -1027,8 +1027,11 @@ nobody has to click away to save notes. Opt in per field:
1027
1027
  the next save waits for the one in flight and sends whatever the text
1028
1028
  is by then, so saves never cross and the latest always wins.
1029
1029
  - Under the text, a quiet line in the muted caption tone
1030
- (`role="status"`): "Saving…" with a spinner while a save is in flight,
1031
- "Saved" with a check once nothing typed is waiting. **On a note longer
1030
+ (`role="status"`, named "Save Status"): "Saving…" with a spinner while a save is in flight,
1031
+ "Saved" with a check once nothing typed is waiting. An editor with
1032
+ `upload` has a live region of its own beside it, named "Uploads", so a
1033
+ test finds the save line by its name:
1034
+ `field.getByRole('status', { name: 'Save Status' })`. **On a note longer
1032
1035
  than the screen the line is pinned to the screen's bottom edge** while
1033
1036
  the note runs past it, so the save's state and a refusal are never off
1034
1037
  screen.
@@ -1184,7 +1187,7 @@ const price = editInPlace({
1184
1187
  table); typing filters ("/warn" finds a warning callout), Enter or Tab
1185
1188
  picks, and Esc closes the list before it gives up the edit. A callout
1186
1189
  is GitHub's `> [!NOTE]` (note, tip, important, warning, caution), its
1187
- icon a menu of kinds. In a table, Tab in the last cell adds a row,
1190
+ icon a menu of kinds; typed, `> [!NOTE]` and Enter makes one. In a table, Tab in the last cell adds a row,
1188
1191
  Enter goes down a column (and out from the last row), bars under and
1189
1192
  beside it add a row or a column, and a grip on the hovered column and
1190
1193
  row opens its menu: insert, move and delete, align, sort (rewriting the
@@ -1206,8 +1209,11 @@ const price = editInPlace({
1206
1209
  toolbar is instead one row pinned to the top of the keyboard while the
1207
1210
  field has focus (Aa for every format, in the keyboard's place; the list
1208
1211
  buttons, Insert, Image (with `upload`) and Undo; with words selected, their formats first, and
1209
- no floating bar under the system's Copy bar), and the checkbox, the
1210
- table grips, the fold button and the callout icon take a 40px tap. A new checklist item
1212
+ no floating bar under the system's Copy bar; its buttons a finger's
1213
+ 44px), and the checkbox, the
1214
+ table grips, the fold button and the callout icon take a 40px tap. A
1215
+ pasted or uploaded image that ends its line leaves the caret on a new
1216
+ line under it. A new checklist item
1211
1217
  shows a "To-do" placeholder and the caret until you type. `[] ` (or
1212
1218
  `[x] `) at a line's start makes it a checklist item, a bulleted item
1213
1219
  too; Enter in one makes the next, its box unticked, and Enter in an
@@ -1219,7 +1225,8 @@ const price = editInPlace({
1219
1225
  app's `upload` (the same one `ImageField` takes) and an image pasted,
1220
1226
  dropped or picked with an Image button (the fixed toolbar's, the tools
1221
1227
  strip's, the phone's row) is uploaded and goes
1222
- in as `![](url)`, a placeholder showing meanwhile (never saved), a
1228
+ in as `![](url)`, a placeholder showing meanwhile (never saved, and
1229
+ read out from a live region named "Uploads"), a
1223
1230
  refusal or failure in a toast. No `upload`, no file handling at all.
1224
1231
  - **The save is the single-field save** (`useRecordUpdate` with
1225
1232
  `optimistic: false, toastOnError: false`, the entity's
@@ -1542,6 +1549,21 @@ const body = editInPlace<string>({
1542
1549
  a key typed at once lands where it was; don't focus the editable
1543
1550
  element through the DOM, which leaves the caret at the text's start
1544
1551
  for a moment.
1552
+ - **A tab switch through the router with `flushSync`** (React Router's
1553
+ `flushSync: true` on `navigate`, so the tab in front is drawn in the
1554
+ same task as the key that moved it) needs `RouterProvider` imported
1555
+ from `react-router/dom`, not `react-router`: only that one hands the
1556
+ router's updates to `flushSync`. With the other, the hidden tab is
1557
+ still in front for a moment, and a key typed right after the switch
1558
+ goes into it.
1559
+ - **An outline beside a long note** is `NotesOutline`, given the note's
1560
+ Markdown and the editor's `foldKey`: its headings as a list to jump
1561
+ with (each opens its section and brings it into view), with Fold All
1562
+ and Open All. Put it beside the editor (in a rail, or above the note
1563
+ on a phone), fed the value the editor last reported. It parses the
1564
+ whole note on every change, so a page with several mounted editors
1565
+ (a notes app's tabs) renders one outline, for the note in front,
1566
+ never one per pane.
1545
1567
  - **An editor that is the page** (a note the app opens on) takes
1546
1568
  `autoFocus="end"`, the caret after its last words, in view, and
1547
1569
  `tabStaysInText`: Tab on a plain line stays in the text (Esc, then
@@ -1560,8 +1582,10 @@ const body = editInPlace<string>({
1560
1582
  closed, a pane unmounted): what was typed goes at once rather than
1561
1583
  after the pause, and a value whose save had been refused tries once
1562
1584
  more. If that save fails, nothing on screen holds the text any more,
1563
- so a toast says "Couldn't save *label*" with the reason and stays until
1564
- dismissed, with **Copy Text** to put what was typed on the clipboard.
1585
+ so a toast says "*Label* wasn't saved and is no longer on the page"
1586
+ (not a refusal's "Couldn't save *label*", which can still be retried
1587
+ where it is) with the reason, and stays until dismissed, with
1588
+ **Copy Text** to put what was typed on the clipboard.
1565
1589
  `onLostEdit`, given `{ label, value, reason }` (`LostEdit`), is for the
1566
1590
  app to do more, such as reopen the note's tab. A record's view and a
1567
1591
  table toast the same way.
@@ -1572,6 +1596,17 @@ const body = editInPlace<string>({
1572
1596
  when one mounts, and the next editor to mount tries again. Keys typed
1573
1597
  into an `autoFocus` editor while its code still loads are kept, and
1574
1598
  typed in once it's up.
1599
+ - **Keys typed before the editor mounts:** call
1600
+ `holdKeysForNextEditor()` on the press that leads to a note (New
1601
+ Note, before its request) and, for a cold start, in `main.tsx` beside
1602
+ `preloadRichTextEditor()`. Until the next `autoFocus` editor mounts,
1603
+ what's typed is held (not delivered to the page, so Enter doesn't
1604
+ press New Note again) and typed into it in order, an IME's composition
1605
+ included. It never takes focus from an input, and lets go, dropping
1606
+ what it held, when focus moves to another control, on a click
1607
+ elsewhere, on Esc, or after `timeout` (5 s); call the function it
1608
+ returns to let go yourself (the request failed). It also starts
1609
+ loading the editor's code.
1575
1610
 
1576
1611
  The stories are `app/EditInPlaceScope` (one note, two in one scope, and
1577
1612
  the two as URL tabs with `staysOnPage`);
@@ -35,6 +35,8 @@ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-run
35
35
  // line under it, and "Saved" goes after two seconds, as at rest.
36
36
  // - Saved: once a save lands, "✓ Saved" shows beside the value
37
37
  // for two seconds (`role="status"`).
38
+ // - Each of its live regions ("Saving…", "Saved") is named "Save Status",
39
+ // so a test finds it by name beside the editor's own ("Uploads").
38
40
  // - `layout="inline"`: the pencil takes no room until hover or
39
41
  // focus, so nothing gaps before what follows the value on its line.
40
42
  // `keepPencilRoom` (and every value inside a KeyStats) keeps it
@@ -60,6 +62,8 @@ import { EditInPlaceContext } from './edit-in-place.js';
60
62
  import { SAVED_FOR_MS } from './edit-row.js';
61
63
  import { escapePassedThrough } from './escape-passthrough.js';
62
64
  import { KeepPencilRoomContext } from './keep-pencil-room.js';
65
+ // The save line's accessible name, on every live region it uses.
66
+ const SAVE_STATUS = 'Save Status';
63
67
  // What a click on the shown value must leave alone: links navigate,
64
68
  // buttons and boxes do their own thing (a list item's done box ticks it).
65
69
  const INTERACTIVE = 'a[href], button, input, select, textarea, label, [role="button"], [role="link"], [role="checkbox"], [role="switch"]';
@@ -439,7 +443,7 @@ export function EditableField({ label, edit, children, layout = 'block', look =
439
443
  // grow with --spacing, and a fixed 0.75rem left the record's
440
444
  // title 3-5px short of its one line (4.145).
441
445
  layout === 'block' ? 'flex w-full' : cn('inline-flex align-top', row ? 'max-w-full' : 'max-w-[calc(100%+var(--spacing)*3)]'), className), children: [_jsxs("span", { className: cn('min-w-0 flex-1', !row &&
442
- 'group-hover/editable:[&_.text-muted-foreground]:text-foreground group-has-[[data-edit]:focus-visible]/editable:[&_.text-muted-foreground]:text-foreground'), children: [children !== undefined ? children : edit.shown, _jsx("span", { role: "status", "data-slot": "editable-value-saved", className: "ml-2 inline-flex items-center gap-1 align-baseline type-caption text-success-text empty:hidden", children: justSaved && (_jsxs(_Fragment, { children: [_jsx(CheckIcon, { "aria-hidden": "true", className: "size-3.5" }), "Saved"] })) })] }), _jsx(InlinePencilRoom, { inline: inlineValue, children: _jsx(Button, { ref: editButton, "data-edit": "", type: "button", variant: "ghost", size: "icon-xs", "aria-label": `Edit ${label}`, onClick: start, className: cn('shrink-0 text-muted-foreground opacity-0 focus-visible:opacity-100 pointer-coarse:opacity-100', row ? 'group-hover/edit-row:opacity-100 hover:bg-transparent max-md:opacity-100' : 'group-hover/editable:opacity-100', inlineValue && 'absolute top-0 left-1 z-10'), children: row ? (_jsxs(_Fragment, { children: [_jsx(PencilIcon, { className: "max-md:hidden pointer-coarse:hidden" }), _jsx(ChevronRightIcon, { className: "hidden max-md:block pointer-coarse:block" })] })) : (_jsx(PencilIcon, {})) }) })] }));
446
+ 'group-hover/editable:[&_.text-muted-foreground]:text-foreground group-has-[[data-edit]:focus-visible]/editable:[&_.text-muted-foreground]:text-foreground'), children: [children !== undefined ? children : edit.shown, _jsx("span", { role: "status", "aria-label": SAVE_STATUS, "data-slot": "editable-value-saved", className: "ml-2 inline-flex items-center gap-1 align-baseline type-caption text-success-text empty:hidden", children: justSaved && (_jsxs(_Fragment, { children: [_jsx(CheckIcon, { "aria-hidden": "true", className: "size-3.5" }), "Saved"] })) })] }), _jsx(InlinePencilRoom, { inline: inlineValue, children: _jsx(Button, { ref: editButton, "data-edit": "", type: "button", variant: "ghost", size: "icon-xs", "aria-label": `Edit ${label}`, onClick: start, className: cn('shrink-0 text-muted-foreground opacity-0 focus-visible:opacity-100 pointer-coarse:opacity-100', row ? 'group-hover/edit-row:opacity-100 hover:bg-transparent max-md:opacity-100' : 'group-hover/editable:opacity-100', inlineValue && 'absolute top-0 left-1 z-10'), children: row ? (_jsxs(_Fragment, { children: [_jsx(PencilIcon, { className: "max-md:hidden pointer-coarse:hidden" }), _jsx(ChevronRightIcon, { className: "hidden max-md:block pointer-coarse:block" })] })) : (_jsx(PencilIcon, {})) }) })] }));
443
447
  }
444
448
  // Always editable, before the store has it (the first render): the saved value.
445
449
  const open = state.status === 'closed' ? { status: 'open', draft: edit.value, error: null, autosave: undefined, revision: 0 } : state;
@@ -459,9 +463,9 @@ export function EditableField({ label, edit, children, layout = 'block', look =
459
463
  // it, so the save's state and a refusal stay in view.
460
464
  style: pin ? { left: pin.left, maxWidth: pin.width } : undefined, className: cn('type-body',
461
465
  // Beside the value, a refusal takes the line under it.
462
- beside && (lineError ? 'basis-full' : 'flex items-center'), pin && 'fixed bottom-3 z-30 w-fit rounded-md border border-border bg-popover px-2 py-1 text-popover-foreground shadow-md'), children: autosave ? (_jsxs(_Fragment, { children: [lineError && _jsx(FieldError, { className: "type-caption", children: lineError }), conflictActions, _jsx("span", { role: "status", className: "inline-flex items-center gap-1.5 type-caption text-muted-foreground", children: autosaving ? (_jsxs(_Fragment, { children: [_jsx(Spinner, { "aria-hidden": "true", className: "size-3.5" }), _jsx("span", { className: cn(beside && 'sr-only'), children: "Saving\u2026" })] })) : (open.autosave === 'saved' &&
466
+ beside && (lineError ? 'basis-full' : 'flex items-center'), pin && 'fixed bottom-3 z-30 w-fit rounded-md border border-border bg-popover px-2 py-1 text-popover-foreground shadow-md'), children: autosave ? (_jsxs(_Fragment, { children: [lineError && _jsx(FieldError, { className: "type-caption", children: lineError }), conflictActions, _jsx("span", { role: "status", "aria-label": SAVE_STATUS, className: "inline-flex items-center gap-1.5 type-caption text-muted-foreground", children: autosaving ? (_jsxs(_Fragment, { children: [_jsx(Spinner, { "aria-hidden": "true", className: "size-3.5" }), _jsx("span", { className: cn(beside && 'sr-only'), children: "Saving\u2026" })] })) : (open.autosave === 'saved' &&
463
467
  !open.error &&
464
- !(beside && savedGone) && (_jsxs(_Fragment, { children: [_jsx(CheckIcon, { "aria-hidden": "true", className: cn('size-3.5', beside && 'text-success-text') }), _jsx("span", { className: cn(beside && 'sr-only'), children: "Saved" })] }))) })] })) : saving ? (_jsxs("span", { role: "status", className: "inline-flex items-center gap-1.5 type-caption text-muted-foreground", children: [_jsx(Spinner, { "aria-hidden": "true", className: "size-3.5" }), "Saving\u2026"] })) : (_jsxs(_Fragment, { children: [lineError && _jsx(FieldError, { className: "type-caption", children: lineError }), conflictActions] })) })] }), _jsx(DiscardChangesDialog, { open: askingDiscard, "data-leave-guard": "", onKeepEditing: () => setAskingDiscard(false), onDiscard: () => {
468
+ !(beside && savedGone) && (_jsxs(_Fragment, { children: [_jsx(CheckIcon, { "aria-hidden": "true", className: cn('size-3.5', beside && 'text-success-text') }), _jsx("span", { className: cn(beside && 'sr-only'), children: "Saved" })] }))) })] })) : saving ? (_jsxs("span", { role: "status", "aria-label": SAVE_STATUS, className: "inline-flex items-center gap-1.5 type-caption text-muted-foreground", children: [_jsx(Spinner, { "aria-hidden": "true", className: "size-3.5" }), "Saving\u2026"] })) : (_jsxs(_Fragment, { children: [lineError && _jsx(FieldError, { className: "type-caption", children: lineError }), conflictActions] })) })] }), _jsx(DiscardChangesDialog, { open: askingDiscard, "data-leave-guard": "", onKeepEditing: () => setAskingDiscard(false), onDiscard: () => {
465
469
  setAskingDiscard(false);
466
470
  refocus.current = true;
467
471
  cancel();
@@ -9,8 +9,10 @@ import { toast } from 'sonner';
9
9
  */
10
10
  export function toastLostEdit({ label, value, reason }) {
11
11
  const text = typeof value === 'string' && value.trim() !== '' ? value : null;
12
- const id = toast.error(`Couldn't save ${label}`, {
13
- description: text ? `${reason} It's no longer on the page: copy what you typed to keep it.` : reason,
12
+ // Its own title, not a refusal's "Couldn't save <label>": that one is
13
+ // still on the page to retry, this one only Copy Text can get back.
14
+ const id = toast.error(`${label} wasn't saved and is no longer on the page`, {
15
+ description: text ? `${reason} Copy what you typed to keep it.` : reason,
14
16
  duration: Infinity,
15
17
  action: text
16
18
  ? {
@@ -55,6 +55,8 @@ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-run
55
55
  // - Images show at most the field's width. With `upload`, an image pasted,
56
56
  // dropped or picked is uploaded through it and goes in as `![](url)`
57
57
  // (rich-text-image-upload.ts); a refusal or a failed upload is a toast.
58
+ // What's uploading is read from a live region named "Uploads"
59
+ // (`role="status"`, empty while nothing uploads).
58
60
  // - `foldKey`: the text folds by its toggle headings, as <Markdown> does
59
61
  // (rich-text-fold.ts), remembered on this device and shared with
60
62
  // NotesOutline; the document never changes.
@@ -75,7 +77,7 @@ import { useInRouterContext, useNavigate } from 'react-router';
75
77
  import { defaultValueCtx, Editor, editorViewCtx, editorViewOptionsCtx, parserCtx, remarkStringifyOptionsCtx, rootCtx, schemaCtx, serializerCtx, } from '@milkdown/kit/core';
76
78
  import { history } from '@milkdown/kit/plugin/history';
77
79
  import { commands, headingSchema, paragraphSchema, keymap, plugins, remarkPreserveEmptyLinePlugin, schema, } from '@milkdown/kit/preset/commonmark';
78
- import { gfm, tableCellSchema, tableHeaderSchema, tableSchema } from '@milkdown/kit/preset/gfm';
80
+ import { extendListItemSchemaForTask, gfm, tableCellSchema, tableHeaderSchema, tableSchema } from '@milkdown/kit/preset/gfm';
79
81
  import { NodeSelection, Plugin, Selection, TextSelection } from '@milkdown/kit/prose/state';
80
82
  import { isInTable, selectedRect, TableMap } from '@milkdown/kit/prose/tables';
81
83
  import { Decoration, DecorationSet } from '@milkdown/kit/prose/view';
@@ -233,6 +235,16 @@ const headerWithWidth = tableHeaderSchema.extendSchema((previous) => (ctx) => {
233
235
  const base = previous(ctx);
234
236
  return { ...base, parseMarkdown: { match: base.parseMarkdown.match, runner: readCell } };
235
237
  });
238
+ // A list item is tight unless the Markdown it came from was loose: one
239
+ // made by typing (`- `, Enter, Tab) is tight, as a list written by hand
240
+ // is, and Enter in a loose list's item makes another loose one (a new
241
+ // item copies the one it split from). Milkdown's default was loose, so a
242
+ // typed item that held a nested list was written with a blank line
243
+ // before it. GFM's task item, which this extends, keeps its tick.
244
+ const tightListItem = extendListItemSchemaForTask.extendSchema((previous) => (ctx) => {
245
+ const base = previous(ctx);
246
+ return { ...base, attrs: { ...base.attrs, spread: { default: false, validate: 'boolean' } } };
247
+ });
236
248
  function emptyImageTitles(node) {
237
249
  if (node.type === 'image' && node.title == null)
238
250
  node.title = '';
@@ -846,6 +858,7 @@ export default function MilkdownEditor({ id, defaultValue, onChange, onProblem,
846
858
  .use(edges)
847
859
  .use(COMMONMARK)
848
860
  .use(gfm)
861
+ .use(tightListItem)
849
862
  .use(taskInputRule)
850
863
  .use(toggleHeadingRemark)
851
864
  .use(toggleHeadingInputRule)
@@ -1333,7 +1346,7 @@ export default function MilkdownEditor({ id, defaultValue, onChange, onProblem,
1333
1346
  const next = event.relatedTarget;
1334
1347
  if (!editorView.dom.contains(next) && !inFloating(next))
1335
1348
  setFocused(false);
1336
- } }))] }), upload && (_jsx("p", { role: "status", className: "sr-only", children: uploading > 0 ? `Uploading ${uploading === 1 ? 'an image' : `${uploading} images`}…` : '' })), showCount && (_jsx("p", { id: counterId, "data-slot": "rich-text-editor-count", className: cn('text-right type-caption tabular-nums', length > maxLength ? 'text-destructive-text' : 'text-muted-foreground'), children: length > maxLength
1349
+ } }))] }), upload && (_jsx("p", { role: "status", "aria-label": "Uploads", className: "sr-only", children: uploading > 0 ? `Uploading ${uploading === 1 ? 'an image' : `${uploading} images`}…` : '' })), showCount && (_jsx("p", { id: counterId, "data-slot": "rich-text-editor-count", className: cn('text-right type-caption tabular-nums', length > maxLength ? 'text-destructive-text' : 'text-muted-foreground'), children: length > maxLength
1337
1350
  ? `${(length - maxLength).toLocaleString()} characters over the limit of ${maxLength.toLocaleString()}`
1338
1351
  : `${length.toLocaleString()} of ${maxLength.toLocaleString()} characters` })), inRouter && _jsx(NavigateBridge, { targetRef: navigateRef }), _jsx(Popover, { open: pageBox !== null, onOpenChange: (open) => !open && !pageBusy && closePage(), children: pageBox && _jsx(PageForm, { box: pageBox, busy: pageBusy, onCreate: createPage }) }), _jsx(Popover, { open: linkBox !== null, onOpenChange: (open) => !open && closeLink(), children: linkBox && (_jsx(LinkForm, { box: linkBox, onApply: (href) => {
1339
1352
  const editor = editorRef.current;
@@ -48,7 +48,9 @@ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-run
48
48
  // an editor loads it ahead with `preloadRichTextEditor()`. Once loaded it's
49
49
  // drawn at once; a load that failed is tried again by the next editor. Keys
50
50
  // typed into an `autoFocus` editor while it loads are held and typed in
51
- // once it's up (rich-text-held-keys.ts), and saved.
51
+ // once it's up (rich-text-held-keys.ts), and saved; so are keys typed
52
+ // before it mounted, after `holdKeysForNextEditor()` (a New Note press, an
53
+ // app's start; rich-text-hold-keys.ts).
52
54
  //
53
55
  // What Markdown can't hold isn't saved: spaces at a line's start or end
54
56
  // (rich-text-empty-paragraph.ts; inline code keeps its own) and blank lines
@@ -57,6 +59,7 @@ import { lazy, Suspense, useLayoutEffect, useRef, useState } from 'react';
57
59
  import { cn } from 'cn';
58
60
  import { Skeleton } from '../ui/skeleton.js';
59
61
  import { Markdown } from './markdown.js';
62
+ import { claimKeyHold, keyHoldWaiting } from './rich-text-hold-keys.js';
60
63
  import { loadedRichTextEditor, loadRichTextEditor } from './rich-text-load.js';
61
64
  // When the editor opens again: each time `defaultValue` changes to
62
65
  // Markdown it didn't report. Adjusted while rendering (React's "storing
@@ -92,14 +95,31 @@ export function RichTextEditor(props) {
92
95
  // typed meanwhile, and the editor types them in once it's up
93
96
  // (rich-text-held-keys.ts). Beside the Suspense boundary, not in its
94
97
  // fallback, which goes the moment the editor's code arrives.
95
- const [holding, setHolding] = useState(() => loadedRichTextEditor() === null && Boolean(props.autoFocus) && !props.readOnly);
98
+ // Keys held from before this editor mounted (`holdKeysForNextEditor()`,
99
+ // rich-text-hold-keys.ts) are taken over instead, loaded or not.
100
+ const [adopting] = useState(() => Boolean(props.autoFocus) && !props.readOnly && keyHoldWaiting());
101
+ const [holding, setHolding] = useState(() => adopting || (loadedRichTextEditor() === null && Boolean(props.autoFocus) && !props.readOnly));
96
102
  const heldRef = useRef(null);
97
103
  const composing = useRef(false);
104
+ const claimed = useRef(null);
98
105
  const [held] = useState(() => ({
99
- element: () => heldRef.current,
100
- composing: () => composing.current,
101
- release: () => setHolding(false),
106
+ element: () => (adopting ? (claimed.current?.element() ?? null) : heldRef.current),
107
+ composing: () => (adopting ? (claimed.current?.composing() ?? false) : composing.current),
108
+ release: () => {
109
+ claimed.current?.release();
110
+ claimed.current = null;
111
+ setHolding(false);
112
+ },
102
113
  }));
114
+ useLayoutEffect(() => {
115
+ if (!adopting)
116
+ return;
117
+ claimed.current = claimKeyHold();
118
+ return () => {
119
+ claimed.current?.giveBack();
120
+ claimed.current = null;
121
+ };
122
+ }, [adopting]);
103
123
  // The `focusKey` last acted on: kept here, so neither a load nor a
104
124
  // remount (a reset) takes an unchanged key for a new one.
105
125
  const focusHandled = useRef(props.focusKey);
@@ -109,7 +129,7 @@ export function RichTextEditor(props) {
109
129
  focusHandled.current = key;
110
130
  return true;
111
131
  });
112
- return (_jsxs(_Fragment, { children: [holding && (_jsx("textarea", { ref: heldRef, id: props.id, "data-slot": "rich-text-editor-held", autoFocus: true, "aria-label": props['aria-label'], "aria-labelledby": props['aria-labelledby'], "aria-describedby": props['aria-describedby'], className: "sr-only", onCompositionStart: () => (composing.current = true), onCompositionEnd: () => (composing.current = false) })), _jsx(Suspense, { fallback: _jsxs("div", { "data-slot": "rich-text-editor", "data-state": "loading", className: cn('flex w-full flex-col', !props.inline && 'rounded-lg border border-input', props.className), children: [(props.toolbar ?? true) === true && _jsx("div", { className: "h-9 border-b border-input pointer-coarse:hidden" }), _jsx("div", { "aria-busy": "true", className: cn('flex flex-col gap-2', props.inline ? 'py-0.5' : 'min-h-24 px-2.5 py-2',
132
+ return (_jsxs(_Fragment, { children: [holding && !adopting && (_jsx("textarea", { ref: heldRef, id: props.id, "data-slot": "rich-text-editor-held", autoFocus: true, "aria-label": props['aria-label'], "aria-labelledby": props['aria-labelledby'], "aria-describedby": props['aria-describedby'], className: "sr-only", onCompositionStart: () => (composing.current = true), onCompositionEnd: () => (composing.current = false) })), _jsx(Suspense, { fallback: _jsxs("div", { "data-slot": "rich-text-editor", "data-state": "loading", className: cn('flex w-full flex-col', !props.inline && 'rounded-lg border border-input', props.className), children: [(props.toolbar ?? true) === true && _jsx("div", { className: "h-9 border-b border-input pointer-coarse:hidden" }), _jsx("div", { "aria-busy": "true", className: cn('flex flex-col gap-2', props.inline ? 'py-0.5' : 'min-h-24 px-2.5 py-2',
113
133
  // The room of the add-row bar the editor draws under a table.
114
134
  !props.readOnly && '[&_table]:mb-5'), children: props.defaultValue.trim() ? (_jsx(Markdown, { headingLevel: props.headingLevel, headingFrom: props.headingFrom, foldKey: props.foldable === false ? undefined : props.foldKey, children: props.defaultValue })) : (_jsxs(_Fragment, { children: [_jsx(Skeleton, { className: "h-4 w-3/4" }), _jsx(Skeleton, { className: "h-4 w-1/2" })] })) })] }), children: _jsx(MilkdownEditor, { ...props, onChange: (markdown) => {
115
135
  if (live.current !== opening)
@@ -0,0 +1,23 @@
1
+ import type { HeldKeys } from './rich-text-held-keys.js';
2
+ export type HoldKeysOptions = {
3
+ /** How long to wait for an editor, in milliseconds. Default 5000. */
4
+ timeout?: number;
5
+ };
6
+ /**
7
+ * Holds the keys typed from now until the next RichTextEditor with
8
+ * `autoFocus` mounts, which types them in. Call it on the press that
9
+ * leads to an editor (New Note, before its request), or as the app starts
10
+ * when it opens on one. Starts loading the editor's code too. Returns a
11
+ * function that lets go (what was held is dropped), for a press whose
12
+ * editor won't come (the request failed).
13
+ */
14
+ export declare function holdKeysForNextEditor(options?: HoldKeysOptions): () => void;
15
+ /** A hold is waiting for an editor (read as an `autoFocus` editor first renders). */
16
+ export declare function keyHoldWaiting(): boolean;
17
+ /** The editor's side of a hold it took over. */
18
+ export type ClaimedHold = HeldKeys & {
19
+ /** The editor went before it took the keys: the hold waits again. */
20
+ giveBack: () => void;
21
+ };
22
+ /** Takes over the waiting hold, if there is one: from now on it's the editor's to let go. */
23
+ export declare function claimKeyHold(): ClaimedHold | null;
@@ -0,0 +1,145 @@
1
+ import { preloadRichTextEditor } from './rich-text-load.js';
2
+ // The hold waiting for an editor. One taken over by an editor is that
3
+ // editor's, and no longer here.
4
+ let waiting = null;
5
+ const TEXT_INPUT = /^(text|search|email|url|tel|password|number|date|datetime-local|month|week|time)$/;
6
+ function takesText(element) {
7
+ if (!(element instanceof HTMLElement))
8
+ return false;
9
+ if (element.isContentEditable || element instanceof HTMLTextAreaElement || element instanceof HTMLSelectElement)
10
+ return true;
11
+ return element instanceof HTMLInputElement && TEXT_INPUT.test(element.type);
12
+ }
13
+ // Keys that are text (or Enter) stop at the textarea: no listener on the
14
+ // page sees them while they're held. Tab, Esc and shortcuts with Ctrl,
15
+ // Cmd or Alt go on.
16
+ function stopTyped(event) {
17
+ if (event.ctrlKey || event.metaKey || event.altKey)
18
+ return;
19
+ if (event.key === 'Tab' || event.key === 'Escape')
20
+ return;
21
+ event.stopPropagation();
22
+ }
23
+ function makeHold(before, timeout) {
24
+ const area = document.createElement('textarea');
25
+ const hold = { area, composing: false, before, timeout, stop: undefined };
26
+ area.setAttribute('data-slot', 'rich-text-editor-held');
27
+ area.setAttribute('aria-label', 'Note, opening');
28
+ area.className = 'sr-only';
29
+ for (const type of ['keydown', 'keypress', 'keyup'])
30
+ area.addEventListener(type, stopTyped);
31
+ area.addEventListener('compositionstart', () => (hold.composing = true));
32
+ area.addEventListener('compositionend', () => (hold.composing = false));
33
+ return hold;
34
+ }
35
+ // Lets go of a waiting hold: what it held is dropped and, asked to, focus
36
+ // goes back where it was.
37
+ function letGo(hold, giveFocusBack) {
38
+ hold.stop?.();
39
+ if (waiting === hold)
40
+ waiting = null;
41
+ if (giveFocusBack && document.activeElement === hold.area) {
42
+ const before = hold.before;
43
+ if (before instanceof HTMLElement && before.isConnected && before !== document.body)
44
+ before.focus({ preventScroll: true });
45
+ else
46
+ hold.area.blur();
47
+ }
48
+ hold.area.remove();
49
+ }
50
+ // While waiting: focus or a pointer going anywhere else, Esc, or the
51
+ // timeout lets go.
52
+ function listen(hold) {
53
+ const onFocus = (event) => {
54
+ if (event.target !== hold.area)
55
+ letGo(hold, false);
56
+ };
57
+ const onPointer = (event) => {
58
+ if (event.target !== hold.area)
59
+ letGo(hold, false);
60
+ };
61
+ const onKey = (event) => {
62
+ if (event.key === 'Escape')
63
+ letGo(hold, true);
64
+ };
65
+ document.addEventListener('focusin', onFocus, true);
66
+ document.addEventListener('pointerdown', onPointer, true);
67
+ hold.area.addEventListener('keydown', onKey);
68
+ const timer = setTimeout(() => letGo(hold, true), hold.timeout);
69
+ hold.stop = () => {
70
+ document.removeEventListener('focusin', onFocus, true);
71
+ document.removeEventListener('pointerdown', onPointer, true);
72
+ hold.area.removeEventListener('keydown', onKey);
73
+ clearTimeout(timer);
74
+ hold.stop = undefined;
75
+ };
76
+ }
77
+ /**
78
+ * Holds the keys typed from now until the next RichTextEditor with
79
+ * `autoFocus` mounts, which types them in. Call it on the press that
80
+ * leads to an editor (New Note, before its request), or as the app starts
81
+ * when it opens on one. Starts loading the editor's code too. Returns a
82
+ * function that lets go (what was held is dropped), for a press whose
83
+ * editor won't come (the request failed).
84
+ */
85
+ export function holdKeysForNextEditor(options = {}) {
86
+ if (typeof document === 'undefined')
87
+ return () => { };
88
+ preloadRichTextEditor();
89
+ const timeout = options.timeout ?? 5000;
90
+ const focused = document.activeElement;
91
+ let hold = waiting;
92
+ if (hold) {
93
+ hold.stop?.();
94
+ hold.timeout = timeout;
95
+ }
96
+ else {
97
+ if (takesText(focused))
98
+ return () => { };
99
+ hold = makeHold(focused, timeout);
100
+ document.body.append(hold.area);
101
+ waiting = hold;
102
+ }
103
+ if (focused !== hold.area && !takesText(focused)) {
104
+ hold.before = focused;
105
+ hold.area.focus({ preventScroll: true });
106
+ }
107
+ listen(hold);
108
+ const mine = hold;
109
+ return () => {
110
+ if (waiting === mine)
111
+ letGo(mine, true);
112
+ };
113
+ }
114
+ /** A hold is waiting for an editor (read as an `autoFocus` editor first renders). */
115
+ export function keyHoldWaiting() {
116
+ return waiting !== null;
117
+ }
118
+ /** Takes over the waiting hold, if there is one: from now on it's the editor's to let go. */
119
+ export function claimKeyHold() {
120
+ const hold = waiting;
121
+ if (!hold)
122
+ return null;
123
+ hold.stop?.();
124
+ waiting = null;
125
+ let done = false;
126
+ return {
127
+ element: () => (done ? null : hold.area),
128
+ composing: () => hold.composing,
129
+ release: () => {
130
+ done = true;
131
+ hold.area.remove();
132
+ },
133
+ giveBack: () => {
134
+ if (done)
135
+ return;
136
+ done = true;
137
+ if (waiting || !hold.area.isConnected) {
138
+ hold.area.remove();
139
+ return;
140
+ }
141
+ waiting = hold;
142
+ listen(hold);
143
+ },
144
+ };
145
+ }
@@ -9,7 +9,9 @@
9
9
  // it is. It moves with the text around it, and what's typed at the caret
10
10
  // meanwhile goes after it, as if the image were already there; when the
11
11
  // upload resolves, the image goes in where it is now and the placeholder
12
- // goes. If the upload fails, the placeholder goes and `onError` gets the
12
+ // goes. An image that lands at the end of its line, the caret just after
13
+ // it, leaves the caret on a new line under it, so the words typed next
14
+ // are a paragraph of their own. If the upload fails, the placeholder goes and `onError` gets the
13
15
  // reason; if the text around it was deleted meanwhile, the image is
14
16
  // dropped.
15
17
  //
@@ -20,8 +22,8 @@
20
22
  // the view draws it), so its rules are unit tested in node
21
23
  // (tests/rich-text-image-upload.test.ts).
22
24
  import { Fragment, Slice } from '@milkdown/kit/prose/model';
23
- import { Plugin, PluginKey } from '@milkdown/kit/prose/state';
24
- import { dropPoint } from '@milkdown/kit/prose/transform';
25
+ import { Plugin, PluginKey, TextSelection } from '@milkdown/kit/prose/state';
26
+ import { canSplit, dropPoint } from '@milkdown/kit/prose/transform';
25
27
  import { Decoration, DecorationSet } from '@milkdown/kit/prose/view';
26
28
  import { imageRefusal, uploadFailure } from '../../lib/image-file.js';
27
29
  const uploadKey = new PluginKey('rich-text-image-upload');
@@ -94,6 +96,26 @@ function imageNode(state, src) {
94
96
  function insertPoint(doc, pos, image) {
95
97
  return dropPoint(doc, pos, new Slice(Fragment.from(image), 0, 0)) ?? pos;
96
98
  }
99
+ // The caret right after an image that just went in at the end of its line
100
+ // (nothing typed after it meanwhile) goes on to a new line under it, so
101
+ // what's typed next is a paragraph of its own, not words on the image's
102
+ // line. Only where a line may be split into two blocks of their own (the
103
+ // text's top level, a quote, a callout): in a list item a second
104
+ // paragraph would change the list, and a table cell holds one line.
105
+ function lineAfterImage(tr, after) {
106
+ const { selection } = tr;
107
+ if (!selection.empty || selection.from !== after)
108
+ return;
109
+ const $after = tr.doc.resolve(after);
110
+ if ($after.parent.type.name !== 'paragraph' || $after.parentOffset !== $after.parent.content.size)
111
+ return;
112
+ if ($after.depth > 1 && !['blockquote', 'callout'].includes($after.node(-1).type.name))
113
+ return;
114
+ if (!canSplit(tr.doc, after))
115
+ return;
116
+ tr.split(after);
117
+ tr.setSelection(TextSelection.create(tr.doc, after + 2));
118
+ }
97
119
  let nextId = 0;
98
120
  /**
99
121
  * Uploads `files` and inserts each as an image: at `at` (a drop's
@@ -129,7 +151,9 @@ export function uploadImages(target, files, at, options) {
129
151
  const image = imageNode(target.state, outcome.src);
130
152
  const where = insertPoint(next.doc, placeholder, image);
131
153
  next.replaceWith(where, where, image);
132
- next.setMeta(uploadKey, { land: id, at: placeholder, after: next.mapping.map(where, -1) + image.nodeSize });
154
+ const after = next.mapping.map(where, -1) + image.nodeSize;
155
+ next.setMeta(uploadKey, { land: id, at: placeholder, after });
156
+ lineAfterImage(next, after);
133
157
  }
134
158
  else {
135
159
  next.setMeta(uploadKey, { remove: id });
@@ -18,7 +18,9 @@ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-run
18
18
  // the keyboard button in its place brings the keyboard back. Focus stays
19
19
  // in the text the whole time (`inputmode="none"` hides the keyboard), so
20
20
  // the selection and the caret are kept.
21
- // - Its buttons are 40px, on semantic tokens only.
21
+ // - Its buttons are 44px, a finger's (the row is 48px tall, and the
22
+ // buttons between Aa and Hide keyboard scroll sideways on a narrow
23
+ // phone), on semantic tokens only.
22
24
  //
23
25
  // Placed inside the field's element, not in a portal, like the floating
24
26
  // toolbar (rich-text-floating-toolbar.tsx says why): `position: fixed`,
@@ -189,15 +191,15 @@ export function RichTextKeyboardBar({ view, state, readOnly, controls, onFormat,
189
191
  };
190
192
  const shown = edge !== null && ready;
191
193
  const bottom = edge ? edge.bottom - (panel ? panelHeight : 0) : 0;
192
- return (_jsxs("div", { ref: ref, "data-slot": "rich-text-keyboard-bar", "data-rich-text-menu": "", onBlur: onBlur, children: [_jsx("span", { ref: probe, "aria-hidden": "true", className: "pointer-events-none fixed top-0 left-0 size-0" }), _jsxs("div", { ref: row, role: "toolbar", "aria-label": "Formatting", "aria-controls": controls, style: edge ? { top: bottom, left: edge.left, width: edge.width } : undefined, className: cn('fixed z-50 flex h-12 -translate-y-full items-center gap-0.5 border-t border-border bg-card px-1 text-card-foreground', !shown && 'invisible'), children: [_jsx(Toggle, { "aria-label": panel ? 'Keyboard' : 'All Formats', pressed: panel, disabled: readOnly, className: "size-10 min-w-10 font-serif text-base aria-pressed:bg-muted aria-pressed:text-foreground [&_svg]:size-5", onMouseDown: keep, onPressedChange: (open) => {
194
+ return (_jsxs("div", { ref: ref, "data-slot": "rich-text-keyboard-bar", "data-rich-text-menu": "", onBlur: onBlur, children: [_jsx("span", { ref: probe, "aria-hidden": "true", className: "pointer-events-none fixed top-0 left-0 size-0" }), _jsxs("div", { ref: row, role: "toolbar", "aria-label": "Formatting", "aria-controls": controls, style: edge ? { top: bottom, left: edge.left, width: edge.width } : undefined, className: cn('fixed z-50 flex h-12 -translate-y-full items-center gap-0.5 border-t border-border bg-card px-1 text-card-foreground', !shown && 'invisible'), children: [_jsx(Toggle, { "aria-label": panel ? 'Keyboard' : 'All Formats', pressed: panel, disabled: readOnly, className: "size-11 min-w-11 font-serif text-base aria-pressed:bg-muted aria-pressed:text-foreground [&_svg]:size-5", onMouseDown: keep, onPressedChange: (open) => {
193
195
  setPanel(open);
194
196
  if (!open)
195
197
  virtualKeyboard()?.show();
196
198
  view.focus();
197
- }, children: panel ? _jsx(KeyboardIcon, { "aria-hidden": "true" }) : 'Aa' }), _jsx(Separator, { orientation: "vertical", className: "mx-1 h-6 data-vertical:self-center" }), _jsxs("div", { className: "flex min-w-0 flex-1 items-center gap-0.5 overflow-x-auto [scrollbar-width:none]", children: [_jsx(FormatButtons, { formats: words ? 'keyboardWords' : 'keyboard', state: state, readOnly: readOnly, onFormat: onFormat, text: text, touch: true }), !words && (_jsxs(_Fragment, { children: [_jsx(Button, { variant: "ghost", size: "icon-lg", "aria-label": "Insert Block", disabled: readOnly || inCode, className: "[&_svg]:size-5", onMouseDown: keep, onClick: () => insertBlock(view), children: _jsx(PlusIcon, { "aria-hidden": "true" }) }), onImage && (_jsx(Button, { variant: "ghost", size: "icon-lg", "aria-label": "Image", disabled: readOnly, className: "[&_svg]:size-5", onMouseDown: keep, onClick: onImage, children: _jsx(ImageIcon, { "aria-hidden": "true" }) })), _jsx(Button, { variant: "ghost", size: "icon-lg", "aria-label": "Undo",
199
+ }, children: panel ? _jsx(KeyboardIcon, { "aria-hidden": "true" }) : 'Aa' }), _jsx(Separator, { orientation: "vertical", className: "mx-1 h-6 data-vertical:self-center" }), _jsxs("div", { className: "flex min-w-0 flex-1 items-center gap-0.5 overflow-x-auto [scrollbar-width:none]", children: [_jsx(FormatButtons, { formats: words ? 'keyboardWords' : 'keyboard', state: state, readOnly: readOnly, onFormat: onFormat, text: text, touch: true }), !words && (_jsxs(_Fragment, { children: [_jsx(Button, { variant: "ghost", size: "icon-lg", "aria-label": "Insert Block", disabled: readOnly || inCode, className: "size-11 [&_svg]:size-5", onMouseDown: keep, onClick: () => insertBlock(view), children: _jsx(PlusIcon, { "aria-hidden": "true" }) }), onImage && (_jsx(Button, { variant: "ghost", size: "icon-lg", "aria-label": "Image", disabled: readOnly, className: "size-11 [&_svg]:size-5", onMouseDown: keep, onClick: onImage, children: _jsx(ImageIcon, { "aria-hidden": "true" }) })), _jsx(Button, { variant: "ghost", size: "icon-lg", "aria-label": "Undo",
198
200
  // Always on: `state` doesn't follow typing, and with nothing
199
201
  // to undo it does nothing.
200
- disabled: readOnly, className: "[&_svg]:size-5", onMouseDown: keep, onClick: press(() => undo(view.state, view.dispatch)), children: _jsx(Undo2Icon, { "aria-hidden": "true" }) })] }))] }), _jsx(Button, { variant: "ghost", size: "icon-lg", "aria-label": "Hide Keyboard", className: "[&_svg]:size-5", onMouseDown: keep, onClick: () => {
202
+ disabled: readOnly, className: "size-11 [&_svg]:size-5", onMouseDown: keep, onClick: press(() => undo(view.state, view.dispatch)), children: _jsx(Undo2Icon, { "aria-hidden": "true" }) })] }))] }), _jsx(Button, { variant: "ghost", size: "icon-lg", "aria-label": "Hide Keyboard", className: "size-11 [&_svg]:size-5", onMouseDown: keep, onClick: () => {
201
203
  setPanel(false);
202
204
  view.dom.blur();
203
205
  }, children: _jsx(ChevronDownIcon, { "aria-hidden": "true" }) })] }), panel && edge && (_jsxs("div", { role: "group", "aria-label": "All Formats", "data-slot": "rich-text-keyboard-panel", style: { top: edge.bottom - panelHeight, left: edge.left, width: edge.width, height: panelHeight }, className: "fixed z-50 flex flex-col gap-3 overflow-y-auto bg-card px-3 py-3 text-card-foreground", onMouseDown: keep, children: [_jsx("p", { className: "type-caption text-muted-foreground", children: "Words" }), _jsx("div", { role: "toolbar", "aria-label": "Format Words", className: "flex flex-wrap items-center gap-1", children: _jsx(FormatButtons, { formats: "selection", state: state, readOnly: readOnly, onFormat: onFormat, text: text, touch: true }) }), _jsx("p", { className: "type-caption text-muted-foreground", children: "Blocks" }), _jsxs("div", { className: "grid grid-cols-4 gap-1.5", children: [BLOCKS.map((item) => {
@@ -27,6 +27,11 @@
27
27
  // here whether or not there is a step to take: ProseMirror's keymap,
28
28
  // finding nothing to redo, would run Shift+Mod+Z's unshifted key, Mod+Z,
29
29
  // so a redo pressed once too often would undo a step.
30
+ // - Enter after `[!NOTE]` (or `[!TIP]`, `[!IMPORTANT]`, `[!WARNING]`,
31
+ // `[!CAUTION]`, any case) alone on a quote's first line makes the quote
32
+ // a callout of that kind, its marker kept as typed, the caret on in it:
33
+ // GitHub's syntax typed as it's written, as `# ` makes a heading
34
+ // (src/lib/markdown-callout.ts). Words after the marker keep it a quote.
30
35
  import { redo, undo } from '@milkdown/kit/prose/history';
31
36
  import { liftListItem, sinkListItem } from '@milkdown/kit/prose/schema-list';
32
37
  import { DEFAULT_HIGHLIGHT } from '../../lib/markdown-highlight.js';
@@ -160,8 +165,32 @@ export function handleEditingKey(state, dispatch, event) {
160
165
  return liftAtItemStart(state, dispatch);
161
166
  if (event.key === 'Tab')
162
167
  return handleTab(state, dispatch, event.shiftKey);
168
+ if (event.key === 'Enter' && !event.shiftKey)
169
+ return calloutFromMarker(state, dispatch);
163
170
  return false;
164
171
  }
172
+ const TYPED_CALLOUT = /^\[!(note|tip|important|warning|caution)\][ \t]*$/i;
173
+ // A quote whose first line is a callout's marker, the caret at its end:
174
+ // made the callout, the marker's line emptied for the caret.
175
+ function calloutFromMarker(state, dispatch) {
176
+ const { selection, schema } = state;
177
+ const callout = schema.nodes.callout;
178
+ const { $from } = selection;
179
+ if (!callout || !selection.empty || $from.depth < 2)
180
+ return false;
181
+ const line = $from.parent;
182
+ if (line.type.name !== 'paragraph' || $from.parentOffset !== line.content.size)
183
+ return false;
184
+ if (line.childCount !== 1 || !line.firstChild.isText || line.firstChild.marks.length > 0)
185
+ return false;
186
+ const found = TYPED_CALLOUT.exec(line.textContent);
187
+ if (!found || $from.node(-1).type.name !== 'blockquote' || $from.index(-1) !== 0)
188
+ return false;
189
+ const tr = state.tr.delete($from.start(), $from.end());
190
+ tr.setNodeMarkup($from.before(-1), callout, { kind: found[1].toLowerCase(), marker: found[0].trim() });
191
+ dispatch(tr.scrollIntoView());
192
+ return true;
193
+ }
165
194
  /**
166
195
  * Runs the shortcut a key press is, if it's one of these. True when it
167
196
  * was (whether or not the format could apply where the caret is: the key
@@ -27,7 +27,7 @@ export type FormatButtonsProps = {
27
27
  fullScreen?: boolean;
28
28
  /** The editable element, for the Highlight menu to give focus back to. */
29
29
  text?: () => HTMLElement | null;
30
- /** 40px buttons, for a touch screen (the keyboard bar's). */
30
+ /** 44px buttons, for a touch screen (the keyboard bar's). */
31
31
  touch?: boolean;
32
32
  };
33
33
  export declare function FormatButtons({ formats, state, readOnly, onFormat, onPage, onImage, onFullScreen, fullScreen, text, touch }: FormatButtonsProps): import("react").JSX.Element;
@@ -66,8 +66,8 @@ export function FormatButtons({ formats, state, readOnly, onFormat, onPage, onIm
66
66
  const pageIndex = onPage ? items.length : -1;
67
67
  const imageIndex = onImage ? items.length + (onPage ? 1 : 0) : -1;
68
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;
69
+ // A touch screen's 44px buttons, a finger's; a laptop's 28px.
70
+ const sized = touch ? 'size-11 min-w-11 [&_svg]:size-5' : undefined;
71
71
  const count = items.length + (onPage ? 1 : 0) + (onImage ? 1 : 0) + (onFullScreen ? 1 : 0);
72
72
  const buttons = useRef([]);
73
73
  // The one button Tab reaches: the last one used.
@@ -95,7 +95,7 @@ export function FormatButtons({ formats, state, readOnly, onFormat, onPage, onIm
95
95
  if (item.id === 'highlight')
96
96
  return (_jsx(RichTextHighlightMenu, { ref: (element) => {
97
97
  buttons.current[index] = element;
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));
98
+ }, state: state, readOnly: readOnly, tabIndex: index === current ? 0 : -1, onFocus: () => setCurrent(index), onKeyDown: onKeyDown, onFormat: onFormat, text: text, className: touch ? 'h-11 min-w-11' : undefined }, item.id));
99
99
  const Icon = item.icon;
100
100
  const tip = [
101
101
  item.label,
package/dist/index.d.ts CHANGED
@@ -73,6 +73,7 @@ export { ListEditor } from './components/app/list-editor.js';
73
73
  export { PasswordInput } from './components/app/password-input.js';
74
74
  export { RichTextEditor, type RichTextEditorProps } from './components/app/rich-text-editor.js';
75
75
  export { preloadRichTextEditor } from './components/app/rich-text-load.js';
76
+ export { holdKeysForNextEditor, type HoldKeysOptions } from './components/app/rich-text-hold-keys.js';
76
77
  export { flushPendingEdits, hasPendingEdits } from './lib/pending-edits.js';
77
78
  export { RouteErrorBoundary } from './components/app/route-error-boundary.js';
78
79
  export { PillFilter, type PillFilterOption, type PillFilterProps } from './components/app/pill-filter.js';
package/dist/index.js CHANGED
@@ -82,6 +82,7 @@ export { ListEditor } from './components/app/list-editor.js';
82
82
  export { PasswordInput } from './components/app/password-input.js';
83
83
  export { RichTextEditor } from './components/app/rich-text-editor.js';
84
84
  export { preloadRichTextEditor } from './components/app/rich-text-load.js';
85
+ export { holdKeysForNextEditor } from './components/app/rich-text-hold-keys.js';
85
86
  // Typing a RichTextEditor holds back until a pause, reported now: call it
86
87
  // before reading a rich-text field's value to save it in your own form.
87
88
  export { flushPendingEdits, hasPendingEdits } from './lib/pending-edits.js';
@@ -38,8 +38,13 @@ function takeCallout(node) {
38
38
  const rest = text.value.slice(found[0].length);
39
39
  if (rest)
40
40
  text.value = rest;
41
- else
41
+ else {
42
42
  paragraph.children.shift();
43
+ // The marker's line ended in a break node (the editor's parser reads
44
+ // each newline as one): it ends the marker, not a line of the body.
45
+ if (paragraph.children[0]?.type === 'break')
46
+ paragraph.children.shift();
47
+ }
43
48
  if (paragraph.children.length === 0)
44
49
  node.children.shift();
45
50
  return { kind: found[1].toLowerCase(), marker: found[0].trim() };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tristan2828/ui-foundation",
3
- "version": "4.152.0",
3
+ "version": "4.154.0",
4
4
  "description": "Shared UI foundation for contract-first, database-backed React apps: shadcn primitives, DataTable/EntityForm composites, auth, the gateway error seam, design tokens, lint rules and the AI playbook.",
5
5
  "license": "MIT",
6
6
  "repository": {