@tristan2828/ui-foundation 4.151.0 → 4.153.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.
@@ -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–1643
30
- - [Presets: one line per field](#presets-one-line-per-field) · lines 1227–1299
31
- - [Several fields edited as one](#several-fields-edited-as-one) · lines 1301–1337
32
- - [A link and its label](#a-link-and-its-label) · lines 1339–1363
33
- - [A list of sub-items](#a-list-of-sub-items) · lines 1365–1498
34
- - [On a page of the app's own: `EditInPlaceScope`](#on-a-page-of-the-apps-own-editinplacescope) · lines 1500–1560
35
- - [In a table's rows](#in-a-tables-rows) · lines 1562–1636
36
- - [A table of a few short columns: `width="content"`](#a-table-of-a-few-short-columns-widthcontent) · lines 1638–1643
37
- - [19. Stage circle for an ordered status](#19-stage-circle-for-an-ordered-status) · lines 1645–1711
38
- - [20. Count linking to the related records](#20-count-linking-to-the-related-records) · lines 1713–1767
39
- - [21. Rows grouped under headings, and a pill filter](#21-rows-grouped-under-headings-and-a-pill-filter) · lines 1769–1851
40
- - [22. A highlighted row, and rows that are done](#22-a-highlighted-row-and-rows-that-are-done) · lines 1853–1878
41
- - [28. A list's rows: hover, lines, rows per page](#28-a-lists-rows-hover-lines-rows-per-page) · lines 1880–1913
42
- - [23. A Group menu, and a record read beside the list](#23-a-group-menu-and-a-record-read-beside-the-list) · lines 1915–1966
43
- - [24. A stored colour beside its name](#24-a-stored-colour-beside-its-name) · lines 1968–2042
44
- - [Picking one on a form: `ColorField`](#picking-one-on-a-form-colorfield) · lines 1988–2042
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 2044–2256
46
- - [The framed look, and sibling lists beside the title](#the-framed-look-and-sibling-lists-beside-the-title) · lines 2205–2256
47
- - [26. A record's related list, capped](#26-a-records-related-list-capped) · lines 2258–2292
48
- - [27. A repeat and its next time](#27-a-repeat-and-its-next-time) · lines 2294–2341
29
+ - [18. Editable value](#18-editable-value) · lines 834–1667
30
+ - [Presets: one line per field](#presets-one-line-per-field) · lines 1237–1309
31
+ - [Several fields edited as one](#several-fields-edited-as-one) · lines 1311–1347
32
+ - [A link and its label](#a-link-and-its-label) · lines 1349–1373
33
+ - [A list of sub-items](#a-list-of-sub-items) · lines 1375–1508
34
+ - [On a page of the app's own: `EditInPlaceScope`](#on-a-page-of-the-apps-own-editinplacescope) · lines 1510–1584
35
+ - [In a table's rows](#in-a-tables-rows) · lines 1586–1660
36
+ - [A table of a few short columns: `width="content"`](#a-table-of-a-few-short-columns-widthcontent) · lines 1662–1667
37
+ - [19. Stage circle for an ordered status](#19-stage-circle-for-an-ordered-status) · lines 1669–1735
38
+ - [20. Count linking to the related records](#20-count-linking-to-the-related-records) · lines 1737–1791
39
+ - [21. Rows grouped under headings, and a pill filter](#21-rows-grouped-under-headings-and-a-pill-filter) · lines 1793–1875
40
+ - [22. A highlighted row, and rows that are done](#22-a-highlighted-row-and-rows-that-are-done) · lines 1877–1902
41
+ - [28. A list's rows: hover, lines, rows per page](#28-a-lists-rows-hover-lines-rows-per-page) · lines 1904–1937
42
+ - [23. A Group menu, and a record read beside the list](#23-a-group-menu-and-a-record-read-beside-the-list) · lines 1939–1990
43
+ - [24. A stored colour beside its name](#24-a-stored-colour-beside-its-name) · lines 1992–2066
44
+ - [Picking one on a form: `ColorField`](#picking-one-on-a-form-colorfield) · lines 2012–2066
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 2068–2280
46
+ - [The framed look, and sibling lists beside the title](#the-framed-look-and-sibling-lists-beside-the-title) · lines 2229–2280
47
+ - [26. A record's related list, capped](#26-a-records-related-list-capped) · lines 2282–2316
48
+ - [27. A repeat and its next time](#27-a-repeat-and-its-next-time) · lines 2318–2365
49
49
 
50
50
  <!-- /index -->
51
51
 
@@ -1020,13 +1020,18 @@ nobody has to click away to save notes. Opt in per field:
1020
1020
 
1021
1021
  - It saves about a second after typing stops, without leaving the field,
1022
1022
  and at once on leaving it (a click or Tab elsewhere, Ctrl/Cmd+Enter,
1023
- opening another value, a link off the page).
1023
+ opening another value, a link off the page). Ctrl/Cmd+S, pressed by
1024
+ habit, saves at once and leaves it open; the browser's Save Page dialog
1025
+ never opens over it.
1024
1026
  - **Never read-only while it saves.** Typing carries on during a save;
1025
1027
  the next save waits for the one in flight and sends whatever the text
1026
1028
  is by then, so saves never cross and the latest always wins.
1027
1029
  - Under the text, a quiet line in the muted caption tone
1028
- (`role="status"`): "Saving…" with a spinner while a save is in flight,
1029
- "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
1030
1035
  than the screen the line is pinned to the screen's bottom edge** while
1031
1036
  the note runs past it, so the save's state and a refusal are never off
1032
1037
  screen.
@@ -1073,8 +1078,8 @@ doesn't move.
1073
1078
 
1074
1079
  **Always editable (`alwaysEditable: true`, implies `autosave`)**: the
1075
1080
  notes are the editor itself, shown at rest, with no pencil and no click
1076
- to open, and it never closes. Ctrl/Cmd+Enter or Esc saves now and leaves
1077
- the caret where it is. It sits beside the one open value rather than
1081
+ to open, and it never closes. Ctrl/Cmd+Enter, Ctrl/Cmd+S or Esc saves now
1082
+ and leaves the caret where it is. It sits beside the one open value rather than
1078
1083
  being it: opening another value leaves it alone. Don't give its control
1079
1084
  `autoFocus`. The cost: at rest the page shows the editor, not the read
1080
1085
  view, and the editor loads on every visit (an app whose first screen is
@@ -1164,7 +1169,11 @@ const price = editInPlace({
1164
1169
  can't save without rewriting text nobody touched is never saved: on a
1165
1170
  form, bind its `onProblem` to the field's error and refuse submit while
1166
1171
  it stands (add-an-entity.md, `widget-form.tsx`); with no `onProblem` it
1167
- says so inside the field. Notion's block keys
1172
+ says so inside the field. The Markdown holds what Markdown can: a
1173
+ paragraph or heading carries no indent, so spaces typed at a line's
1174
+ start (or end) show until the note is next opened and aren't saved
1175
+ (inline code keeps its own), and blank lines typed for spacing aren't
1176
+ saved either: three Enters leave one paragraph break. Notion's block keys
1168
1177
  work: Ctrl+Shift+1 to 3 for headings, +4 tasks, +5 bullets, +6 numbers,
1169
1178
  +8 a code block, +0 back to text (Cmd+Option on a Mac), and
1170
1179
  Ctrl/Cmd+Shift+S strikes through. Ctrl/Cmd+Enter stays the save, in a
@@ -1213,7 +1222,8 @@ const price = editInPlace({
1213
1222
  app's `upload` (the same one `ImageField` takes) and an image pasted,
1214
1223
  dropped or picked with an Image button (the fixed toolbar's, the tools
1215
1224
  strip's, the phone's row) is uploaded and goes
1216
- in as `![](url)`, a placeholder showing meanwhile (never saved), a
1225
+ in as `![](url)`, a placeholder showing meanwhile (never saved, and
1226
+ read out from a live region named "Uploads"), a
1217
1227
  refusal or failure in a toast. No `upload`, no file handling at all.
1218
1228
  - **The save is the single-field save** (`useRecordUpdate` with
1219
1229
  `optimistic: false, toastOnError: false`, the entity's
@@ -1531,6 +1541,16 @@ const body = editInPlace<string>({
1531
1541
  tabs are: one pane per open note, all mounted, only the one in front
1532
1542
  shown (the others `hidden`), so each keeps its caret and undo. A
1533
1543
  hidden value still saves, and the one leave guard covers them all.
1544
+ The editor's `focusKey` (a number the app bumps as a tab comes to the
1545
+ front) focuses it again with its caret put back in the same task, so
1546
+ a key typed at once lands where it was; don't focus the editable
1547
+ element through the DOM, which leaves the caret at the text's start
1548
+ for a moment.
1549
+ - **An editor that is the page** (a note the app opens on) takes
1550
+ `autoFocus="end"`, the caret after its last words, in view, and
1551
+ `tabStaysInText`: Tab on a plain line stays in the text (Esc, then
1552
+ Tab, moves on, which the field tells and shows), so a Tab typed out of
1553
+ habit doesn't land on the next control and a Space press it.
1534
1554
  - **Tabs that are URLs** (`/notes/1`, `/notes/2`, the one in front
1535
1555
  being the route) pass `staysOnPage`, given the next location (and the
1536
1556
  current one), true for a move that only brings another of the scope's
@@ -1544,8 +1564,10 @@ const body = editInPlace<string>({
1544
1564
  closed, a pane unmounted): what was typed goes at once rather than
1545
1565
  after the pause, and a value whose save had been refused tries once
1546
1566
  more. If that save fails, nothing on screen holds the text any more,
1547
- so a toast says "Couldn't save *label*" with the reason and stays until
1548
- dismissed, with **Copy Text** to put what was typed on the clipboard.
1567
+ so a toast says "*Label* wasn't saved and is no longer on the page"
1568
+ (not a refusal's "Couldn't save *label*", which can still be retried
1569
+ where it is) with the reason, and stays until dismissed, with
1570
+ **Copy Text** to put what was typed on the clipboard.
1549
1571
  `onLostEdit`, given `{ label, value, reason }` (`LostEdit`), is for the
1550
1572
  app to do more, such as reopen the note's tab. A record's view and a
1551
1573
  table toast the same way.
@@ -1553,7 +1575,9 @@ const body = editInPlace<string>({
1553
1575
  as it starts (in `main.tsx`), so the editor's code is loading while
1554
1576
  the note is fetched, not after. It returns nothing, never throws, and
1555
1577
  is safe to call more than once; a failed load is the editor's to meet
1556
- when one mounts.
1578
+ when one mounts, and the next editor to mount tries again. Keys typed
1579
+ into an `autoFocus` editor while its code still loads are kept, and
1580
+ typed in once it's up.
1557
1581
 
1558
1582
  The stories are `app/EditInPlaceScope` (one note, two in one scope, and
1559
1583
  the two as URL tabs with `staysOnPage`);
@@ -197,6 +197,12 @@ export declare class EditInPlaceStore {
197
197
  * sent is saved (or there was nothing to send).
198
198
  */
199
199
  private flush;
200
+ /**
201
+ * Saves an autosaving field's draft now, without waiting for the pause
202
+ * (Ctrl/Cmd+S), and leaves it open. Resolves true once it's saved, or
203
+ * there was nothing to save.
204
+ */
205
+ saveNow(key: string): Promise<boolean>;
200
206
  /**
201
207
  * Saves every autosaving field that holds something unsaved, now
202
208
  * (leaving the page). Resolves true once nothing unsaved is left.
@@ -524,6 +524,16 @@ export class EditInPlaceStore {
524
524
  this.autosaving.set(key, flight);
525
525
  return flight.promise;
526
526
  }
527
+ /**
528
+ * Saves an autosaving field's draft now, without waiting for the pause
529
+ * (Ctrl/Cmd+S), and leaves it open. Resolves true once it's saved, or
530
+ * there was nothing to save.
531
+ */
532
+ saveNow(key) {
533
+ if (!this.autosaves(key))
534
+ return Promise.resolve(false);
535
+ return this.flush(key);
536
+ }
527
537
  /**
528
538
  * Saves every autosaving field that holds something unsaved, now
529
539
  * (leaving the page). Resolves true once nothing unsaved is left.
@@ -14,7 +14,8 @@ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-run
14
14
  // the server agrees. Failed: it stays, with the draft and the reason.
15
15
  // - `autosave`: it saves itself a pause after typing stops and stays
16
16
  // editable while it does ("Saving…", then "Saved" under it). Leaving,
17
- // Ctrl/Cmd+Enter and Esc save what's left now and close it. On a note
17
+ // Ctrl/Cmd+Enter and Esc save what's left now and close it; Ctrl/Cmd+S
18
+ // saves now and leaves it open (never the browser's Save dialog). On a note
18
19
  // longer than the screen the line under it is pinned to the screen's
19
20
  // bottom edge, so a refusal or a failed save is never off screen, and
20
21
  // the first one also toasts.
@@ -26,7 +27,7 @@ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-run
26
27
  // unsaved, the caret keeping its block; under unsaved typing the line
27
28
  // says so, with "Keep Mine" and "Show Saved".
28
29
  // - `alwaysEditable`: the control is shown at rest, with no pencil and no
29
- // click to open, and never closes. Ctrl/Cmd+Enter and Esc save now.
30
+ // click to open, and never closes. Ctrl/Cmd+Enter, Ctrl/Cmd+S and Esc save now.
30
31
  // - `inline`: always editable, and the control is told to look like the
31
32
  // value it edits (`inline` among its props).
32
33
  // - Always editable and a `choice` (`inPlace.rating`'s stars): a
@@ -34,6 +35,8 @@ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-run
34
35
  // line under it, and "Saved" goes after two seconds, as at rest.
35
36
  // - Saved: once a save lands, "✓ Saved" shows beside the value
36
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").
37
40
  // - `layout="inline"`: the pencil takes no room until hover or
38
41
  // focus, so nothing gaps before what follows the value on its line.
39
42
  // `keepPencilRoom` (and every value inside a KeyStats) keeps it
@@ -59,6 +62,8 @@ import { EditInPlaceContext } from './edit-in-place.js';
59
62
  import { SAVED_FOR_MS } from './edit-row.js';
60
63
  import { escapePassedThrough } from './escape-passthrough.js';
61
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';
62
67
  // What a click on the shown value must leave alone: links navigate,
63
68
  // buttons and boxes do their own thing (a list item's done box ticks it).
64
69
  const INTERACTIVE = 'a[href], button, input, select, textarea, label, [role="button"], [role="link"], [role="checkbox"], [role="switch"]';
@@ -66,6 +71,10 @@ const INTERACTIVE = 'a[href], button, input, select, textarea, label, [role="but
66
71
  // order (a picker's text box before its chips' remove buttons). A box's
67
72
  // own native input (a checkbox's, hidden and out of the tab order) isn't
68
73
  // a place to type: a list item's text box comes first.
74
+ // Ctrl/Cmd+S, by the key's place (a layout whose S key types another letter too).
75
+ function isSaveKey(event) {
76
+ return (event.metaKey || event.ctrlKey) && !event.shiftKey && !event.altKey && (event.code === 'KeyS' || event.key.toLowerCase() === 's');
77
+ }
69
78
  const FOCUS_ORDER = [
70
79
  'input:not([type="hidden"]):not([tabindex="-1"]):not([aria-hidden="true"]), textarea, [contenteditable="true"]',
71
80
  '[role="combobox"], [role="switch"], button, [tabindex]:not([tabindex="-1"])',
@@ -384,6 +393,13 @@ export function EditableField({ label, edit, children, layout = 'block', look =
384
393
  else
385
394
  commitFromKeyboard();
386
395
  }
396
+ else if (autosave && isSaveKey(event)) {
397
+ // Ctrl/Cmd+S, by habit: saves now and stays open, in place of the
398
+ // browser's Save Page dialog over a value that saves itself.
399
+ event.preventDefault();
400
+ window.clearTimeout(blurTimer.current);
401
+ void store.saveNow(key);
402
+ }
387
403
  else if (event.key === 'Enter' && edit.kind === 'text' && !event.shiftKey && !event.altKey) {
388
404
  event.preventDefault();
389
405
  commitFromKeyboard();
@@ -427,7 +443,7 @@ export function EditableField({ label, edit, children, layout = 'block', look =
427
443
  // grow with --spacing, and a fixed 0.75rem left the record's
428
444
  // title 3-5px short of its one line (4.145).
429
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 &&
430
- '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, {})) }) })] }));
431
447
  }
432
448
  // Always editable, before the store has it (the first render): the saved value.
433
449
  const open = state.status === 'closed' ? { status: 'open', draft: edit.value, error: null, autosave: undefined, revision: 0 } : state;
@@ -447,9 +463,9 @@ export function EditableField({ label, edit, children, layout = 'block', look =
447
463
  // it, so the save's state and a refusal stay in view.
448
464
  style: pin ? { left: pin.left, maxWidth: pin.width } : undefined, className: cn('type-body',
449
465
  // Beside the value, a refusal takes the line under it.
450
- 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' &&
451
467
  !open.error &&
452
- !(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: () => {
453
469
  setAskingDiscard(false);
454
470
  refocus.current = true;
455
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
  ? {
@@ -1,3 +1,11 @@
1
+ import { type HeldKeys } from './rich-text-held-keys.js';
1
2
  import type { RichTextEditorProps } from './rich-text-editor.js';
2
3
  export declare const MERGE_PAUSE_MS = 300;
3
- export default function MilkdownEditor({ id, defaultValue, onChange, onProblem, readOnly, autoFocus, placeholder, maxLength, toolbar, inline, upload, imageAccept, imageMaxSize, headingLevel, headingFrom, foldKey, tableLook, pageLink, onCreatePage, className, 'aria-label': ariaLabel, 'aria-labelledby': ariaLabelledBy, 'aria-describedby': ariaDescribedBy, 'aria-invalid': ariaInvalid, }: RichTextEditorProps): import("react").JSX.Element;
4
+ /** RichTextEditor's props, and what it hands the editor itself. */
5
+ export type MilkdownEditorProps = RichTextEditorProps & {
6
+ /** Keys typed while the editor's code loaded, to type in once it's up (rich-text-held-keys.ts). */
7
+ held?: HeldKeys;
8
+ /** Whether `focusKey` is one not yet acted on (RichTextEditor keeps the last across a remount or a load). */
9
+ isNewFocus?: (key: string | number | undefined) => boolean;
10
+ };
11
+ export default function MilkdownEditor({ id, defaultValue, onChange, onProblem, readOnly, autoFocus, focusKey, tabStaysInText, held, isNewFocus, placeholder, maxLength, toolbar, inline, upload, imageAccept, imageMaxSize, headingLevel, headingFrom, foldKey, tableLook, pageLink, onCreatePage, className, 'aria-label': ariaLabel, 'aria-labelledby': ariaLabelledBy, 'aria-describedby': ariaDescribedBy, 'aria-invalid': ariaInvalid, }: MilkdownEditorProps): import("react").JSX.Element;
@@ -55,21 +55,30 @@ 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.
63
+ // - Built in a layout effect, focused (`autoFocus`, `'end'` after the last
64
+ // words shown) only once the baseline is read, with any keys typed while
65
+ // it loaded typed in after (rich-text-held-keys.ts). `focusKey` focuses
66
+ // it again, the caret put back as focus arrives.
67
+ // - `tabStaysInText`: Tab and Shift+Tab nothing in the text took stay in
68
+ // it; Esc, then Tab, moves on, told through the field's description and
69
+ // shown under it the first time.
61
70
  // - `pageLink`: links the app marks as its pages drawn as page links,
62
71
  // opened in this tab; `onCreatePage`: "/page" and Turn into page make
63
72
  // one through the app and link it (a title box, rich-text-page-box.tsx).
64
73
  // The Markdown stays a plain link.
65
- import { useEffect, useId, useRef, useState } from 'react';
74
+ import { useEffect, useId, useLayoutEffect, useRef, useState } from 'react';
66
75
  import { createPortal } from 'react-dom';
67
76
  import { useInRouterContext, useNavigate } from 'react-router';
68
77
  import { defaultValueCtx, Editor, editorViewCtx, editorViewOptionsCtx, parserCtx, remarkStringifyOptionsCtx, rootCtx, schemaCtx, serializerCtx, } from '@milkdown/kit/core';
69
78
  import { history } from '@milkdown/kit/plugin/history';
70
79
  import { commands, headingSchema, paragraphSchema, keymap, plugins, remarkPreserveEmptyLinePlugin, schema, } from '@milkdown/kit/preset/commonmark';
71
80
  import { gfm, tableCellSchema, tableHeaderSchema, tableSchema } from '@milkdown/kit/preset/gfm';
72
- import { NodeSelection, Plugin, TextSelection } from '@milkdown/kit/prose/state';
81
+ import { NodeSelection, Plugin, Selection, TextSelection } from '@milkdown/kit/prose/state';
73
82
  import { isInTable, selectedRect, TableMap } from '@milkdown/kit/prose/tables';
74
83
  import { Decoration, DecorationSet } from '@milkdown/kit/prose/view';
75
84
  import { $markSchema, $nodeSchema, $prose, $remark, getMarkdown } from '@milkdown/kit/utils';
@@ -81,7 +90,7 @@ import { linkHref } from '../../lib/link-href.js';
81
90
  import { messageOf } from '../../lib/refusal.js';
82
91
  import { restorePage } from './page-restore.js';
83
92
  import { insertPageLink, pageLinksPlugin, pendingPagePlugin, refreshPageLinks, setPendingPage, } from './rich-text-page-links.js';
84
- import { passEscapeThrough } from './escape-passthrough.js';
93
+ import { escapePassedThrough, passEscapeThrough } from './escape-passthrough.js';
85
94
  import { calloutHandler, remarkCalloutNodes } from '../../lib/markdown-callout.js';
86
95
  import { formatTableWidths, remarkTableWidths } from '../../lib/markdown-table-widths.js';
87
96
  import { DEFAULT_HIGHLIGHT, highlightHandler, isHighlightColor, remarkHighlightNodes } from '../../lib/markdown-highlight.js';
@@ -91,7 +100,8 @@ import { holdPendingEdit } from '../../lib/pending-edits.js';
91
100
  import { foldStore, listenForOtherTabs } from '../../hooks/fold-store.js';
92
101
  import { toggleFold } from '../../lib/markdown-fold.js';
93
102
  import { DEFAULT_HEADING_LEVEL } from './prose-look.js';
94
- import { foldPlugin, setFolds } from './rich-text-fold.js';
103
+ import { foldPlugin, setFolds, shownEnd } from './rich-text-fold.js';
104
+ import { replayKeys } from './rich-text-held-keys.js';
95
105
  import { headingView } from './rich-text-heading-view.js';
96
106
  import { taskItemView, toggleTaskItem } from './rich-text-task-item-view.js';
97
107
  import { applyLink, followLink, linkTarget, notePress } from './rich-text-links.js';
@@ -279,7 +289,11 @@ function NavigateBridge({ targetRef }) {
279
289
  }, [navigate, targetRef]);
280
290
  return null;
281
291
  }
282
- export default function MilkdownEditor({ id, defaultValue, onChange, onProblem, readOnly = false, autoFocus = false, placeholder, maxLength, toolbar = true, inline = false, upload, imageAccept, imageMaxSize, headingLevel = DEFAULT_HEADING_LEVEL, headingFrom = 'hash', foldKey, tableLook = 'compact', pageLink, onCreatePage, className, 'aria-label': ariaLabel, 'aria-labelledby': ariaLabelledBy, 'aria-describedby': ariaDescribedBy, 'aria-invalid': ariaInvalid, }) {
292
+ // What the field tells, and shows the first time a Tab stays in the text.
293
+ const TAB_HINT = 'Tab stays in the text. Press Esc, then Tab, to move on.';
294
+ // Keys on their own that come before another (Shift, for Shift+Tab).
295
+ const MODIFIER_KEYS = new Set(['Shift', 'Control', 'Alt', 'Meta']);
296
+ export default function MilkdownEditor({ id, defaultValue, onChange, onProblem, readOnly = false, autoFocus = false, focusKey, tabStaysInText = false, held, isNewFocus, placeholder, maxLength, toolbar = true, inline = false, upload, imageAccept, imageMaxSize, headingLevel = DEFAULT_HEADING_LEVEL, headingFrom = 'hash', foldKey, tableLook = 'compact', pageLink, onCreatePage, className, 'aria-label': ariaLabel, 'aria-labelledby': ariaLabelledBy, 'aria-describedby': ariaDescribedBy, 'aria-invalid': ariaInvalid, }) {
283
297
  const rootRef = useRef(null);
284
298
  const editorRef = useRef(null);
285
299
  const [linkBox, setLinkBox] = useState(null);
@@ -331,9 +345,9 @@ export default function MilkdownEditor({ id, defaultValue, onChange, onProblem,
331
345
  // rendered into through a portal.
332
346
  const [widgets, setWidgets] = useState([]);
333
347
  // The latest props, for the editor's callbacks, which are set up once.
334
- const latest = useRef({ onChange, onProblem, readOnly, placeholder, upload, imageAccept, imageMaxSize, pageLink, onCreatePage });
348
+ const latest = useRef({ onChange, onProblem, readOnly, placeholder, upload, imageAccept, imageMaxSize, pageLink, onCreatePage, tabStaysInText });
335
349
  useEffect(() => {
336
- latest.current = { onChange, onProblem, readOnly, placeholder, upload, imageAccept, imageMaxSize, pageLink, onCreatePage };
350
+ latest.current = { onChange, onProblem, readOnly, placeholder, upload, imageAccept, imageMaxSize, pageLink, onCreatePage, tabStaysInText };
337
351
  });
338
352
  // Whether focus is on the floating toolbar, or in a menu opened from it
339
353
  // (the Highlight menu's popup is in a portal).
@@ -373,7 +387,15 @@ export default function MilkdownEditor({ id, defaultValue, onChange, onProblem,
373
387
  // The field says it itself when the app hears of it through no
374
388
  // `onProblem` (a form that passes none would save the old text quietly).
375
389
  const ownProblem = onProblem ? null : refused;
376
- const describedBy = [ariaDescribedBy, ownProblem ? problemId : undefined, showCount ? counterId : undefined].filter(Boolean).join(' ');
390
+ // Tab staying in the text: the way out, told through the description,
391
+ // shown under the text the first time a Tab stays (until focus leaves).
392
+ const tabHintId = `${ids}-tab-hint`;
393
+ const tellsTab = tabStaysInText && !readOnly;
394
+ const [tabHintShown, setTabHintShown] = useState(false);
395
+ const tabHintUsed = useRef(false);
396
+ const describedBy = [ariaDescribedBy, tellsTab ? tabHintId : undefined, ownProblem ? problemId : undefined, showCount ? counterId : undefined]
397
+ .filter(Boolean)
398
+ .join(' ');
377
399
  const attributes = {
378
400
  'aria-multiline': 'true',
379
401
  'aria-readonly': String(readOnly),
@@ -408,8 +430,13 @@ export default function MilkdownEditor({ id, defaultValue, onChange, onProblem,
408
430
  attributes['aria-activedescendant'] = slashOptionId(slashListId, slashIndex);
409
431
  }
410
432
  const attributesKey = JSON.stringify(attributes);
411
- // The editor is made once, from the Markdown it opened with.
412
- useEffect(() => {
433
+ // `focusKey` changed: focus wanted, done at once or once the editor is up.
434
+ const focusWanted = useRef(false);
435
+ // The editor is made once, from the Markdown it opened with: in a layout
436
+ // effect, so the editor is built, and focused, in the task that puts it
437
+ // in the page, with no frame drawn between (an empty field there, an
438
+ // inline one collapsed for a moment, a key typed into nothing).
439
+ useLayoutEffect(() => {
413
440
  const root = rootRef.current;
414
441
  if (!root)
415
442
  return;
@@ -855,13 +882,88 @@ export default function MilkdownEditor({ id, defaultValue, onChange, onProblem,
855
882
  setEditorView(view);
856
883
  shown = shownKey(view.state);
857
884
  setEditorState(view.state);
858
- if (autoFocus)
859
- editor.action((ctx) => ctx.get(editorViewCtx).focus());
860
885
  if (foldKey !== undefined) {
861
886
  listenForOtherTabs();
862
887
  stopFolds = foldStore.subscribe(foldKey, () => view.dispatch(setFolds(view.state, foldStore.get(foldKey))));
863
888
  }
889
+ // Focus, and the keys typed while it loaded, only now that the
890
+ // baseline is read: typed in before, they'd be part of it, and never
891
+ // saved.
892
+ if (autoFocus)
893
+ start(view);
894
+ if (focusWanted.current) {
895
+ focusWanted.current = false;
896
+ view.focus();
897
+ }
864
898
  });
899
+ // autoFocus: the caret placed (at the start, or after the last words
900
+ // shown), focus, and the held keys typed in. Focus goes from the
901
+ // textarea to the text in one task, so a field around them (editing
902
+ // in place) never sees focus leave. Mid-composition, after it ends.
903
+ const start = (view) => {
904
+ const area = held?.element() ?? null;
905
+ const handOver = () => {
906
+ if (cancelled || view.isDestroyed)
907
+ return;
908
+ const text = area?.value ?? '';
909
+ if (autoFocus === 'end') {
910
+ const end = Selection.findFrom(view.state.doc.resolve(shownEnd(view.state)), -1, true);
911
+ if (end)
912
+ view.dispatch(view.state.tr.setSelection(end));
913
+ }
914
+ // Focus moved on from the textarea meanwhile (Tab): it stays there.
915
+ if (!area || document.activeElement === area)
916
+ view.focus();
917
+ if (text)
918
+ replayKeys(view, text);
919
+ if (autoFocus === 'end' || text)
920
+ view.dispatch(view.state.tr.scrollIntoView());
921
+ held?.release();
922
+ };
923
+ if (area && held?.composing())
924
+ area.addEventListener('compositionend', handOver, { once: true });
925
+ else
926
+ handOver();
927
+ };
928
+ // tabStaysInText: Tab and Shift+Tab that nothing in the text took
929
+ // (a list's indent, a table's next cell) stay in it, after
930
+ // ProseMirror's own keys. An Esc that reaches the field lets the next
931
+ // Tab go on to the page; any other key, a click or focus leaving
932
+ // takes that back.
933
+ let tabGoesOn = false;
934
+ const onRootKeyDown = (event) => {
935
+ if (!latest.current.tabStaysInText)
936
+ return;
937
+ if (event.key === 'Escape') {
938
+ tabGoesOn = !event.defaultPrevented || escapePassedThrough(event);
939
+ return;
940
+ }
941
+ if (event.key !== 'Tab') {
942
+ if (!MODIFIER_KEYS.has(event.key))
943
+ tabGoesOn = false;
944
+ return;
945
+ }
946
+ if (tabGoesOn) {
947
+ tabGoesOn = false;
948
+ return;
949
+ }
950
+ const view = editorRef.current?.action((ctx) => ctx.get(editorViewCtx));
951
+ if (!view || !view.editable || event.defaultPrevented || event.isComposing || event.ctrlKey || event.metaKey || event.altKey)
952
+ return;
953
+ if (!(event.target instanceof Node) || !view.dom.contains(event.target))
954
+ return;
955
+ event.preventDefault();
956
+ if (!tabHintUsed.current) {
957
+ tabHintUsed.current = true;
958
+ setTabHintShown(true);
959
+ }
960
+ };
961
+ const tabStays = () => {
962
+ tabGoesOn = false;
963
+ };
964
+ root.addEventListener('keydown', onRootKeyDown);
965
+ root.addEventListener('mousedown', tabStays);
966
+ root.addEventListener('focusout', tabStays);
865
967
  // Hiding the page (another tab, a phone's home screen) reports what
866
968
  // was typed: the page may not come back.
867
969
  const onHidden = () => {
@@ -871,6 +973,9 @@ export default function MilkdownEditor({ id, defaultValue, onChange, onProblem,
871
973
  document.addEventListener('visibilitychange', onHidden);
872
974
  window.addEventListener('pagehide', emit);
873
975
  return () => {
976
+ root.removeEventListener('keydown', onRootKeyDown);
977
+ root.removeEventListener('mousedown', tabStays);
978
+ root.removeEventListener('focusout', tabStays);
874
979
  document.removeEventListener('visibilitychange', onHidden);
875
980
  window.removeEventListener('pagehide', emit);
876
981
  // Unmounting reports what was typed since the last pause.
@@ -890,6 +995,26 @@ export default function MilkdownEditor({ id, defaultValue, onChange, onProblem,
890
995
  // Attributes and read-only follow below.
891
996
  // eslint-disable-next-line react-hooks/exhaustive-deps
892
997
  }, []);
998
+ // `focusKey` changed since it was last acted on: the text focused, the
999
+ // caret put back where it was in the same task (ProseMirror's focus
1000
+ // does), so a key typed at once lands there.
1001
+ const focusSeen = useRef(focusKey);
1002
+ const [ownNewFocus] = useState(() => (key) => {
1003
+ if (focusSeen.current === key)
1004
+ return false;
1005
+ focusSeen.current = key;
1006
+ return true;
1007
+ });
1008
+ const newFocus = isNewFocus ?? ownNewFocus;
1009
+ useLayoutEffect(() => {
1010
+ if (!newFocus(focusKey))
1011
+ return;
1012
+ const view = editorRef.current?.action((ctx) => ctx.get(editorViewCtx));
1013
+ if (view)
1014
+ view.focus();
1015
+ else
1016
+ focusWanted.current = true;
1017
+ }, [focusKey, newFocus]);
893
1018
  // The page links follow the app's answers (a page renamed, removed or
894
1019
  // restored): redrawn only when those have changed.
895
1020
  useEffect(() => {
@@ -1182,7 +1307,9 @@ export default function MilkdownEditor({ id, defaultValue, onChange, onProblem,
1182
1307
  // Raw HTML from the text: shown as its characters, never as markup.
1183
1308
  '[&_span[data-type=html]]:rounded [&_span[data-type=html]]:bg-muted [&_span[data-type=html]]:px-1 [&_span[data-type=html]]:font-mono [&_span[data-type=html]]:text-foreground',
1184
1309
  // The placeholder, in an empty document only (a decoration).
1185
- '[&_p[data-placeholder]]:before:pointer-events-none [&_p[data-placeholder]]:before:float-left [&_p[data-placeholder]]:before:h-0 [&_p[data-placeholder]]:before:text-muted-foreground [&_p[data-placeholder]]:before:content-[attr(data-placeholder)]') }), ownProblem && (_jsx("p", { id: problemId, role: "alert", "data-slot": "rich-text-editor-problem", className: cn('type-caption text-destructive-text', inline ? 'pt-1' : 'border-t border-border px-2.5 py-1.5', fullScreen && 'px-4 md:px-8'), children: ownProblem })), widgets.map((widget) => {
1310
+ '[&_p[data-placeholder]]:before:pointer-events-none [&_p[data-placeholder]]:before:float-left [&_p[data-placeholder]]:before:h-0 [&_p[data-placeholder]]:before:text-muted-foreground [&_p[data-placeholder]]:before:content-[attr(data-placeholder)]') }), tellsTab && (_jsx("p", { id: tabHintId, "data-slot": "rich-text-editor-tab-hint", className: tabHintShown && focused
1311
+ ? cn('type-caption text-muted-foreground', inline ? 'pt-1' : 'border-t border-border px-2.5 py-1.5', fullScreen && 'px-4 md:px-8')
1312
+ : 'sr-only', children: TAB_HINT })), ownProblem && (_jsx("p", { id: problemId, role: "alert", "data-slot": "rich-text-editor-problem", className: cn('type-caption text-destructive-text', inline ? 'pt-1' : 'border-t border-border px-2.5 py-1.5', fullScreen && 'px-4 md:px-8'), children: ownProblem })), widgets.map((widget) => {
1186
1313
  if (widget.type === 'callout')
1187
1314
  return createPortal(_jsx(CalloutKindMenu, { kind: widget.kind, readOnly: readOnly, onPick: (kind) => changeCallout(widget.getPos, kind), onRemove: () => changeCallout(widget.getPos, null), text: textElement }), widget.slot, widget.key);
1188
1315
  const active = caretTable !== undefined && caretTable === widget.getPos();
@@ -1208,7 +1335,7 @@ export default function MilkdownEditor({ id, defaultValue, onChange, onProblem,
1208
1335
  const next = event.relatedTarget;
1209
1336
  if (!editorView.dom.contains(next) && !inFloating(next))
1210
1337
  setFocused(false);
1211
- } }))] }), 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
1338
+ } }))] }), 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
1212
1339
  ? `${(length - maxLength).toLocaleString()} characters over the limit of ${maxLength.toLocaleString()}`
1213
1340
  : `${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) => {
1214
1341
  const editor = editorRef.current;
@@ -29,7 +29,35 @@ export type RichTextEditorProps = {
29
29
  onProblem?: (message: string | null) => void;
30
30
  /** Shown but not editable (while a save is in flight). */
31
31
  readOnly?: boolean;
32
- autoFocus?: boolean;
32
+ /**
33
+ * Takes focus as it mounts. `true`: the caret at the text's start;
34
+ * `'end'`: after its last words (past a divider or an image that ends
35
+ * it, and in a folded last section, at the end of its heading, which
36
+ * stays folded), scrolled into view. Neither saves anything. Keys typed
37
+ * while the editor's code is still loading are kept and typed in once
38
+ * it's up.
39
+ */
40
+ autoFocus?: boolean | 'end';
41
+ /**
42
+ * Focuses the text again, the caret where it was, each time this
43
+ * changes after the editor mounts: for an editor kept mounted while
44
+ * hidden (a tab behind another) that comes back to the front. The
45
+ * caret is put back as focus arrives, so a key typed at once lands
46
+ * where it was; focusing the editable element yourself leaves the
47
+ * caret at the start for a moment. A change before the editor is up
48
+ * focuses it once it is.
49
+ */
50
+ focusKey?: string | number;
51
+ /**
52
+ * Tab and Shift+Tab stay in the text, for an editor that is the page (a
53
+ * notes app's note): in a list or code they indent as always, and on a
54
+ * plain line they do nothing (Markdown holds no indent). Esc, then Tab,
55
+ * moves on (Shift+Tab back); Alt+F10 still reaches the toolbar. The way
56
+ * out is told through the field's description, and shown under it the
57
+ * first time a Tab stays. Default `false`: Tab on a plain line leaves the
58
+ * text, the keyboard's way on to the rest of the page.
59
+ */
60
+ tabStaysInText?: boolean;
33
61
  /** Shown while the document is empty (and given to screen readers as `aria-placeholder`). */
34
62
  placeholder?: string;
35
63
  /**
@@ -45,13 +45,19 @@ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-run
45
45
  // Markdown never downloads it. Until it arrives the text shows as
46
46
  // <Markdown> draws it, the field's size, so nothing moves when the editor
47
47
  // takes its place; an empty one shows skeleton lines. An app that opens on
48
- // an editor loads it ahead with `preloadRichTextEditor()`.
48
+ // an editor loads it ahead with `preloadRichTextEditor()`. Once loaded it's
49
+ // drawn at once; a load that failed is tried again by the next editor. Keys
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.
52
+ //
53
+ // What Markdown can't hold isn't saved: spaces at a line's start or end
54
+ // (rich-text-empty-paragraph.ts; inline code keeps its own) and blank lines
55
+ // typed for spacing.
49
56
  import { lazy, Suspense, useLayoutEffect, useRef, useState } from 'react';
50
57
  import { cn } from 'cn';
51
58
  import { Skeleton } from '../ui/skeleton.js';
52
59
  import { Markdown } from './markdown.js';
53
- import { loadRichTextEditor } from './rich-text-load.js';
54
- const MilkdownEditor = lazy(loadRichTextEditor);
60
+ import { loadedRichTextEditor, loadRichTextEditor } from './rich-text-load.js';
55
61
  // When the editor opens again: each time `defaultValue` changes to
56
62
  // Markdown it didn't report. Adjusted while rendering (React's "storing
57
63
  // information from previous renders"), so the new text never shows a
@@ -78,12 +84,37 @@ export function RichTextEditor(props) {
78
84
  useLayoutEffect(() => {
79
85
  live.current = opening;
80
86
  });
81
- return (_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',
82
- // The room of the add-row bar the editor draws under a table.
83
- !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) => {
84
- if (live.current !== opening)
85
- return;
86
- report(markdown);
87
- onChange(markdown);
88
- }, foldKey: props.foldable === false ? undefined : props.foldKey }, opening) }));
87
+ // Chosen once per mount: the editor itself when its code is here (drawn
88
+ // at once, no loading view), else loaded behind Suspense. The lazy is
89
+ // this mount's own, so a load that failed isn't kept for the next.
90
+ const [MilkdownEditor] = useState(() => loadedRichTextEditor()?.default ?? lazy(loadRichTextEditor));
91
+ // Loading, focused: a textarea beside the loading view holds the keys
92
+ // typed meanwhile, and the editor types them in once it's up
93
+ // (rich-text-held-keys.ts). Beside the Suspense boundary, not in its
94
+ // fallback, which goes the moment the editor's code arrives.
95
+ const [holding, setHolding] = useState(() => loadedRichTextEditor() === null && Boolean(props.autoFocus) && !props.readOnly);
96
+ const heldRef = useRef(null);
97
+ const composing = useRef(false);
98
+ const [held] = useState(() => ({
99
+ element: () => heldRef.current,
100
+ composing: () => composing.current,
101
+ release: () => setHolding(false),
102
+ }));
103
+ // The `focusKey` last acted on: kept here, so neither a load nor a
104
+ // remount (a reset) takes an unchanged key for a new one.
105
+ const focusHandled = useRef(props.focusKey);
106
+ const [isNewFocus] = useState(() => (key) => {
107
+ if (focusHandled.current === key)
108
+ return false;
109
+ focusHandled.current = key;
110
+ return true;
111
+ });
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',
113
+ // The room of the add-row bar the editor draws under a table.
114
+ !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
+ if (live.current !== opening)
116
+ return;
117
+ report(markdown);
118
+ onChange(markdown);
119
+ }, foldKey: props.foldable === false ? undefined : props.foldKey, held: holding ? held : undefined, isNewFocus: isNewFocus }, opening) })] }));
89
120
  }
@@ -1,4 +1,15 @@
1
+ import { Fragment } from '@milkdown/kit/prose/model';
1
2
  import type { NodeSchema } from '@milkdown/kit/transformer';
3
+ /**
4
+ * A line's spaces at its ends left out: at a text's start and end, and on
5
+ * either side of a hard break. Markdown keeps no indent and drops spaces at
6
+ * a line's end on reading, so these would save a note that reads back
7
+ * without them; remark-stringify writes one at a line's start as `&#x20;`.
8
+ * Not written out escaped instead: four spaces or a tab at a line's start
9
+ * would read back as a code block. Inline code keeps its own. The content
10
+ * itself when there's nothing to leave out.
11
+ */
12
+ export declare function withoutLineSpaces(content: Fragment): Fragment;
2
13
  /**
3
14
  * How a paragraph goes to Markdown, past Milkdown's own:
4
15
  *
@@ -9,9 +20,8 @@ import type { NodeSchema } from '@milkdown/kit/transformer';
9
20
  * ("- [ ] ", Enter at a list's end) would throw there and the edit would
10
21
  * never be saved.
11
22
  *
12
- * And a paragraph's spaces at its end are left out: Markdown drops them on
13
- * reading, so a pause after a space would save a note that reads back
14
- * without it, and remark-stringify sometimes writes it as `&#x20;`. A hard
15
- * break's spaces aren't these: it is a node of its own.
23
+ * And a paragraph carries no indent: spaces at the ends of its lines are
24
+ * left out (withoutLineSpaces), so a pause after a space, or an indent
25
+ * typed at a line's start, never saves as `&#x20;`.
16
26
  */
17
27
  export declare function withEmptyParagraphChildren<Ctx>(previous: (ctx: Ctx) => NodeSchema): (ctx: Ctx) => NodeSchema;
@@ -1,3 +1,50 @@
1
+ import { Fragment } from '@milkdown/kit/prose/model';
2
+ const HARD_BREAK = 'hardbreak';
3
+ // Text that is code keeps its spaces: they're part of what it says.
4
+ const isCode = (node) => node.marks.some((mark) => mark.type.spec.code);
5
+ /**
6
+ * A line's spaces at its ends left out: at a text's start and end, and on
7
+ * either side of a hard break. Markdown keeps no indent and drops spaces at
8
+ * a line's end on reading, so these would save a note that reads back
9
+ * without them; remark-stringify writes one at a line's start as `&#x20;`.
10
+ * Not written out escaped instead: four spaces or a tab at a line's start
11
+ * would read back as a code block. Inline code keeps its own. The content
12
+ * itself when there's nothing to leave out.
13
+ */
14
+ export function withoutLineSpaces(content) {
15
+ const nodes = [];
16
+ content.forEach((node) => nodes.push(node));
17
+ let changed = false;
18
+ const trim = (index, side) => {
19
+ // Past text that is only spaces, to the text that ends the line.
20
+ for (let at = index; at >= 0 && at < nodes.length; at += side === 'start' ? 1 : -1) {
21
+ const node = nodes[at];
22
+ if (!node.isText || isCode(node))
23
+ return;
24
+ const text = node.text ?? '';
25
+ const kept = side === 'start' ? text.replace(/^[ \t]+/, '') : text.replace(/[ \t]+$/, '');
26
+ if (kept === text)
27
+ return;
28
+ changed = true;
29
+ if (kept) {
30
+ nodes[at] = node.type.schema.text(kept, node.marks);
31
+ return;
32
+ }
33
+ nodes.splice(at, 1);
34
+ if (side === 'start')
35
+ at -= 1;
36
+ }
37
+ };
38
+ trim(0, 'start');
39
+ trim(nodes.length - 1, 'end');
40
+ for (let index = nodes.length - 1; index >= 0; index--) {
41
+ if (nodes[index].type.name !== HARD_BREAK)
42
+ continue;
43
+ trim(index + 1, 'start');
44
+ trim(index - 1, 'end');
45
+ }
46
+ return changed ? Fragment.fromArray(nodes) : content;
47
+ }
1
48
  /**
2
49
  * How a paragraph goes to Markdown, past Milkdown's own:
3
50
  *
@@ -8,10 +55,9 @@
8
55
  * ("- [ ] ", Enter at a list's end) would throw there and the edit would
9
56
  * never be saved.
10
57
  *
11
- * And a paragraph's spaces at its end are left out: Markdown drops them on
12
- * reading, so a pause after a space would save a note that reads back
13
- * without it, and remark-stringify sometimes writes it as `&#x20;`. A hard
14
- * break's spaces aren't these: it is a node of its own.
58
+ * And a paragraph carries no indent: spaces at the ends of its lines are
59
+ * left out (withoutLineSpaces), so a pause after a space, or an indent
60
+ * typed at a line's start, never saves as `&#x20;`.
15
61
  */
16
62
  export function withEmptyParagraphChildren(previous) {
17
63
  return (ctx) => {
@@ -22,9 +68,8 @@ export function withEmptyParagraphChildren(previous) {
22
68
  toMarkdown: {
23
69
  ...base.toMarkdown,
24
70
  runner: (state, node) => {
25
- const last = node.lastChild;
26
- const spaces = last?.isText ? (/[ \t]+$/.exec(last.text ?? '')?.[0].length ?? 0) : 0;
27
- const kept = spaces ? node.copy(node.content.cut(0, node.content.size - spaces)) : node;
71
+ const content = withoutLineSpaces(node.content);
72
+ const kept = content === node.content ? node : node.copy(content);
28
73
  if (kept.content.size === 0)
29
74
  state.addNode('paragraph', []);
30
75
  else
@@ -21,6 +21,12 @@ export declare function docFoldPlan(doc: ProseNode, folded?: ReadonlySet<string>
21
21
  export declare function foldSpecOf(decorations: readonly Decoration[]): FoldSpec | null;
22
22
  /** A transaction that sets what's folded, from outside the editor. */
23
23
  export declare function setFolds(state: EditorState, folded: ReadonlySet<string>): import("prosemirror-state").Transaction;
24
+ /**
25
+ * Where the text that shows ends: the document's end, or, when its last
26
+ * blocks are folded away, the end of the outermost heading folding them
27
+ * (a caret put past it would open the section).
28
+ */
29
+ export declare function shownEnd(state: EditorState): number;
24
30
  export declare function foldPlugin(options: {
25
31
  initial: ReadonlySet<string>;
26
32
  onChange: (folded: ReadonlySet<string>) => void;
@@ -64,6 +64,26 @@ function caretToEnd(state, index) {
64
64
  });
65
65
  return state.tr.setSelection(TextSelection.create(state.doc, end)).scrollIntoView();
66
66
  }
67
+ /**
68
+ * Where the text that shows ends: the document's end, or, when its last
69
+ * blocks are folded away, the end of the outermost heading folding them
70
+ * (a caret put past it would open the section).
71
+ */
72
+ export function shownEnd(state) {
73
+ const fold = foldPluginKey.getState(state);
74
+ const last = state.doc.childCount - 1;
75
+ if (!fold || !fold.plan.hidden.has(last))
76
+ return state.doc.content.size;
77
+ const outer = fold.plan.headings.find((heading) => heading.foldable && fold.folded.has(heading.id) && heading.index < last && last < heading.end);
78
+ if (!outer)
79
+ return state.doc.content.size;
80
+ let end = state.doc.content.size;
81
+ state.doc.forEach((node, offset, index) => {
82
+ if (index === outer.index)
83
+ end = offset + node.nodeSize - 1;
84
+ });
85
+ return end;
86
+ }
67
87
  export function foldPlugin(options) {
68
88
  return new Plugin({
69
89
  key: foldPluginKey,
@@ -0,0 +1,12 @@
1
+ import type { EditorView } from '@milkdown/kit/prose/view';
2
+ /** The textarea's side of the hand-over (rich-text-editor.tsx). */
3
+ export type HeldKeys = {
4
+ /** The textarea holding the keys, if it's still there. */
5
+ element: () => HTMLTextAreaElement | null;
6
+ /** A composition (an IME, a phone's suggestions) is open in it. */
7
+ composing: () => boolean;
8
+ /** The editor has the text: the textarea goes. */
9
+ release: () => void;
10
+ };
11
+ /** Types `text` into the view at its caret, as typed: each character as text input, each newline as Enter. */
12
+ export declare function replayKeys(view: EditorView, text: string): void;
@@ -0,0 +1,15 @@
1
+ /** Types `text` into the view at its caret, as typed: each character as text input, each newline as Enter. */
2
+ export function replayKeys(view, text) {
3
+ for (const character of text.replace(/\r\n?/g, '\n')) {
4
+ if (character === '\n') {
5
+ const enter = new KeyboardEvent('keydown', { key: 'Enter', code: 'Enter', bubbles: true, cancelable: true });
6
+ if (!view.someProp('handleKeyDown', (handle) => handle(view, enter)))
7
+ view.dispatch(view.state.tr.split(view.state.selection.from).scrollIntoView());
8
+ continue;
9
+ }
10
+ const { from, to } = view.state.selection;
11
+ const typed = () => view.state.tr.insertText(character, from, to);
12
+ if (!view.someProp('handleTextInput', (handle) => handle(view, from, to, character, typed)))
13
+ view.dispatch(typed().scrollIntoView());
14
+ }
15
+ }
@@ -1,11 +1,15 @@
1
- /** The editor's module, fetched once: later calls get the same one. */
2
- export declare const loadRichTextEditor: () => Promise<typeof import("./milkdown-editor.js")>;
1
+ type EditorModule = typeof import('./milkdown-editor.js');
2
+ /** The editor's module, fetched once: later calls get the same one. A failed load is tried again by the next call. */
3
+ export declare function loadRichTextEditor(): Promise<EditorModule>;
4
+ /** The editor's module if it has loaded, else `null`. */
5
+ export declare function loadedRichTextEditor(): EditorModule | null;
3
6
  /**
4
7
  * Starts loading the editor now, before one is on screen: an app whose
5
8
  * first screen is an editor (a notes app that opens on a note) calls it as
6
9
  * the app starts, so the editor is there when the note is, not a moment
7
10
  * after it. Safe to call more than once, and anywhere: it never throws,
8
- * and a failed load is swallowed here, so the page goes on; the editor
9
- * meets the same failure when one mounts, as it would with no preload.
11
+ * and a failed load is swallowed here, so the page goes on; the next
12
+ * editor to mount tries again.
10
13
  */
11
14
  export declare function preloadRichTextEditor(): void;
15
+ export {};
@@ -1,15 +1,34 @@
1
1
  // The editor's own code (Milkdown), loaded apart from the page that shows
2
2
  // it: RichTextEditor asks for it when it first mounts, and an app that
3
3
  // opens on an editor asks ahead with `preloadRichTextEditor()`.
4
- /** The editor's module, fetched once: later calls get the same one. */
5
- export const loadRichTextEditor = () => import('./milkdown-editor.js');
4
+ //
5
+ // Once loaded, the module is kept: an editor mounted after that is drawn
6
+ // at once, with no loading view. A load that fails is forgotten, so the
7
+ // next editor to mount asks again (a chunk that failed once, the network
8
+ // down for a moment, needn't fail every editor until a reload).
9
+ let loaded = null;
10
+ let loading = null;
11
+ /** The editor's module, fetched once: later calls get the same one. A failed load is tried again by the next call. */
12
+ export function loadRichTextEditor() {
13
+ if (loaded)
14
+ return Promise.resolve(loaded);
15
+ loading ??= import('./milkdown-editor.js').then((module) => (loaded = module), (error) => {
16
+ loading = null;
17
+ throw error;
18
+ });
19
+ return loading;
20
+ }
21
+ /** The editor's module if it has loaded, else `null`. */
22
+ export function loadedRichTextEditor() {
23
+ return loaded;
24
+ }
6
25
  /**
7
26
  * Starts loading the editor now, before one is on screen: an app whose
8
27
  * first screen is an editor (a notes app that opens on a note) calls it as
9
28
  * the app starts, so the editor is there when the note is, not a moment
10
29
  * after it. Safe to call more than once, and anywhere: it never throws,
11
- * and a failed load is swallowed here, so the page goes on; the editor
12
- * meets the same failure when one mounts, as it would with no preload.
30
+ * and a failed load is swallowed here, so the page goes on; the next
31
+ * editor to mount tries again.
13
32
  */
14
33
  export function preloadRichTextEditor() {
15
34
  void loadRichTextEditor().catch(() => { });
@@ -20,7 +20,9 @@
20
20
  // the text where it can't move (a first item): Tab leaving the editor
21
21
  // from one item and not the next would be a surprise. In a code block they
22
22
  // indent and outdent its lines by two spaces. On a plain line Tab still
23
- // leaves the editor, the keyboard's way on to the rest of the page.
23
+ // leaves the editor, the keyboard's way on to the rest of the page,
24
+ // unless the editor has `tabStaysInText` (milkdown-editor.tsx: Esc, then
25
+ // Tab, moves on).
24
26
  // - Undo and redo (Mod+Z; Mod+Shift+Z, and Ctrl+Y off Apple) are taken
25
27
  // here whether or not there is a step to take: ProseMirror's keymap,
26
28
  // finding nothing to redo, would run Shift+Mod+Z's unshifted key, Mod+Z,
@@ -15,6 +15,7 @@ import { headingSchema } from '@milkdown/kit/preset/commonmark';
15
15
  import { textblockTypeInputRule } from '@milkdown/kit/prose/inputrules';
16
16
  import { $inputRule, $remark } from '@milkdown/kit/utils';
17
17
  import { remarkToggleHeadings, TOGGLE_MARKER } from '../../lib/markdown-toggle.js';
18
+ import { withoutLineSpaces } from './rich-text-empty-paragraph.js';
18
19
  export const toggleHeadingRemark = $remark('remarkToggleHeadings', () => remarkToggleHeadings);
19
20
  /**
20
21
  * Milkdown's heading schema with the `toggle` attribute, read from and
@@ -38,9 +39,11 @@ export function withToggle(previous) {
38
39
  match: (node) => node.type.name === 'heading',
39
40
  runner: (state, node) => {
40
41
  state.openNode('heading', undefined, { depth: node.attrs.level });
41
- // A hard break at the end is left out, as Milkdown's own does.
42
+ // A hard break at the end is left out, as Milkdown's own does,
43
+ // and spaces at either end (withoutLineSpaces): a heading's
44
+ // Markdown keeps neither, and one at the start is `&#x20;`.
42
45
  const last = node.lastChild;
43
- const content = last?.type.name === 'hardbreak' ? node.content.cut(0, node.content.size - last.nodeSize) : node.content;
46
+ const content = withoutLineSpaces(last?.type.name === 'hardbreak' ? node.content.cut(0, node.content.size - last.nodeSize) : node.content);
44
47
  state.next(content);
45
48
  if (node.attrs.toggle)
46
49
  state.addNode('text', undefined, content.size > 0 ? ` ${TOGGLE_MARKER}` : TOGGLE_MARKER);
@@ -122,6 +122,23 @@ function meaning(node, definitions) {
122
122
  else
123
123
  out[key] = key === 'children' && INLINE_PARENTS.has(md.type) ? runs(md.children ?? [], definitions) : meaning(value, definitions);
124
124
  }
125
+ if (LINE_PARENTS.has(md.type))
126
+ withoutEndSpaces(out.children);
127
+ return finish(md, out);
128
+ }
129
+ // Blocks whose spaces at either end mean nothing: the editor leaves them
130
+ // out of what it writes (rich-text-empty-paragraph.ts), so a note that
131
+ // holds one (`&#x20;` at a paragraph's start) still matches what it shows.
132
+ const LINE_PARENTS = new Set(['paragraph', 'heading']);
133
+ function withoutEndSpaces(children) {
134
+ const first = children[0];
135
+ if (first?.type === 'text')
136
+ first.value = String(first.value).replace(/^[ \t]+/, '');
137
+ const last = children.at(-1);
138
+ if (last?.type === 'text')
139
+ last.value = String(last.value).replace(/[ \t]+$/, '');
140
+ }
141
+ function finish(md, out) {
125
142
  if ((md.type === 'link' || md.type === 'image') && out.title === undefined)
126
143
  out.title = null;
127
144
  if (md.type === 'table') {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tristan2828/ui-foundation",
3
- "version": "4.151.0",
3
+ "version": "4.153.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": {