@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
@@ -0,0 +1,44 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ // A page link as <Markdown> draws it (src/lib/page-link.ts says what one
3
+ // is): the page icon and the page's title, a link to the page in this tab
4
+ // (through the router when there is one), or, for a page the app reports
5
+ // removed, "Page removed" and a Restore button. A paragraph that holds
6
+ // only a page link is a page line, a row of its own (markdown.tsx marks
7
+ // it). The look: styles/index.css "Page links in written text".
8
+ import { useEffect, useRef, useState } from 'react';
9
+ import { Link, useInRouterContext } from 'react-router';
10
+ import { Button } from '../ui/button.js';
11
+ import { PAGE_ICON_PATHS, pageName } from '../../lib/page-link.js';
12
+ import { restorePage } from './page-restore.js';
13
+ /** The page icon, drawn from the same shape as the editor's (PAGE_ICON_PATHS). */
14
+ export function PageIcon() {
15
+ return (_jsx("svg", { "aria-hidden": "true", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 2, strokeLinecap: "round", strokeLinejoin: "round", className: "page-link-icon", children: PAGE_ICON_PATHS.map((d) => (_jsx("path", { d: d }, d))) }));
16
+ }
17
+ function RestorePageButton({ info, name }) {
18
+ const [busy, setBusy] = useState(false);
19
+ const mounted = useRef(true);
20
+ useEffect(() => {
21
+ mounted.current = true;
22
+ return () => {
23
+ mounted.current = false;
24
+ };
25
+ }, []);
26
+ return (_jsx(Button, { variant: "outline", size: "xs", disabled: busy, "aria-label": `Restore ${name}`, "data-slot": "page-restore",
27
+ // Restoring is all it does: a click never reaches whatever the text
28
+ // sits in (a card that opens the record).
29
+ onClick: (event) => {
30
+ event.stopPropagation();
31
+ setBusy(true);
32
+ void restorePage(info, name).then(() => mounted.current && setBusy(false));
33
+ }, children: busy ? 'Restoring…' : 'Restore' }));
34
+ }
35
+ export function PageLinkView({ href, info, words, children }) {
36
+ const inRouter = useInRouterContext();
37
+ const name = pageName(info, words);
38
+ const title = info.title?.trim() ? info.title.trim() : children;
39
+ if (info.removed)
40
+ return (_jsxs("span", { "data-slot": "page-link", "data-removed": "", className: "page-link-removed", children: [_jsx(PageIcon, {}), _jsx("span", { className: "page-link-title", children: title }), _jsx("span", { className: "page-removed-note", children: "Page removed" }), info.onRestore && _jsx(RestorePageButton, { info: info, name: name })] }));
41
+ const content = (_jsxs(_Fragment, { children: [_jsx(PageIcon, {}), title] }));
42
+ // A page of the app's own opens here, not in a new tab like other links.
43
+ return inRouter ? (_jsx(Link, { to: href, "data-slot": "page-link", className: "page-link", children: content })) : (_jsx("a", { href: href, "data-slot": "page-link", className: "page-link", children: content }));
44
+ }
@@ -0,0 +1,3 @@
1
+ import type { PageLinkInfo } from '../../lib/page-link.js';
2
+ /** Runs the app's restore, toasting a refusal. Resolves either way. */
3
+ export declare function restorePage(info: PageLinkInfo, name: string): Promise<void>;
@@ -0,0 +1,14 @@
1
+ // A removed page's Restore, shared by <Markdown>'s button (page-link.tsx)
2
+ // and the editor's (rich-text-page-links.ts): the app's `onRestore`, its
3
+ // refusal toasted in the gateway's words (messageOf).
4
+ import { toast } from 'sonner';
5
+ import { messageOf } from './edit-in-place-store.js';
6
+ /** Runs the app's restore, toasting a refusal. Resolves either way. */
7
+ export async function restorePage(info, name) {
8
+ try {
9
+ await info.onRestore?.();
10
+ }
11
+ catch (error) {
12
+ toast.error(`Couldn't restore ${name}: ${messageOf(error)}`);
13
+ }
14
+ }
@@ -0,0 +1,17 @@
1
+ /** One step of the trail: its name, and where it goes (not the last one's). */
2
+ export type PageCrumb = {
3
+ label: string;
4
+ /** Where the crumb goes. The last crumb, the page itself, needs none. */
5
+ href?: string;
6
+ };
7
+ export type PageTrailProps = {
8
+ /**
9
+ * From the top (the record, or the list it's in) down to the page
10
+ * itself, last. Any number: one is just the page.
11
+ */
12
+ crumbs: PageCrumb[];
13
+ /** The trail's name for screen readers. Defaults to "Breadcrumb". */
14
+ 'aria-label'?: string;
15
+ className?: string;
16
+ };
17
+ export declare function PageTrail({ crumbs, 'aria-label': ariaLabel, className }: PageTrailProps): import("react").JSX.Element;
@@ -0,0 +1,71 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ // The way back from a page: the record it belongs to, each page above it,
3
+ // and the page itself (`Notes › Project plan › Getting Started › Setup`), as a
4
+ // breadcrumb (shadcn's Breadcrumb). Pages nest to any depth, so a trail
5
+ // can be any length: when it doesn't fit on one line, the crumbs after the
6
+ // first are folded into a "…" menu, from the top down, until it does; the
7
+ // first and the page itself always show, the page's own name cut short
8
+ // with an ellipsis if even that is too wide (a phone). Every crumb but the
9
+ // last is a link (through the router when there is one); the last is the
10
+ // page you're on (`aria-current="page"`).
11
+ import { useLayoutEffect, useRef, useState } from 'react';
12
+ import { Link, useInRouterContext } from 'react-router';
13
+ import { cn } from 'cn';
14
+ import { ChevronRightIcon } from 'lucide-react';
15
+ import { Breadcrumb, BreadcrumbEllipsis, BreadcrumbItem, BreadcrumbLink, BreadcrumbList, BreadcrumbPage, BreadcrumbSeparator, } from '../ui/breadcrumb.js';
16
+ import { crumbsToFold } from '../../lib/page-trail.js';
17
+ import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '../ui/dropdown-menu.js';
18
+ // A crumb's widest, so one long title can't take the whole line.
19
+ const CRUMB = 'block max-w-48 truncate';
20
+ function CrumbLink({ crumb, inRouter }) {
21
+ if (!crumb.href)
22
+ return _jsx("span", { className: cn(CRUMB, 'text-muted-foreground'), children: crumb.label });
23
+ return (_jsx(BreadcrumbLink, { className: CRUMB, title: crumb.label, render: inRouter ? _jsx(Link, { to: crumb.href }) : _jsx("a", { href: crumb.href }), children: crumb.label }));
24
+ }
25
+ export function PageTrail({ crumbs, 'aria-label': ariaLabel, className }) {
26
+ const inRouter = useInRouterContext();
27
+ const navRef = useRef(null);
28
+ const measureRef = useRef(null);
29
+ const [folded, setFolded] = useState(0);
30
+ const key = crumbs.map((crumb) => `${crumb.label}\u0000${crumb.href ?? ''}`).join('\u0001');
31
+ // Measured from a copy of the whole trail nobody sees, each time the
32
+ // trail's room or its crumbs change.
33
+ useLayoutEffect(() => {
34
+ const nav = navRef.current;
35
+ const measure = measureRef.current;
36
+ if (!nav || !measure)
37
+ return;
38
+ const update = () => {
39
+ const items = [...measure.querySelectorAll('[data-measure=crumb]')].map((item) => item.offsetWidth);
40
+ const separator = measure.querySelector('[data-measure=separator]')?.offsetWidth ?? 0;
41
+ const ellipsis = measure.querySelector('[data-measure=ellipsis]')?.offsetWidth ?? 0;
42
+ // A separator's share of the list's gaps: one each side.
43
+ const gap = parseFloat(getComputedStyle(measure).columnGap) || 0;
44
+ setFolded(crumbsToFold(items, separator + gap * 2, ellipsis, nav.clientWidth));
45
+ };
46
+ update();
47
+ const observer = new ResizeObserver(update);
48
+ observer.observe(nav);
49
+ return () => observer.disconnect();
50
+ }, [key]);
51
+ const last = crumbs.length - 1;
52
+ const hidden = crumbs.slice(1, 1 + folded);
53
+ const shown = crumbs
54
+ .map((crumb, index) => ({ crumb, index }))
55
+ .filter(({ index }) => index === 0 || index > folded);
56
+ const separator = (id) => _jsx(BreadcrumbSeparator, {}, id);
57
+ const items = [];
58
+ shown.forEach(({ crumb, index }, at) => {
59
+ if (at > 0)
60
+ items.push(separator(`separator-${index}`));
61
+ if (index === 0 && hidden.length > 0) {
62
+ items.push(_jsx(BreadcrumbItem, { className: "shrink-0", children: _jsx(CrumbLink, { crumb: crumb, inRouter: inRouter }) }, "first"), separator('separator-menu'), _jsx(BreadcrumbItem, { className: "shrink-0", children: _jsxs(DropdownMenu, { children: [_jsx(DropdownMenuTrigger, { "aria-label": hidden.length === 1 ? 'Show 1 more page' : `Show ${hidden.length} more pages`, "data-slot": "page-trail-more", className: "flex items-center rounded-md transition-colors outline-none hover:text-foreground focus-visible:ring-3 focus-visible:ring-ring/50", children: _jsx(BreadcrumbEllipsis, {}) }), _jsx(DropdownMenuContent, { align: "start", className: "max-w-72", children: hidden.map((item, offset) => (_jsx(DropdownMenuItem, { render: item.href ? inRouter ? _jsx(Link, { to: item.href }) : _jsx("a", { href: item.href }) : undefined, disabled: !item.href, children: _jsx("span", { className: "truncate", children: item.label }) }, offset))) })] }) }, "menu"));
63
+ return;
64
+ }
65
+ if (index === last)
66
+ items.push(_jsx(BreadcrumbItem, { className: "min-w-0", children: _jsx(BreadcrumbPage, { className: "block truncate", title: crumb.label, children: crumb.label }) }, "page"));
67
+ else
68
+ items.push(_jsx(BreadcrumbItem, { className: index === 0 ? 'shrink-0' : 'min-w-0', children: _jsx(CrumbLink, { crumb: crumb, inRouter: inRouter }) }, `crumb-${index}`));
69
+ });
70
+ return (_jsxs(Breadcrumb, { ref: navRef, "aria-label": ariaLabel ?? 'Breadcrumb', "data-slot": "page-trail", className: cn('relative min-w-0', className), children: [_jsx(BreadcrumbList, { className: "flex-nowrap", children: items }), _jsx("div", { "aria-hidden": "true", className: "pointer-events-none invisible absolute inset-x-0 top-0 h-0 overflow-hidden", children: _jsxs("ol", { ref: measureRef, className: "flex w-max gap-1.5 text-sm whitespace-nowrap", children: [crumbs.map((crumb, index) => (_jsx("li", { "data-measure": "crumb", className: index === last ? 'block' : CRUMB, children: crumb.label }, index))), _jsx("li", { "data-measure": "separator", children: _jsx(ChevronRightIcon, { className: "size-3.5" }) }), _jsx("li", { "data-measure": "ellipsis", className: "flex size-5" })] }) })] }));
71
+ }
@@ -1,4 +1,5 @@
1
1
  import type { ImageUpload } from '../../lib/image-file.js';
2
+ import type { CreatePage, PageLinkResolver } from '../../lib/page-link.js';
2
3
  import type { HeadingFrom, HeadingLevel, TableLook } from './prose-look.js';
3
4
  export type RichTextEditorProps = {
4
5
  /** The editable element's id, for a label's `htmlFor` or a test. */
@@ -98,6 +99,27 @@ export type RichTextEditorProps = {
98
99
  * zebra rows. The same on <Markdown>. Either way columns fit their words.
99
100
  */
100
101
  tableLook?: TableLook;
102
+ /**
103
+ * Which links are the app's own pages, as on `<Markdown>`
104
+ * (src/lib/page-link.ts): each link's address in, what the app knows of
105
+ * the page (title, removed, `onRestore`) or `null` out. A page link
106
+ * shows the page icon and its words in the page-link look, a row of its
107
+ * own when alone in a paragraph; a click opens it in this tab (through
108
+ * the router when there is one). A removed page is struck through, with
109
+ * "Page removed" and, given `onRestore`, Restore. The Markdown is never
110
+ * changed. Called again on each render, so pass the app's latest data.
111
+ */
112
+ pageLink?: PageLinkResolver;
113
+ /**
114
+ * Lets the text make pages: "/page" in the slash menu, and Turn into
115
+ * page on selected words, ask for a title (the selected words to start
116
+ * with), call this with it, and once it resolves to the new page's
117
+ * address put `[title](href)` where the "/page" or the words were. While
118
+ * it's pending the title box waits; a rejection is shown in the box in
119
+ * the gateway's words and the text is left as it was. Where the page
120
+ * lives (under this record, or under a page, any depth) is the app's.
121
+ */
122
+ onCreatePage?: CreatePage;
101
123
  className?: string;
102
124
  /** The field's label. A rich-text area must have one: this, or `aria-labelledby`. */
103
125
  'aria-label'?: string;
@@ -35,6 +35,14 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
35
35
  // from the slash menu (Toggle heading 1 to 3) or made from the heading the
36
36
  // caret is in with the toolbar's Toggle heading. Plain is the default.
37
37
  //
38
+ // With `pageLink`, links the app marks as its pages (src/lib/page-link.ts)
39
+ // draw as page links, as on <Markdown>: the page icon, a row of their own
40
+ // when alone in a paragraph, "Page removed" with Restore. A click opens the
41
+ // page in this tab. With `onCreatePage`, "/page" (or Turn into page on
42
+ // selected words) asks for a title, has the app make the page, and puts
43
+ // in `[title](href)`. Pages may nest to any depth: a page's own note takes
44
+ // the same props. The Markdown stays plain links.
45
+ //
38
46
  // `defaultValue` is read when it mounts, then followed: a new value the
39
47
  // editor didn't report itself (a form's loaded record arriving after the
40
48
  // editor, a reset) replaces the text, as if it opened with it. Its own
@@ -13,6 +13,8 @@ export interface RichTextFloatingToolbarProps {
13
13
  controls: string;
14
14
  /** A button pressed: run the format on the editor and give it focus back. */
15
15
  onFormat: (id: FormatId) => void;
16
+ /** The Page button pressed (the words become a new page's link). No button without it. */
17
+ onPage?: () => void;
16
18
  /** Esc: hide it until the selection changes. */
17
19
  onDismiss: () => void;
18
20
  /** Esc or Tab: focus back to the text. */
@@ -22,4 +24,4 @@ export interface RichTextFloatingToolbarProps {
22
24
  /** Its element, for Alt+F10 to reach it and for the editor's own blur. */
23
25
  ref?: Ref<HTMLDivElement>;
24
26
  }
25
- export declare function RichTextFloatingToolbar({ view, state, field, controls, onFormat, onDismiss, onReturn, onBlur, ref, }: RichTextFloatingToolbarProps): import("react").JSX.Element;
27
+ export declare function RichTextFloatingToolbar({ view, state, field, controls, onFormat, onPage, onDismiss, onReturn, onBlur, ref, }: RichTextFloatingToolbarProps): import("react").JSX.Element;
@@ -53,7 +53,7 @@ function place(view, from, to, field, bar) {
53
53
  const left = Math.max(0, Math.min(centre - box.left, box.width - width));
54
54
  return { top: top - box.top, left, side: above ? 'top' : 'bottom' };
55
55
  }
56
- export function RichTextFloatingToolbar({ view, state, field, controls, onFormat, onDismiss, onReturn, onBlur, ref, }) {
56
+ export function RichTextFloatingToolbar({ view, state, field, controls, onFormat, onPage, onDismiss, onReturn, onBlur, ref, }) {
57
57
  const [bar, setBar] = useState(null);
58
58
  const [placement, setPlacement] = useState(null);
59
59
  const { from, to } = state.selection;
@@ -88,5 +88,5 @@ export function RichTextFloatingToolbar({ view, state, field, controls, onFormat
88
88
  ref.current = element;
89
89
  }, role: "toolbar", "aria-label": "Format selection", "aria-controls": controls, "data-slot": "rich-text-floating-toolbar", "data-side": placement?.side, style: placement ? { top: placement.top, left: placement.left } : undefined, className: cn('absolute z-50 flex items-center gap-0.5 rounded-lg bg-popover p-1 text-popover-foreground shadow-md ring-1 ring-foreground/10', 'animate-in fade-in-0 zoom-in-95 duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=top]:slide-in-from-bottom-2',
90
90
  // Measured before it's seen, so it never shows in the wrong place.
91
- !placement && 'invisible'), onKeyDown: onKeyDown, onBlur: onBlur, children: _jsx(FormatButtons, { formats: "selection", state: state, readOnly: false, onFormat: onFormat }) }));
91
+ !placement && 'invisible'), onKeyDown: onKeyDown, onBlur: onBlur, children: _jsx(FormatButtons, { formats: "selection", state: state, readOnly: false, onFormat: onFormat, onPage: onPage }) }));
92
92
  }
@@ -0,0 +1,44 @@
1
+ import { Plugin, type EditorState, type Transaction } from '@milkdown/kit/prose/state';
2
+ import { DecorationSet, type EditorView } from '@milkdown/kit/prose/view';
3
+ import { type PageLinkInfo, type PageLinkResolver } from '../../lib/page-link.js';
4
+ export type PageLinksOptions = {
5
+ /** The app's `pageLink` now (it may change between renders). */
6
+ resolve: () => PageLinkResolver | undefined;
7
+ /** A Restore button pressed: resolves once the app's restore settles. */
8
+ restore: (info: PageLinkInfo, name: string) => Promise<void>;
9
+ /** Whether the text can be edited now (no Restore while it can't). */
10
+ editable: () => boolean;
11
+ };
12
+ type PageLinksState = {
13
+ decorations: DecorationSet;
14
+ signature: string;
15
+ };
16
+ /** The plugin: the page links' look, drawn again when the text changes or `refreshPageLinks` asks. */
17
+ export declare function pageLinksPlugin(options: PageLinksOptions): Plugin<PageLinksState>;
18
+ /**
19
+ * Redraws the page links if what the app answers for them has changed
20
+ * (a title, removed or restored, Restore offered or not, read-only or
21
+ * not). Cheap to call after every render: it dispatches only on a change.
22
+ */
23
+ export declare function refreshPageLinks(view: EditorView, resolve: PageLinkResolver | undefined, editable: boolean): void;
24
+ /** What the app says of the page a link points to, if it's one. */
25
+ export declare function pageLinkInfo(resolve: PageLinkResolver | undefined, href: string): PageLinkInfo | null;
26
+ /** Where the new page's link goes: what was typed ("/page") or selected. */
27
+ export type PageSpan = {
28
+ from: number;
29
+ to: number;
30
+ };
31
+ /** Keeps the span a page being made will replace in step with edits made meanwhile. */
32
+ export declare function pendingPagePlugin(): Plugin<PageSpan | null>;
33
+ /** Marks (or, with null, forgets) the span the page being made will go in. */
34
+ export declare function setPendingPage(tr: Transaction, span: PageSpan | null): Transaction;
35
+ /** The span the page being made will go in, if one is. */
36
+ export declare function pendingPage(state: EditorState): PageSpan | null;
37
+ /**
38
+ * Puts the new page's link in its span: the title as the link's words,
39
+ * linked to `href`, in one transaction (one undo step). The caret goes
40
+ * after it, and what's typed next isn't part of the link. False when
41
+ * there's no span any more.
42
+ */
43
+ export declare function insertPageLink(view: EditorView, title: string, href: string): boolean;
44
+ export {};
@@ -0,0 +1,201 @@
1
+ import { Plugin, PluginKey, TextSelection } from '@milkdown/kit/prose/state';
2
+ import { Decoration, DecorationSet } from '@milkdown/kit/prose/view';
3
+ import { buttonVariants } from '../ui/button.js';
4
+ import { PAGE_ICON_PATHS, pageLinkSignature, pageName } from '../../lib/page-link.js';
5
+ // Every link in the text, as runs of text under one link mark.
6
+ function linkRuns(doc) {
7
+ const runs = [];
8
+ doc.descendants((node, pos) => {
9
+ if (!node.isTextblock)
10
+ return true;
11
+ let run = null;
12
+ node.forEach((child, offset) => {
13
+ const start = pos + 1 + offset;
14
+ const mark = child.marks.find((candidate) => candidate.type.name === 'link');
15
+ if (mark && run && run.mark.eq(mark) && run.to === start) {
16
+ run.to = start + child.nodeSize;
17
+ run.words += child.text ?? '';
18
+ return;
19
+ }
20
+ if (run)
21
+ runs.push(run);
22
+ const href = mark ? String(mark.attrs.href ?? '') : '';
23
+ run = mark && href ? { from: start, to: start + child.nodeSize, mark, href, words: child.text ?? '', parent: node, parentPos: pos } : null;
24
+ });
25
+ if (run)
26
+ runs.push(run);
27
+ return false;
28
+ });
29
+ return runs;
30
+ }
31
+ function pageIcon() {
32
+ const box = document.createElement('span');
33
+ box.setAttribute('aria-hidden', 'true');
34
+ const svgNs = 'http://www.w3.org/2000/svg';
35
+ const svg = document.createElementNS(svgNs, 'svg');
36
+ for (const [name, value] of Object.entries({
37
+ viewBox: '0 0 24 24',
38
+ fill: 'none',
39
+ stroke: 'currentColor',
40
+ 'stroke-width': '2',
41
+ 'stroke-linecap': 'round',
42
+ 'stroke-linejoin': 'round',
43
+ class: 'page-link-icon',
44
+ }))
45
+ svg.setAttribute(name, value);
46
+ for (const d of PAGE_ICON_PATHS) {
47
+ const path = document.createElementNS(svgNs, 'path');
48
+ path.setAttribute('d', d);
49
+ svg.appendChild(path);
50
+ }
51
+ box.appendChild(svg);
52
+ return box;
53
+ }
54
+ const pageLinksKey = new PluginKey('rich-text-page-links');
55
+ function draw(doc, options) {
56
+ const resolve = options.resolve();
57
+ if (!resolve)
58
+ return { decorations: DecorationSet.empty, signature: '' };
59
+ const decorations = [];
60
+ const signature = [];
61
+ for (const run of linkRuns(doc)) {
62
+ const info = resolve(run.href);
63
+ signature.push(`${run.href}:${pageLinkSignature(info)}`);
64
+ if (!info)
65
+ continue;
66
+ const removed = Boolean(info.removed);
67
+ decorations.push(
68
+ // The icon inside the link (its marks), so a click on it is one on the link.
69
+ Decoration.widget(run.from, pageIcon, { side: -1, marks: [run.mark], key: 'page-icon', ignoreSelection: true }), Decoration.inline(run.from, run.to, { class: 'page-link-text', 'data-page-link': '', ...(removed ? { 'data-removed': '' } : {}) }));
70
+ if (run.parent.type.name === 'paragraph' && run.from === run.parentPos + 1 && run.to === run.parentPos + 1 + run.parent.content.size)
71
+ decorations.push(Decoration.node(run.parentPos, run.parentPos + run.parent.nodeSize, { class: 'page-line', 'data-page-line': '' }));
72
+ if (removed) {
73
+ const name = pageName(info, run.words);
74
+ const restorable = Boolean(info.onRestore) && options.editable();
75
+ decorations.push(Decoration.widget(run.to, () => removedNote(info, name, restorable, options), {
76
+ side: 1,
77
+ key: `page-removed:${restorable}:${name}`,
78
+ ignoreSelection: true,
79
+ // The button's own events: ProseMirror leaves them alone.
80
+ stopEvent: () => true,
81
+ }));
82
+ }
83
+ }
84
+ return { decorations: DecorationSet.create(doc, decorations), signature: signature.join('\n') };
85
+ }
86
+ // "Page removed", and Restore when the app gives one.
87
+ function removedNote(info, name, restorable, options) {
88
+ const box = document.createElement('span');
89
+ box.className = 'page-removed';
90
+ box.dataset.slot = 'page-removed';
91
+ const note = document.createElement('span');
92
+ note.className = 'page-removed-note';
93
+ note.textContent = 'Page removed';
94
+ box.appendChild(note);
95
+ if (!restorable)
96
+ return box;
97
+ const button = document.createElement('button');
98
+ button.type = 'button';
99
+ button.className = buttonVariants({ variant: 'outline', size: 'xs' });
100
+ button.dataset.slot = 'page-restore';
101
+ button.setAttribute('aria-label', `Restore ${name}`);
102
+ button.textContent = 'Restore';
103
+ // A press never moves the caret.
104
+ button.addEventListener('mousedown', (event) => event.preventDefault());
105
+ button.addEventListener('click', (event) => {
106
+ event.preventDefault();
107
+ event.stopPropagation();
108
+ button.disabled = true;
109
+ button.textContent = 'Restoring…';
110
+ void options.restore(info, name).then(() => {
111
+ button.disabled = false;
112
+ button.textContent = 'Restore';
113
+ });
114
+ });
115
+ box.appendChild(button);
116
+ return box;
117
+ }
118
+ /** The plugin: the page links' look, drawn again when the text changes or `refreshPageLinks` asks. */
119
+ export function pageLinksPlugin(options) {
120
+ return new Plugin({
121
+ key: pageLinksKey,
122
+ state: {
123
+ init: (_config, state) => draw(state.doc, options),
124
+ apply: (tr, value, _previous, next) => (tr.docChanged || tr.getMeta(pageLinksKey) ? draw(next.doc, options) : value),
125
+ },
126
+ props: {
127
+ decorations: (state) => pageLinksKey.getState(state)?.decorations,
128
+ },
129
+ });
130
+ }
131
+ /**
132
+ * Redraws the page links if what the app answers for them has changed
133
+ * (a title, removed or restored, Restore offered or not, read-only or
134
+ * not). Cheap to call after every render: it dispatches only on a change.
135
+ */
136
+ export function refreshPageLinks(view, resolve, editable) {
137
+ const current = pageLinksKey.getState(view.state);
138
+ if (!current)
139
+ return;
140
+ const signature = resolve
141
+ ? linkRuns(view.state.doc)
142
+ .map((run) => `${run.href}:${pageLinkSignature(resolve(run.href))}`)
143
+ .join('\n')
144
+ : '';
145
+ const key = `${editable}|${signature}`;
146
+ if (key === refreshed.get(view))
147
+ return;
148
+ refreshed.set(view, key);
149
+ view.dispatch(view.state.tr.setMeta(pageLinksKey, true).setMeta('addToHistory', false));
150
+ }
151
+ const refreshed = new WeakMap();
152
+ /** What the app says of the page a link points to, if it's one. */
153
+ export function pageLinkInfo(resolve, href) {
154
+ return resolve?.(href) ?? null;
155
+ }
156
+ const pendingKey = new PluginKey('rich-text-pending-page');
157
+ /** Keeps the span a page being made will replace in step with edits made meanwhile. */
158
+ export function pendingPagePlugin() {
159
+ return new Plugin({
160
+ key: pendingKey,
161
+ state: {
162
+ init: () => null,
163
+ apply: (tr, value) => {
164
+ const meta = tr.getMeta(pendingKey);
165
+ if (meta !== undefined)
166
+ return meta;
167
+ if (!value)
168
+ return null;
169
+ const from = tr.mapping.map(value.from, 1);
170
+ const to = Math.max(from, tr.mapping.map(value.to, -1));
171
+ return { from, to };
172
+ },
173
+ },
174
+ });
175
+ }
176
+ /** Marks (or, with null, forgets) the span the page being made will go in. */
177
+ export function setPendingPage(tr, span) {
178
+ return tr.setMeta(pendingKey, span);
179
+ }
180
+ /** The span the page being made will go in, if one is. */
181
+ export function pendingPage(state) {
182
+ return pendingKey.getState(state) ?? null;
183
+ }
184
+ /**
185
+ * Puts the new page's link in its span: the title as the link's words,
186
+ * linked to `href`, in one transaction (one undo step). The caret goes
187
+ * after it, and what's typed next isn't part of the link. False when
188
+ * there's no span any more.
189
+ */
190
+ export function insertPageLink(view, title, href) {
191
+ const span = pendingPage(view.state);
192
+ if (!span || span.to > view.state.doc.content.size)
193
+ return false;
194
+ const { schema } = view.state;
195
+ const link = schema.marks.link.create({ href });
196
+ const tr = setPendingPage(view.state.tr.replaceWith(span.from, span.to, schema.text(title, [link])), null);
197
+ tr.setSelection(TextSelection.create(tr.doc, span.from + title.length));
198
+ tr.removeStoredMark(schema.marks.link);
199
+ view.dispatch(tr.scrollIntoView());
200
+ return true;
201
+ }
@@ -1,6 +1,5 @@
1
1
  import type { EditorView } from '@milkdown/kit/prose/view';
2
- import type { FormatItem } from './rich-text-format-items.js';
3
- import type { FormatId } from './rich-text-formats.js';
2
+ import { type SlashItem } from './rich-text-slash.js';
4
3
  export interface RichTextSlashMenuProps {
5
4
  /** The list's id, for the text's `aria-controls`. */
6
5
  id: string;
@@ -9,10 +8,10 @@ export interface RichTextSlashMenuProps {
9
8
  at: number;
10
9
  /** The field's element it's placed against (positioned: `relative`). */
11
10
  field: HTMLElement | null;
12
- items: FormatItem[];
11
+ items: SlashItem[];
13
12
  /** The highlighted item: Enter picks it. */
14
13
  active: number;
15
14
  onHighlight: (index: number) => void;
16
- onPick: (id: FormatId) => void;
15
+ onPick: (id: SlashItem['id']) => void;
17
16
  }
18
17
  export declare function RichTextSlashMenu({ id, view, at, field, items, active, onHighlight, onPick }: RichTextSlashMenuProps): import("react").JSX.Element;
@@ -14,14 +14,23 @@ export type SlashQuery = {
14
14
  };
15
15
  /** The open menu's span and query, or null when it's closed. */
16
16
  export declare function slashQuery(state: EditorState): SlashQuery | null;
17
- /** The transaction that closes the menu, leaving what was typed as text (Esc). */
17
+ /** The transaction that closes the menu, leaving what was typed as text (Esc, or the page's title box opening). */
18
18
  export declare function closeSlash(state: EditorState): Transaction;
19
19
  /** The id of the menu's item at `index`, for the text's `aria-activedescendant`. */
20
20
  export declare function slashOptionId(listId: string, index: number): string;
21
21
  /** The plugin: opens on a typed "/", follows the text, closes once the span stops qualifying. */
22
22
  export declare function slashPlugin(): Plugin<SlashState>;
23
- /** The blocks matching what's typed after the "/": in the name, or the start of a keyword. */
24
- export declare function slashItems(query: string): FormatItem[];
23
+ /** A slash menu item: a block, or the new page (only with the app's `onCreatePage`). */
24
+ export type SlashItem = Omit<FormatItem, 'id'> & {
25
+ id: FormatId | 'page';
26
+ };
27
+ /**
28
+ * The blocks matching what's typed after the "/": in the name, or the
29
+ * start of a keyword. With `page`, the new page too.
30
+ */
31
+ export declare function slashItems(query: string, options?: {
32
+ page?: boolean;
33
+ }): SlashItem[];
25
34
  /**
26
35
  * Picks an item: the "/…" goes and the paragraph becomes that block, in one
27
36
  * transaction (one undo step, which brings the "/…" back).
@@ -8,6 +8,7 @@
8
8
  // `/usr/bin`) never does, and neither does a "/" mid-line or inside a
9
9
  // list, a quote or a code block.
10
10
  import { Plugin, PluginKey } from '@milkdown/kit/prose/state';
11
+ import { FileTextIcon } from 'lucide-react';
11
12
  import { CALLOUT_VARIANTS, FORMAT_GROUPS, HIGHLIGHT_VARIANTS, TOGGLE_HEADING_VARIANTS } from './rich-text-format-items.js';
12
13
  import { toggleFormat } from './rich-text-formats.js';
13
14
  const slashKey = new PluginKey('rich-text-slash');
@@ -43,7 +44,7 @@ export function slashQuery(state) {
43
44
  const open = slashKey.getState(state);
44
45
  return open ? queryAt(state, open.from) : null;
45
46
  }
46
- /** The transaction that closes the menu, leaving what was typed as text (Esc). */
47
+ /** The transaction that closes the menu, leaving what was typed as text (Esc, or the page's title box opening). */
47
48
  export function closeSlash(state) {
48
49
  return state.tr.setMeta(slashKey, 'close');
49
50
  }
@@ -108,15 +109,25 @@ const KEYWORDS = {
108
109
  // once something's typed ("/warn"), so the list "/" opens with stays short.
109
110
  const BLOCKS = FORMAT_GROUPS.flat().filter((item) => KEYWORDS[item.id]);
110
111
  BLOCKS.splice(BLOCKS.findIndex((item) => item.id === 'heading3') + 1, 0, ...TOGGLE_HEADING_VARIANTS);
111
- /** The blocks matching what's typed after the "/": in the name, or the start of a keyword. */
112
- export function slashItems(query) {
112
+ // A page of its own, linked from here (src/lib/page-link.ts): last, since
113
+ // it's the only item that leaves the editor (a title box, then the app).
114
+ const PAGE_ITEM = { id: 'page', label: 'Page', icon: FileTextIcon };
115
+ const PAGE_KEYWORDS = ['page', 'subpage', 'child', 'link', 'new'];
116
+ /**
117
+ * The blocks matching what's typed after the "/": in the name, or the
118
+ * start of a keyword. With `page`, the new page too.
119
+ */
120
+ export function slashItems(query, options = {}) {
113
121
  const typed = query.trim().toLowerCase();
122
+ const page = options.page && (!typed || 'page'.includes(typed) || PAGE_KEYWORDS.some((word) => word.startsWith(typed))) ? [PAGE_ITEM] : [];
114
123
  if (!typed)
115
- return BLOCKS;
124
+ return [...BLOCKS, ...page];
116
125
  const blocks = [...BLOCKS];
117
126
  blocks.splice(BLOCKS.findIndex((item) => item.id === 'callout') + 1, 0, ...CALLOUT_VARIANTS);
118
127
  blocks.push(...HIGHLIGHT_VARIANTS);
119
- return blocks.filter((item) => item.label.toLowerCase().includes(typed) || KEYWORDS[item.id].some((word) => word.startsWith(typed)));
128
+ const matches = blocks.filter((item) => item.label.toLowerCase().includes(typed) || KEYWORDS[item.id].some((word) => word.startsWith(typed)));
129
+ // "/page" puts the page first: it's what was asked for by name.
130
+ return typed.length >= 2 && 'page'.startsWith(typed) ? [...page, ...matches] : [...matches, ...page];
120
131
  }
121
132
  /**
122
133
  * Picks an item: the "/…" goes and the paragraph becomes that block, in one
@@ -15,6 +15,8 @@ export type FormatButtonsProps = {
15
15
  readOnly: boolean;
16
16
  /** A button pressed: run the format on the editor and give it focus back. */
17
17
  onFormat: (id: FormatId) => void;
18
+ /** The Page button pressed: the selected words become a new page's link. No button without it. */
19
+ onPage?: () => void;
18
20
  /** The Image button pressed: pick images to upload. No button without it. */
19
21
  onImage?: () => void;
20
22
  /** The Full screen button pressed. No button without it. */
@@ -24,7 +26,7 @@ export type FormatButtonsProps = {
24
26
  /** The editable element, for the Highlight menu to give focus back to. */
25
27
  text?: () => HTMLElement | null;
26
28
  };
27
- export declare function FormatButtons({ formats, state, readOnly, onFormat, onImage, onFullScreen, fullScreen, text }: FormatButtonsProps): import("react").JSX.Element;
29
+ export declare function FormatButtons({ formats, state, readOnly, onFormat, onPage, onImage, onFullScreen, fullScreen, text }: FormatButtonsProps): import("react").JSX.Element;
28
30
  export interface RichTextToolbarProps {
29
31
  /** The editor's state now, to show which formats are on. Null until it's made. */
30
32
  state: EditorState | null;