@tristan2828/ui-foundation 4.150.0 → 4.152.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–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
49
49
 
50
50
  <!-- /index -->
51
51
 
@@ -1020,7 +1020,9 @@ 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.
@@ -1073,8 +1075,8 @@ doesn't move.
1073
1075
 
1074
1076
  **Always editable (`alwaysEditable: true`, implies `autosave`)**: the
1075
1077
  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
1078
+ to open, and it never closes. Ctrl/Cmd+Enter, Ctrl/Cmd+S or Esc saves now
1079
+ and leaves the caret where it is. It sits beside the one open value rather than
1078
1080
  being it: opening another value leaves it alone. Don't give its control
1079
1081
  `autoFocus`. The cost: at rest the page shows the editor, not the read
1080
1082
  view, and the editor loads on every visit (an app whose first screen is
@@ -1164,7 +1166,11 @@ const price = editInPlace({
1164
1166
  can't save without rewriting text nobody touched is never saved: on a
1165
1167
  form, bind its `onProblem` to the field's error and refuse submit while
1166
1168
  it stands (add-an-entity.md, `widget-form.tsx`); with no `onProblem` it
1167
- says so inside the field. Notion's block keys
1169
+ says so inside the field. The Markdown holds what Markdown can: a
1170
+ paragraph or heading carries no indent, so spaces typed at a line's
1171
+ start (or end) show until the note is next opened and aren't saved
1172
+ (inline code keeps its own), and blank lines typed for spacing aren't
1173
+ saved either: three Enters leave one paragraph break. Notion's block keys
1168
1174
  work: Ctrl+Shift+1 to 3 for headings, +4 tasks, +5 bullets, +6 numbers,
1169
1175
  +8 a code block, +0 back to text (Cmd+Option on a Mac), and
1170
1176
  Ctrl/Cmd+Shift+S strikes through. Ctrl/Cmd+Enter stays the save, in a
@@ -1531,6 +1537,16 @@ const body = editInPlace<string>({
1531
1537
  tabs are: one pane per open note, all mounted, only the one in front
1532
1538
  shown (the others `hidden`), so each keeps its caret and undo. A
1533
1539
  hidden value still saves, and the one leave guard covers them all.
1540
+ The editor's `focusKey` (a number the app bumps as a tab comes to the
1541
+ front) focuses it again with its caret put back in the same task, so
1542
+ a key typed at once lands where it was; don't focus the editable
1543
+ element through the DOM, which leaves the caret at the text's start
1544
+ for a moment.
1545
+ - **An editor that is the page** (a note the app opens on) takes
1546
+ `autoFocus="end"`, the caret after its last words, in view, and
1547
+ `tabStaysInText`: Tab on a plain line stays in the text (Esc, then
1548
+ Tab, moves on, which the field tells and shows), so a Tab typed out of
1549
+ habit doesn't land on the next control and a Space press it.
1534
1550
  - **Tabs that are URLs** (`/notes/1`, `/notes/2`, the one in front
1535
1551
  being the route) pass `staysOnPage`, given the next location (and the
1536
1552
  current one), true for a move that only brings another of the scope's
@@ -1553,7 +1569,9 @@ const body = editInPlace<string>({
1553
1569
  as it starts (in `main.tsx`), so the editor's code is loading while
1554
1570
  the note is fetched, not after. It returns nothing, never throws, and
1555
1571
  is safe to call more than once; a failed load is the editor's to meet
1556
- when one mounts.
1572
+ when one mounts, and the next editor to mount tries again. Keys typed
1573
+ into an `autoFocus` editor while its code still loads are kept, and
1574
+ typed in once it's up.
1557
1575
 
1558
1576
  The stories are `app/EditInPlaceScope` (one note, two in one scope, and
1559
1577
  the two as URL tabs with `staysOnPage`);
@@ -9,7 +9,7 @@ to the device, where the app's service worker shows it.
9
9
 
10
10
  | Part | Where | What it does |
11
11
  |---|---|---|
12
- | `pwa({ name })` | `vite.config.ts`, from `@tristan2828/ui-foundation/vite` | The app installable: a manifest, icons in the theme's colours, and `/push-sw.js`, the service worker that shows pushes and opens their path |
12
+ | `pwa({ name })` | `vite.config.ts`, from `@tristan2828/ui-foundation/vite` | The app installable: a manifest, icons in the theme's colours (or the app's own), and `/push-sw.js`, the service worker that shows pushes and opens their path |
13
13
  | `usePushPermission()` | the package | Whether this device gets reminders, and `enable`/`disable` |
14
14
  | `AllowReminders` | the package | The control: says what reminders are, then asks, on a click |
15
15
  | `/push/public-key`, `/push/subscriptions` | `openapi.yaml`, the foundation's part (optional) | The VAPID key to subscribe with; this device's subscription saved or dropped |
@@ -53,6 +53,38 @@ there is no push at all, so `usePushPermission` says `needs-install` and
53
53
  `AllowReminders` shows the steps. `pwa()`'s manifest (`display:
54
54
  standalone`) is what makes the Home Screen app an app.
55
55
 
56
+ ## The app's own icon
57
+
58
+ Without one, `pwa()` draws the icons: an SVG with the name's first letter,
59
+ and PNGs of the theme colour alone (a letter in a PNG needs a font
60
+ rasteriser the package doesn't carry). An app with its own mark passes it,
61
+ each a path from the Vite root:
62
+
63
+ ```ts
64
+ pwa({
65
+ name: 'Quick Jot',
66
+ icon: 'icons/icon-512.png', // a square PNG, 512×512 or more
67
+ smallIcon: 'icons/icon-192.png', // the same at 192×192
68
+ maskableIcon: 'icons/icon-maskable-512.png', // the mark inside the safe zone, background to the edges
69
+ iconSvg: 'icons/icon.svg', // the mark as an SVG
70
+ })
71
+ ```
72
+
73
+ | Option | In the manifest | Used for |
74
+ |---|---|---|
75
+ | `icon` (a PNG) | an `any` entry | iOS's Home Screen (the apple-touch-icon), a push's icon without `smallIcon`, and wherever nothing better fits |
76
+ | `smallIcon` (a PNG) | an `any` entry | Windows' Start menu and taskbar and the install prompt, which would scale the large one down; a push's icon |
77
+ | `maskableIcon` (a PNG) | the `maskable` entry | Android's Home Screen, cropped to the launcher's circle or squircle. Keep the mark inside the central 80% circle and the background to every edge. Without one, Android draws `icon` shrunk on a plain disc |
78
+ | `iconSvg` (an SVG) | an `any` entry with `sizes: "any"` | Chrome and Android, sharp at every size |
79
+
80
+ Each PNG's `sizes` is read from its own header, so a 1024×1024 `icon` is
81
+ named 1024x1024. The three beside `icon` need it (iOS takes a PNG only)
82
+ and are each optional: `icon` alone gives the manifest that one entry, as
83
+ before. `pwa()` can't resize a PNG (that needs a rasteriser, which isn't on
84
+ the allowlist), so export the 192 and maskable copies from the same artwork
85
+ in an image editor and commit the PNGs beside the large one. An SVG passed as `icon` is refused:
86
+ pass it as `iconSvg` beside a PNG.
87
+
56
88
  ## Home-screen shortcuts
57
89
 
58
90
  `pwa({ name, shortcuts: [{ name: 'Add To-Do', url: '/todo/add' }] })` writes
@@ -214,9 +214,10 @@ function CollapsibleNavGroup({ group, activeTo }) {
214
214
  }
215
215
  // The phone's back arrow, below the md breakpoint only: the
216
216
  // shell's own way up from a page below a nav entry. Its label is the
217
- // place it goes, so it reads "Back to Accounts".
217
+ // place it goes, so it reads "Back to Accounts". A finger's 44px tall on
218
+ // a touch screen, inside the 56px bar; a mouse keeps the 32px button.
218
219
  function PhoneBack({ back }) {
219
- return (_jsxs(Link, { to: back.to, "data-slot": "app-shell-back", "aria-label": `Back to ${back.label}`, className: cn(buttonVariants({ variant: 'ghost', size: 'sm' }), '-ml-2 max-w-[60vw] gap-0.5 px-1.5 text-link hover:text-link md:hidden'), children: [_jsx(ChevronLeftIcon, { "aria-hidden": "true" }), _jsx("span", { className: "truncate", children: back.label })] }));
220
+ return (_jsxs(Link, { to: back.to, "data-slot": "app-shell-back", "aria-label": `Back to ${back.label}`, className: cn(buttonVariants({ variant: 'ghost', size: 'sm' }), '-ml-2 max-w-[60vw] gap-0.5 px-1.5 text-link hover:text-link pointer-coarse:h-11 md:hidden'), children: [_jsx(ChevronLeftIcon, { "aria-hidden": "true" }), _jsx("span", { className: "truncate", children: back.label })] }));
220
221
  }
221
222
  function AppShellSkeleton() {
222
223
  return (_jsxs("div", { className: "flex h-screen w-full gap-4 p-4", "data-state": "loading", children: [_jsx(Skeleton, { className: "h-full w-56 shrink-0" }), _jsxs("div", { className: "flex-1 space-y-4 pt-2", children: [_jsx(Skeleton, { className: "h-8 w-64" }), _jsx(Skeleton, { className: "h-40 w-full" })] })] }));
@@ -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
@@ -66,6 +67,10 @@ const INTERACTIVE = 'a[href], button, input, select, textarea, label, [role="but
66
67
  // order (a picker's text box before its chips' remove buttons). A box's
67
68
  // own native input (a checkbox's, hidden and out of the tab order) isn't
68
69
  // a place to type: a list item's text box comes first.
70
+ // Ctrl/Cmd+S, by the key's place (a layout whose S key types another letter too).
71
+ function isSaveKey(event) {
72
+ return (event.metaKey || event.ctrlKey) && !event.shiftKey && !event.altKey && (event.code === 'KeyS' || event.key.toLowerCase() === 's');
73
+ }
69
74
  const FOCUS_ORDER = [
70
75
  'input:not([type="hidden"]):not([tabindex="-1"]):not([aria-hidden="true"]), textarea, [contenteditable="true"]',
71
76
  '[role="combobox"], [role="switch"], button, [tabindex]:not([tabindex="-1"])',
@@ -384,6 +389,13 @@ export function EditableField({ label, edit, children, layout = 'block', look =
384
389
  else
385
390
  commitFromKeyboard();
386
391
  }
392
+ else if (autosave && isSaveKey(event)) {
393
+ // Ctrl/Cmd+S, by habit: saves now and stays open, in place of the
394
+ // browser's Save Page dialog over a value that saves itself.
395
+ event.preventDefault();
396
+ window.clearTimeout(blurTimer.current);
397
+ void store.saveNow(key);
398
+ }
387
399
  else if (event.key === 'Enter' && edit.kind === 'text' && !event.shiftKey && !event.altKey) {
388
400
  event.preventDefault();
389
401
  commitFromKeyboard();
@@ -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;
@@ -58,18 +58,25 @@ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-run
58
58
  // - `foldKey`: the text folds by its toggle headings, as <Markdown> does
59
59
  // (rich-text-fold.ts), remembered on this device and shared with
60
60
  // NotesOutline; the document never changes.
61
+ // - Built in a layout effect, focused (`autoFocus`, `'end'` after the last
62
+ // words shown) only once the baseline is read, with any keys typed while
63
+ // it loaded typed in after (rich-text-held-keys.ts). `focusKey` focuses
64
+ // it again, the caret put back as focus arrives.
65
+ // - `tabStaysInText`: Tab and Shift+Tab nothing in the text took stay in
66
+ // it; Esc, then Tab, moves on, told through the field's description and
67
+ // shown under it the first time.
61
68
  // - `pageLink`: links the app marks as its pages drawn as page links,
62
69
  // opened in this tab; `onCreatePage`: "/page" and Turn into page make
63
70
  // one through the app and link it (a title box, rich-text-page-box.tsx).
64
71
  // The Markdown stays a plain link.
65
- import { useEffect, useId, useRef, useState } from 'react';
72
+ import { useEffect, useId, useLayoutEffect, useRef, useState } from 'react';
66
73
  import { createPortal } from 'react-dom';
67
74
  import { useInRouterContext, useNavigate } from 'react-router';
68
75
  import { defaultValueCtx, Editor, editorViewCtx, editorViewOptionsCtx, parserCtx, remarkStringifyOptionsCtx, rootCtx, schemaCtx, serializerCtx, } from '@milkdown/kit/core';
69
76
  import { history } from '@milkdown/kit/plugin/history';
70
77
  import { commands, headingSchema, paragraphSchema, keymap, plugins, remarkPreserveEmptyLinePlugin, schema, } from '@milkdown/kit/preset/commonmark';
71
78
  import { gfm, tableCellSchema, tableHeaderSchema, tableSchema } from '@milkdown/kit/preset/gfm';
72
- import { NodeSelection, Plugin, TextSelection } from '@milkdown/kit/prose/state';
79
+ import { NodeSelection, Plugin, Selection, TextSelection } from '@milkdown/kit/prose/state';
73
80
  import { isInTable, selectedRect, TableMap } from '@milkdown/kit/prose/tables';
74
81
  import { Decoration, DecorationSet } from '@milkdown/kit/prose/view';
75
82
  import { $markSchema, $nodeSchema, $prose, $remark, getMarkdown } from '@milkdown/kit/utils';
@@ -81,7 +88,7 @@ import { linkHref } from '../../lib/link-href.js';
81
88
  import { messageOf } from '../../lib/refusal.js';
82
89
  import { restorePage } from './page-restore.js';
83
90
  import { insertPageLink, pageLinksPlugin, pendingPagePlugin, refreshPageLinks, setPendingPage, } from './rich-text-page-links.js';
84
- import { passEscapeThrough } from './escape-passthrough.js';
91
+ import { escapePassedThrough, passEscapeThrough } from './escape-passthrough.js';
85
92
  import { calloutHandler, remarkCalloutNodes } from '../../lib/markdown-callout.js';
86
93
  import { formatTableWidths, remarkTableWidths } from '../../lib/markdown-table-widths.js';
87
94
  import { DEFAULT_HIGHLIGHT, highlightHandler, isHighlightColor, remarkHighlightNodes } from '../../lib/markdown-highlight.js';
@@ -91,7 +98,8 @@ import { holdPendingEdit } from '../../lib/pending-edits.js';
91
98
  import { foldStore, listenForOtherTabs } from '../../hooks/fold-store.js';
92
99
  import { toggleFold } from '../../lib/markdown-fold.js';
93
100
  import { DEFAULT_HEADING_LEVEL } from './prose-look.js';
94
- import { foldPlugin, setFolds } from './rich-text-fold.js';
101
+ import { foldPlugin, setFolds, shownEnd } from './rich-text-fold.js';
102
+ import { replayKeys } from './rich-text-held-keys.js';
95
103
  import { headingView } from './rich-text-heading-view.js';
96
104
  import { taskItemView, toggleTaskItem } from './rich-text-task-item-view.js';
97
105
  import { applyLink, followLink, linkTarget, notePress } from './rich-text-links.js';
@@ -279,7 +287,11 @@ function NavigateBridge({ targetRef }) {
279
287
  }, [navigate, targetRef]);
280
288
  return null;
281
289
  }
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, }) {
290
+ // What the field tells, and shows the first time a Tab stays in the text.
291
+ const TAB_HINT = 'Tab stays in the text. Press Esc, then Tab, to move on.';
292
+ // Keys on their own that come before another (Shift, for Shift+Tab).
293
+ const MODIFIER_KEYS = new Set(['Shift', 'Control', 'Alt', 'Meta']);
294
+ 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
295
  const rootRef = useRef(null);
284
296
  const editorRef = useRef(null);
285
297
  const [linkBox, setLinkBox] = useState(null);
@@ -331,9 +343,9 @@ export default function MilkdownEditor({ id, defaultValue, onChange, onProblem,
331
343
  // rendered into through a portal.
332
344
  const [widgets, setWidgets] = useState([]);
333
345
  // 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 });
346
+ const latest = useRef({ onChange, onProblem, readOnly, placeholder, upload, imageAccept, imageMaxSize, pageLink, onCreatePage, tabStaysInText });
335
347
  useEffect(() => {
336
- latest.current = { onChange, onProblem, readOnly, placeholder, upload, imageAccept, imageMaxSize, pageLink, onCreatePage };
348
+ latest.current = { onChange, onProblem, readOnly, placeholder, upload, imageAccept, imageMaxSize, pageLink, onCreatePage, tabStaysInText };
337
349
  });
338
350
  // Whether focus is on the floating toolbar, or in a menu opened from it
339
351
  // (the Highlight menu's popup is in a portal).
@@ -373,7 +385,15 @@ export default function MilkdownEditor({ id, defaultValue, onChange, onProblem,
373
385
  // The field says it itself when the app hears of it through no
374
386
  // `onProblem` (a form that passes none would save the old text quietly).
375
387
  const ownProblem = onProblem ? null : refused;
376
- const describedBy = [ariaDescribedBy, ownProblem ? problemId : undefined, showCount ? counterId : undefined].filter(Boolean).join(' ');
388
+ // Tab staying in the text: the way out, told through the description,
389
+ // shown under the text the first time a Tab stays (until focus leaves).
390
+ const tabHintId = `${ids}-tab-hint`;
391
+ const tellsTab = tabStaysInText && !readOnly;
392
+ const [tabHintShown, setTabHintShown] = useState(false);
393
+ const tabHintUsed = useRef(false);
394
+ const describedBy = [ariaDescribedBy, tellsTab ? tabHintId : undefined, ownProblem ? problemId : undefined, showCount ? counterId : undefined]
395
+ .filter(Boolean)
396
+ .join(' ');
377
397
  const attributes = {
378
398
  'aria-multiline': 'true',
379
399
  'aria-readonly': String(readOnly),
@@ -408,8 +428,13 @@ export default function MilkdownEditor({ id, defaultValue, onChange, onProblem,
408
428
  attributes['aria-activedescendant'] = slashOptionId(slashListId, slashIndex);
409
429
  }
410
430
  const attributesKey = JSON.stringify(attributes);
411
- // The editor is made once, from the Markdown it opened with.
412
- useEffect(() => {
431
+ // `focusKey` changed: focus wanted, done at once or once the editor is up.
432
+ const focusWanted = useRef(false);
433
+ // The editor is made once, from the Markdown it opened with: in a layout
434
+ // effect, so the editor is built, and focused, in the task that puts it
435
+ // in the page, with no frame drawn between (an empty field there, an
436
+ // inline one collapsed for a moment, a key typed into nothing).
437
+ useLayoutEffect(() => {
413
438
  const root = rootRef.current;
414
439
  if (!root)
415
440
  return;
@@ -855,13 +880,88 @@ export default function MilkdownEditor({ id, defaultValue, onChange, onProblem,
855
880
  setEditorView(view);
856
881
  shown = shownKey(view.state);
857
882
  setEditorState(view.state);
858
- if (autoFocus)
859
- editor.action((ctx) => ctx.get(editorViewCtx).focus());
860
883
  if (foldKey !== undefined) {
861
884
  listenForOtherTabs();
862
885
  stopFolds = foldStore.subscribe(foldKey, () => view.dispatch(setFolds(view.state, foldStore.get(foldKey))));
863
886
  }
887
+ // Focus, and the keys typed while it loaded, only now that the
888
+ // baseline is read: typed in before, they'd be part of it, and never
889
+ // saved.
890
+ if (autoFocus)
891
+ start(view);
892
+ if (focusWanted.current) {
893
+ focusWanted.current = false;
894
+ view.focus();
895
+ }
864
896
  });
897
+ // autoFocus: the caret placed (at the start, or after the last words
898
+ // shown), focus, and the held keys typed in. Focus goes from the
899
+ // textarea to the text in one task, so a field around them (editing
900
+ // in place) never sees focus leave. Mid-composition, after it ends.
901
+ const start = (view) => {
902
+ const area = held?.element() ?? null;
903
+ const handOver = () => {
904
+ if (cancelled || view.isDestroyed)
905
+ return;
906
+ const text = area?.value ?? '';
907
+ if (autoFocus === 'end') {
908
+ const end = Selection.findFrom(view.state.doc.resolve(shownEnd(view.state)), -1, true);
909
+ if (end)
910
+ view.dispatch(view.state.tr.setSelection(end));
911
+ }
912
+ // Focus moved on from the textarea meanwhile (Tab): it stays there.
913
+ if (!area || document.activeElement === area)
914
+ view.focus();
915
+ if (text)
916
+ replayKeys(view, text);
917
+ if (autoFocus === 'end' || text)
918
+ view.dispatch(view.state.tr.scrollIntoView());
919
+ held?.release();
920
+ };
921
+ if (area && held?.composing())
922
+ area.addEventListener('compositionend', handOver, { once: true });
923
+ else
924
+ handOver();
925
+ };
926
+ // tabStaysInText: Tab and Shift+Tab that nothing in the text took
927
+ // (a list's indent, a table's next cell) stay in it, after
928
+ // ProseMirror's own keys. An Esc that reaches the field lets the next
929
+ // Tab go on to the page; any other key, a click or focus leaving
930
+ // takes that back.
931
+ let tabGoesOn = false;
932
+ const onRootKeyDown = (event) => {
933
+ if (!latest.current.tabStaysInText)
934
+ return;
935
+ if (event.key === 'Escape') {
936
+ tabGoesOn = !event.defaultPrevented || escapePassedThrough(event);
937
+ return;
938
+ }
939
+ if (event.key !== 'Tab') {
940
+ if (!MODIFIER_KEYS.has(event.key))
941
+ tabGoesOn = false;
942
+ return;
943
+ }
944
+ if (tabGoesOn) {
945
+ tabGoesOn = false;
946
+ return;
947
+ }
948
+ const view = editorRef.current?.action((ctx) => ctx.get(editorViewCtx));
949
+ if (!view || !view.editable || event.defaultPrevented || event.isComposing || event.ctrlKey || event.metaKey || event.altKey)
950
+ return;
951
+ if (!(event.target instanceof Node) || !view.dom.contains(event.target))
952
+ return;
953
+ event.preventDefault();
954
+ if (!tabHintUsed.current) {
955
+ tabHintUsed.current = true;
956
+ setTabHintShown(true);
957
+ }
958
+ };
959
+ const tabStays = () => {
960
+ tabGoesOn = false;
961
+ };
962
+ root.addEventListener('keydown', onRootKeyDown);
963
+ root.addEventListener('mousedown', tabStays);
964
+ root.addEventListener('focusout', tabStays);
865
965
  // Hiding the page (another tab, a phone's home screen) reports what
866
966
  // was typed: the page may not come back.
867
967
  const onHidden = () => {
@@ -871,6 +971,9 @@ export default function MilkdownEditor({ id, defaultValue, onChange, onProblem,
871
971
  document.addEventListener('visibilitychange', onHidden);
872
972
  window.addEventListener('pagehide', emit);
873
973
  return () => {
974
+ root.removeEventListener('keydown', onRootKeyDown);
975
+ root.removeEventListener('mousedown', tabStays);
976
+ root.removeEventListener('focusout', tabStays);
874
977
  document.removeEventListener('visibilitychange', onHidden);
875
978
  window.removeEventListener('pagehide', emit);
876
979
  // Unmounting reports what was typed since the last pause.
@@ -890,6 +993,26 @@ export default function MilkdownEditor({ id, defaultValue, onChange, onProblem,
890
993
  // Attributes and read-only follow below.
891
994
  // eslint-disable-next-line react-hooks/exhaustive-deps
892
995
  }, []);
996
+ // `focusKey` changed since it was last acted on: the text focused, the
997
+ // caret put back where it was in the same task (ProseMirror's focus
998
+ // does), so a key typed at once lands there.
999
+ const focusSeen = useRef(focusKey);
1000
+ const [ownNewFocus] = useState(() => (key) => {
1001
+ if (focusSeen.current === key)
1002
+ return false;
1003
+ focusSeen.current = key;
1004
+ return true;
1005
+ });
1006
+ const newFocus = isNewFocus ?? ownNewFocus;
1007
+ useLayoutEffect(() => {
1008
+ if (!newFocus(focusKey))
1009
+ return;
1010
+ const view = editorRef.current?.action((ctx) => ctx.get(editorViewCtx));
1011
+ if (view)
1012
+ view.focus();
1013
+ else
1014
+ focusWanted.current = true;
1015
+ }, [focusKey, newFocus]);
893
1016
  // The page links follow the app's answers (a page renamed, removed or
894
1017
  // restored): redrawn only when those have changed.
895
1018
  useEffect(() => {
@@ -1182,7 +1305,9 @@ export default function MilkdownEditor({ id, defaultValue, onChange, onProblem,
1182
1305
  // Raw HTML from the text: shown as its characters, never as markup.
1183
1306
  '[&_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
1307
  // 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) => {
1308
+ '[&_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
1309
+ ? 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')
1310
+ : '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
1311
  if (widget.type === 'callout')
1187
1312
  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
1313
  const active = caretTable !== undefined && caretTable === widget.getPos();
@@ -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.150.0",
3
+ "version": "4.152.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": {
package/vite/index.d.ts CHANGED
@@ -45,9 +45,32 @@ export type PwaOptions = {
45
45
  backgroundColor?: string
46
46
  /**
47
47
  * The app's own icon, a square PNG of at least 512×512 (path from the Vite
48
- * root). Replaces the generated ones everywhere.
48
+ * root). Replaces the generated ones everywhere: the manifest's `any`
49
+ * entry (its `sizes` read from the PNG), the apple-touch-icon and, without
50
+ * a `smallIcon`, a push's icon. Alone it is the manifest's only icon;
51
+ * the three below add the rest.
49
52
  */
50
53
  icon?: string
54
+ /**
55
+ * A smaller copy of `icon`, a square PNG of 192×192 (path from the Vite
56
+ * root): a second `any` entry, for the places that would scale the large
57
+ * one down (Windows, the install prompt), and a push's icon. Needs `icon`.
58
+ */
59
+ smallIcon?: string
60
+ /**
61
+ * The icon to crop to the device's mask shape (Android's circle or
62
+ * squircle), a square PNG of at least 512×512 (path from the Vite root)
63
+ * with the mark inside the central 80% circle and the background to the
64
+ * edges: the manifest's `maskable` entry. Without one, Android draws
65
+ * `icon` shrunk on a plain disc. Needs `icon`.
66
+ */
67
+ maskableIcon?: string
68
+ /**
69
+ * The app's mark as an SVG (path from the Vite root): an `any` entry
70
+ * with `sizes: 'any'`, which Chrome and Android draw sharp at every size.
71
+ * Needs `icon`, since iOS's Home Screen takes a PNG only.
72
+ */
73
+ iconSvg?: string
51
74
  /**
52
75
  * Home-screen shortcuts: actions offered when the installed icon is
53
76
  * long-pressed (Android, Chrome and Edge on desktop). Left out, the manifest
package/vite/pwa.d.ts CHANGED
@@ -5,6 +5,7 @@ import type { PwaOptions } from './index'
5
5
 
6
6
  export function themeToken(css: string, name: string): string
7
7
  export function oklchToHex(value: string): string
8
+ export function pngSize(bytes: Buffer): { width: number; height: number } | undefined
8
9
  export function solidPng(size: number, hex: string): Buffer
9
10
  export function letterSvg(name: string, background: string, foreground: string): string
10
11
  export function pwaFiles(
package/vite/pwa.js CHANGED
@@ -11,7 +11,9 @@
11
11
  // - /icons/: an SVG with the name's first letter (Chrome, Android) and
12
12
  // plain PNGs in the theme colour (iOS's Home Screen icon must be a PNG,
13
13
  // and drawing a letter into one needs a font rasteriser the package
14
- // doesn't carry). `icon` replaces them all with the app's own PNG.
14
+ // doesn't carry). `icon` replaces them all with the app's own PNG, and
15
+ // `smallIcon`, `maskableIcon` and `iconSvg` add its other sizes and
16
+ // shapes beside it; each PNG's `sizes` is read from its header.
15
17
  // - /push-sw.js: ./push-sw.js, showing pushes, opening their path, and
16
18
  // posting a message's action (a Done button) to the app's own path.
17
19
  // And adds the manifest, theme-color and apple-touch-icon tags to
@@ -150,6 +152,37 @@ export function letterSvg(name, background, foreground) {
150
152
  )
151
153
  }
152
154
 
155
+ // ---------------------------------------------------------- own icons
156
+
157
+ const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
158
+
159
+ /** A PNG's width and height, from its IHDR chunk; undefined if it isn't a PNG. */
160
+ export function pngSize(bytes) {
161
+ if (bytes.length < 24 || !bytes.subarray(0, 8).equals(PNG_SIGNATURE)) return undefined
162
+ if (bytes.toString('ascii', 12, 16) !== 'IHDR') return undefined
163
+ return { width: bytes.readUInt32BE(16), height: bytes.readUInt32BE(20) }
164
+ }
165
+
166
+ /** An app's own PNG (path from the Vite root), with the manifest's `sizes` read from it. */
167
+ function ownPng(file, option, root) {
168
+ const own = path.resolve(root, file)
169
+ if (own.toLowerCase().endsWith('.svg')) {
170
+ throw new Error(`pwa: ${option} must be a PNG file; an SVG goes in \`iconSvg\`, beside a PNG \`icon\` (iOS's Home Screen takes a PNG only).`)
171
+ }
172
+ const bytes = fs.existsSync(own) ? fs.readFileSync(own) : undefined
173
+ const size = bytes && pngSize(bytes)
174
+ if (!size) throw new Error(`pwa: ${option} must be a PNG file; ${own} isn't one.`)
175
+ return { bytes, sizes: `${size.width}x${size.height}` }
176
+ }
177
+
178
+ /** An app's own SVG (path from the Vite root). */
179
+ function ownSvg(file, option, root) {
180
+ const own = path.resolve(root, file)
181
+ const source = own.toLowerCase().endsWith('.svg') && fs.existsSync(own) ? fs.readFileSync(own, 'utf8') : undefined
182
+ if (!source || !/<svg[\s>]/.test(source)) throw new Error(`pwa: ${option} must be an SVG file; ${own} isn't one.`)
183
+ return source
184
+ }
185
+
153
186
  // --------------------------------------------------------------- plugin
154
187
 
155
188
  /**
@@ -169,13 +202,34 @@ export function pwaFiles(options, base = '/', root = process.cwd()) {
169
202
  const files = new Map()
170
203
  let icons
171
204
  let touchIcon
205
+ let workerIcon
172
206
  if (options.icon) {
173
- const own = path.resolve(root, options.icon)
174
- if (!own.endsWith('.png') || !fs.existsSync(own)) throw new Error(`pwa: icon must be a PNG file; ${own} isn't one.`)
175
- files.set('icons/icon.png', { type: 'image/png', source: fs.readFileSync(own) })
176
- icons = [{ src: at('icons/icon.png'), sizes: '512x512', type: 'image/png', purpose: 'any' }]
207
+ // The app's own: its PNG (the Home Screen's on iOS, the push's), and
208
+ // beside it any of a smaller PNG, a maskable PNG and an SVG it has.
209
+ const own = ownPng(options.icon, 'icon', root)
210
+ files.set('icons/icon.png', { type: 'image/png', source: own.bytes })
211
+ icons = [{ src: at('icons/icon.png'), sizes: own.sizes, type: 'image/png', purpose: 'any' }]
212
+ workerIcon = 'icons/icon.png'
213
+ if (options.smallIcon) {
214
+ const small = ownPng(options.smallIcon, 'smallIcon', root)
215
+ files.set('icons/icon-small.png', { type: 'image/png', source: small.bytes })
216
+ icons.unshift({ src: at('icons/icon-small.png'), sizes: small.sizes, type: 'image/png', purpose: 'any' })
217
+ workerIcon = 'icons/icon-small.png'
218
+ }
219
+ if (options.iconSvg) {
220
+ files.set('icons/icon.svg', { type: 'image/svg+xml', source: ownSvg(options.iconSvg, 'iconSvg', root) })
221
+ icons.unshift({ src: at('icons/icon.svg'), sizes: 'any', type: 'image/svg+xml', purpose: 'any' })
222
+ }
223
+ if (options.maskableIcon) {
224
+ const maskable = ownPng(options.maskableIcon, 'maskableIcon', root)
225
+ files.set('icons/icon-maskable.png', { type: 'image/png', source: maskable.bytes })
226
+ icons.push({ src: at('icons/icon-maskable.png'), sizes: maskable.sizes, type: 'image/png', purpose: 'maskable' })
227
+ }
177
228
  touchIcon = 'icons/icon.png'
178
229
  } else {
230
+ for (const option of ['iconSvg', 'smallIcon', 'maskableIcon']) {
231
+ if (options[option]) throw new Error(`pwa: \`${option}\` goes with \`icon\`, the app's own PNG; pass that too.`)
232
+ }
179
233
  files.set('icons/icon.svg', { type: 'image/svg+xml', source: letterSvg(shortName, theme, onTheme) })
180
234
  for (const size of [192, 512]) files.set(`icons/icon-${size}.png`, { type: 'image/png', source: solidPng(size, theme) })
181
235
  files.set('icons/apple-touch-icon.png', { type: 'image/png', source: solidPng(180, theme) })
@@ -187,6 +241,7 @@ export function pwaFiles(options, base = '/', root = process.cwd()) {
187
241
  { src: at('icons/icon-512.png'), sizes: '512x512', type: 'image/png', purpose: 'maskable' },
188
242
  ]
189
243
  touchIcon = 'icons/apple-touch-icon.png'
244
+ workerIcon = 'icons/icon-192.png'
190
245
  }
191
246
  const shortcuts = (options.shortcuts ?? []).map((shortcut, index) => {
192
247
  const label = shortcut?.name?.trim()
@@ -197,11 +252,10 @@ export function pwaFiles(options, base = '/', root = process.cwd()) {
197
252
  }
198
253
  let icon
199
254
  if (shortcut.icon) {
200
- const own = path.resolve(root, shortcut.icon)
201
- if (!own.endsWith('.png') || !fs.existsSync(own)) throw new Error(`pwa: shortcuts[${index}].icon must be a PNG file; ${own} isn't one.`)
255
+ const own = ownPng(shortcut.icon, `shortcuts[${index}].icon`, root)
202
256
  const file = `icons/shortcut-${index}.png`
203
- files.set(file, { type: 'image/png', source: fs.readFileSync(own) })
204
- icon = [{ src: at(file), sizes: '192x192', type: 'image/png' }]
257
+ files.set(file, { type: 'image/png', source: own.bytes })
258
+ icon = [{ src: at(file), sizes: own.sizes, type: 'image/png' }]
205
259
  }
206
260
  return {
207
261
  name: label,
@@ -226,7 +280,7 @@ export function pwaFiles(options, base = '/', root = process.cwd()) {
226
280
  type: 'application/manifest+json',
227
281
  source: `${JSON.stringify(manifest, null, 2)}\n`,
228
282
  })
229
- const worker = fs.readFileSync(WORKER_SOURCE, 'utf8').replace('__ICON__', options.icon ? at('icons/icon.png') : at('icons/icon-192.png'))
283
+ const worker = fs.readFileSync(WORKER_SOURCE, 'utf8').replace('__ICON__', at(workerIcon))
230
284
  files.set('push-sw.js', { type: 'text/javascript', source: worker })
231
285
  return {
232
286
  files,