@tristan2828/ui-foundation 4.72.0 → 4.73.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/conventions/docs/add-an-entity.md +38 -14
  2. package/conventions/docs/design-language.md +27 -15
  3. package/dist/components/app/markdown.d.ts +13 -1
  4. package/dist/components/app/markdown.js +43 -8
  5. package/dist/components/app/milkdown-editor.d.ts +1 -1
  6. package/dist/components/app/milkdown-editor.js +184 -19
  7. package/dist/components/app/page-link.d.ts +13 -0
  8. package/dist/components/app/page-link.js +44 -0
  9. package/dist/components/app/page-restore.d.ts +3 -0
  10. package/dist/components/app/page-restore.js +14 -0
  11. package/dist/components/app/page-trail.d.ts +17 -0
  12. package/dist/components/app/page-trail.js +71 -0
  13. package/dist/components/app/rich-text-editor.d.ts +22 -0
  14. package/dist/components/app/rich-text-editor.js +8 -0
  15. package/dist/components/app/rich-text-floating-toolbar.d.ts +3 -1
  16. package/dist/components/app/rich-text-floating-toolbar.js +2 -2
  17. package/dist/components/app/rich-text-page-links.d.ts +44 -0
  18. package/dist/components/app/rich-text-page-links.js +201 -0
  19. package/dist/components/app/rich-text-slash-menu.d.ts +3 -4
  20. package/dist/components/app/rich-text-slash.d.ts +12 -3
  21. package/dist/components/app/rich-text-slash.js +16 -5
  22. package/dist/components/app/rich-text-toolbar.d.ts +3 -1
  23. package/dist/components/app/rich-text-toolbar.js +10 -7
  24. package/dist/components/ui/breadcrumb.d.ts +10 -0
  25. package/dist/components/ui/breadcrumb.js +37 -0
  26. package/dist/index.d.ts +2 -0
  27. package/dist/index.js +1 -0
  28. package/dist/lib/page-link.d.ts +40 -0
  29. package/dist/lib/page-link.js +32 -0
  30. package/dist/lib/page-trail.d.ts +7 -0
  31. package/dist/lib/page-trail.js +24 -0
  32. package/package.json +1 -1
  33. package/styles/index.css +63 -0
@@ -4,25 +4,25 @@
4
4
  ## Index
5
5
 
6
6
  - [The reference files](#the-reference-files) · lines 41–63
7
- - [Before anything: the entity plan](#before-anything-the-entity-plan) · lines 65–758
7
+ - [Before anything: the entity plan](#before-anything-the-entity-plan) · lines 65–782
8
8
  - Step 1: Add `<Entity>` to `openapi.yaml` · lines 107–114
9
9
  - Step 2: `npm run gen:api` · lines 115–116
10
10
  - Step 3: Add gateway tests in `tests/gateway/<entity>.test.ts`, derived from the spec · lines 117–128
11
11
  - Step 4: Add MSW handlers in `src/mocks/<entity>.ts` · lines 129–138
12
12
  - Step 5: Add a gateway module in `src/api/gateway/<entity>.ts` · lines 139–143
13
- - Step 6: Copy the reference files, one for one, not just the two screens · lines 144–645
14
- - Step 7: Register routes · lines 646–661
15
- - Step 8: Add Playwright specs for all three screens · lines 662–740
16
- - Step 9: Register the nav entry and route names · lines 741–755
17
- - Step 10: `npm run verify`. · lines 756–758
18
- - [How a list opens a record](#how-a-list-opens-a-record) · lines 760–898
19
- - [The record view](#the-record-view) · lines 873–898
20
- - [What not to copy](#what-not-to-copy) · lines 900–926
21
- - [After a commit, in the backend](#after-a-commit-in-the-backend) · lines 928–945
22
- - [Deleting](#deleting) · lines 947–976
23
- - [Fields only a script writes](#fields-only-a-script-writes) · lines 978–999
24
- - [Searching one part of the app](#searching-one-part-of-the-app) · lines 1001–1010
25
- - [What a chat is told about an entity](#what-a-chat-is-told-about-an-entity) · lines 1013–1052
13
+ - Step 6: Copy the reference files, one for one, not just the two screens · lines 144–669
14
+ - Step 7: Register routes · lines 670–685
15
+ - Step 8: Add Playwright specs for all three screens · lines 686–764
16
+ - Step 9: Register the nav entry and route names · lines 765–779
17
+ - Step 10: `npm run verify`. · lines 780–782
18
+ - [How a list opens a record](#how-a-list-opens-a-record) · lines 784–922
19
+ - [The record view](#the-record-view) · lines 897–922
20
+ - [What not to copy](#what-not-to-copy) · lines 924–950
21
+ - [After a commit, in the backend](#after-a-commit-in-the-backend) · lines 952–969
22
+ - [Deleting](#deleting) · lines 971–1000
23
+ - [Fields only a script writes](#fields-only-a-script-writes) · lines 1002–1023
24
+ - [Searching one part of the app](#searching-one-part-of-the-app) · lines 1025–1034
25
+ - [What a chat is told about an entity](#what-a-chat-is-told-about-an-entity) · lines 1037–1076
26
26
 
27
27
  <!-- /index -->
28
28
 
@@ -502,6 +502,30 @@ is a filled-in example while the Widgets demo is still here).
502
502
  (`useEdit<Entity>Field`). Without the prop the boxes are pictures
503
503
  and the text stays read-only. A list's "2/5" column counts them
504
504
  with `countTasks(text)` (`{ done, total }`; `total` 0 for none).
505
+ - **Pages in the notes** (a record's notes linking to pages of their
506
+ own, each a title and its own Markdown at its own URL, and a page's
507
+ notes linking to pages under it, to any depth): the app keeps the
508
+ pages (a table, an API, a screen per page); the foundation only
509
+ draws and makes the links. A page is linked by an ordinary Markdown
510
+ link, `[Getting Started](/notes/12/pages/3)`, so the notes stay
511
+ Markdown and nothing about how they're stored changes. Give
512
+ `<Markdown>` and `RichTextEditor` the same `pageLink={(href) => …}`:
513
+ return `{ title, removed, onRestore }` for an address that is one of
514
+ the app's pages (look it up in the record's pages, already loaded),
515
+ `null` for any other link. A page link shows the page icon and the
516
+ page's title and opens it in this tab; alone on its line it's a row
517
+ of its own; a removed page (soft-deleted) shows "Page removed" and,
518
+ with `onRestore` (the app's undelete, returning its promise),
519
+ Restore. Give the editor `onCreatePage={(title) => createPage(title).then((page) => pagePath(page))}`
520
+ too: "/page" (and Turn into page on selected words) asks for a
521
+ title, awaits the new page's address and puts in the link; a
522
+ rejection shows in the title box in the gateway's words and leaves
523
+ the text as it was. The page's own screen puts `PageTrail` above its
524
+ title (`crumbs`: the list, the record, every page above this one,
525
+ then this one, last, with no `href`): it folds the middle into a "…"
526
+ menu when it doesn't fit. A page's notes take the same two props, so
527
+ nothing assumes one level: the app decides where a new page lives
528
+ (under the record, or under the page whose note it's in).
505
529
  - **Notes worth taking on paper** (a visit's prep and questions, a
506
530
  guide, a checklist to tick by hand): mark each of those sections
507
531
  `print: true`. The header gets a Print notes button (`printLabel`
@@ -13,21 +13,21 @@
13
13
  - [Categorical colour](#categorical-colour) · lines 269–339
14
14
  - [A stored colour](#a-stored-colour) · lines 341–389
15
15
  - [Shapes and sizes](#shapes-and-sizes) · lines 391–412
16
- - [Typography](#typography) · lines 414–508
17
- - [Written text (notes)](#written-text-notes) · lines 448–508
18
- - [Density](#density) · lines 510–596
19
- - [Rows on this device](#rows-on-this-device) · lines 569–596
20
- - [Widget cards (hub pages)](#widget-cards-hub-pages) · lines 598–712
21
- - [Module cards (a hub's places)](#module-cards-a-hubs-places) · lines 714–783
22
- - [Notices](#notices) · lines 785–813
23
- - [A value over time](#a-value-over-time) · lines 815–901
24
- - [Several values over time](#several-values-over-time) · lines 864–901
25
- - [A list as a board](#a-list-as-a-board) · lines 903–954
26
- - [A list as cards](#a-list-as-cards) · lines 956–1002
27
- - [Key numbers on a record](#key-numbers-on-a-record) · lines 1004–1026
28
- - [Picking at random](#picking-at-random) · lines 1028–1059
29
- - [Filling in what's missing](#filling-in-whats-missing) · lines 1061–1128
30
- - [Values edited in place: the presets' looks](#values-edited-in-place-the-presets-looks) · lines 1130–1155
16
+ - [Typography](#typography) · lines 414–520
17
+ - [Written text (notes)](#written-text-notes) · lines 448–520
18
+ - [Density](#density) · lines 522–608
19
+ - [Rows on this device](#rows-on-this-device) · lines 581–608
20
+ - [Widget cards (hub pages)](#widget-cards-hub-pages) · lines 610–724
21
+ - [Module cards (a hub's places)](#module-cards-a-hubs-places) · lines 726–795
22
+ - [Notices](#notices) · lines 797–825
23
+ - [A value over time](#a-value-over-time) · lines 827–913
24
+ - [Several values over time](#several-values-over-time) · lines 876–913
25
+ - [A list as a board](#a-list-as-a-board) · lines 915–966
26
+ - [A list as cards](#a-list-as-cards) · lines 968–1014
27
+ - [Key numbers on a record](#key-numbers-on-a-record) · lines 1016–1038
28
+ - [Picking at random](#picking-at-random) · lines 1040–1071
29
+ - [Filling in what's missing](#filling-in-whats-missing) · lines 1073–1140
30
+ - [Values edited in place: the presets' looks](#values-edited-in-place-the-presets-looks) · lines 1142–1167
31
31
 
32
32
  <!-- /index -->
33
33
 
@@ -494,6 +494,18 @@ shade: note `info`, tip `success`, important category slot 2, warning
494
494
  `warning`, caution `destructive`. The package draws all of it; an app
495
495
  only renders `<Markdown>` or the editor.
496
496
 
497
+ A page link (a link the app marks as one of its pages, `pageLink`) is the
498
+ page icon in `--muted-foreground`, then the title in the text's own
499
+ colour at medium weight, underlined in `--muted-foreground` (the colour
500
+ of the words around it, so the underline is what tells it apart). Alone
501
+ on its line it's a page line, a row that tints `--muted` on hover. A
502
+ removed page is muted and struck through, "Page removed" beside it in
503
+ the caption size, with an outline `xs` Restore button. Both renderers
504
+ draw it from the same CSS (styles/index.css "Page links in written
505
+ text"). The trail back from a page, `PageTrail`, is shadcn's Breadcrumb:
506
+ crumbs in `--muted-foreground`, the page itself in `--foreground`, on
507
+ one line, the middle folded into a "…" menu when it doesn't fit.
508
+
497
509
  Highlighted words (`==words==` in the Markdown) have four colour tokens:
498
510
  `--highlight-amber` (the default), `--highlight-yellow`,
499
511
  `--highlight-green` and `--highlight-red` (`bg-highlight-amber`, …). Each
@@ -1,4 +1,5 @@
1
1
  import { type ComponentProps } from 'react';
2
+ import type { PageLinkResolver } from '../../lib/page-link.js';
2
3
  import { type HeadingFrom, type HeadingLevel, type TableLook } from './prose-look.js';
3
4
  export type MarkdownProps = {
4
5
  /** The Markdown source. Raw HTML in it is shown as text, never rendered. */
@@ -50,6 +51,17 @@ export type MarkdownProps = {
50
51
  * RichTextEditor. Either way columns fit their words.
51
52
  */
52
53
  tableLook?: TableLook;
54
+ /**
55
+ * Which links are the app's own pages (src/lib/page-link.ts): called
56
+ * with each link's address, it returns what the app knows of that page
57
+ * (its title, whether it's removed, how to restore it), or `null` for
58
+ * an ordinary link. A page link shows the page icon and the page's
59
+ * title and opens the page in this tab; alone in a paragraph it's a row
60
+ * of its own. A removed page shows "Page removed" and, with
61
+ * `onRestore`, a Restore button. The Markdown is never changed. Pages
62
+ * may nest to any depth: the package never asks whose page it is.
63
+ */
64
+ pageLink?: PageLinkResolver;
53
65
  className?: string;
54
66
  } & Omit<ComponentProps<'div'>, 'children'>;
55
- export declare function Markdown({ children, headingLevel, headingFrom, foldKey: foldKeyProp, foldable, onTasksChange: onTasksChangeProp, tableLook, className, ...rest }: MarkdownProps): import("react").JSX.Element;
67
+ export declare function Markdown({ children, headingLevel, headingFrom, foldKey: foldKeyProp, foldable, onTasksChange: onTasksChangeProp, tableLook, pageLink, className, ...rest }: MarkdownProps): import("react").JSX.Element;
@@ -55,6 +55,13 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
55
55
  // Printed (EntityView's Print notes, PrintingContext), it's the whole
56
56
  // text: nothing folded, no fold buttons, task boxes as glyphs.
57
57
  //
58
+ // With `pageLink`, a link the app says is one of its pages (a child page
59
+ // of the record, or of a page, to any depth: src/lib/page-link.ts) is a
60
+ // page link: the page icon and the page's title, opening the page in this
61
+ // tab. Alone in its paragraph, it's a page line, a row of its own. A page
62
+ // the app reports removed shows "Page removed", with Restore when the app
63
+ // gives one. Every other link is as it was; the text is never changed.
64
+ //
58
65
  // A task item (`- [ ] to do`, `- [x] done`) shows its box as a glyph
59
66
  // with its state in words: read-only text has nothing to tick. With
60
67
  // `onTasksChange`, each box is a real checkbox, named for its item's
@@ -76,6 +83,7 @@ import { remarkToggleHeadings } from '../../lib/markdown-toggle.js';
76
83
  import { toggleTaskAt } from '../../lib/markdown-tasks.js';
77
84
  import { textTopHeading } from '../../lib/markdown-top-heading.js';
78
85
  import { CALLOUT_BOX, CALLOUT_LOOK, DEFAULT_HEADING_LEVEL, FOLD_BUTTON, FOLD_HEADING, headingBand, headingClass, headingTag, PROSE, PROSE_INSET, } from './prose-look.js';
86
+ import { PageLinkView } from './page-link.js';
79
87
  import { usePrinting } from './print-context.js';
80
88
  import { headerTexts, TABLE_SCROLL_FOCUS, watchTableScroll } from './prose-table-scroll.js';
81
89
  const REMARK_PLUGINS = [remarkGfm, remarkCallouts, remarkHighlights, remarkToggleHeadings];
@@ -138,6 +146,37 @@ function TaskBox({ checked }) {
138
146
  onClick: (event) => event.stopPropagation(), "aria-label": item.name || (checked ? 'Done' : 'Not done'), "data-slot": "task-box", className: "mr-2 inline-flex align-[-0.1875rem]" }));
139
147
  return checked ? (_jsx(SquareCheckIcon, { role: "img", "aria-label": "Done", className: "mr-2 inline-block size-4 align-[-0.1875rem] text-foreground" })) : (_jsx(SquareIcon, { role: "img", "aria-label": "Not done", className: "mr-2 inline-block size-4 align-[-0.1875rem] text-muted-foreground" }));
140
148
  }
149
+ // Says which links are the app's pages: given only with `pageLink`.
150
+ const PageLinkContext = createContext(null);
151
+ // The address of the one link a paragraph holds and nothing else (spaces
152
+ // aside), or null: a page line, when the app says it's a page.
153
+ function soleLinkHref(node) {
154
+ const children = (node?.children ?? []).filter((child) => !(child.type === 'text' && !(child.value ?? '').trim()));
155
+ const only = children.length === 1 ? children[0] : null;
156
+ const href = only?.tagName === 'a' ? only.properties?.href : undefined;
157
+ return typeof href === 'string' && href ? href : null;
158
+ }
159
+ // A link: a page link when the app says its address is one of its pages,
160
+ // else an ordinary one, opening in a new tab.
161
+ function MarkdownLink(props) {
162
+ const resolve = useContext(PageLinkContext);
163
+ const { href, children, ...rest } = omitNode(props);
164
+ if (!href)
165
+ return _jsx("span", { children: children });
166
+ const info = resolve?.(href);
167
+ if (info)
168
+ return _jsx(PageLinkView, { href: href, info: info, words: itemText(props.node), children: children });
169
+ return (_jsxs("a", { ...rest, href: href, target: "_blank", rel: "noreferrer", className: PROSE.link, children: [children, _jsx(ExternalLinkIcon, { "aria-hidden": "true", className: "ml-0.5 inline size-3 align-baseline" }), _jsx("span", { className: "sr-only", children: " (opens in a new tab)" })] }));
170
+ }
171
+ // A paragraph: a page line when all it holds is a page link.
172
+ function MarkdownParagraph(props) {
173
+ const resolve = useContext(PageLinkContext);
174
+ const rest = omitNode(props);
175
+ const href = resolve ? soleLinkHref(props.node) : null;
176
+ if (href && resolve?.(href))
177
+ return _jsx("p", { ...rest, "data-page-line": "", className: "page-line" });
178
+ return _jsx("p", { ...rest });
179
+ }
141
180
  // Folds a section by its heading's id: given only with `foldKey`.
142
181
  const FoldContext = createContext(null);
143
182
  // A heading by its Markdown level: the element the page's outline gives
@@ -165,12 +204,8 @@ function heading(level, top, textTop) {
165
204
  }
166
205
  // Everything but the headings, which follow `headingLevel` (componentsFor).
167
206
  const COMPONENTS = {
168
- a: (props) => {
169
- const { href, children, ...rest } = omitNode(props);
170
- if (!href)
171
- return _jsx("span", { children: children });
172
- return (_jsxs("a", { ...rest, href: href, target: "_blank", rel: "noreferrer", className: PROSE.link, children: [children, _jsx(ExternalLinkIcon, { "aria-hidden": "true", className: "ml-0.5 inline size-3 align-baseline" }), _jsx("span", { className: "sr-only", children: " (opens in a new tab)" })] }));
173
- },
207
+ a: MarkdownLink,
208
+ p: MarkdownParagraph,
174
209
  // A list can mix plain and task items (`- a` then `- [ ] b` is one
175
210
  // list): each task item drops its own bullet, the rest keep theirs. Its
176
211
  // box is inline, so a loose list's item (its text in a <p>) lays out
@@ -238,7 +273,7 @@ function componentsFor(top, textTop) {
238
273
  }
239
274
  return components;
240
275
  }
241
- export function Markdown({ children, headingLevel = DEFAULT_HEADING_LEVEL, headingFrom = 'hash', foldKey: foldKeyProp, foldable = true, onTasksChange: onTasksChangeProp, tableLook = 'compact', className, ...rest }) {
276
+ export function Markdown({ children, headingLevel = DEFAULT_HEADING_LEVEL, headingFrom = 'hash', foldKey: foldKeyProp, foldable = true, onTasksChange: onTasksChangeProp, tableLook = 'compact', pageLink, className, ...rest }) {
242
277
  // On paper (EntityView's Print notes): every heading plain and open,
243
278
  // every task box a picture.
244
279
  const printing = usePrinting();
@@ -263,5 +298,5 @@ export function Markdown({ children, headingLevel = DEFAULT_HEADING_LEVEL, headi
263
298
  if (saving && typeof saving.then === 'function')
264
299
  saving.then(undefined, () => setPending((current) => (current?.sent.includes(next) ? null : current)));
265
300
  }, [onTasksChange, children, shown, live]);
266
- return (_jsx("div", { "data-slot": "markdown", "data-table-look": tableLook, "data-fold-scope": foldKey, ...rest, className: cn('flex min-w-0 flex-col gap-3 type-body text-foreground break-words', PROSE_INSET, className), children: _jsx(FoldContext.Provider, { value: foldKey === undefined ? null : toggle, children: _jsx(TaskToggleContext.Provider, { value: onTasksChange ? tickTask : null, children: _jsx(ReactMarkdown, { remarkPlugins: REMARK_PLUGINS, rehypePlugins: rehypePlugins, components: components, children: onTasksChange ? shown : children }) }) }) }));
301
+ return (_jsx("div", { "data-slot": "markdown", "data-table-look": tableLook, "data-fold-scope": foldKey, ...rest, className: cn('flex min-w-0 flex-col gap-3 type-body text-foreground break-words', PROSE_INSET, className), children: _jsx(PageLinkContext.Provider, { value: pageLink ?? null, children: _jsx(FoldContext.Provider, { value: foldKey === undefined ? null : toggle, children: _jsx(TaskToggleContext.Provider, { value: onTasksChange ? tickTask : null, children: _jsx(ReactMarkdown, { remarkPlugins: REMARK_PLUGINS, rehypePlugins: rehypePlugins, components: components, children: onTasksChange ? shown : children }) }) }) }) }));
267
302
  }
@@ -1,2 +1,2 @@
1
1
  import type { RichTextEditorProps } from './rich-text-editor.js';
2
- export default function MilkdownEditor({ id, defaultValue, onChange, onProblem, readOnly, autoFocus, placeholder, maxLength, toolbar, inline, upload, imageAccept, imageMaxSize, headingLevel, headingFrom, foldKey, tableLook, className, 'aria-label': ariaLabel, 'aria-labelledby': ariaLabelledBy, 'aria-describedby': ariaDescribedBy, 'aria-invalid': ariaInvalid, }: RichTextEditorProps): import("react").JSX.Element;
2
+ 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;
@@ -62,8 +62,13 @@ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-run
62
62
  // - `foldKey`: the text folds by its toggle headings, as <Markdown> does
63
63
  // (rich-text-fold.ts), remembered on this device and shared with
64
64
  // NotesOutline; the document never changes.
65
+ // - `pageLink`: links the app marks as its pages drawn as page links
66
+ // (rich-text-page-links.ts), opened in this tab; `onCreatePage`: "/page"
67
+ // and Turn into page make one through the app and link it (a title box,
68
+ // PageForm). The Markdown stays a plain link.
65
69
  import { useEffect, useId, useRef, useState } from 'react';
66
70
  import { createPortal } from 'react-dom';
71
+ import { useInRouterContext, useNavigate } from 'react-router';
67
72
  import { defaultValueCtx, Editor, editorViewCtx, editorViewOptionsCtx, parserCtx, remarkStringifyOptionsCtx, rootCtx, schemaCtx, serializerCtx, } from '@milkdown/kit/core';
68
73
  import { history } from '@milkdown/kit/plugin/history';
69
74
  import { commands, headingSchema, inputRules, keymap, markInputRules, plugins, remarkPreserveEmptyLinePlugin, schema, } from '@milkdown/kit/preset/commonmark';
@@ -81,6 +86,9 @@ import { Input } from '../ui/input.js';
81
86
  import { Popover, PopoverContent } from '../ui/popover.js';
82
87
  import { acceptAttribute } from '../../lib/image-file.js';
83
88
  import { linkHref, linkRefusal } from '../../lib/link-href.js';
89
+ import { messageOf } from './edit-in-place-store.js';
90
+ import { restorePage } from './page-restore.js';
91
+ import { insertPageLink, pageLinkInfo, pageLinksPlugin, pendingPagePlugin, refreshPageLinks, setPendingPage, } from './rich-text-page-links.js';
84
92
  import { passEscapeThrough } from './escape-passthrough.js';
85
93
  import { calloutHandler, remarkCalloutNodes } from '../../lib/markdown-callout.js';
86
94
  import { DEFAULT_HIGHLIGHT, highlightHandler, isHighlightColor, remarkHighlightNodes } from '../../lib/markdown-highlight.js';
@@ -384,7 +392,11 @@ function linkTarget(state) {
384
392
  // into. Read-only too, where the browser would otherwise follow it in this
385
393
  // tab. To edit a link's words, put the caret in them from the keyboard or
386
394
  // drag over them; Ctrl/Cmd+K edits its address.
387
- function followLink(view, event) {
395
+ //
396
+ // A page link (`pageLink`) opens its page in this tab instead (`open`:
397
+ // the router's, when there is one), and a removed page's link opens
398
+ // nothing.
399
+ function followLink(view, event, pages) {
388
400
  if (event.button !== 0 || event.shiftKey || event.altKey)
389
401
  return false;
390
402
  const anchor = event.target instanceof Element ? event.target.closest('a[href]') : null;
@@ -392,13 +404,38 @@ function followLink(view, event) {
392
404
  return false;
393
405
  if (!view.state.selection.empty)
394
406
  return false;
395
- const href = linkHref(anchor.getAttribute('href') ?? '');
407
+ const written = anchor.getAttribute('href') ?? '';
408
+ const page = pageLinkInfo(pages.resolve, written);
409
+ if (page) {
410
+ event.preventDefault();
411
+ if (page.removed)
412
+ return false;
413
+ const href = linkHref(written);
414
+ if (!href)
415
+ return false;
416
+ pages.open(href);
417
+ return true;
418
+ }
419
+ const href = linkHref(written);
396
420
  if (!href)
397
421
  return false;
398
422
  event.preventDefault();
399
423
  window.open(href, '_blank', 'noopener,noreferrer');
400
424
  return true;
401
425
  }
426
+ // The router's navigate, handed to the editor's callbacks: rendered only
427
+ // inside a router, so an editor outside one still works (a page link
428
+ // then loads the page).
429
+ function NavigateBridge({ targetRef }) {
430
+ const navigate = useNavigate();
431
+ useEffect(() => {
432
+ targetRef.current = (href) => void navigate(href);
433
+ return () => {
434
+ targetRef.current = null;
435
+ };
436
+ }, [navigate, targetRef]);
437
+ return null;
438
+ }
402
439
  // Sets (or, with `href` empty, removes) the link on the target. With
403
440
  // nothing selected and no link there, the address goes in as the link's
404
441
  // own text.
@@ -417,10 +454,26 @@ function applyLink(view, target, href) {
417
454
  }
418
455
  view.dispatch(tr.scrollIntoView());
419
456
  }
420
- 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', className, 'aria-label': ariaLabel, 'aria-labelledby': ariaLabelledBy, 'aria-describedby': ariaDescribedBy, 'aria-invalid': ariaInvalid, }) {
457
+ // A box's place: a point in the text.
458
+ function anchorAt(view, pos) {
459
+ const point = view.coordsAtPos(pos);
460
+ return {
461
+ getBoundingClientRect: () => new DOMRect(point.left, point.top, 0, point.bottom - point.top),
462
+ contextElement: view.dom,
463
+ };
464
+ }
465
+ 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, }) {
421
466
  const rootRef = useRef(null);
422
467
  const editorRef = useRef(null);
423
468
  const [linkBox, setLinkBox] = useState(null);
469
+ // The new page's title box, and whether the app is making the page.
470
+ const [pageBox, setPageBox] = useState(null);
471
+ const [pageBusy, setPageBusy] = useState(false);
472
+ // Opens the title box: from the slash menu's keys (set up once) too.
473
+ const startPageRef = useRef(() => { });
474
+ // The router's navigate, for a page link's click (NavigateBridge).
475
+ const navigateRef = useRef(null);
476
+ const inRouter = useInRouterContext();
424
477
  const [length, setLength] = useState(defaultValue.length);
425
478
  // The editor's state after each change, for the toolbar's pressed buttons.
426
479
  const [editorState, setEditorState] = useState(null);
@@ -449,9 +502,9 @@ export default function MilkdownEditor({ id, defaultValue, onChange, onProblem,
449
502
  // rendered into through a portal.
450
503
  const [widgets, setWidgets] = useState([]);
451
504
  // The latest props, for the editor's callbacks, which are set up once.
452
- const latest = useRef({ onChange, onProblem, readOnly, placeholder, upload, imageAccept, imageMaxSize });
505
+ const latest = useRef({ onChange, onProblem, readOnly, placeholder, upload, imageAccept, imageMaxSize, pageLink, onCreatePage });
453
506
  useEffect(() => {
454
- latest.current = { onChange, onProblem, readOnly, placeholder, upload, imageAccept, imageMaxSize };
507
+ latest.current = { onChange, onProblem, readOnly, placeholder, upload, imageAccept, imageMaxSize, pageLink, onCreatePage };
455
508
  });
456
509
  // Whether focus is on the floating toolbar, or in a menu opened from it
457
510
  // (the Highlight menu's popup is in a portal).
@@ -505,7 +558,7 @@ export default function MilkdownEditor({ id, defaultValue, onChange, onProblem,
505
558
  // The slash menu: open while a "/" typed at a line's start is followed
506
559
  // by something some block answers to, and the field has focus.
507
560
  const slash = menus && !readOnly && focused && editorState ? slashQuery(editorState) : null;
508
- const slashMatches = slash ? slashItems(slash.query) : [];
561
+ const slashMatches = slash ? slashItems(slash.query, { page: Boolean(onCreatePage) }) : [];
509
562
  const slashOpen = slash !== null && slashMatches.length > 0;
510
563
  const slashMenuKey = slash ? `${slash.from}:${slash.query}` : '';
511
564
  const slashIndex = slashActive.key === slashMenuKey ? Math.min(slashActive.index, slashMatches.length - 1) : 0;
@@ -594,14 +647,7 @@ export default function MilkdownEditor({ id, defaultValue, onChange, onProblem,
594
647
  if (!view.editable)
595
648
  return;
596
649
  const target = linkTarget(view.state);
597
- const point = view.coordsAtPos(target.from);
598
- setLinkBox({
599
- ...target,
600
- anchor: {
601
- getBoundingClientRect: () => new DOMRect(point.left, point.top, 0, point.bottom - point.top),
602
- contextElement: view.dom,
603
- },
604
- });
650
+ setLinkBox({ ...target, anchor: anchorAt(view, target.from) });
605
651
  };
606
652
  openLinkRef.current = openLink;
607
653
  // Folding by headings, with `foldKey` (read once, when it mounts):
@@ -613,6 +659,10 @@ export default function MilkdownEditor({ id, defaultValue, onChange, onProblem,
613
659
  let stopFolds = () => { };
614
660
  // Paste, copy, the editor's own keys and the placeholder.
615
661
  const slashing = $prose(() => slashPlugin());
662
+ // Page links, drawn from the app's `pageLink`; and where a page being
663
+ // made will be linked.
664
+ const pageLinks = $prose(() => pageLinksPlugin({ resolve: () => latest.current.pageLink, restore: restorePage, editable: () => !latest.current.readOnly }));
665
+ const pendingPages = $prose(() => pendingPagePlugin());
616
666
  // Images pasted or dropped, uploaded through the app's `upload`; with
617
667
  // none given, a paste or drop is left to the handlers after this one,
618
668
  // as if this weren't here.
@@ -695,7 +745,10 @@ export default function MilkdownEditor({ id, defaultValue, onChange, onProblem,
695
745
  return false;
696
746
  },
697
747
  // A click on a link follows it (followLink).
698
- click: (view, event) => followLink(view, event),
748
+ click: (view, event) => followLink(view, event, {
749
+ resolve: latest.current.pageLink,
750
+ open: (href) => (navigateRef.current ? navigateRef.current(href) : window.location.assign(href)),
751
+ }),
699
752
  // The floating toolbar waits for the mouse to be up: a drag
700
753
  // is still choosing the words.
701
754
  mousedown: (_view, event) => {
@@ -800,7 +853,11 @@ export default function MilkdownEditor({ id, defaultValue, onChange, onProblem,
800
853
  }
801
854
  if ((event.key === 'Enter' || event.key === 'Tab') && plain) {
802
855
  event.preventDefault();
803
- applySlash(view, menu.span, menu.items[menu.index].id);
856
+ const item = menu.items[menu.index];
857
+ if (item.id === 'page')
858
+ startPageRef.current(view, menu.span, '');
859
+ else
860
+ applySlash(view, menu.span, item.id);
804
861
  return true;
805
862
  }
806
863
  // Esc closes the menu only: the field's own Esc (editing in
@@ -859,6 +916,8 @@ export default function MilkdownEditor({ id, defaultValue, onChange, onProblem,
859
916
  .use(history)
860
917
  .use(changes)
861
918
  .use(slashing)
919
+ .use(pageLinks)
920
+ .use(pendingPages)
862
921
  .use(imageUploads)
863
922
  .use(imageInput)
864
923
  .use(input)
@@ -896,6 +955,12 @@ export default function MilkdownEditor({ id, defaultValue, onChange, onProblem,
896
955
  // Attributes and read-only follow below.
897
956
  // eslint-disable-next-line react-hooks/exhaustive-deps
898
957
  }, []);
958
+ // The page links follow the app's answers (a page renamed, removed or
959
+ // restored): redrawn only when those have changed.
960
+ useEffect(() => {
961
+ if (editorView)
962
+ refreshPageLinks(editorView, pageLink, !readOnly);
963
+ });
899
964
  // Read-only and the ARIA attributes follow their props.
900
965
  useEffect(() => {
901
966
  const editor = editorRef.current;
@@ -1014,6 +1079,7 @@ export default function MilkdownEditor({ id, defaultValue, onChange, onProblem,
1014
1079
  focused &&
1015
1080
  !selecting &&
1016
1081
  linkBox === null &&
1082
+ pageBox === null &&
1017
1083
  selection &&
1018
1084
  !selection.empty &&
1019
1085
  !(selection instanceof NodeSelection) &&
@@ -1042,6 +1108,67 @@ export default function MilkdownEditor({ id, defaultValue, onChange, onProblem,
1042
1108
  useEffect(() => {
1043
1109
  slashMenuRef.current = slashOpen && slash ? { key: slashMenuKey, span: slash, items: slashMatches, index: slashIndex } : null;
1044
1110
  });
1111
+ // The new page's title box: opened for the "/page" typed (left as it is
1112
+ // until the page is made) or the words selected, which the link will
1113
+ // replace. The span is kept in step with the text meanwhile.
1114
+ const startPage = (view, span, title) => {
1115
+ if (!view.editable || !latest.current.onCreatePage)
1116
+ return;
1117
+ view.dispatch(setPendingPage(closeSlash(view.state), { from: span.from, to: span.to }));
1118
+ setPageBox({ title, anchor: anchorAt(view, span.from) });
1119
+ };
1120
+ useEffect(() => {
1121
+ startPageRef.current = startPage;
1122
+ });
1123
+ // Selected words in one block (a double-click takes the space after a
1124
+ // word too: the link gets the words, the spaces stay).
1125
+ const selectionInOneBlock = Boolean(editorState && editorState.selection.$from.sameParent(editorState.selection.$to));
1126
+ const pageFromSelection = () => {
1127
+ if (!editorView)
1128
+ return;
1129
+ const { from, to } = editorView.state.selection;
1130
+ const text = editorView.state.doc.textBetween(from, to);
1131
+ const start = from + (text.length - text.trimStart().length);
1132
+ const end = Math.max(start, to - (text.length - text.trimEnd().length));
1133
+ startPage(editorView, { from: start, to: end }, text.replace(/\s+/g, ' ').trim());
1134
+ };
1135
+ // Closed without a page: the text as it was, the caret back in it.
1136
+ const closePage = () => {
1137
+ setPageBox(null);
1138
+ setPageBusy(false);
1139
+ if (editorView) {
1140
+ editorView.dispatch(setPendingPage(editorView.state.tr, null));
1141
+ editorView.focus();
1142
+ }
1143
+ };
1144
+ // The app makes the page; its link goes in once it has. A refusal is
1145
+ // the box's to show (in the gateway's words): the text isn't touched.
1146
+ const createPage = async (title) => {
1147
+ const create = latest.current.onCreatePage;
1148
+ if (!create)
1149
+ return "Pages can't be made here.";
1150
+ setPageBusy(true);
1151
+ let href;
1152
+ try {
1153
+ href = linkHref(await create(title));
1154
+ }
1155
+ catch (error) {
1156
+ setPageBusy(false);
1157
+ return messageOf(error);
1158
+ }
1159
+ setPageBusy(false);
1160
+ if (!href)
1161
+ return "The new page's address can't be linked.";
1162
+ const view = editorRef.current?.action((ctx) => ctx.get(editorViewCtx));
1163
+ if (!view || !insertPageLink(view, title, href)) {
1164
+ toast.error(`${title} was made, but its link couldn't go in here. Add it with Ctrl+K.`);
1165
+ setPageBox(null);
1166
+ return null;
1167
+ }
1168
+ setPageBox(null);
1169
+ view.focus();
1170
+ return null;
1171
+ };
1045
1172
  const closeLink = () => {
1046
1173
  setLinkBox(null);
1047
1174
  editorRef.current?.action((ctx) => ctx.get(editorViewCtx).focus());
@@ -1094,17 +1221,17 @@ export default function MilkdownEditor({ id, defaultValue, onChange, onProblem,
1094
1221
  editorView &&
1095
1222
  createPortal(_jsx(TableGrips, { view: editorView, state: editorState, getPos: widget.getPos, frame: widget.frame, box: widget.box, table: widget.table, readOnly: readOnly, focused: focused, onAction: (cell, action) => runTableAt(widget.getPos, cell, action), onColor: (cell, scope, color) => colorTableAt(widget.getPos, cell, scope, color), text: textElement }), widget.grips, `${widget.key}-grips`),
1096
1223
  ];
1097
- }), slashOpen && slash && editorView && (_jsx(RichTextSlashMenu, { id: slashListId, view: editorView, at: slash.to, field: field, items: slashMatches, active: slashIndex, onHighlight: (index) => setSlashActive({ key: slashMenuKey, index }), onPick: (format) => applySlash(editorView, slash, format) })), toolsOpen && (_jsx(RichTextToolsBar, { ref: toolsRef, state: editorState, readOnly: readOnly, fullScreen: fullScreen, controls: editableId, onFormat: runFormat, onFullScreen: toggleFullScreen, onReturn: returnToText, onBlur: (event) => {
1224
+ }), slashOpen && slash && editorView && (_jsx(RichTextSlashMenu, { id: slashListId, view: editorView, at: slash.to, field: field, items: slashMatches, active: slashIndex, onHighlight: (index) => setSlashActive({ key: slashMenuKey, index }), onPick: (item) => (item === 'page' ? startPage(editorView, slash, '') : applySlash(editorView, slash, item)) })), toolsOpen && (_jsx(RichTextToolsBar, { ref: toolsRef, state: editorState, readOnly: readOnly, fullScreen: fullScreen, controls: editableId, onFormat: runFormat, onFullScreen: toggleFullScreen, onReturn: returnToText, onBlur: (event) => {
1098
1225
  const next = event.relatedTarget;
1099
1226
  if (editorView && !editorView.dom.contains(next) && !inFloating(next))
1100
1227
  setFocused(false);
1101
- } })), floatingOpen && editorView && editorState && (_jsx(RichTextFloatingToolbar, { ref: floatingRef, view: editorView, state: editorState, field: field, controls: editableId, onFormat: runFormat, onDismiss: () => setDismissed({ from: editorState.selection.from, to: editorState.selection.to }), onReturn: returnToText, onBlur: (event) => {
1228
+ } })), floatingOpen && editorView && editorState && (_jsx(RichTextFloatingToolbar, { ref: floatingRef, view: editorView, state: editorState, field: field, controls: editableId, onFormat: runFormat, onPage: onCreatePage && selectionInOneBlock ? pageFromSelection : undefined, onDismiss: () => setDismissed({ from: editorState.selection.from, to: editorState.selection.to }), onReturn: returnToText, onBlur: (event) => {
1102
1229
  const next = event.relatedTarget;
1103
1230
  if (!editorView.dom.contains(next) && !inFloating(next))
1104
1231
  setFocused(false);
1105
1232
  } }))] }), upload && (_jsx("p", { role: "status", className: "sr-only", children: uploading > 0 ? `Uploading ${uploading === 1 ? 'an image' : `${uploading} images`}…` : '' })), showCount && (_jsx("p", { id: counterId, "data-slot": "rich-text-editor-count", className: cn('text-right type-caption tabular-nums', length > maxLength ? 'text-destructive-text' : 'text-muted-foreground'), children: length > maxLength
1106
1233
  ? `${(length - maxLength).toLocaleString()} characters over the limit of ${maxLength.toLocaleString()}`
1107
- : `${length.toLocaleString()} of ${maxLength.toLocaleString()} characters` })), _jsx(Popover, { open: linkBox !== null, onOpenChange: (open) => !open && closeLink(), children: linkBox && (_jsx(LinkForm, { box: linkBox, onApply: (href) => {
1234
+ : `${length.toLocaleString()} of ${maxLength.toLocaleString()} characters` })), inRouter && _jsx(NavigateBridge, { targetRef: navigateRef }), _jsx(Popover, { open: pageBox !== null, onOpenChange: (open) => !open && !pageBusy && closePage(), children: pageBox && _jsx(PageForm, { box: pageBox, busy: pageBusy, onCreate: createPage }) }), _jsx(Popover, { open: linkBox !== null, onOpenChange: (open) => !open && closeLink(), children: linkBox && (_jsx(LinkForm, { box: linkBox, onApply: (href) => {
1108
1235
  const editor = editorRef.current;
1109
1236
  editor?.action((ctx) => applyLink(ctx.get(editorViewCtx), linkBox, href));
1110
1237
  closeLink();
@@ -1142,3 +1269,41 @@ function LinkForm({ box, onApply }) {
1142
1269
  setError(null);
1143
1270
  } }), error && _jsx(FieldError, { id: errorId, children: error })] }), _jsxs("div", { className: "flex gap-2", children: [_jsx(Button, { size: "sm", onClick: apply, children: "Apply" }), box.href && (_jsx(Button, { size: "sm", variant: "outline", onClick: () => onApply(''), children: "Remove link" }))] })] }));
1144
1271
  }
1272
+ // The new page's title box: the title (the selected words to start with),
1273
+ // and Create page. While the app makes the page it waits, its controls
1274
+ // held; a refusal shows under the title, in the gateway's words, and the
1275
+ // text is left as it was. Enter creates; Esc is the popover's, and closes
1276
+ // it (not while the app is still working).
1277
+ function PageForm({ box, busy, onCreate }) {
1278
+ const [typed, setTyped] = useState(box.title);
1279
+ const [error, setError] = useState(null);
1280
+ const inputRef = useRef(null);
1281
+ const inputId = useId();
1282
+ const errorId = `${inputId}-error`;
1283
+ const create = () => {
1284
+ const title = typed.replace(/\s+/g, ' ').trim();
1285
+ if (!title) {
1286
+ setError('Give the page a title.');
1287
+ return;
1288
+ }
1289
+ setError(null);
1290
+ void onCreate(title).then((refused) => {
1291
+ if (refused) {
1292
+ setError(refused);
1293
+ inputRef.current?.focus();
1294
+ }
1295
+ });
1296
+ };
1297
+ const onKeyDown = (event) => {
1298
+ if (event.key === 'Enter' && event.target === inputRef.current) {
1299
+ event.preventDefault();
1300
+ event.stopPropagation();
1301
+ if (!busy)
1302
+ create();
1303
+ }
1304
+ };
1305
+ return (_jsxs(PopoverContent, { anchor: box.anchor, align: "start", "aria-label": "New page", initialFocus: inputRef, finalFocus: false, className: "w-80", "data-rich-text-menu": "", "data-slot": "page-form", onKeyDown: onKeyDown, children: [_jsxs(Field, { "data-invalid": error ? true : undefined, children: [_jsx(FieldLabel, { htmlFor: inputId, children: "Page title" }), _jsx(Input, { ref: inputRef, id: inputId, value: typed, autoComplete: "off", readOnly: busy, "aria-invalid": error ? true : undefined, "aria-describedby": error ? errorId : undefined, onChange: (event) => {
1306
+ setTyped(event.target.value);
1307
+ setError(null);
1308
+ } }), error && _jsx(FieldError, { id: errorId, children: error })] }), _jsx("div", { className: "flex gap-2", children: _jsx(Button, { size: "sm", onClick: create, disabled: busy, children: busy ? 'Creating…' : 'Create page' }) })] }));
1309
+ }
@@ -0,0 +1,13 @@
1
+ import { type ReactNode } from 'react';
2
+ import { type PageLinkInfo } from '../../lib/page-link.js';
3
+ /** The page icon, drawn from the same shape as the editor's (PAGE_ICON_PATHS). */
4
+ export declare function PageIcon(): import("react").JSX.Element;
5
+ export type PageLinkViewProps = {
6
+ href: string;
7
+ info: PageLinkInfo;
8
+ /** The link's own words, as plain text (a removed page's name, when the app gives no title). */
9
+ words: string;
10
+ /** The link's own words, as rendered: shown when the app gives no title. */
11
+ children: ReactNode;
12
+ };
13
+ export declare function PageLinkView({ href, info, words, children }: PageLinkViewProps): import("react").JSX.Element;