@memorysmithapp/markdown-renderer 0.10.2 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -22,6 +22,8 @@ import 'katex/dist/katex.min.css';
22
22
  fileOf={(name) => describe(name)} // { mimeType, bytes, url, description }: drawn by its type, as MemorySmith does
23
23
  renderLink={({ href, className, children }) => <a href={href} className={className} onClick={follow(href)}>{children}</a>} // follow: your router's navigate, captured where it is
24
24
  loadNote={(name) => fetchTheBodyOf(name)} // for an embedded note; the package never fetches
25
+ noteAddress={addressOf(note)} // the note drawn, so ![[its own name]] reaches the file of that name
26
+ loadNoteAt={(address) => fetchTheNoteAt(address)} // …or another note of that name, told apart by address
25
27
  queryTable={(request) => queryYourTable(request)} // the rows a ```table block asks for: one page, the count, the total
26
28
  writable
27
29
  onToggleTask={(ordinal) => save(toggleTaskAt(latest(), ordinal))} // a promise locks the item under "Updating…" until it settles
@@ -30,7 +32,7 @@ import 'katex/dist/katex.min.css';
30
32
  />;
31
33
  ```
32
34
 
33
- Every prop is optional, and every default is the safe one: with no `resolve` every link is pending, with no `keeps` no embed reaches a file. A file `fileOf` describes is drawn by its media type, never its name: an image, an audio or a video player, and anything else a card with its type, size, description, *Open* where a browser shows it and *Download*; give `renderAttachment` instead to draw files yourself. A `table` block is drawn as its table through `queryTable`: it hands you the table, the columns, the filter as written, the order, the page and its size and the column to sum, you run the filter and answer the table's columns with their kinds, the page's rows — a number as its digits, so none is rounded — the row count, the total and when you read them; `runTableQuery` answers from rows you hold in memory. A reader sorts by a header for themselves, which asks you again; a block that cannot be answered says why in its place; without `queryTable` the block is a code block. To print, set `printing`, wait until no `[aria-busy="true"]` is left under the note, then print: every block has then asked for every row, and carries its header on each page, its total and a line saying what was read and when. A print command does not wait for an answer, so a note printed with no `printing` carries the page each table was on. In edit mode, `renderLink`, `renderAttachment` and a theme's slots may be drawn in a root of their own, outside your React tree, so what they return must not read your context: a router's `<Link>` throws there, and the block shows its Markdown under a notice instead. The stylesheet styles nothing outside `.markdown`. The faces of the default theme are Inter and Space Grotesk, which the page loads.
35
+ Every prop is optional, and every default is the safe one: with no `resolve` every link is pending, with no `keeps` no embed reaches a file. A note comes before a file of the same name, and an embed never reaches the note it is written in: give `noteAddress` for a note you keep, and leave it out for a guidance, a template or a draft, which excludes nothing. A file `fileOf` describes is drawn by its media type, never its name: an image, an audio or a video player, and anything else a card with its type, size, description, *Open* where a browser shows it and *Download*; give `renderAttachment` instead to draw files yourself. A `table` block is drawn as its table through `queryTable`: it hands you the table, the columns, the filter as written, the order, the page and its size and the column to sum, you run the filter and answer the table's columns with their kinds, the page's rows — a number as its digits, so none is rounded — the row count, the total and when you read them; `runTableQuery` answers from rows you hold in memory. A reader sorts by a header for themselves, which asks you again; a block that cannot be answered says why in its place; without `queryTable` the block is a code block. To print, set `printing`, wait until no `[aria-busy="true"]` is left under the note, then print: every block has then asked for every row, and carries its header on each page, its total and a line saying what was read and when. A print command does not wait for an answer, so a note printed with no `printing` carries the page each table was on. In edit mode, `renderLink`, `renderAttachment` and a theme's slots may be drawn in a root of their own, outside your React tree, so what they return must not read your context: a router's `<Link>` throws there, and the block shows its Markdown under a notice instead. The stylesheet styles nothing outside `.markdown`. The faces of the default theme are Inter and Space Grotesk, which the page loads.
34
36
 
35
37
  ## Themes
36
38
 
package/dist/NoteBody.js CHANGED
@@ -3,7 +3,7 @@ import { lazy, Suspense, useMemo, useRef, useState } from 'react';
3
3
  import { ICON_EDIT, ICON_VIEW } from './mode-icons.js';
4
4
  import { ButtonFace, NoteActions } from './NoteActions.js';
5
5
  import { drawSlot } from './slots.js';
6
- import { HOST_KEYS, HostProvider, resolveHost, useHost } from './host.js';
6
+ import { HOST_KEYS, HostProvider, resolveHost, useDrawing, useHost } from './host.js';
7
7
  import { planFootnotes } from './footnotes.js';
8
8
  import { Markdown } from './Markdown.js';
9
9
  import { readingPlugins } from './reading.js';
@@ -15,6 +15,7 @@ import { taskBoxes } from './tasklist.js';
15
15
  import { rootStyle } from './theme.js';
16
16
  import { Transclusion } from './Transclusion.js';
17
17
  import { splitEmbeds } from './embeds.js';
18
+ import { embedsFile } from './embed-target.js';
18
19
  import { wikilinkAddress } from './wikilink-address.js';
19
20
  /** The editor, loaded the first time a note is edited, so a host that only draws never loads it. */
20
21
  const NoteEditor = lazy(() => import('./edit/NoteEditor.js').then((module) => ({ default: module.NoteEditor })));
@@ -85,9 +86,11 @@ function HostOnly({ host, children }) {
85
86
  }
86
87
  /** The note drawn for reading: the page MemorySmith's reading page draws. */
87
88
  function NoteView({ markdown, writable = false, onToggleTask, corner, switched = false, buttons = 'icon', ...host }) {
88
- const resolved = useMemo(() => resolveHost(host),
89
+ const given = useMemo(() => resolveHost(host),
89
90
  // Every member of the contract, so a host that passes the same functions keeps the same host.
90
91
  HOST_KEYS.map((key) => host[key]));
92
+ // The note itself, which an embed of its own name does not reach (§5.2, #147).
93
+ const resolved = useDrawing(given, host.noteAddress, markdown);
91
94
  // The frontmatter is drawn apart from the body, as the theme decides, so the
92
95
  // runs start after it. Everything below counts task items from there.
93
96
  // Each tick the host answers with a promise locks its item until the save settles.
@@ -98,12 +101,14 @@ function NoteView({ markdown, writable = false, onToggleTask, corner, switched =
98
101
  const body = hideComments(markdown.slice(split)).text;
99
102
  // The body is cut into runs of text and the embeds between them; each run
100
103
  // is parsed on its own, as on MemorySmith's reading page.
101
- const segments = splitEmbeds(body, resolved.keeps).map((segment) => segment.kind === 'text'
104
+ // A note answers an embed before a file of its name does (§5.8, #148).
105
+ const file = embedsFile(resolved);
106
+ const segments = splitEmbeds(body, file).map((segment) => segment.kind === 'text'
102
107
  ? {
103
108
  ...segment,
104
109
  // One resolver for every run: one note is a link, several are the
105
110
  // choice, and none is pending and still asks.
106
- rendered: resolveWikilinks(segment.text, (name) => wikilinkAddress(resolved, name), resolved.keeps),
111
+ rendered: resolveWikilinks(segment.text, (name) => wikilinkAddress(resolved, name), file),
107
112
  }
108
113
  : segment);
109
114
  /**
@@ -150,7 +155,7 @@ function NoteView({ markdown, writable = false, onToggleTask, corner, switched =
150
155
  let run = 0;
151
156
  return (_jsx(HostProvider, { value: resolved, children: _jsxs("div", { className: `markdown markdown-theme-${resolved.theme.name}${corner ? ' has-note-corner' : ''}${switched ? ' has-mode-switch' : ''}${corner && buttons === 'responsive' ? ' has-responsive-buttons' : ''}`, "data-theme": resolved.scheme, style: rootStyle(resolved.theme, resolved.scheme), children: [corner, _jsx(Properties, { properties: properties }), segments.map((segment, index) => {
152
157
  if (!('rendered' in segment)) {
153
- return _jsx(Transclusion, { target: segment.target, anchor: segment.anchor }, index);
158
+ return _jsx(Transclusion, { target: segment.target, anchor: segment.anchor, source: segment.source }, index);
154
159
  }
155
160
  const base = seen;
156
161
  seen += taskBoxes(segment.rendered).length;
@@ -5,7 +5,8 @@
5
5
  * indistinguishable from what the author wrote, and a notebook rests on
6
6
  * knowing who asserted what.
7
7
  */
8
- export declare function Transclusion({ target, anchor }: {
8
+ export declare function Transclusion({ target, anchor, source }: {
9
9
  target: string;
10
10
  anchor: string | null;
11
+ source?: string;
11
12
  }): string | number | bigint | boolean | import("react").JSX.Element | Iterable<import("react").ReactNode> | Promise<string | number | bigint | boolean | import("react").ReactPortal | import("react").ReactElement<unknown, string | import("react").JSXElementConstructor<any>> | Iterable<import("react").ReactNode> | null | undefined> | null | undefined;
@@ -1,15 +1,36 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { useEffect, useState } from 'react';
2
+ import { useEffect, useMemo, useState } from 'react';
3
3
  import { useHost } from './host.js';
4
4
  import { Markdown } from './Markdown.js';
5
5
  import { drawSlot, useSlot } from './slots.js';
6
6
  import { bodyStart, hideComments, resolveWikilinks } from './source.js';
7
7
  import { blockOf, demoteEmbeds, isBlockAnchor, sectionOf } from './embeds.js';
8
8
  import { wikilinkAddress } from './wikilink-address.js';
9
+ import { drawing, drawnNote, embedsFile, embedTarget } from './embed-target.js';
9
10
  /** The shape of what is coming, in the position it will occupy, while the host answers. */
10
11
  function TransclusionSkeleton({ loading }) {
11
12
  return (_jsxs("div", { className: "skeleton-region", "aria-busy": "true", "aria-live": "polite", children: [_jsx("span", { className: "visually-hidden", children: loading }), _jsxs("figure", { className: "embed embed-skeleton", children: [_jsx("div", { className: "embed-body", children: _jsxs("span", { className: "skeleton-text", children: [_jsx("span", { className: "skeleton", style: { width: '96%', height: '1rem' } }), _jsx("span", { className: "skeleton", style: { width: '58%', height: '1rem' } })] }) }), _jsx("figcaption", { className: "embed-source", children: _jsx("span", { className: "skeleton", style: { width: '8rem', height: '0.8rem' } }) })] })] }));
12
13
  }
14
+ /**
15
+ * What an embed reaches, or `null` while the host's `choose` is asked. Decided at once in every case
16
+ * but one, so a server's render draws the pending marker of a target nothing answers.
17
+ */
18
+ function useDecision(host, name) {
19
+ const answer = useMemo(() => embedTarget(host, name), [host, name]);
20
+ const [settled, setSettled] = useState(null);
21
+ useEffect(() => {
22
+ if (!(answer instanceof Promise))
23
+ return;
24
+ let alive = true;
25
+ answer.then((target) => alive && setSettled({ answer, target }), () => alive && setSettled({ answer, target: { kind: 'pending' } }));
26
+ return () => {
27
+ alive = false;
28
+ };
29
+ }, [answer]);
30
+ if (!(answer instanceof Promise))
31
+ return answer;
32
+ return settled?.answer === answer ? settled.target : null;
33
+ }
13
34
  /**
14
35
  * One transcluded block: the content of another note, shown in place.
15
36
  *
@@ -17,30 +38,39 @@ function TransclusionSkeleton({ loading }) {
17
38
  * indistinguishable from what the author wrote, and a notebook rests on
18
39
  * knowing who asserted what.
19
40
  */
20
- export function Transclusion({ target, anchor }) {
41
+ export function Transclusion({ target, anchor, source }) {
21
42
  const host = useHost();
22
43
  const { strings } = host;
23
44
  const name = target.normalize('NFC');
24
45
  // A transclusion expands ONE note, so it expands what a wikilink would
25
46
  // navigate to: an ambiguous target is a choice a reader makes and not a
26
- // passage the page can inline on their behalf.
27
- const one = host.loadNote !== null && host.reaches(name) === 1;
47
+ // passage the page can inline on their behalf. What it reaches is decided
48
+ // at once, unless the note being drawn carries the name and only the host's
49
+ // `choose` can say which other note is left (§5.2, #147).
50
+ const decided = useDecision(host, name);
51
+ const load = decided?.kind === 'note' ? decided.load : null;
28
52
  const [loaded, setLoaded] = useState({ state: 'loading' });
29
53
  const slot = useSlot('embed');
30
54
  useEffect(() => {
31
- if (!one || !host.loadNote)
55
+ if (!load)
32
56
  return;
33
57
  let alive = true;
34
58
  setLoaded({ state: 'loading' });
35
- host.loadNote(name).then((note) => alive && setLoaded(note ? { state: 'ready', note } : { state: 'missing' }), () => alive && setLoaded({ state: 'missing' }));
59
+ load().then((note) => alive && setLoaded(note ? { state: 'ready', note } : { state: 'missing' }), () => alive && setLoaded({ state: 'missing' }));
36
60
  return () => {
37
61
  alive = false;
38
62
  };
39
- }, [one, host, name]);
63
+ }, [load]);
64
+ // The note itself was the only note its own name matched, and the notebook
65
+ // keeps a file of that name: the embed is the file's, drawn as written.
66
+ if (decided?.kind === 'file') {
67
+ const written = source ?? `![[${target}${anchor ? `#${anchor}` : ''}]]`;
68
+ return _jsx(Markdown, { children: resolveWikilinks(written, (each) => wikilinkAddress(host, each), () => true) });
69
+ }
40
70
  // The same pending marker a wikilink uses. A notebook is read most while it
41
71
  // is still being written, so a target that does not exist yet is an
42
72
  // expected state and never an error that stops the page.
43
- if (!one || loaded.state === 'missing') {
73
+ if ((decided !== null && !load) || loaded.state === 'missing') {
44
74
  const marker = (_jsx("p", { className: "embed-pending", children: _jsx("span", { className: "wikilink-pending", title: strings.pendingLink, children: target }) }));
45
75
  return slot ? drawSlot(slot, { state: 'pending', target, anchor, caption: null, children: marker }) : marker;
46
76
  }
@@ -59,6 +89,8 @@ export function Transclusion({ target, anchor }) {
59
89
  const cut = !anchor ? whole : isBlockAnchor(anchor) ? blockOf(whole, anchor.slice(1)) : sectionOf(whole, anchor);
60
90
  const caption = anchor ? `${sourceLabel} › ${anchor}` : sourceLabel;
61
91
  const named = note.address === null ? caption : host.renderLink({ href: note.address, children: caption });
92
+ // Inside the embedded note, an embed of ITS name is read as that note reads it.
93
+ const inner = drawing(host, drawnNote(note.address, note.markdown));
62
94
  const content = cut === null ? (_jsx("p", { className: "embed-missing", children: strings.embedSectionMissing(anchor ?? '') })) : (
63
95
  /**
64
96
  * Resolved, like every other run of the note. Without this every
@@ -68,7 +100,7 @@ export function Transclusion({ target, anchor }) {
68
100
  * content into a wikilink, and that embed is drawn as A LINK to its
69
101
  * target. Raw text is not a link.
70
102
  */
71
- _jsx(Markdown, { children: resolveWikilinks(demoteEmbeds(cut, host.keeps), (each) => wikilinkAddress(host, each), host.keeps) }));
103
+ _jsx(Markdown, { children: resolveWikilinks(demoteEmbeds(cut, embedsFile(inner)), (each) => wikilinkAddress(host, each), embedsFile(inner)) }));
72
104
  if (slot) {
73
105
  return drawSlot(slot, {
74
106
  state: cut === null ? 'section-missing' : 'ready',
@@ -34,7 +34,7 @@ export interface Notice {
34
34
  * What the notebook answers, as `NoteBody` asks it. With neither `resolve` nor `reaches`, nothing
35
35
  * is known about the notebook and no link is reported as pending.
36
36
  */
37
- export interface DiagnoseOptions extends Pick<NoteHost, 'resolve' | 'reaches' | 'keeps'> {
37
+ export interface DiagnoseOptions extends Pick<NoteHost, 'resolve' | 'reaches' | 'keeps' | 'choose' | 'noteAddress'> {
38
38
  /** Whether to read each `mermaid` block with Mermaid, which is loaded for it. Defaults to true. */
39
39
  readonly diagrams?: boolean;
40
40
  /**
package/dist/diagnose.js CHANGED
@@ -11,6 +11,7 @@
11
11
  * note, or beside an editor. KaTeX checks a formula as `rehype-katex` would typeset it, and Mermaid
12
12
  * reads a diagram as the page would draw it, loaded only when a note carries one.
13
13
  */
14
+ import { drawnNote, embedTarget } from './embed-target.js';
14
15
  import { keptImageName } from './kept-image.js';
15
16
  import katex from 'katex';
16
17
  import remarkParse from 'remark-parse';
@@ -181,7 +182,7 @@ export async function diagnose(markdown, options = {}) {
181
182
  }
182
183
  }
183
184
  });
184
- pending(hidden, split, options, report);
185
+ await pending(text, hidden, split, options, report);
185
186
  // An image whose destination names no host names a kept file, and only a kept file (§5.8, #104).
186
187
  if (options.resolve || options.reaches) {
187
188
  const keeps = options.keeps ?? (() => false);
@@ -314,15 +315,17 @@ function outline(tree, span, report) {
314
315
  }
315
316
  /**
316
317
  * The wikilinks and embeds no note answers, when the host says which notes exist: a link reaches
317
- * a note, and an embed a note or a kept file (§5.2, §5.8). Read on the body outside code, as
318
- * `resolveWikilinks` reads it.
318
+ * a note, and an embed a note other than the one it is written in, or a kept file (§5.2, §5.8).
319
+ * Read on the body outside code, as `resolveWikilinks` reads it.
319
320
  */
320
- function pending(hidden, split, options, report) {
321
+ async function pending(markdown, hidden, split, options, report) {
321
322
  const body = hidden.text;
322
323
  const { resolve, reaches, keeps = () => false } = options;
323
324
  if (!resolve && !reaches)
324
325
  return;
325
- const answered = (name) => reaches ? reaches(name.normalize('NFC')) > 0 : resolve(name.normalize('NFC')) !== null;
326
+ const count = (name) => (reaches ? reaches(name) : resolve(name) === null ? 0 : 1);
327
+ const answered = (name) => count(name.normalize('NFC')) > 0;
328
+ const embeds = { reaches: count, keeps, choose: options.choose ?? null, drawn: drawnNote(options.noteAddress, markdown) };
326
329
  const code = codeRegions(body);
327
330
  for (const match of body.matchAll(WIKILINK)) {
328
331
  if (insideCode(code, match.index))
@@ -335,7 +338,7 @@ function pending(hidden, split, options, report) {
335
338
  if (hasParameterReference(name))
336
339
  continue;
337
340
  const embed = match[1] !== undefined;
338
- if (answered(name) || (embed && keeps(name)))
341
+ if (embed ? (await embedTarget(embeds, name)).kind !== 'pending' : answered(name))
339
342
  continue;
340
343
  const end = match.index + match[0].length;
341
344
  report(embed ? 'embed-pending' : 'link-pending', split + hidden.original(match.index), split + hidden.original(end, true), name);
@@ -14,7 +14,7 @@ import { markdown, markdownKeymap } from '@codemirror/lang-markdown';
14
14
  import { Annotation, Compartment, EditorState } from '@codemirror/state';
15
15
  import { EditorView, keymap } from '@codemirror/view';
16
16
  import { useEffect, useLayoutEffect, useMemo, useReducer, useRef, useState } from 'react';
17
- import { HOST_KEYS, HostProvider, isAttachRefusal, resolveHost } from '../host.js';
17
+ import { HOST_KEYS, HostProvider, isAttachRefusal, resolveHost, useDrawing } from '../host.js';
18
18
  import { rootStyle } from '../theme.js';
19
19
  import { ICONS } from './blocks.js';
20
20
  import { BLOCKS, command, headingLevel, insertBlock, insertFootnote, insertLink, insertWikilink, setHeading, toggleComment, toggleList, toggleMark, toggleQuote, } from './commands.js';
@@ -176,9 +176,12 @@ function SaveStatus({ saves, blocked, deciding, open, setOpen, host, onDecided,
176
176
  */
177
177
  const redoKeys = [{ key: 'Mod-Shift-z', run: redo, preventDefault: true }];
178
178
  export function NoteEditor({ markdown: given, onChange, editable = true, corner, buttons = 'icon', autoFocus = false, leaving = false, onLeave, ...host }) {
179
- const resolved = useMemo(() => resolveHost(host),
179
+ const contract = useMemo(() => resolveHost(host),
180
180
  // Every member of the contract, so a host that passes the same functions keeps the same host.
181
181
  HOST_KEYS.map((key) => host[key]));
182
+ // The note itself, read from what the host gave rather than from the text being typed: the host
183
+ // counts the note under the name it keeps, so a rename takes effect once it is saved (#147).
184
+ const resolved = useDrawing(contract, host.noteAddress, given);
182
185
  const parent = useRef(null);
183
186
  const [view, setView] = useState(null);
184
187
  const [, redraw] = useReducer((count) => count + 1, 0);
@@ -16,6 +16,7 @@ import { hideComments, resolveWikilinks } from '../source.js';
16
16
  import { isTrue, readProperties } from '../properties.js';
17
17
  import { Transclusion } from '../Transclusion.js';
18
18
  import { splitEmbeds } from '../embeds.js';
19
+ import { embedsFile } from '../embed-target.js';
19
20
  import { wikilinkAddress } from '../wikilink-address.js';
20
21
  import { ICON_OWN_SIZE, ICON_RATIO_FREE, ICON_RATIO_LOCKED, ICON_RESIZE } from '../mode-icons.js';
21
22
  import { describeImage, MAX_IMAGE_WIDTH, readImageSize, resizeImage } from './image-size.js';
@@ -51,7 +52,8 @@ function write(view, changes, event = 'input.form') {
51
52
  export function Snippet({ text }) {
52
53
  const host = useHost();
53
54
  const body = hideComments(text).text;
54
- return (_jsx(_Fragment, { children: splitEmbeds(body, host.keeps).map((segment, index) => segment.kind === 'text' ? (_jsx(Markdown, { children: resolveWikilinks(segment.text, (name) => wikilinkAddress(host, name), host.keeps) }, index)) : (_jsx(Transclusion, { target: segment.target, anchor: segment.anchor }, index))) }));
55
+ const file = embedsFile(host);
56
+ return (_jsx(_Fragment, { children: splitEmbeds(body, file).map((segment, index) => segment.kind === 'text' ? (_jsx(Markdown, { children: resolveWikilinks(segment.text, (name) => wikilinkAddress(host, name), file) }, index)) : (_jsx(Transclusion, { target: segment.target, anchor: segment.anchor, source: segment.source }, index))) }));
55
57
  }
56
58
  /** A small button of the editor's own, outside the note's notation. */
57
59
  function Control({ label, onClick, children, pressed, disabled, focusable = false, }) {
package/dist/edit/live.js CHANGED
@@ -14,6 +14,7 @@ import { createRoot } from 'react-dom/client';
14
14
  import { followable } from '../address.js';
15
15
  import { highlightTree, languageToLoad, loadGrammar } from '../highlight.js';
16
16
  import { HostProvider, resolveHost } from '../host.js';
17
+ import { embedReach } from '../embed-target.js';
17
18
  import { MarkdownImage } from '../Markdown.js';
18
19
  import { highlightLanguage } from '../highlight.js';
19
20
  import { analyze } from './analyze.js';
@@ -552,7 +553,7 @@ function build(state) {
552
553
  if (open)
553
554
  out.push(mark('cm-ms-wikilink').range(from, to));
554
555
  // A kept image is sized from the image itself (#98); a note's embed draws no image of its own.
555
- else if (host.keeps(construct.target))
556
+ else if (embedReach(host, construct.target) === 'file')
556
557
  block(from, to, 'embed', `embed:${source}`, (view) => createElement(ImageBlock, { view, source }, createElement(Snippet, { text: source })));
557
558
  else
558
559
  block(from, to, 'embed', `embed:${source}`, () => createElement(Snippet, { text: source }));
@@ -661,8 +662,10 @@ function build(state) {
661
662
  }
662
663
  break;
663
664
  }
664
- const pending = host.reaches(construct.target) === 0 && !host.keeps(construct.target);
665
- if (construct.embed && host.keeps(construct.target) && !touches(from, to)) {
665
+ // A link reaches notes alone; an embed reaches a note before a file of its name (§5.8).
666
+ const reach = construct.embed ? embedReach(host, construct.target) : null;
667
+ const pending = construct.embed ? reach === 'pending' : host.reaches(construct.target) === 0 && !host.keeps(construct.target);
668
+ if (reach === 'file' && !touches(from, to)) {
666
669
  const source = text.slice(from, to);
667
670
  out.push(Decoration.replace({
668
671
  // A kept image is sized from the image itself, as a Markdown one is (#98).
@@ -1062,7 +1065,7 @@ const embedPremeasure = ViewPlugin.define((view) => {
1062
1065
  const metrics = view.state.field(metricsField);
1063
1066
  const doc = view.state.doc;
1064
1067
  for (const construct of view.state.field(analysisField).constructs) {
1065
- if (construct.kind !== 'embed' || host.keeps(construct.target) || host.reaches(construct.target) !== 1)
1068
+ if (construct.kind !== 'embed' || embedReach(host, construct.target) !== 'note')
1066
1069
  continue;
1067
1070
  const end = construct.to > construct.from && doc.sliceString(construct.to - 1, construct.to) === '\n' ? construct.to - 1 : construct.to;
1068
1071
  const source = doc.sliceString(doc.lineAt(construct.from).from, doc.lineAt(end).to);
@@ -0,0 +1,83 @@
1
+ /**
2
+ * What an embed reaches (`SPEC.md` §5.2, §5.8): a note of that name, else an attachment of that
3
+ * name, else nothing.
4
+ *
5
+ * **A note comes first.** What a target is is decided by what the notebook holds, in that order,
6
+ * so a file reaches an embed only when no note answers its name: by name, or, when no name matched,
7
+ * by alias, which is what `reaches` counts. The page used to ask for the file first, so a note and a
8
+ * file of one name drew the file while the index made the edge to the note (#148).
9
+ *
10
+ * **An embed never reaches the note it is written in** (§5.2, #147). It is resolved as any
11
+ * reference is, and the note itself is then taken out of what matched; when the note was the only
12
+ * match, no later step is tried, and the embed reaches the file of that name, else nothing. So
13
+ * `![[x]]` in the note `x` beside the file `x` draws the file, which is what an author naming a note
14
+ * after the file it shows means. The renderer knows the note by the address the host gives
15
+ * (`noteAddress`), and reads its name and aliases from its own frontmatter (§5.3, §6.4):
16
+ *
17
+ * - matched **by its name**, the note is one of the name matches, so the count less one is the
18
+ * number of other notes, known at once and with no request;
19
+ * - matched **by an alias**, the count does not say whether a name matched first, so the host's
20
+ * `choose`, which says `by` what and lists the addresses, is asked;
21
+ * - and the one other note left is loaded **by its address**, `loadNoteAt`, because by name the
22
+ * host answers no single note.
23
+ *
24
+ * Every place that decides between a note and a file asks here: the runs of the reading page, the
25
+ * content of an embedded note, the editor's blocks and marks, and `diagnose`.
26
+ */
27
+ import type { EmbeddedNote, ResolvedHost } from './host.js';
28
+ /** The note being drawn, which an embed of its own name or alias does not reach. */
29
+ export interface DrawnNote {
30
+ /** Its address, as the host's `choose` gives addresses. */
31
+ readonly address: string;
32
+ /** Its name, from its frontmatter, in NFC; `null` for a note that has none. */
33
+ readonly name: string | null;
34
+ /** Its aliases, from its frontmatter, in NFC. */
35
+ readonly aliases: readonly string[];
36
+ }
37
+ /**
38
+ * The note at `address` whose text is `markdown`, or `null` with no address: what is not a note the
39
+ * notebook keeps — a guidance, a template, a dashboard, a draft never saved — excludes nothing,
40
+ * because the host counts no note for it.
41
+ */
42
+ export declare function drawnNote(address: string | null | undefined, markdown: string): DrawnNote | null;
43
+ /** The same host drawing `drawn`; the host itself when nothing changes, so its identity holds. */
44
+ export declare function drawing<T extends {
45
+ readonly drawn: DrawnNote | null;
46
+ }>(host: T, drawn: DrawnNote | null): T;
47
+ /** What the host says, at once, an embed reaches. */
48
+ export type EmbedReach =
49
+ /** Exactly one note: it is expanded in place. */
50
+ 'note'
51
+ /** Several notes: a choice the reader makes, never expanded. */
52
+ | 'choice'
53
+ /** No note, and a file the notebook keeps under the name. */
54
+ | 'file'
55
+ /** Nothing the notebook holds. */
56
+ | 'pending'
57
+ /** The note being drawn carries the name as an alias: only `choose` can say what is left. */
58
+ | 'ask';
59
+ /** What the decision reads of the host. */
60
+ export type EmbedHost = Pick<ResolvedHost, 'reaches' | 'keeps' | 'choose' | 'drawn'>;
61
+ /** What an embed of `name` reaches, as far as the count of the host tells at once. */
62
+ export declare function embedReach(host: EmbedHost, name: string): EmbedReach;
63
+ /**
64
+ * Whether an embed of a name draws a file: the predicate `splitEmbeds`, `demoteEmbeds` and
65
+ * `resolveWikilinks` take, which leaves the bang on an embed of a file and turns every other
66
+ * embed into a note's. An embed the count cannot decide is a note's here, and is decided where it
67
+ * is expanded.
68
+ */
69
+ export declare function embedsFile(host: EmbedHost): (name: string) => boolean;
70
+ /** What an embed reaches, decided: the note with how to load it, or what is drawn instead. */
71
+ export type EmbedTarget = {
72
+ readonly kind: 'note';
73
+ readonly load: (() => Promise<EmbeddedNote | null>) | null;
74
+ } | {
75
+ readonly kind: 'choice' | 'file' | 'pending';
76
+ };
77
+ /** What the decision reads of the host to load the note it reaches. */
78
+ export type EmbedLoadHost = EmbedHost & Partial<Pick<ResolvedHost, 'loadNote' | 'loadNoteAt'>>;
79
+ /**
80
+ * What an embed of `name` reaches, asking `choose` only when the note being drawn is among the
81
+ * notes the name matches and another one has to be told from it. Answered at once otherwise.
82
+ */
83
+ export declare function embedTarget(host: EmbedLoadHost, name: string): EmbedTarget | Promise<EmbedTarget>;
@@ -0,0 +1,119 @@
1
+ /**
2
+ * What an embed reaches (`SPEC.md` §5.2, §5.8): a note of that name, else an attachment of that
3
+ * name, else nothing.
4
+ *
5
+ * **A note comes first.** What a target is is decided by what the notebook holds, in that order,
6
+ * so a file reaches an embed only when no note answers its name: by name, or, when no name matched,
7
+ * by alias, which is what `reaches` counts. The page used to ask for the file first, so a note and a
8
+ * file of one name drew the file while the index made the edge to the note (#148).
9
+ *
10
+ * **An embed never reaches the note it is written in** (§5.2, #147). It is resolved as any
11
+ * reference is, and the note itself is then taken out of what matched; when the note was the only
12
+ * match, no later step is tried, and the embed reaches the file of that name, else nothing. So
13
+ * `![[x]]` in the note `x` beside the file `x` draws the file, which is what an author naming a note
14
+ * after the file it shows means. The renderer knows the note by the address the host gives
15
+ * (`noteAddress`), and reads its name and aliases from its own frontmatter (§5.3, §6.4):
16
+ *
17
+ * - matched **by its name**, the note is one of the name matches, so the count less one is the
18
+ * number of other notes, known at once and with no request;
19
+ * - matched **by an alias**, the count does not say whether a name matched first, so the host's
20
+ * `choose`, which says `by` what and lists the addresses, is asked;
21
+ * - and the one other note left is loaded **by its address**, `loadNoteAt`, because by name the
22
+ * host answers no single note.
23
+ *
24
+ * Every place that decides between a note and a file asks here: the runs of the reading page, the
25
+ * content of an embedded note, the editor's blocks and marks, and `diagnose`.
26
+ */
27
+ import { readProperties } from './properties.js';
28
+ /**
29
+ * The note at `address` whose text is `markdown`, or `null` with no address: what is not a note the
30
+ * notebook keeps — a guidance, a template, a dashboard, a draft never saved — excludes nothing,
31
+ * because the host counts no note for it.
32
+ */
33
+ export function drawnNote(address, markdown) {
34
+ if (!address)
35
+ return null;
36
+ const read = readProperties(markdown);
37
+ const aliases = read.entries.find((entry) => entry.key === 'aliases')?.values ?? [];
38
+ return {
39
+ address,
40
+ name: read.name === null ? null : read.name.normalize('NFC'),
41
+ aliases: aliases.map((alias) => alias.normalize('NFC')),
42
+ };
43
+ }
44
+ /** The same host drawing `drawn`; the host itself when nothing changes, so its identity holds. */
45
+ export function drawing(host, drawn) {
46
+ if (host.drawn === drawn)
47
+ return host;
48
+ if (host.drawn && drawn && sameNote(host.drawn, drawn))
49
+ return host;
50
+ return { ...host, drawn };
51
+ }
52
+ function sameNote(one, other) {
53
+ return (one.address === other.address &&
54
+ one.name === other.name &&
55
+ one.aliases.length === other.aliases.length &&
56
+ one.aliases.every((alias, index) => alias === other.aliases[index]));
57
+ }
58
+ /** What an embed of `name` reaches, as far as the count of the host tells at once. */
59
+ export function embedReach(host, name) {
60
+ const target = name.normalize('NFC');
61
+ const notes = host.reaches(target);
62
+ const { drawn } = host;
63
+ // Matched by its name, the note is one of the matches; when it was the only one, no alias is
64
+ // tried, and the file of that name is next (§5.2).
65
+ if (drawn !== null && drawn.name === target)
66
+ return byCount(host, name, Math.max(0, notes - 1));
67
+ // Matched by an alias, it is among the matches only when no name matched, which the count does
68
+ // not say. A host without `choose` cannot say it either, and its count is taken as it is.
69
+ if (drawn !== null && drawn.aliases.includes(target) && host.choose)
70
+ return 'ask';
71
+ return byCount(host, name, notes);
72
+ }
73
+ function byCount(host, name, notes) {
74
+ if (notes === 1)
75
+ return 'note';
76
+ if (notes > 1)
77
+ return 'choice';
78
+ return host.keeps(name) ? 'file' : 'pending';
79
+ }
80
+ /**
81
+ * Whether an embed of a name draws a file: the predicate `splitEmbeds`, `demoteEmbeds` and
82
+ * `resolveWikilinks` take, which leaves the bang on an embed of a file and turns every other
83
+ * embed into a note's. An embed the count cannot decide is a note's here, and is decided where it
84
+ * is expanded.
85
+ */
86
+ export function embedsFile(host) {
87
+ return (name) => embedReach(host, name) === 'file';
88
+ }
89
+ /**
90
+ * What an embed of `name` reaches, asking `choose` only when the note being drawn is among the
91
+ * notes the name matches and another one has to be told from it. Answered at once otherwise.
92
+ */
93
+ export function embedTarget(host, name) {
94
+ const target = name.normalize('NFC');
95
+ const reach = embedReach(host, name);
96
+ const { drawn, choose } = host;
97
+ const loadNote = host.loadNote ?? null;
98
+ if (reach === 'choice' || reach === 'file' || reach === 'pending')
99
+ return { kind: reach };
100
+ const itself = drawn !== null && (reach === 'ask' || drawn.name === target);
101
+ if (!itself)
102
+ return { kind: 'note', load: loadNote ? () => loadNote(target) : null };
103
+ // The one note left is not the one a name answers: only its address says which it is.
104
+ if (!choose)
105
+ return { kind: 'note', load: null };
106
+ return choose(target).then(({ notes }) => {
107
+ const rest = notes.filter((note) => note.address !== drawn.address);
108
+ if (rest.length === 0)
109
+ return { kind: host.keeps(name) ? 'file' : 'pending' };
110
+ if (rest.length > 1)
111
+ return { kind: 'choice' };
112
+ const address = rest[0].address;
113
+ const loadNoteAt = host.loadNoteAt ?? null;
114
+ if (loadNoteAt)
115
+ return { kind: 'note', load: () => loadNoteAt(address) };
116
+ // By name, the host answers one note only when the count is one: the note itself was not counted.
117
+ return { kind: 'note', load: loadNote && host.reaches(target) === 1 ? () => loadNote(target) : null };
118
+ });
119
+ }
package/dist/embeds.d.ts CHANGED
@@ -19,10 +19,13 @@
19
19
  export type BodySegment = {
20
20
  kind: 'text';
21
21
  text: string;
22
- } | {
22
+ }
23
+ /** An embed of a note, with what was written, which is drawn as written when it reaches a file after all. */
24
+ | {
23
25
  kind: 'embed';
24
26
  target: string;
25
27
  anchor: string | null;
28
+ source: string;
26
29
  };
27
30
  /**
28
31
  * How many embeds one page expands. Past it the rest stay as links: the cost
@@ -37,7 +40,8 @@ export declare const EMBED_LIMIT = 10;
37
40
  */
38
41
  export declare function splitEmbeds(body: string,
39
42
  /**
40
- * Whether the notebook keeps a FILE under that name. An embed of one
43
+ * Whether an embed of that name draws a FILE: no note answers it and the
44
+ * notebook keeps one (§5.8), which `embedsFile` decides. An embed of one
41
45
  * expands nothing here: it stays in the text run, where the wikilink pass
42
46
  * turns it into the attachment the page draws by its type.
43
47
  */
package/dist/embeds.js CHANGED
@@ -33,7 +33,8 @@ export const EMBED_LIMIT = 10;
33
33
  */
34
34
  export function splitEmbeds(body,
35
35
  /**
36
- * Whether the notebook keeps a FILE under that name. An embed of one
36
+ * Whether an embed of that name draws a FILE: no note answers it and the
37
+ * notebook keeps one (§5.8), which `embedsFile` decides. An embed of one
37
38
  * expands nothing here: it stays in the text run, where the wikilink pass
38
39
  * turns it into the attachment the page draws by its type.
39
40
  */
@@ -78,7 +79,7 @@ keeps = () => false, limit = EMBED_LIMIT) {
78
79
  const before = demoteEmbeds(body.slice(cursor, at), keeps);
79
80
  if (before.length > 0)
80
81
  segments.push({ kind: 'text', text: before });
81
- segments.push({ kind: 'embed', target, anchor: match[2]?.trim() ?? null });
82
+ segments.push({ kind: 'embed', target, anchor: match[2]?.trim() ?? null, source: match[0] });
82
83
  cursor = at + match[0].length;
83
84
  expanded += 1;
84
85
  }
package/dist/host.d.ts CHANGED
@@ -2,6 +2,7 @@ import { type ReactNode } from 'react';
2
2
  import { type NoteStrings, type NoteStringsInput } from './strings.js';
3
3
  import type { TablePage, TableRequest } from './table-block.js';
4
4
  import { type Scheme, type Theme } from './theme.js';
5
+ import { type DrawnNote } from './embed-target.js';
5
6
  /**
6
7
  * The host contract: everything the renderer needs from the notebook a note lives in, given by
7
8
  * whoever draws it.
@@ -44,6 +45,21 @@ export interface NoteHost {
44
45
  * before it is reached (#94): a host that loads from the network may cache what it answered.
45
46
  */
46
47
  readonly loadNote?: (name: string) => Promise<EmbeddedNote | null>;
48
+ /**
49
+ * The note at an address, as `choose` gave it, for an embed to draw in place. It is asked when a
50
+ * name alone cannot say which note: an embed of its own name in a note that another note also
51
+ * carries reaches that other note (§5.2), and only its address tells the two apart. Without it,
52
+ * such an embed is drawn as an ambiguous one is, pending.
53
+ */
54
+ readonly loadNoteAt?: (address: string) => Promise<EmbeddedNote | null>;
55
+ /**
56
+ * The address of the note being drawn, as `choose` gives addresses, when it is a note the
57
+ * notebook keeps. An embed never reaches the note it is written in (§5.2): with it, the renderer
58
+ * takes the note out of what an embed of its own name or alias reaches, so `![[x]]` in the note
59
+ * `x` reaches another note `x`, else the file `x`, else nothing. Leave it out for what is not a
60
+ * kept note — a guidance, a template, a dashboard, a draft never saved — and nothing is excluded.
61
+ */
62
+ readonly noteAddress?: string;
47
63
  /**
48
64
  * The rows a `table` block asks for (`SPEC.md` §7.15, #138): the table it names, the columns, the
49
65
  * filter as written, the order, the page and its size, and the column to sum. The host runs the
@@ -79,7 +95,10 @@ export interface NoteHost {
79
95
  * but a promise, no lock is drawn.
80
96
  */
81
97
  readonly onToggleTask?: (ordinal: number) => unknown;
82
- /** Whether the notebook keeps a file under that name. Only an embed reaches a file. */
98
+ /**
99
+ * Whether the notebook keeps a file under that name. Only an embed reaches a file, and only when no
100
+ * note answers the name (§5.8): a note comes first.
101
+ */
83
102
  readonly keeps?: (name: string) => boolean;
84
103
  /**
85
104
  * The names of notes that start with, or contain, what an author typed after `[[` in edit mode,
@@ -255,6 +274,12 @@ export interface ResolvedHost {
255
274
  readonly navigate: (address: string) => void;
256
275
  readonly remoteNotice: boolean;
257
276
  readonly loadNote: ((name: string) => Promise<EmbeddedNote | null>) | null;
277
+ readonly loadNoteAt: ((address: string) => Promise<EmbeddedNote | null>) | null;
278
+ /**
279
+ * The note being drawn, when the host gave its address: what an embed of its own name or alias
280
+ * takes it out of (§5.2). Set by the view that draws a note, never by `resolveHost`.
281
+ */
282
+ readonly drawn: DrawnNote | null;
258
283
  readonly queryTable: ((request: TableRequest) => Promise<TablePage | null>) | null;
259
284
  readonly printing: boolean;
260
285
  readonly keeps: (name: string) => boolean;
@@ -274,3 +299,9 @@ export declare function resolveHost(host: NoteHost): ResolvedHost;
274
299
  export declare const HostProvider: import("react").Provider<ResolvedHost>;
275
300
  /** The host the note is drawn under, read by every part of the surface. */
276
301
  export declare function useHost(): ResolvedHost;
302
+ /**
303
+ * The host drawing the note at `address` whose text is `markdown` (§5.2, #147): the same object
304
+ * while the note's address, name and aliases stay what they were, so an edit to its body changes
305
+ * no host.
306
+ */
307
+ export declare function useDrawing(host: ResolvedHost, address: string | undefined, markdown: string): ResolvedHost;
package/dist/host.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
- import { createContext, useContext } from 'react';
2
+ import { createContext, useContext, useMemo } from 'react';
3
3
  import { withDefaults } from './strings.js';
4
4
  import { DEFAULT_THEME, schemeOf } from './theme.js';
5
+ import { drawing, drawnNote } from './embed-target.js';
5
6
  /** Whether a rejection is a refusal the host worded for the author, and not an error. */
6
7
  export function isAttachRefusal(value) {
7
8
  return (typeof value === 'object' &&
@@ -21,6 +22,8 @@ export const HOST_KEYS = Object.keys({
21
22
  targetAddress: 1,
22
23
  navigate: 1,
23
24
  loadNote: 1,
25
+ loadNoteAt: 1,
26
+ noteAddress: 1,
24
27
  queryTable: 1,
25
28
  printing: 1,
26
29
  writable: 1,
@@ -56,6 +59,8 @@ export function resolveHost(host) {
56
59
  navigate: host.navigate ?? ((address) => window.location.assign(address)),
57
60
  remoteNotice: host.remoteNotice ?? true,
58
61
  loadNote: host.loadNote ?? null,
62
+ loadNoteAt: host.loadNoteAt ?? null,
63
+ drawn: null,
59
64
  queryTable: host.queryTable ?? null,
60
65
  printing: host.printing ?? false,
61
66
  keeps: host.keeps ?? never,
@@ -75,3 +80,14 @@ export const HostProvider = HostContext.Provider;
75
80
  export function useHost() {
76
81
  return useContext(HostContext);
77
82
  }
83
+ /**
84
+ * The host drawing the note at `address` whose text is `markdown` (§5.2, #147): the same object
85
+ * while the note's address, name and aliases stay what they were, so an edit to its body changes
86
+ * no host.
87
+ */
88
+ export function useDrawing(host, address, markdown) {
89
+ const drawn = useMemo(() => drawnNote(address, markdown), [address, markdown]);
90
+ const key = drawn === null ? '' : JSON.stringify(drawn);
91
+ // The key is the note's identity; `drawn` is read from the render that made it.
92
+ return useMemo(() => drawing(host, drawn), [host, key]);
93
+ }
package/dist/source.d.ts CHANGED
@@ -65,7 +65,8 @@ export declare function hideComments(text: string): HiddenComments;
65
65
  export declare function outsideCode(body: string, rewrite: (text: string) => string): string;
66
66
  export declare function resolveWikilinks(body: string, resolve: (name: string) => string | null,
67
67
  /**
68
- * Whether the notebook keeps a FILE under that name. The extension of a
68
+ * Whether an embed of that name draws a FILE: no note answers it and the
69
+ * notebook keeps one, which `embedsFile` decides (§5.8). The extension of a
69
70
  * name decides nothing, so what a target is cannot be read off it: it is
70
71
  * read off what the notebook holds, which is the host's to answer.
71
72
  */
package/dist/source.js CHANGED
@@ -317,7 +317,8 @@ export function outsideCode(body, rewrite) {
317
317
  // note route; unresolved ones become pending: links styled by the renderer.
318
318
  export function resolveWikilinks(body, resolve,
319
319
  /**
320
- * Whether the notebook keeps a FILE under that name. The extension of a
320
+ * Whether an embed of that name draws a FILE: no note answers it and the
321
+ * notebook keeps one, which `embedsFile` decides (§5.8). The extension of a
321
322
  * name decides nothing, so what a target is cannot be read off it: it is
322
323
  * read off what the notebook holds, which is the host's to answer.
323
324
  */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@memorysmithapp/markdown-renderer",
3
- "version": "0.10.2",
3
+ "version": "0.11.1",
4
4
  "description": "A React component that draws a MemorySmith note exactly as MemorySmith's reading page does.",
5
5
  "keywords": [
6
6
  "markdown",
@@ -80,7 +80,7 @@
80
80
  "unified": "11.0.5"
81
81
  },
82
82
  "devDependencies": {
83
- "@memorysmithapp/markdown-spec": "0.10.2",
83
+ "@memorysmithapp/markdown-spec": "0.11.1",
84
84
  "@types/hast": "3.0.5",
85
85
  "@types/react": "19.2.18",
86
86
  "@types/react-dom": "19.2.4",