@memorysmithapp/markdown-renderer 0.8.5 → 0.10.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.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @memorysmithapp/markdown-renderer
2
2
 
3
- A React component that draws the body of a MemorySmith note exactly as MemorySmith's reading page does: callouts, wikilinks, embedded notes, task boxes, code with highlighting and diagrams, mathematics, footnotes — the notation of the [MemorySmith Markdown Specification](https://www.npmjs.com/package/@memorysmithapp/markdown-spec).
3
+ A React component that draws the body of a MemorySmith note exactly as MemorySmith's reading page does: callouts, wikilinks, embedded notes, task boxes, code with highlighting and diagrams, mathematics, footnotes, the parameters of a model — the notation of the [MemorySmith Markdown Specification](https://www.npmjs.com/package/@memorysmithapp/markdown-spec).
4
4
 
5
5
  The package knows no API, no router and no i18n library. Everything it needs from the notebook a note lives in reaches it as props, and it never rewrites the note: ticking a task box reports which box, and the host applies it.
6
6
 
@@ -22,6 +22,7 @@ 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
+ queryTable={(request) => queryYourTable(request)} // the rows a ```table block asks for: one page, the count, the total
25
26
  writable
26
27
  onToggleTask={(ordinal) => save(toggleTaskAt(latest(), ordinal))} // a promise locks the item under "Updating…" until it settles
27
28
  theme="dark"
@@ -29,7 +30,7 @@ import 'katex/dist/katex.min.css';
29
30
  />;
30
31
  ```
31
32
 
32
- 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. 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.
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.
33
34
 
34
35
  ## Themes
35
36
 
@@ -130,13 +131,14 @@ import { diagnose } from '@memorysmithapp/markdown-renderer/diagnose';
130
131
  const notices = await diagnose(note, {
131
132
  resolve: (name) => addressOfTheOneNoteNamed(name), // or reaches; leave both out and no link is pending
132
133
  keeps: (name) => notebookKeepsAFile(name),
134
+ tables: (name) => columnsOfTheTableNamed(name), // { name, columns: [{ name, kind }] }, or null
133
135
  });
134
136
  // [{ code: 'heading-skipped-level', severity: 'notice', section: '3.3',
135
137
  // message: 'This heading skips a level below the heading before it.',
136
138
  // line: 12, column: 1, endLine: 12, endColumn: 14 }, …]
137
139
  ```
138
140
 
139
- A `notice` says the page will differ from the text — a fence never closed, a formula KaTeX cannot typeset, a diagram Mermaid cannot read, raw HTML, a footnote with no definition or no reference, a single-tilde strikethrough, a frontmatter never closed, a `name` that leaves the note unnamed or none at all, `aliases` or `tags` that are not a list, a body that does not start at `#` or skips a level. A `hint` says nothing is drawn wrong: no `aliases`, no `tags`, a link or an embed no note answers yet. Lines and columns count from 1 over the whole note, frontmatter included, and the `message` is English; a host words it in its own language from the `code`, which is stable. Mermaid is loaded only for a note that holds a diagram, and `diagrams: false` skips it.
141
+ A `notice` says the page will differ from the text — a fence never closed, a formula KaTeX cannot typeset, a diagram Mermaid cannot read, raw HTML, a footnote with no definition or no reference, a single-tilde strikethrough, a frontmatter never closed, a `name` that leaves the note unnamed or none at all, `aliases` or `tags` that are not a list, a body that does not start at `#` or skips a level, and a `table` block that names no table, holds a key it does not have or cannot read, names a column its table lacks, or filters with a query that cannot be answered. A `hint` says nothing is drawn wrong: no `aliases`, no `tags`, a link or an embed no note answers yet, a `table` block naming a table the notebook does not keep. Without `tables`, nothing is known of the notebook's tables, so no block is pending and none is checked against its columns. Lines and columns count from 1 over the whole note, frontmatter included, and the `message` is English; a host words it in its own language from the `code`, which is stable. Mermaid is loaded only for a note that holds a diagram, and `diagrams: false` skips it.
140
142
 
141
143
  The host contract, the stylesheet's properties, the slots and the decisions behind them are in the repository's [`ARCHITECTURE.md`](https://github.com/memorysmithapp/memorysmithapp-markdown/blob/main/docs/ARCHITECTURE.md).
142
144
 
@@ -0,0 +1,37 @@
1
+ /**
2
+ * A `table` block drawn as the table it asks for (`SPEC.md` §7.15, #138).
3
+ *
4
+ * The block holds the question and the host the answer: the component reads the block, asks
5
+ * `queryTable` for one page, and draws the header, the rows, the pages and the total. The host runs
6
+ * the filter, so a page is the page of the whole filter, and so is the order a reader asks for by
7
+ * a header, which asks the host again and never changes the note.
8
+ *
9
+ * Values are drawn in the reader's locale and always as text: nothing in a row is parsed as
10
+ * Markdown, so a `[[link]]` or a `<b>` a row holds is its characters (§7.15, §7.9). A number
11
+ * arrives as its digits and is formatted from them, so a decimal of 38 digits is never rounded.
12
+ *
13
+ * A block that cannot be answered is drawn as what is wrong with it, in place of the table and in
14
+ * the reader's words, each mistake with the line that makes it (§7.15, #139). A host that failed is
15
+ * no mistake of the block: it says so above `fallback`, the code block the block would be with no
16
+ * tables, so nothing the author wrote is hidden.
17
+ *
18
+ * With `printing`, the block asks for every row in its declared order and is drawn with no control
19
+ * a page of paper could not use, closed by the line that says what was read and when (§7.15, #139).
20
+ */
21
+ import { type ReactNode } from 'react';
22
+ import { type TableColumn, type TableValue } from './table-block.js';
23
+ export declare function DataTable({ source, fallback }: {
24
+ readonly source: string;
25
+ readonly fallback: ReactNode;
26
+ }): import("react").JSX.Element;
27
+ /** A value as the reader's locale writes it, and as text. */
28
+ export declare function formatValue(value: TableValue, column: TableColumn, strings: {
29
+ readonly locale: string;
30
+ readonly yes: string;
31
+ readonly no: string;
32
+ }): string;
33
+ /**
34
+ * A number from its digits, in the reader's locale. `Intl.NumberFormat` reads a string as the
35
+ * decimal it writes, so no digit is lost to a floating point; what is not a number stays as typed.
36
+ */
37
+ export declare function formatNumber(digits: string, locale: string): string;
@@ -0,0 +1,149 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ /**
3
+ * A `table` block drawn as the table it asks for (`SPEC.md` §7.15, #138).
4
+ *
5
+ * The block holds the question and the host the answer: the component reads the block, asks
6
+ * `queryTable` for one page, and draws the header, the rows, the pages and the total. The host runs
7
+ * the filter, so a page is the page of the whole filter, and so is the order a reader asks for by
8
+ * a header, which asks the host again and never changes the note.
9
+ *
10
+ * Values are drawn in the reader's locale and always as text: nothing in a row is parsed as
11
+ * Markdown, so a `[[link]]` or a `<b>` a row holds is its characters (§7.15, §7.9). A number
12
+ * arrives as its digits and is formatted from them, so a decimal of 38 digits is never rounded.
13
+ *
14
+ * A block that cannot be answered is drawn as what is wrong with it, in place of the table and in
15
+ * the reader's words, each mistake with the line that makes it (§7.15, #139). A host that failed is
16
+ * no mistake of the block: it says so above `fallback`, the code block the block would be with no
17
+ * tables, so nothing the author wrote is hidden.
18
+ *
19
+ * With `printing`, the block asks for every row in its declared order and is drawn with no control
20
+ * a page of paper could not use, closed by the line that says what was read and when (§7.15, #139).
21
+ */
22
+ import { useEffect, useMemo, useRef, useState } from 'react';
23
+ import { useHost } from './host.js';
24
+ import { checkTableBlock, fold, readTableBlock, } from './table-block.js';
25
+ export function DataTable({ source, fallback }) {
26
+ const { queryTable, strings, printing } = useHost();
27
+ const block = useMemo(() => readTableBlock(source), [source]);
28
+ const readable = block.table !== null && block.problems.length === 0;
29
+ // Read through a ref: a host that gives its functions anew on each render asks nothing again (#99).
30
+ const query = useRef(queryTable);
31
+ query.current = queryTable;
32
+ const [page, setPage] = useState(1);
33
+ // The reader's order, from a header: theirs alone, and gone when the note is opened again.
34
+ const [order, setOrder] = useState(null);
35
+ const [state, setState] = useState({ kind: 'loading', answer: null });
36
+ const asked = useRef(0);
37
+ useEffect(() => {
38
+ setPage(1);
39
+ setOrder(null);
40
+ }, [source]);
41
+ useEffect(() => {
42
+ if (!readable || block.table === null || !query.current)
43
+ return;
44
+ const ticket = ++asked.current;
45
+ setState((before) => ({ kind: 'loading', answer: before.kind === 'loading' || before.kind === 'ready' ? before.answer : null }));
46
+ query.current({
47
+ table: block.table,
48
+ columns: block.columns,
49
+ where: block.whereText,
50
+ // Paper carries the declared order, whatever a reader asked for on the screen.
51
+ sort: printing ? (block.sort ?? []) : (order ?? block.sort ?? []),
52
+ page: printing ? 1 : page,
53
+ size: printing ? 'all' : block.page,
54
+ total: block.total,
55
+ }).then((answer) => {
56
+ if (ticket !== asked.current)
57
+ return;
58
+ const problems = checkTableBlock(block, answer ? answer.schema : null);
59
+ setState(answer && problems.length === 0 ? { kind: 'ready', answer } : { kind: 'problems', problems });
60
+ }, () => ticket === asked.current && setState({ kind: 'failed' }));
61
+ }, [readable, block, order, page, printing]);
62
+ if (!readable)
63
+ return _jsx(TableProblems, { block: block, source: source, problems: block.problems });
64
+ if (state.kind === 'problems')
65
+ return _jsx(TableProblems, { block: block, source: source, problems: state.problems });
66
+ if (state.kind === 'failed') {
67
+ return (_jsxs("div", { className: "data-table-failed", children: [_jsx("p", { role: "status", children: strings.failed }), fallback] }));
68
+ }
69
+ const answer = state.answer;
70
+ if (!answer) {
71
+ return (_jsx("div", { className: "data-table data-table-loading", "aria-busy": "true", children: strings.loading }));
72
+ }
73
+ const columns = drawnColumns(answer.schema.columns, block.columns);
74
+ const pages = Math.max(1, Math.ceil(answer.count / block.page));
75
+ const current = order ?? block.sort ?? [];
76
+ const sortBy = (column) => {
77
+ const first = current[0];
78
+ const descending = first !== undefined && fold(first.column) === fold(column.name) && !first.descending;
79
+ setOrder([{ column: column.name, descending }]);
80
+ setPage(1);
81
+ };
82
+ const totalAt = block.total === null ? -1 : columns.findIndex((column) => fold(column.name) === fold(block.total));
83
+ return (_jsxs("div", { className: printing ? 'data-table data-table-printing' : 'data-table', "aria-busy": state.kind === 'loading', children: [_jsx("div", { className: "data-table-scroll", children: _jsxs("table", { children: [_jsx("thead", { children: _jsx("tr", { children: columns.map((column) => {
84
+ const first = current[0];
85
+ const sorted = first !== undefined && fold(first.column) === fold(column.name) ? (first.descending ? 'descending' : 'ascending') : undefined;
86
+ return (_jsx("th", { "aria-sort": sorted, className: alignOf(column), children: printing ? (_jsx("span", { className: "data-table-sort", children: column.name })) : (_jsxs("button", { type: "button", className: "data-table-sort", title: strings.tableSortBy(column.name), onClick: () => sortBy(column), children: [column.name, sorted && _jsx("span", { "aria-hidden": "true", children: sorted === 'ascending' ? ' ▲' : ' ▼' })] })) }, column.name));
87
+ }) }) }), _jsx("tbody", { children: answer.rows.length === 0 ? (_jsx("tr", { children: _jsx("td", { className: "data-table-empty", colSpan: columns.length, children: strings.tableEmpty }) })) : (answer.rows.map((row, index) => (_jsx("tr", { children: columns.map((column) => (_jsx("td", { className: alignOf(column), children: formatValue(row[column.name] ?? null, column, strings) }, column.name))) }, index)))) }), totalAt !== -1 && answer.total !== null && (_jsx("tfoot", { children: _jsx("tr", { children: columns.map((column, index) => (_jsx("td", { className: alignOf(column), children: index === totalAt ? formatNumber(answer.total, strings.locale) : index === 0 ? strings.tableTotal : null }, column.name))) }) }))] }) }), printing ? (_jsx("p", { className: "data-table-printed", children: strings.tablePrinted({ table: block.table ?? '', filter: block.whereText, count: answer.count, readAt: formatDate(answer.readAt, strings.locale) ?? answer.readAt }) })) : (_jsxs("div", { className: "data-table-footer", children: [_jsx("span", { className: "data-table-count", children: strings.tableRows(answer.count) }), pages > 1 && (_jsxs("span", { className: "data-table-pages", children: [_jsx("button", { type: "button", className: "data-table-page", disabled: page <= 1, onClick: () => setPage(page - 1), "aria-label": strings.tablePrevious, title: strings.tablePrevious, children: "\u2039" }), _jsx("span", { children: strings.tablePage(Math.min(page, pages), pages) }), _jsx("button", { type: "button", className: "data-table-page", disabled: page >= pages, onClick: () => setPage(page + 1), "aria-label": strings.tableNext, title: strings.tableNext, children: "\u203A" })] }))] }))] }));
88
+ }
89
+ /** What is wrong with a block, in place of its table: each mistake, with the line that makes it. */
90
+ function TableProblems({ block, source, problems }) {
91
+ const { strings } = useHost();
92
+ const lines = source.split('\n');
93
+ return (_jsx("div", { className: "data-table-problems", role: "status", "data-table-name": block.table ?? undefined, children: _jsx("ul", { children: problems.map((problem, index) => (_jsxs("li", { "data-code": problem.code, children: [strings.tableProblem(problem.code, block.table), problem.line > 0 && _jsx("code", { children: lines[problem.line - 1]?.trim() })] }, index))) }) }));
94
+ }
95
+ /** The columns a block draws, as the table writes them: the ones it names, in its order, or all. */
96
+ function drawnColumns(schema, named) {
97
+ if (named === null)
98
+ return [...schema];
99
+ return named.map((name) => schema.find((column) => fold(column.name) === fold(name))).filter((column) => column !== undefined);
100
+ }
101
+ const alignOf = (column) => column.kind === 'number' ? 'data-table-number' : column.kind === 'date' ? 'data-table-date' : undefined;
102
+ /** A value as the reader's locale writes it, and as text. */
103
+ export function formatValue(value, column, strings) {
104
+ if (value === null || value === '')
105
+ return '';
106
+ if (Array.isArray(value))
107
+ return value.join(', ');
108
+ if (column.kind === 'boolean')
109
+ return value === true || value === 'true' ? strings.yes : value === false || value === 'false' ? strings.no : String(value);
110
+ if (column.kind === 'number')
111
+ return formatNumber(String(value), strings.locale);
112
+ if (column.kind === 'date')
113
+ return formatDate(String(value), strings.locale) ?? String(value);
114
+ return String(value);
115
+ }
116
+ /**
117
+ * A number from its digits, in the reader's locale. `Intl.NumberFormat` reads a string as the
118
+ * decimal it writes, so no digit is lost to a floating point; what is not a number stays as typed.
119
+ */
120
+ export function formatNumber(digits, locale) {
121
+ const typed = digits.trim();
122
+ const match = /^-?\d+(?:\.(\d+))?$/.exec(typed);
123
+ if (!match)
124
+ return typed;
125
+ const fraction = match[1]?.length ?? 0;
126
+ try {
127
+ const format = new Intl.NumberFormat(locale, { minimumFractionDigits: fraction, maximumFractionDigits: fraction });
128
+ return format.format(typed);
129
+ }
130
+ catch {
131
+ return typed;
132
+ }
133
+ }
134
+ /** A date or a date-time in ISO 8601, in the reader's locale, read in UTC as a property's date is. */
135
+ function formatDate(value, locale) {
136
+ const match = /^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2}))?/.exec(value.trim());
137
+ if (!match)
138
+ return null;
139
+ const [, year, month, day, hours, minutes] = match;
140
+ const when = new Date(Date.UTC(Number(year), Number(month) - 1, Number(day), Number(hours ?? 0), Number(minutes ?? 0)));
141
+ if (when.getUTCDate() !== Number(day))
142
+ return null;
143
+ try {
144
+ return new Intl.DateTimeFormat(locale, { dateStyle: 'medium', ...(hours ? { timeStyle: 'short' } : {}), timeZone: 'UTC' }).format(when);
145
+ }
146
+ catch {
147
+ return null;
148
+ }
149
+ }
package/dist/Markdown.js CHANGED
@@ -9,6 +9,8 @@ import { CopyButton } from './CopyButton.js';
9
9
  import { fileAddress, fileKind, formatBytes, opensInBrowser, rendersAs } from './file-types.js';
10
10
  import { keptImageName } from './kept-image.js';
11
11
  import { highlightLanguage, highlightTree, languageToLoad, loadGrammar } from './highlight.js';
12
+ import { DataTable } from './DataTable.js';
13
+ import { isTableBlock } from './table-block.js';
12
14
  import { useHost } from './host.js';
13
15
  import { readDimensions, readImageAlt, sizedAttributes } from './image-dimensions.js';
14
16
  import { choiceTargetOf, LinkChoice } from './LinkChoice.js';
@@ -188,6 +190,11 @@ export function MarkdownAnchor({ href, children, node: _node, ...rest }) {
188
190
  const name = measured ? address.slice(0, at) : address;
189
191
  return _jsx(Attachment, { name: name, size: measured ?? { width: null, height: null, percent: null } });
190
192
  }
193
+ // A wikilink whose target writes a parameter (§7.14): it leads nowhere until a notebook is
194
+ // created from the model, so it is the parameter it holds, drawn, and not something to follow.
195
+ if (href?.startsWith('parameter:')) {
196
+ return (_jsx("span", { className: "wikilink-parameter", title: host.strings.parameterLink, children: children }));
197
+ }
191
198
  if (href?.startsWith('pending:')) {
192
199
  const pending = (label) => (_jsx("span", { className: "wikilink-pending", title: host.strings.pendingLink, children: label }));
193
200
  return wikilinkSlot ? drawSlot(wikilinkSlot, { pending: true, children, link: pending }) : pending(children);
@@ -281,7 +288,7 @@ function MarkdownCode({ className, children, node: _node, ...rest }) {
281
288
  * nothing to copy.
282
289
  */
283
290
  function MarkdownPre({ children, node, ...rest }) {
284
- const { strings } = useHost();
291
+ const { strings, queryTable } = useHost();
285
292
  const slot = useSlot('codeBlock');
286
293
  const code = node?.children?.find((child) => child.tagName === 'code');
287
294
  const classes = code?.properties?.['className'];
@@ -291,13 +298,17 @@ function MarkdownPre({ children, node, ...rest }) {
291
298
  // The bytes as typed: the text of the fence, less the newline before its closing line.
292
299
  const typed = textOf(code).replace(/\n$/, '');
293
300
  const copy = _jsx(CopyButton, { className: "code-copy", label: strings.copy, done: strings.copied, text: () => typed });
294
- if (slot) {
295
- const language = Array.isArray(classes)
296
- ? (classes.map(String).find((name) => name.startsWith('language-'))?.slice('language-'.length) ?? null)
297
- : null;
298
- return _jsx(InBlock.Provider, { value: true, children: drawSlot(slot, { language, code: typed, children, copy }) });
301
+ const language = Array.isArray(classes)
302
+ ? (classes.map(String).find((name) => name.startsWith('language-'))?.slice('language-'.length) ?? null)
303
+ : null;
304
+ const drawn = slot ? (_jsx(InBlock.Provider, { value: true, children: drawSlot(slot, { language, code: typed, children, copy }) })) : (_jsxs("div", { className: "code-block", children: [_jsx(InBlock.Provider, { value: true, children: _jsx("pre", { ...rest, children: children }) }), copy] }));
305
+ // A `table` block is the table it asks for, where the host reaches the notebook's tables, and the
306
+ // code block it is everywhere else (§7.15).
307
+ const meta = code?.data?.meta;
308
+ if (queryTable && isTableBlock(language, typeof meta === 'string' ? meta : null)) {
309
+ return _jsx(DataTable, { source: typed, fallback: drawn });
299
310
  }
300
- return (_jsxs("div", { className: "code-block", children: [_jsx(InBlock.Provider, { value: true, children: _jsx("pre", { ...rest, children: children }) }), copy] }));
311
+ return drawn;
301
312
  }
302
313
  /** The text of a hast element, which for a fence is the code as typed. */
303
314
  function textOf(node) {
@@ -373,7 +384,7 @@ export function Markdown({ children, source, onToggleTask, taskSave, writable =
373
384
  return (
374
385
  // The pass that draws a cut note's footnotes continues the note rather than opening a run,
375
386
  // so its section keeps the space a section takes at the end of a note.
376
- _jsx("div", { className: footnotes === 'section' ? 'markdown footnotes-run' : 'markdown', children: _jsx(ReactMarkdown, { remarkPlugins: readingPlugins(calloutTitle),
387
+ _jsx("div", { className: footnotes === 'section' ? 'markdown footnotes-run' : 'markdown', children: _jsx(ReactMarkdown, { remarkPlugins: readingPlugins(calloutTitle, strings.parameter),
377
388
  // Raw HTML is NOT enabled, and its absence is the point: no
378
389
  // `rehype-raw` is loaded, so a note carrying `<script>` is text. It is
379
390
  // a security boundary rather than a rendering preference, because a
@@ -13,6 +13,11 @@
13
13
  */
14
14
  import type { ReactNode } from 'react';
15
15
  import { type NoteProperties } from './properties.js';
16
+ /**
17
+ * Text as it was typed, with each parameter it writes drawn as one (§7.14): a value of the
18
+ * frontmatter, or the name of a note, in a model.
19
+ */
20
+ export declare function useParameters(): (text: string) => ReactNode;
16
21
  export declare function Properties({ properties }: {
17
22
  properties: NoteProperties;
18
23
  }): string | number | bigint | boolean | import("react").JSX.Element | Iterable<ReactNode> | Promise<string | number | bigint | boolean | import("react").ReactPortal | import("react").ReactElement<unknown, string | import("react").JSXElementConstructor<any>> | Iterable<ReactNode> | null | undefined> | null | undefined;
@@ -1,30 +1,46 @@
1
1
  import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { useHost } from './host.js';
3
3
  import { MarkdownAnchor } from './Markdown.js';
4
+ import { hasParameterReference, splitParameters } from './parameters.js';
4
5
  import { DRAWN_RESERVED_KEYS, isTrue, VALUE_LINK, } from './properties.js';
5
6
  import { drawSlot, useSlot } from './slots.js';
6
7
  import { wikilinkAddress } from './wikilink-address.js';
8
+ /**
9
+ * Text as it was typed, with each parameter it writes drawn as one (§7.14): a value of the
10
+ * frontmatter, or the name of a note, in a model.
11
+ */
12
+ export function useParameters() {
13
+ const { strings } = useHost();
14
+ return (text) => {
15
+ const pieces = splitParameters(text);
16
+ if (pieces.length === 1 && typeof pieces[0] === 'string')
17
+ return pieces[0];
18
+ return pieces.map((piece, index) => typeof piece === 'string' ? (piece) : (_jsx("span", { className: "parameter", "data-parameter": piece.name, title: strings.parameter, children: text.slice(piece.from, piece.to) }, index)));
19
+ };
20
+ }
7
21
  /**
8
22
  * A value as the note means it: a wikilink a link to where the host resolved it — the note, the
9
23
  * choice, or the pending marker — a Markdown link or a bare address to the web a link to it, each
10
24
  * through the anchor the body's links take, so the address filter holds and a theme's `wikilink`
11
- * slot draws them too; everything else as text, never as markup.
25
+ * slot draws them too; a parameter as a parameter; everything else as text, never as markup.
12
26
  */
13
27
  function useValue() {
14
28
  const host = useHost();
29
+ const drawn = useParameters();
15
30
  return (text) => {
16
31
  const parts = [];
17
32
  let cursor = 0;
18
33
  for (const match of text.matchAll(VALUE_LINK)) {
19
34
  const at = match.index ?? 0;
20
35
  if (at > cursor)
21
- parts.push(text.slice(cursor, at));
36
+ parts.push(drawn(text.slice(cursor, at)));
22
37
  const [whole, wikiTarget, wikiLabel, mdLabel, mdUrl, rawUrl] = match;
23
38
  if (wikiTarget) {
24
39
  const target = wikiTarget.trim();
25
40
  const name = target.split('#')[0]?.trim() ?? '';
26
- const address = name ? wikilinkAddress(host, name.normalize('NFC')) : null;
27
- parts.push(_jsx(MarkdownAnchor, { href: address ?? `pending:${encodeURIComponent(name)}`, children: wikiLabel?.trim() || target }, at));
41
+ // A target that writes a parameter leads nowhere until a notebook is created from the model.
42
+ const address = hasParameterReference(name) ? 'parameter:' : name ? wikilinkAddress(host, name.normalize('NFC')) : null;
43
+ parts.push(_jsx(MarkdownAnchor, { href: address ?? `pending:${encodeURIComponent(name)}`, children: drawn(wikiLabel?.trim() || target) }, at));
28
44
  }
29
45
  else {
30
46
  parts.push(_jsx(MarkdownAnchor, { href: mdUrl ?? rawUrl, children: mdLabel ?? rawUrl }, at));
@@ -32,7 +48,7 @@ function useValue() {
32
48
  cursor = at + whole.length;
33
49
  }
34
50
  if (cursor < text.length)
35
- parts.push(text.slice(cursor));
51
+ parts.push(drawn(text.slice(cursor)));
36
52
  return parts.length === 1 ? parts[0] : _jsx(_Fragment, { children: parts });
37
53
  };
38
54
  }
@@ -100,8 +116,9 @@ export function Properties({ properties }) {
100
116
  const { strings } = useHost();
101
117
  const slot = useSlot('properties');
102
118
  const value = useValue();
119
+ const drawn = useParameters();
103
120
  if (slot)
104
121
  return drawSlot(slot, { name: properties.name, entries: properties.entries, value });
105
122
  const shown = ordered(properties.entries);
106
- return (_jsxs(_Fragment, { children: [_jsx("h1", { className: properties.name === null ? 'note-title note-unnamed' : 'note-title', children: properties.name ?? strings.unnamedNote }), shown.length > 0 && (_jsxs("details", { className: "properties-box", open: true, children: [_jsx("summary", { children: strings.properties }), _jsx("div", { className: "metadata-container", children: shown.map((entry, index) => (_jsxs("div", { className: "metadata-property", "data-property-type": iconType(entry), children: [_jsx("span", { className: "metadata-property-key", children: entry.key }), _jsx("span", { className: "metadata-property-value", children: _jsx(PropertyValue, { entry: entry, value: value }) })] }, index))) })] }))] }));
123
+ return (_jsxs(_Fragment, { children: [_jsx("h1", { className: properties.name === null ? 'note-title note-unnamed' : 'note-title', children: properties.name === null ? strings.unnamedNote : drawn(properties.name) }), shown.length > 0 && (_jsxs("details", { className: "properties-box", open: true, children: [_jsx("summary", { children: strings.properties }), _jsx("div", { className: "metadata-container", children: shown.map((entry, index) => (_jsxs("div", { className: "metadata-property", "data-property-type": iconType(entry), children: [_jsx("span", { className: "metadata-property-key", children: entry.key }), _jsx("span", { className: "metadata-property-value", children: _jsx(PropertyValue, { entry: entry, value: value }) })] }, index))) })] }))] }));
107
124
  }
package/dist/address.d.ts CHANGED
@@ -15,7 +15,7 @@
15
15
  * **What passes, and why:**
16
16
  *
17
17
  * - `pending:` — ours, and the reason the filter was off in the first place;
18
- * and `attachment:` and `choice:`, ours too.
18
+ * and `attachment:`, `choice:` and `parameter:`, ours too.
19
19
  * - A path of the application (`/`), a relative one (`./`, `../`) and an
20
20
  * anchor of the page (`#`).
21
21
  * - `http:` and `https:` — the web, which is what a note cites.
package/dist/address.js CHANGED
@@ -15,7 +15,7 @@
15
15
  * **What passes, and why:**
16
16
  *
17
17
  * - `pending:` — ours, and the reason the filter was off in the first place;
18
- * and `attachment:` and `choice:`, ours too.
18
+ * and `attachment:`, `choice:` and `parameter:`, ours too.
19
19
  * - A path of the application (`/`), a relative one (`./`, `../`) and an
20
20
  * anchor of the page (`#`).
21
21
  * - `http:` and `https:` — the web, which is what a note cites.
@@ -43,14 +43,15 @@
43
43
  * specification gives to a notation it does not implement.
44
44
  */
45
45
  /**
46
- * `pending:`, `attachment:` and `choice:` are this surface's own: a wikilink
47
- * that matched no note, a reference to a file the notebook keeps beside its
48
- * notes, and a wikilink several notes may answer. None of them leaves the page
46
+ * `pending:`, `attachment:`, `choice:` and `parameter:` are this surface's own:
47
+ * a wikilink that matched no note, a reference to a file the notebook keeps
48
+ * beside its notes, a wikilink several notes may answer, and a wikilink whose
49
+ * target writes a parameter (§7.14). None of them leaves the page
49
50
  * — the anchor of the surface turns each into what it is — and they are listed
50
51
  * here so the filter does not empty them into the refusal case, which says
51
52
  * something else entirely.
52
53
  */
53
- const ALLOWED_SCHEME = /^(https?|mailto|pending|attachment|choice):/i;
54
+ const ALLOWED_SCHEME = /^(https?|mailto|pending|attachment|choice|parameter):/i;
54
55
  /** Anything of the shape `word:`, which is what makes an address absolute. */
55
56
  const HAS_SCHEME = /^[a-z][a-z0-9+.-]*:/i;
56
57
  /**
@@ -12,8 +12,9 @@
12
12
  * reads a diagram as the page would draw it, loaded only when a note carries one.
13
13
  */
14
14
  import type { NoteHost } from './host.js';
15
+ import { type TableNoticeCode, type TableSchema } from './table-block.js';
15
16
  /** The codes of §7.13, which `spec.json` declares as `notices`. */
16
- export type NoticeCode = 'fence-unclosed' | 'math-unclosed' | 'formula-invalid' | 'diagram-invalid' | 'frontmatter-unclosed' | 'name-missing' | 'name-unusable' | 'reserved-not-a-list' | 'aliases-missing' | 'tags-missing' | 'heading-first-level' | 'heading-skipped-level' | 'footnote-undefined' | 'footnote-unreferenced' | 'raw-html' | 'strikethrough-single-tilde' | 'link-pending' | 'embed-pending';
17
+ export type NoticeCode = 'fence-unclosed' | 'math-unclosed' | 'formula-invalid' | 'diagram-invalid' | 'frontmatter-unclosed' | 'name-missing' | 'name-unusable' | 'reserved-not-a-list' | 'aliases-missing' | 'tags-missing' | 'heading-first-level' | 'heading-skipped-level' | 'footnote-undefined' | 'footnote-unreferenced' | 'raw-html' | 'strikethrough-single-tilde' | 'link-pending' | 'embed-pending' | TableNoticeCode;
17
18
  /** `notice`: the page will differ from what was typed. `hint`: nothing is drawn wrong. */
18
19
  export type NoticeSeverity = 'notice' | 'hint';
19
20
  /** One place in a note, by a code of §7.13. Lines and columns count from 1 over the whole note. */
@@ -36,6 +37,12 @@ export interface Notice {
36
37
  export interface DiagnoseOptions extends Pick<NoteHost, 'resolve' | 'reaches' | 'keeps'> {
37
38
  /** Whether to read each `mermaid` block with Mermaid, which is loaded for it. Defaults to true. */
38
39
  readonly diagrams?: boolean;
40
+ /**
41
+ * The table of that name the notebook keeps, with its columns, or `null` when it keeps none
42
+ * (§5.9); the name is compared after NFC with case folded. With no `tables`, nothing is known of
43
+ * the notebook's tables: no `table` block is pending, and none is checked against its columns.
44
+ */
45
+ readonly tables?: (name: string) => TableSchema | null;
39
46
  }
40
47
  /** The table of §7.13, as `spec.json` carries it: a test holds the two equal. */
41
48
  export declare const NOTICES: Readonly<Record<NoticeCode, {
@@ -48,3 +55,4 @@ export declare const NOTICES: Readonly<Record<NoticeCode, {
48
55
  * frontmatter included; the positions are into it.
49
56
  */
50
57
  export declare function diagnose(markdown: string, options?: DiagnoseOptions): Promise<Notice[]>;
58
+ export type { TableColumn, TableColumnKind, TableSchema } from './table-block.js';
package/dist/diagnose.js CHANGED
@@ -16,8 +16,10 @@ import katex from 'katex';
16
16
  import remarkParse from 'remark-parse';
17
17
  import { unified } from 'unified';
18
18
  import { bodyStart, codeRegions, hideComments, insideCode, toUnixNewlines } from './source.js';
19
+ import { hasParameterReference } from './parameters.js';
19
20
  import { readProperties } from './properties.js';
20
21
  import { readingPlugins } from './reading.js';
22
+ import { checkTableBlock, isTableBlock, readTableBlock } from './table-block.js';
21
23
  /** The table of §7.13, as `spec.json` carries it: a test holds the two equal. */
22
24
  export const NOTICES = {
23
25
  'fence-unclosed': { severity: 'notice', section: '3.7', message: 'This fence is never closed: it runs to the end of its block, and everything after it is code.' },
@@ -38,6 +40,12 @@ export const NOTICES = {
38
40
  'strikethrough-single-tilde': { severity: 'notice', section: '4.3', message: 'One tilde strikes nothing: the tildes stay on the page. Strikethrough is ~~two~~.' },
39
41
  'link-pending': { severity: 'hint', section: '7.4', message: 'No note answers this link yet, so it is drawn as pending.' },
40
42
  'embed-pending': { severity: 'hint', section: '7.3', message: 'No note and no kept file answers this embed, or no kept file this image, so it is drawn as pending.' },
43
+ 'table-unnamed': { severity: 'notice', section: '7.15', message: 'This table block names no table: its table key is missing, empty or written twice.' },
44
+ 'table-key-unknown': { severity: 'notice', section: '7.15', message: 'This line is not one of the keys of a table block, so the block says so in place of the table.' },
45
+ 'table-key-invalid': { severity: 'notice', section: '7.15', message: 'This key is written twice, or its value cannot be read, so the block says so in place of the table.' },
46
+ 'table-column-unknown': { severity: 'notice', section: '7.15', message: 'The table has no column of this name, so the block says so in place of the table.' },
47
+ 'table-filter-invalid': { severity: 'notice', section: '7.15', message: 'This filter cannot be answered, so the block says so in place of the table.' },
48
+ 'table-pending': { severity: 'hint', section: '7.15', message: 'The notebook keeps no table of this name yet, so the block says so in its place.' },
41
49
  };
42
50
  /** A footnote reference left as text, which is one with no definition (§7.12). */
43
51
  const UNDEFINED_REFERENCE = /\[\^[^\]\s]+\]/g;
@@ -108,6 +116,7 @@ export async function diagnose(markdown, options = {}) {
108
116
  const referenced = new Set();
109
117
  const definitions = [];
110
118
  const images = [];
119
+ const tables = [];
111
120
  walk(tree, (node) => {
112
121
  const at = span(node);
113
122
  if (!at)
@@ -118,6 +127,8 @@ export async function diagnose(markdown, options = {}) {
118
127
  report('fence-unclosed', at[0], at[1]);
119
128
  else if (node.lang === 'mermaid')
120
129
  diagrams.push({ source: node.value ?? '', at });
130
+ if (isTableBlock(node.lang, node.meta))
131
+ tables.push({ value: node.value ?? '', at });
121
132
  }
122
133
  else if (node.type === 'math') {
123
134
  if (!closes(source, /^(\${2,})/))
@@ -178,6 +189,17 @@ export async function diagnose(markdown, options = {}) {
178
189
  if (!keeps(image.name))
179
190
  report('embed-pending', image.at[0], image.at[1], image.name);
180
191
  }
192
+ // A `table` block raises its own notices, each on the line of its key (§7.13, §7.15).
193
+ for (const table of tables) {
194
+ const block = readTableBlock(table.value);
195
+ const schema = options.tables && block.table !== null ? options.tables(block.table) : undefined;
196
+ const first = pointOf(table.at[0]).line - 1;
197
+ for (const problem of checkTableBlock(block, schema)) {
198
+ const start = lineStarts[first + problem.line] ?? table.at[0];
199
+ const next = lineStarts[first + problem.line + 1];
200
+ report(problem.code, start, next === undefined ? text.length : next - 1, problem.detail);
201
+ }
202
+ }
181
203
  if (diagrams.length > 0 && options.diagrams !== false) {
182
204
  const mermaid = (await import('mermaid')).default;
183
205
  for (const diagram of diagrams) {
@@ -309,6 +331,9 @@ function pending(hidden, split, options, report) {
309
331
  // `[[#Section]]` is a link within the note itself.
310
332
  if (!name)
311
333
  continue;
334
+ // A target that writes a parameter is neither a link nor pending (§7.14).
335
+ if (hasParameterReference(name))
336
+ continue;
312
337
  const embed = match[1] !== undefined;
313
338
  if (answered(name) || (embed && keeps(name)))
314
339
  continue;
@@ -50,6 +50,13 @@ export type Construct = {
50
50
  /** What the page shows: the alias, or the target. */
51
51
  readonly label: Span;
52
52
  readonly embed: boolean;
53
+ /** Its target writes a parameter (§7.14): it leads nowhere until a notebook is created from the model. */
54
+ readonly parameter: boolean;
55
+ } | {
56
+ readonly kind: 'parameter';
57
+ readonly from: number;
58
+ readonly to: number;
59
+ readonly name: string;
53
60
  } | {
54
61
  readonly kind: 'image';
55
62
  readonly from: number;
@@ -18,6 +18,7 @@ import { unified } from 'unified';
18
18
  import { codeRegions, commentRegions, insideCode } from '../source.js';
19
19
  import { CALLOUT_MARKER } from '../remark-callouts.js';
20
20
  import { breaksDollarRule } from '../remark-ring.js';
21
+ import { hasParameterReference, parameterReferences } from '../parameters.js';
21
22
  let parser = null;
22
23
  function parse(text) {
23
24
  // The micromark extensions of `readingPlugins`, at its options; the transforms that rewrite the
@@ -76,7 +77,8 @@ export function analyze(text) {
76
77
  : { from: head, to: head + target.length };
77
78
  wikilinks.push({ from, to });
78
79
  // In a table cell the pipe before an alias is escaped, and the backslash is not part of the target.
79
- found.push({ kind: 'wikilink', from, to, target: target.split('#')[0].replace(/\\$/, '').trim(), label, embed });
80
+ const name = target.split('#')[0].replace(/\\$/, '').trim();
81
+ found.push({ kind: 'wikilink', from, to, target: name, label, embed, parameter: hasParameterReference(name) });
80
82
  }
81
83
  const inWikilink = (span) => wikilinks.some((link) => span.from < link.to && span.to > link.from);
82
84
  const visit = (node, inCallout) => {
@@ -84,6 +86,16 @@ export function analyze(text) {
84
86
  const children = node.children ?? [];
85
87
  if (span && !inComment(span.from)) {
86
88
  switch (node.type) {
89
+ case 'text': {
90
+ // A parameter is written in text, and only there (§7.14): code, math, raw HTML and a
91
+ // destination are not text nodes, and an autolink's text is its address.
92
+ for (const reference of parameterReferences(text.slice(span.from, span.to))) {
93
+ const from = span.from + reference.from;
94
+ if (!inComment(from))
95
+ found.push({ kind: 'parameter', from, to: span.from + reference.to, name: reference.name });
96
+ }
97
+ break;
98
+ }
87
99
  case 'heading': {
88
100
  const line = text.slice(span.from, span.to);
89
101
  const marker = /^#{1,6}(?:[ \t]+|$)/.exec(line);
@@ -126,9 +138,15 @@ export function analyze(text) {
126
138
  break;
127
139
  }
128
140
  case 'link': {
141
+ const raw = text.slice(span.from, span.to);
142
+ // An autolink is its address, which writes no parameter.
143
+ if (!raw.startsWith('[')) {
144
+ if (!inWikilink(span))
145
+ found.push({ kind: 'link', ...span, label: null, url: node.url ?? '' });
146
+ return;
147
+ }
129
148
  if (inWikilink(span))
130
149
  break;
131
- const raw = text.slice(span.from, span.to);
132
150
  const first = children[0] && offsets(children[0]);
133
151
  const last = children[children.length - 1] && offsets(children[children.length - 1]);
134
152
  const label = raw.startsWith('[') && first && last ? { from: first.from, to: last.to } : null;
@@ -215,7 +233,8 @@ export function analyze(text) {
215
233
  case 'paragraph': {
216
234
  const raw = text.slice(span.from, span.to);
217
235
  const embed = EMBED_LINE.exec(raw.trim());
218
- if (embed && !raw.includes('\n') && !inCallout && span.from === text.lastIndexOf('\n', span.from - 1) + 1) {
236
+ // An embed of a parameter transcludes nothing (§7.14): it is drawn as a wikilink is.
237
+ if (embed && !hasParameterReference(embed[1]) && !raw.includes('\n') && !inCallout && span.from === text.lastIndexOf('\n', span.from - 1) + 1) {
219
238
  found.push({ kind: 'embed', ...span, target: embed[1].trim(), anchor: embed[2]?.trim() ?? null });
220
239
  return;
221
240
  }