@memorysmithapp/markdown-renderer 0.9.0 → 0.10.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,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';
@@ -286,7 +288,7 @@ function MarkdownCode({ className, children, node: _node, ...rest }) {
286
288
  * nothing to copy.
287
289
  */
288
290
  function MarkdownPre({ children, node, ...rest }) {
289
- const { strings } = useHost();
291
+ const { strings, queryTable } = useHost();
290
292
  const slot = useSlot('codeBlock');
291
293
  const code = node?.children?.find((child) => child.tagName === 'code');
292
294
  const classes = code?.properties?.['className'];
@@ -296,13 +298,17 @@ function MarkdownPre({ children, node, ...rest }) {
296
298
  // The bytes as typed: the text of the fence, less the newline before its closing line.
297
299
  const typed = textOf(code).replace(/\n$/, '');
298
300
  const copy = _jsx(CopyButton, { className: "code-copy", label: strings.copy, done: strings.copied, text: () => typed });
299
- if (slot) {
300
- const language = Array.isArray(classes)
301
- ? (classes.map(String).find((name) => name.startsWith('language-'))?.slice('language-'.length) ?? null)
302
- : null;
303
- 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 });
304
310
  }
305
- return (_jsxs("div", { className: "code-block", children: [_jsx(InBlock.Provider, { value: true, children: _jsx("pre", { ...rest, children: children }) }), copy] }));
311
+ return drawn;
306
312
  }
307
313
  /** The text of a hast element, which for a fence is the code as typed. */
308
314
  function textOf(node) {
@@ -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
@@ -19,6 +19,7 @@ import { bodyStart, codeRegions, hideComments, insideCode, toUnixNewlines } from
19
19
  import { hasParameterReference } from './parameters.js';
20
20
  import { readProperties } from './properties.js';
21
21
  import { readingPlugins } from './reading.js';
22
+ import { checkTableBlock, isTableBlock, readTableBlock } from './table-block.js';
22
23
  /** The table of §7.13, as `spec.json` carries it: a test holds the two equal. */
23
24
  export const NOTICES = {
24
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.' },
@@ -39,6 +40,12 @@ export const NOTICES = {
39
40
  'strikethrough-single-tilde': { severity: 'notice', section: '4.3', message: 'One tilde strikes nothing: the tildes stay on the page. Strikethrough is ~~two~~.' },
40
41
  'link-pending': { severity: 'hint', section: '7.4', message: 'No note answers this link yet, so it is drawn as pending.' },
41
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.' },
42
49
  };
43
50
  /** A footnote reference left as text, which is one with no definition (§7.12). */
44
51
  const UNDEFINED_REFERENCE = /\[\^[^\]\s]+\]/g;
@@ -109,6 +116,7 @@ export async function diagnose(markdown, options = {}) {
109
116
  const referenced = new Set();
110
117
  const definitions = [];
111
118
  const images = [];
119
+ const tables = [];
112
120
  walk(tree, (node) => {
113
121
  const at = span(node);
114
122
  if (!at)
@@ -119,6 +127,8 @@ export async function diagnose(markdown, options = {}) {
119
127
  report('fence-unclosed', at[0], at[1]);
120
128
  else if (node.lang === 'mermaid')
121
129
  diagrams.push({ source: node.value ?? '', at });
130
+ if (isTableBlock(node.lang, node.meta))
131
+ tables.push({ value: node.value ?? '', at });
122
132
  }
123
133
  else if (node.type === 'math') {
124
134
  if (!closes(source, /^(\${2,})/))
@@ -179,6 +189,17 @@ export async function diagnose(markdown, options = {}) {
179
189
  if (!keeps(image.name))
180
190
  report('embed-pending', image.at[0], image.at[1], image.name);
181
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
+ }
182
203
  if (diagrams.length > 0 && options.diagrams !== false) {
183
204
  const mermaid = (await import('mermaid')).default;
184
205
  for (const diagram of diagrams) {
package/dist/edit/live.js CHANGED
@@ -573,6 +573,13 @@ function build(state) {
573
573
  block(from, to, 'diagram', `diagram:${source}`, () => createElement(Snippet, { text: source }));
574
574
  break;
575
575
  }
576
+ // A `table` block is drawn as the table it asks for while the author is elsewhere, where the
577
+ // host reaches the notebook's tables, and edited as its lines (§7.15, #138).
578
+ const fence = construct.open ? doc.sliceString(construct.open.from, construct.open.to) : '';
579
+ if (host.queryTable && !open && alone(from, to) && /^\s*(`{3,}|~{3,})\s*table\s*$/.test(fence)) {
580
+ block(from, to, 'diagram', `table-block:${source}`, () => createElement(Snippet, { text: source }));
581
+ break;
582
+ }
576
583
  codeLines(construct, out, doc, text);
577
584
  // The language, chosen at the block's top right from every grammar Prism carries (#84).
578
585
  if (construct.open) {
package/dist/host.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { type ReactNode } from 'react';
2
2
  import { type NoteStrings, type NoteStringsInput } from './strings.js';
3
+ import type { TablePage, TableRequest } from './table-block.js';
3
4
  import { type Scheme, type Theme } from './theme.js';
4
5
  /**
5
6
  * The host contract: everything the renderer needs from the notebook a note lives in, given by
@@ -43,6 +44,24 @@ export interface NoteHost {
43
44
  * before it is reached (#94): a host that loads from the network may cache what it answered.
44
45
  */
45
46
  readonly loadNote?: (name: string) => Promise<EmbeddedNote | null>;
47
+ /**
48
+ * The rows a `table` block asks for (`SPEC.md` §7.15, #138): the table it names, the columns, the
49
+ * filter as written, the order, the page and its size, and the column to sum. The host runs the
50
+ * filter and answers the table's columns, the page's rows, the row count of the whole filter, the
51
+ * total and when the rows were read; `null` says the notebook keeps no table of that name. A block
52
+ * that cannot be read asks nothing. Without it, a `table` block is a code block, its lines as
53
+ * written, as it is wherever no tables are kept. The package never fetches; `runTableQuery`
54
+ * answers a request from rows held in memory.
55
+ */
56
+ readonly queryTable?: (request: TableRequest) => Promise<TablePage | null>;
57
+ /**
58
+ * Whether the note is being drawn for paper or a PDF (#139). Each `table` block then asks
59
+ * `queryTable` for every row its filter returns, in its declared order, and is drawn with no
60
+ * control, closed by the line naming what was read. It is the host that knows: an answer cannot
61
+ * arrive between the browser's print command and its page, so give it, wait until no
62
+ * `[aria-busy="true"]` is left under the note, then print. Defaults to `false`.
63
+ */
64
+ readonly printing?: boolean;
46
65
  /**
47
66
  * Whether the reader may tick the task boxes of this note. Defaults to `false`: every box shows
48
67
  * its state and none answers a click.
@@ -236,6 +255,8 @@ export interface ResolvedHost {
236
255
  readonly navigate: (address: string) => void;
237
256
  readonly remoteNotice: boolean;
238
257
  readonly loadNote: ((name: string) => Promise<EmbeddedNote | null>) | null;
258
+ readonly queryTable: ((request: TableRequest) => Promise<TablePage | null>) | null;
259
+ readonly printing: boolean;
239
260
  readonly keeps: (name: string) => boolean;
240
261
  readonly suggest: ((query: string) => readonly string[] | PromiseLike<readonly string[]>) | null;
241
262
  readonly attach: ((file: File, attributes: AttachAttributes, progress: (report: AttachProgress) => void) => string | PromiseLike<string>) | null;
package/dist/host.js CHANGED
@@ -21,6 +21,8 @@ export const HOST_KEYS = Object.keys({
21
21
  targetAddress: 1,
22
22
  navigate: 1,
23
23
  loadNote: 1,
24
+ queryTable: 1,
25
+ printing: 1,
24
26
  writable: 1,
25
27
  onToggleTask: 1,
26
28
  keeps: 1,
@@ -54,6 +56,8 @@ export function resolveHost(host) {
54
56
  navigate: host.navigate ?? ((address) => window.location.assign(address)),
55
57
  remoteNotice: host.remoteNotice ?? true,
56
58
  loadNote: host.loadNote ?? null,
59
+ queryTable: host.queryTable ?? null,
60
+ printing: host.printing ?? false,
57
61
  keeps: host.keeps ?? never,
58
62
  suggest: host.suggest ?? null,
59
63
  attach: host.attach ?? null,
package/dist/index.d.ts CHANGED
@@ -11,3 +11,4 @@ export { codeRegions, fenceRegions, headingKey, remoteImageHosts, resolveWikilin
11
11
  export { ordinalAt, taskBoxes, taskCheckedAt, toggleTaskAt } from './tasklist.js';
12
12
  export { readProperties, type NoteProperties, type PropertyEntry, type PropertyShape } from './properties.js';
13
13
  export { DELEGATED_TO_THE_BASE_PARSER, unclassified } from './delegated.js';
14
+ export { runTableQuery, type TableColumn, type TableColumnKind, type TablePage, type TableRequest, type TableRow, type TableSchema, type TableSortKey, type TableValue, } from './table-block.js';
package/dist/index.js CHANGED
@@ -9,3 +9,4 @@ export { codeRegions, fenceRegions, headingKey, remoteImageHosts, resolveWikilin
9
9
  export { ordinalAt, taskBoxes, taskCheckedAt, toggleTaskAt } from './tasklist.js';
10
10
  export { readProperties } from './properties.js';
11
11
  export { DELEGATED_TO_THE_BASE_PARSER, unclassified } from './delegated.js';
12
+ export { runTableQuery, } from './table-block.js';
package/dist/strings.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { TableNoticeCode } from './table-block.js';
1
2
  /**
2
3
  * The words the reading surface shows of its own, around what a note says.
3
4
  *
@@ -27,6 +28,28 @@ export interface NoteStrings {
27
28
  readonly parameter: string;
28
29
  /** The title of a wikilink whose target writes a parameter, which leads nowhere until then. */
29
30
  readonly parameterLink: string;
31
+ /** How many rows the filter of a `table` block returns (§7.15). */
32
+ readonly tableRows: (count: number) => string;
33
+ /** Which page of a `table` block is drawn, of how many. */
34
+ readonly tablePage: (page: number, pages: number) => string;
35
+ /** The buttons that move a `table` block to the page before and after. */
36
+ readonly tablePrevious: string;
37
+ readonly tableNext: string;
38
+ /** The label of the row that closes a table with its total. */
39
+ readonly tableTotal: string;
40
+ /** What a `table` block says when its filter returns no row. */
41
+ readonly tableEmpty: string;
42
+ /** The title of a column's header, which sorts the table by it for the reader alone. */
43
+ readonly tableSortBy: (column: string) => string;
44
+ /** What a `table` block says in place of its table, by the code of its notice (§7.13); `table` is what it names, if anything. */
45
+ readonly tableProblem: (code: TableNoticeCode, table: string | null) => string;
46
+ /** The line that closes a printed `table` block: the table, its filter or `null`, how many rows and when they were read. */
47
+ readonly tablePrinted: (read: {
48
+ readonly table: string;
49
+ readonly filter: string | null;
50
+ readonly count: number;
51
+ readonly readAt: string;
52
+ }) => string;
30
53
  /** The title of an embed naming a file the notebook does not keep. */
31
54
  readonly attachmentMissing: string;
32
55
  /** A card's ways to a file: open it where a browser shows it, and save it (#77). */
package/dist/strings.js CHANGED
@@ -41,6 +41,30 @@ export const ENGLISH = {
41
41
  refusedLink: 'This address is not one the reading surface follows, so the text stays and the link does not.',
42
42
  parameter: 'Parameter: filled in when a notebook is created from this model.',
43
43
  parameterLink: 'A link to a parameter: it leads to a note once a notebook is created from this model.',
44
+ tableRows: (count) => (count === 1 ? '1 row' : `${count.toLocaleString('en-US')} rows`),
45
+ tablePage: (page, pages) => `Page ${page} of ${pages}`,
46
+ tablePrevious: 'Previous page',
47
+ tableNext: 'Next page',
48
+ tableTotal: 'Total',
49
+ tableEmpty: 'No row answers this filter.',
50
+ tableSortBy: (column) => `Sort by ${column}, for you alone: the note keeps its order`,
51
+ tableProblem: (code, table) => {
52
+ switch (code) {
53
+ case 'table-unnamed':
54
+ return 'This table block names no table: write its name once, as table: name.';
55
+ case 'table-key-unknown':
56
+ return 'A table block has six keys, and this line is none of them:';
57
+ case 'table-key-invalid':
58
+ return 'This key is written twice, or its value cannot be read:';
59
+ case 'table-column-unknown':
60
+ return `The table ${table ?? ''} has no such column:`;
61
+ case 'table-filter-invalid':
62
+ return 'This filter cannot be answered:';
63
+ case 'table-pending':
64
+ return `This notebook keeps no table named ${table ?? ''} yet.`;
65
+ }
66
+ },
67
+ tablePrinted: ({ table, filter, count, readAt }) => `Table ${table}${filter === null ? '' : `, filtered by ${filter}`}: ${count === 1 ? '1 row' : `${count.toLocaleString('en-US')} rows`}, read on ${readAt}.`,
44
68
  attachmentMissing: 'This notebook keeps no file under that name.',
45
69
  attachmentOpen: 'Open',
46
70
  attachmentDownload: 'Download',