@tristan2828/ui-foundation 4.72.0 → 4.74.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 (34) hide show
  1. package/conventions/docs/add-an-entity.md +38 -14
  2. package/conventions/docs/design-language.md +103 -26
  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 +73 -0
  34. package/styles/theme.css +55 -1
@@ -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
+ }
@@ -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 {};