@tristan2828/ui-foundation 4.153.0 → 4.154.0

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