@tristan2828/ui-foundation 4.71.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 (50) hide show
  1. package/conventions/docs/add-an-entity.md +45 -15
  2. package/conventions/docs/cell-patterns.md +210 -37
  3. package/conventions/docs/design-language.md +64 -24
  4. package/dist/components/app/edit-in-place-controls.d.ts +34 -0
  5. package/dist/components/app/edit-in-place-controls.js +92 -0
  6. package/dist/components/app/edit-in-place-presets.d.ts +187 -0
  7. package/dist/components/app/edit-in-place-presets.js +409 -0
  8. package/dist/components/app/edit-in-place-store.d.ts +9 -0
  9. package/dist/components/app/edit-in-place-store.js +14 -7
  10. package/dist/components/app/edit-in-place.d.ts +101 -4
  11. package/dist/components/app/editable-list.js +158 -23
  12. package/dist/components/app/editable-value.d.ts +2 -2
  13. package/dist/components/app/editable-value.js +7 -3
  14. package/dist/components/app/entity-view.d.ts +6 -2
  15. package/dist/components/app/entity-view.js +11 -2
  16. package/dist/components/app/markdown.d.ts +13 -1
  17. package/dist/components/app/markdown.js +43 -8
  18. package/dist/components/app/milkdown-editor.d.ts +1 -1
  19. package/dist/components/app/milkdown-editor.js +184 -19
  20. package/dist/components/app/page-link.d.ts +13 -0
  21. package/dist/components/app/page-link.js +44 -0
  22. package/dist/components/app/page-restore.d.ts +3 -0
  23. package/dist/components/app/page-restore.js +14 -0
  24. package/dist/components/app/page-trail.d.ts +17 -0
  25. package/dist/components/app/page-trail.js +71 -0
  26. package/dist/components/app/rich-text-editor.d.ts +22 -0
  27. package/dist/components/app/rich-text-editor.js +8 -0
  28. package/dist/components/app/rich-text-floating-toolbar.d.ts +3 -1
  29. package/dist/components/app/rich-text-floating-toolbar.js +2 -2
  30. package/dist/components/app/rich-text-page-links.d.ts +44 -0
  31. package/dist/components/app/rich-text-page-links.js +201 -0
  32. package/dist/components/app/rich-text-slash-menu.d.ts +3 -4
  33. package/dist/components/app/rich-text-slash.d.ts +12 -3
  34. package/dist/components/app/rich-text-slash.js +16 -5
  35. package/dist/components/app/rich-text-toolbar.d.ts +3 -1
  36. package/dist/components/app/rich-text-toolbar.js +10 -7
  37. package/dist/components/app/row-edit-cells.d.ts +9 -0
  38. package/dist/components/app/row-edit-cells.js +12 -16
  39. package/dist/components/ui/breadcrumb.d.ts +10 -0
  40. package/dist/components/ui/breadcrumb.js +37 -0
  41. package/dist/index.d.ts +5 -1
  42. package/dist/index.js +4 -1
  43. package/dist/lib/link-href.d.ts +28 -0
  44. package/dist/lib/link-href.js +40 -0
  45. package/dist/lib/page-link.d.ts +40 -0
  46. package/dist/lib/page-link.js +32 -0
  47. package/dist/lib/page-trail.d.ts +7 -0
  48. package/dist/lib/page-trail.js +24 -0
  49. package/package.json +1 -1
  50. package/styles/index.css +63 -0
@@ -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;
@@ -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
+ }