@memorysmithapp/markdown-renderer 0.12.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/README.md +8 -2
  2. package/dist/ContentsBlock.d.ts +82 -0
  3. package/dist/ContentsBlock.js +162 -0
  4. package/dist/DataTable.js +31 -4
  5. package/dist/InPageAnchor.d.ts +20 -0
  6. package/dist/InPageAnchor.js +35 -0
  7. package/dist/Markdown.d.ts +7 -1
  8. package/dist/Markdown.js +48 -31
  9. package/dist/NoteBody.js +107 -28
  10. package/dist/PropertiesBlock.d.ts +54 -3
  11. package/dist/PropertiesBlock.js +91 -5
  12. package/dist/Transclusion.js +4 -1
  13. package/dist/appendices.d.ts +30 -0
  14. package/dist/appendices.js +11 -4
  15. package/dist/contents.d.ts +92 -0
  16. package/dist/contents.js +224 -0
  17. package/dist/diagnose.d.ts +3 -1
  18. package/dist/diagnose.js +25 -0
  19. package/dist/edit/ContentsDialog.d.ts +39 -0
  20. package/dist/edit/ContentsDialog.js +126 -0
  21. package/dist/edit/NoteEditor.js +56 -4
  22. package/dist/edit/PropertiesDialog.d.ts +42 -0
  23. package/dist/edit/PropertiesDialog.js +103 -0
  24. package/dist/edit/StyleDialog.js +5 -3
  25. package/dist/edit/blocks.d.ts +29 -0
  26. package/dist/edit/blocks.js +100 -3
  27. package/dist/edit/contents.d.ts +30 -0
  28. package/dist/edit/contents.js +76 -0
  29. package/dist/edit/live.js +72 -2
  30. package/dist/edit/properties.d.ts +26 -0
  31. package/dist/edit/properties.js +60 -0
  32. package/dist/host.d.ts +24 -0
  33. package/dist/host.js +6 -0
  34. package/dist/index.d.ts +3 -0
  35. package/dist/index.js +3 -0
  36. package/dist/kept-files.d.ts +11 -0
  37. package/dist/kept-files.js +49 -0
  38. package/dist/note-style.d.ts +9 -1
  39. package/dist/note-style.js +4 -2
  40. package/dist/outline.d.ts +227 -0
  41. package/dist/outline.js +366 -0
  42. package/dist/properties-block.d.ts +62 -0
  43. package/dist/properties-block.js +175 -0
  44. package/dist/slots.js +11 -2
  45. package/dist/strings.d.ts +60 -0
  46. package/dist/strings.js +43 -1
  47. package/dist/table-block.d.ts +13 -1
  48. package/dist/table-block.js +2 -1
  49. package/dist/theme.d.ts +19 -0
  50. package/package.json +4 -2
  51. package/structure.css +54 -0
  52. package/theme-default.css +56 -0
@@ -0,0 +1,366 @@
1
+ /**
2
+ * The outline of a note and the ids of its headings (`SPEC.md` §3.3, §7.17, #173), apart from
3
+ * React: what a `contents` block lists, and what a link to `#section` lands on.
4
+ *
5
+ * Every heading is given the GitHub slug of its text, unique in the note, a repeat taking `-1`,
6
+ * `-2`: the note's own headings carry it as their id, prefixed so it never meets an id of the
7
+ * host's page, and every heading carries it as `data-heading`, which is what a link written inside
8
+ * an embed finds there, where no id is given. The outline is the headings at the top level of the
9
+ * note, outside quotes, callouts, lists and code: the ones `heading-first-level` examines.
10
+ *
11
+ * The note is drawn in runs an embed cuts, each parsed on its own; the slugs are counted across
12
+ * them here, once, over the same text and the same plugins the runs are drawn with, and each run
13
+ * is handed its own, in the order it meets its headings.
14
+ */
15
+ import remarkParse from 'remark-parse';
16
+ import { unified } from 'unified';
17
+ import { CLOBBER_PREFIX } from './footnotes.js';
18
+ import { readingPlugins } from './reading.js';
19
+ import { isContentsBlock } from './contents.js';
20
+ import { isPropertiesBlock } from './properties-block.js';
21
+ import { keptImageName } from './kept-image.js';
22
+ import { isTableBlock, readTableBlock } from './table-block.js';
23
+ /** The keyword of a Markdown table's caption (#175): `Table:`, Pandoc's, case folded. */
24
+ const CAPTION = /^table:[ \t]*/i;
25
+ /** The kept file an attachment link names, as `resolveWikilinks` writes it: `attachment:name|size`. */
26
+ export function attachmentName(url) {
27
+ if (!url.startsWith('attachment:'))
28
+ return null;
29
+ let address;
30
+ try {
31
+ address = decodeURIComponent(url.slice('attachment:'.length));
32
+ }
33
+ catch {
34
+ address = url.slice('attachment:'.length);
35
+ }
36
+ const at = address.lastIndexOf('|');
37
+ return (at === -1 ? address : address.slice(0, at)).normalize('NFC');
38
+ }
39
+ /** The kept file or remote image a node references, or `null`. */
40
+ export function referenceOf(node) {
41
+ if (node.type === 'link' && node.url) {
42
+ const name = attachmentName(node.url);
43
+ return name === null ? null : { kept: true, name, title: null, form: 'embed' };
44
+ }
45
+ if (node.type === 'image' && node.url) {
46
+ const name = keptImageName(node.url);
47
+ if (name !== null)
48
+ return { kept: true, name, title: node.title ?? null, form: 'image' };
49
+ const last = node.url.split(/[?#]/, 1)[0].split('/').filter(Boolean).pop() ?? node.url;
50
+ let decoded = last;
51
+ try {
52
+ decoded = decodeURIComponent(last);
53
+ }
54
+ catch {
55
+ // An escape that is not one is left as written.
56
+ }
57
+ return { kept: false, name: decoded, title: node.title ?? null, form: 'image' };
58
+ }
59
+ return null;
60
+ }
61
+ /** The one image or file a paragraph holds and nothing else, which makes it a figure's candidate (#175). */
62
+ export function aloneIn(paragraph) {
63
+ if (paragraph.type !== 'paragraph')
64
+ return null;
65
+ const meaningful = (paragraph.children ?? []).filter((child) => !(child.type === 'text' && (child.value ?? '').trim() === ''));
66
+ const only = meaningful.length === 1 ? meaningful[0] : null;
67
+ return only && referenceOf(only) ? only : null;
68
+ }
69
+ /** Whether a node is a table the note draws: a Markdown table, or a `table` block where tables are reached. */
70
+ export function isTableNode(node, blocks) {
71
+ return node.type === 'table' || (blocks && node.type === 'code' && isTableBlock(node.lang, node.meta));
72
+ }
73
+ /** The paragraph right after a table that captions it (`Table: …`), or `null`. */
74
+ export function captionAfter(node, parent) {
75
+ if (node.type !== 'table' || !parent?.children)
76
+ return null;
77
+ const next = parent.children[parent.children.indexOf(node) + 1];
78
+ const first = next?.type === 'paragraph' ? next.children?.[0] : undefined;
79
+ return first?.type === 'text' && CAPTION.test(first.value ?? '') ? next : null;
80
+ }
81
+ /** A caption's inlines without its keyword. */
82
+ export function captionContent(paragraph) {
83
+ const [first, ...rest] = paragraph.children ?? [];
84
+ if (!first)
85
+ return [];
86
+ const value = (first.value ?? '').replace(CAPTION, '');
87
+ return value === '' ? rest : [{ ...first, value }, ...rest];
88
+ }
89
+ /** The id a heading of the note carries on the page. */
90
+ export function headingId(slug) {
91
+ return `${CLOBBER_PREFIX}${slug}`;
92
+ }
93
+ /**
94
+ * GitHub's slug of a heading's text: lower case, letters with their marks, digits, `-` and `_`
95
+ * kept, every space a `-`, anything else dropped.
96
+ */
97
+ export function slugOf(text) {
98
+ return text
99
+ .toLowerCase()
100
+ .replace(/[^\p{L}\p{M}\p{N}\p{Pc}\- ]/gu, '')
101
+ .replace(/ /g, '-');
102
+ }
103
+ /** Hands out slugs, a repeat taking `-1`, `-2`, as GitHub's slugger does. */
104
+ export class Slugger {
105
+ seen = new Map();
106
+ slug(text) {
107
+ const base = slugOf(text);
108
+ let slug = base;
109
+ while (this.seen.has(slug)) {
110
+ const count = this.seen.get(base) + 1;
111
+ this.seen.set(base, count);
112
+ slug = `${base}-${count}`;
113
+ }
114
+ this.seen.set(slug, 0);
115
+ return slug;
116
+ }
117
+ }
118
+ /** The text of a node, as a heading's slug reads it. */
119
+ export function textOf(node) {
120
+ if (node.type === 'footnoteReference')
121
+ return '';
122
+ if (typeof node.value === 'string' && node.type !== 'html')
123
+ return node.value;
124
+ if (node.type === 'image')
125
+ return node.alt ?? '';
126
+ return (node.children ?? []).map(textOf).join('');
127
+ }
128
+ /** Visits every node of a tree, parents before their children, as remark does. */
129
+ export function walkTree(node, visit, parent = null) {
130
+ visit(node, parent);
131
+ for (const child of node.children ?? [])
132
+ walkTree(child, visit, node);
133
+ }
134
+ /** A heading's inlines as an entry draws them: a link is its text, a footnote reference is gone. */
135
+ function entryContent(nodes) {
136
+ return nodes.flatMap((node) => {
137
+ if (node.type === 'footnoteReference')
138
+ return [];
139
+ if (node.type === 'link' || node.type === 'linkReference')
140
+ return entryContent(node.children ?? []);
141
+ if (node.children)
142
+ return [{ ...node, children: entryContent(node.children) }];
143
+ return [node];
144
+ });
145
+ }
146
+ const processor = unified().use(remarkParse).use(readingPlugins(() => undefined));
147
+ /** A run's tree, as the page parses and transforms it. */
148
+ export function parseRun(text) {
149
+ return processor.runSync(processor.parse(text), text);
150
+ }
151
+ /**
152
+ * The numbers of the headings of an outline (#174): `decimal` ones counted 1, 1.1, 1.2 from the
153
+ * highest level they reach; one the style leaves at `none` takes no number and advances no counter.
154
+ */
155
+ export function numberHeadings(headings) {
156
+ const numbered = headings.filter((heading) => heading.numbering === 'decimal');
157
+ if (numbered.length === 0)
158
+ return headings.map(() => null);
159
+ const top = Math.min(...numbered.map((heading) => heading.level));
160
+ const counters = [];
161
+ return headings.map(({ level, numbering }) => {
162
+ if (numbering !== 'decimal')
163
+ return null;
164
+ const depth = level - top;
165
+ counters.length = depth + 1;
166
+ counters[depth] = (counters[depth] ?? 0) + 1;
167
+ return Array.from({ length: depth + 1 }, (_, index) => counters[index] ?? 0).join('.');
168
+ });
169
+ }
170
+ /**
171
+ * The outline of a note drawn in these runs, the text of each as it is drawn. `numberingAt` says
172
+ * how the heading at a line of a run is numbered, as the style that reaches it says (#174).
173
+ */
174
+ export function planOutline(runs, numberingAt = () => 'none',
175
+ /** Whether a `table` block is drawn as a table, which it is where the host reaches tables. */
176
+ tableBlocks = false) {
177
+ const slugger = new Slugger();
178
+ const found = [];
179
+ const at = [];
180
+ const blocks = [];
181
+ const propertiesBlocks = [];
182
+ const sequence = [];
183
+ const figureCandidates = [];
184
+ const tables = [];
185
+ const kept = [];
186
+ const planned = runs.map((text, run) => {
187
+ const tree = parseRun(text);
188
+ const slugs = [];
189
+ const firstBlock = blocks.length;
190
+ const firstProperties = propertiesBlocks.length;
191
+ walkTree(tree, (node, parent) => {
192
+ if (node.type === 'code' && isContentsBlock(node.lang, node.meta)) {
193
+ sequence.push({ kind: 'contents', ordinal: blocks.length });
194
+ blocks.push(node.value ?? '');
195
+ }
196
+ if (node.type === 'code' && isPropertiesBlock(node.lang, node.meta)) {
197
+ sequence.push({ kind: 'properties', ordinal: propertiesBlocks.length });
198
+ propertiesBlocks.push(node.value ?? '');
199
+ }
200
+ const alone = aloneIn(node);
201
+ if (alone)
202
+ figureCandidates.push({ run, ...referenceOf(alone) });
203
+ if (isTableNode(node, tableBlocks)) {
204
+ if (node.type === 'code') {
205
+ const block = readTableBlock(node.value ?? '');
206
+ tables.push({ run, kind: 'block', caption: null, title: block.title ?? block.table });
207
+ }
208
+ else {
209
+ const caption = captionAfter(node, parent);
210
+ tables.push({ run, kind: 'markdown', caption: caption ? entryContent(captionContent(caption)) : null, title: null });
211
+ }
212
+ }
213
+ const reference = referenceOf(node);
214
+ if (reference?.kept)
215
+ kept.push({ run, name: reference.name, title: reference.title });
216
+ if (node.type !== 'heading')
217
+ return;
218
+ const slug = slugger.slug(textOf(node));
219
+ slugs.push(slug);
220
+ if (parent === tree && node.depth !== undefined) {
221
+ found.push({ id: headingId(slug), slug, level: node.depth, content: entryContent(node.children ?? []), run, line: node.position?.start?.line ?? 1 });
222
+ at.push({ run, index: slugs.length - 1 });
223
+ }
224
+ });
225
+ return { slugs, firstBlock, firstProperties };
226
+ });
227
+ const numbers = numberHeadings(found.map((heading) => ({ level: heading.level, numbering: numberingAt(heading.run, heading.line) })));
228
+ const perRun = planned.map((run) => run.slugs.map(() => null));
229
+ numbers.forEach((number, index) => {
230
+ perRun[at[index].run][at[index].index] = number;
231
+ });
232
+ return {
233
+ runs: planned.map((run, index) => ({ ...run, numbers: perRun[index] })),
234
+ headings: found.map((heading, index) => ({ ...heading, number: numbers[index] ?? null })),
235
+ blocks,
236
+ propertiesBlocks,
237
+ sequence,
238
+ figureCandidates,
239
+ tables,
240
+ kept,
241
+ };
242
+ }
243
+ export const figureId = (number) => `contents-figure-${number}`;
244
+ export const tableId = (number) => `contents-table-${number}`;
245
+ export const attachmentId = (number) => `contents-attachment-${number}`;
246
+ /**
247
+ * Numbers a note's figures, tables and attachments (#175). An image alone in its paragraph is a
248
+ * figure when it is remote, or when the file it names is an image, which only its media type says
249
+ * (§5.8); an attachment is listed once, at the first reference to its name.
250
+ */
251
+ export function planItems(outline, kindOf, keeps = () => true) {
252
+ const runs = outline.runs.map(() => ({ figures: [], tables: [], attachments: [] }));
253
+ const figures = [];
254
+ let pending = false;
255
+ for (const candidate of outline.figureCandidates) {
256
+ const kind = !candidate.kept ? 'image' : keeps(candidate.name) ? kindOf(candidate.name, candidate.form) : 'other';
257
+ if (kind === 'pending')
258
+ pending = true;
259
+ if (kind !== 'image') {
260
+ runs[candidate.run].figures.push(null);
261
+ continue;
262
+ }
263
+ const number = figures.length + 1;
264
+ figures.push({ id: figureId(number), number, ...candidate });
265
+ runs[candidate.run].figures.push(number);
266
+ }
267
+ const tables = outline.tables.map((table, index) => {
268
+ runs[table.run].tables.push(index + 1);
269
+ return { id: tableId(index + 1), number: index + 1, kind: table.kind, caption: table.caption, title: table.title };
270
+ });
271
+ const attachments = [];
272
+ const seen = new Set();
273
+ for (const reference of outline.kept) {
274
+ if (seen.has(reference.name) || !keeps(reference.name)) {
275
+ runs[reference.run].attachments.push(null);
276
+ continue;
277
+ }
278
+ seen.add(reference.name);
279
+ const id = attachmentId(attachments.length + 1);
280
+ attachments.push({ id, name: reference.name, title: reference.title });
281
+ runs[reference.run].attachments.push(id);
282
+ }
283
+ return { figures, tables, attachments, runs, pending };
284
+ }
285
+ /**
286
+ * The remark plugin that gives the headings of a run their ids and numbers its `contents` blocks.
287
+ * Handed the run's slugs, it gives each heading its id and its slug; with none it counts its own,
288
+ * for a note drawn in one run, and with `ids: false` — inside an embed — gives the slug alone.
289
+ */
290
+ export function remarkOutline(options = {}) {
291
+ return (tree) => {
292
+ const own = options.slugs ? null : new Slugger();
293
+ let heading = 0;
294
+ let block = options.firstBlock ?? 0;
295
+ let propertiesBlock = options.firstProperties ?? 0;
296
+ let figure = 0;
297
+ let table = 0;
298
+ let reference = 0;
299
+ const mark = (node, properties) => {
300
+ node.data = { ...node.data, hProperties: { ...node.data?.hProperties, ...properties } };
301
+ };
302
+ walkTree(tree, (node, parent) => {
303
+ if (node.type === 'code' && isContentsBlock(node.lang, node.meta)) {
304
+ mark(node, { dataContents: block++ });
305
+ return;
306
+ }
307
+ if (node.type === 'code' && isPropertiesBlock(node.lang, node.meta)) {
308
+ mark(node, { dataProperties: propertiesBlock++ });
309
+ return;
310
+ }
311
+ // An image alone in its paragraph that is a figure carries its id, and its caption's place (#175).
312
+ if (aloneIn(node)) {
313
+ const number = options.figures?.[figure++] ?? null;
314
+ if (number !== null) {
315
+ mark(node, { id: figureId(number), className: ['figure'] });
316
+ node.children.push({ type: 'msCaption', data: { hName: 'ms-caption', hProperties: { dataKind: 'figure', dataNumber: number } }, children: [] });
317
+ }
318
+ }
319
+ if (isTableNode(node, options.tableBlocks ?? false)) {
320
+ const number = options.tables?.[table++];
321
+ if (node.type === 'code') {
322
+ if (number !== undefined)
323
+ mark(node, { dataTable: number });
324
+ return;
325
+ }
326
+ if (number !== undefined)
327
+ mark(node, { id: tableId(number) });
328
+ // Its caption, `Table: …`, is drawn without the keyword, and where none is written the place
329
+ // for its number (#175).
330
+ const caption = captionAfter(node, parent);
331
+ const properties = { dataKind: 'table', ...(number !== undefined ? { dataNumber: number } : {}) };
332
+ if (caption) {
333
+ caption.children = captionContent(caption);
334
+ caption.type = 'msCaption';
335
+ caption.data = { ...caption.data, hName: 'ms-caption', hProperties: properties };
336
+ }
337
+ else if (number !== undefined && parent?.children) {
338
+ parent.children.splice(parent.children.indexOf(node) + 1, 0, { type: 'msCaption', data: { hName: 'ms-caption', hProperties: properties }, children: [] });
339
+ }
340
+ return;
341
+ }
342
+ if (referenceOf(node)?.kept) {
343
+ const id = options.attachments?.[reference++] ?? null;
344
+ // The first reference to a file is where its entry leads (#175).
345
+ if (id !== null && parent?.children) {
346
+ const index = parent.children.indexOf(node);
347
+ parent.children[index] = { type: 'msAnchor', data: { hName: 'span', hProperties: { id, className: ['attachment-anchor'] } }, children: [node] };
348
+ }
349
+ return;
350
+ }
351
+ if (node.type !== 'heading')
352
+ return;
353
+ const slug = own ? own.slug(textOf(node)) : options.slugs?.[heading];
354
+ const number = own ? null : (options.numbers?.[heading] ?? null);
355
+ heading++;
356
+ if (slug === undefined)
357
+ return;
358
+ const properties = { dataHeading: slug };
359
+ if (number !== null)
360
+ properties['dataNumber'] = number;
361
+ if (options.ids !== false)
362
+ properties['id'] = headingId(slug);
363
+ mark(node, properties);
364
+ });
365
+ };
366
+ }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * The `properties` block (`SPEC.md` §7.18, #172): how a note's properties are drawn — which keys,
3
+ * under which title, folded or open, and where — read and resolved, with no React and no DOM.
4
+ *
5
+ * It shares the `contents` block's grammar and its host settings' shape (`contents.ts`): options at
6
+ * the root apply to every medium, `screen` and `print` groups override them for theirs or draw
7
+ * nothing there with `none`, and the host's settings, `NoteHost.properties`, are the defaults of
8
+ * whatever a block leaves unset, `place` excepted. A note with no block draws its properties at the
9
+ * top, as it always did, unless the host's settings say otherwise.
10
+ */
11
+ import { type ContentsMedium, type ContentsPlace } from './contents.js';
12
+ /** The options of one layer of a `properties` block. */
13
+ export interface PropertiesLayer {
14
+ /** The keys drawn, in this order; the rest are not drawn. Absent, every key, the reserved first. */
15
+ readonly keys?: readonly string[];
16
+ /** The title of the drawing; absent, the theme's. */
17
+ readonly title?: string;
18
+ /** Whether the drawing starts folded; absent, the theme's. */
19
+ readonly fold?: 'open' | 'closed';
20
+ /** Where it is drawn when not where its block is written, or, for the host, where at all. */
21
+ readonly place?: ContentsPlace;
22
+ }
23
+ /** The settings of a `properties` block, as a block writes them and as a host gives them. */
24
+ export type PropertiesSettings = PropertiesLayer & {
25
+ readonly screen?: PropertiesLayer | 'none';
26
+ readonly print?: PropertiesLayer | 'none';
27
+ };
28
+ /** The codes a `properties` block raises (§7.13). */
29
+ export type PropertiesNoticeCode = 'properties-key-unknown' | 'properties-value-invalid';
30
+ export interface PropertiesProblem {
31
+ readonly code: PropertiesNoticeCode;
32
+ readonly line: number;
33
+ }
34
+ /** Whether a fenced block is a `properties` block: its info string is `properties` and nothing else. */
35
+ export declare function isPropertiesBlock(lang: string | null | undefined, meta: string | null | undefined): boolean;
36
+ /**
37
+ * Reads the lines of a `properties` block into its settings, and what is wrong with them. A
38
+ * mistake sets nothing and the rest is read.
39
+ */
40
+ export declare function readPropertiesBlock(source: string): {
41
+ settings: PropertiesSettings;
42
+ problems: PropertiesProblem[];
43
+ };
44
+ /** Settings with only what they can mean: a host's, read from YAML or JSON, or a block's. */
45
+ export declare function cleanProperties(given: unknown, medium?: boolean): PropertiesSettings | null;
46
+ /** What a note's properties draw in one medium, and where: `null` is where its block is written. */
47
+ export interface PropertiesPlan {
48
+ readonly keys: readonly string[] | null;
49
+ readonly title: string | null;
50
+ readonly fold: 'open' | 'closed' | null;
51
+ readonly place: ContentsPlace | null;
52
+ }
53
+ /**
54
+ * What a note's block draws in a medium, over the host's settings: `null` where the block says
55
+ * `none`. Each option is the nearest that sets it; `place` is the block's own, never the host's.
56
+ */
57
+ export declare function resolvePropertiesBlock(block: PropertiesSettings, host: PropertiesSettings | null, medium: ContentsMedium): PropertiesPlan | null;
58
+ /**
59
+ * What a note with no block draws in a medium: its properties at the start, as always, unless the
60
+ * host's settings say where, which keys, or `none`.
61
+ */
62
+ export declare function resolvePropertiesHost(host: PropertiesSettings | null, medium: ContentsMedium): PropertiesPlan | null;
@@ -0,0 +1,175 @@
1
+ /**
2
+ * The `properties` block (`SPEC.md` §7.18, #172): how a note's properties are drawn — which keys,
3
+ * under which title, folded or open, and where — read and resolved, with no React and no DOM.
4
+ *
5
+ * It shares the `contents` block's grammar and its host settings' shape (`contents.ts`): options at
6
+ * the root apply to every medium, `screen` and `print` groups override them for theirs or draw
7
+ * nothing there with `none`, and the host's settings, `NoteHost.properties`, are the defaults of
8
+ * whatever a block leaves unset, `place` excepted. A note with no block draws its properties at the
9
+ * top, as it always did, unless the host's settings say otherwise.
10
+ */
11
+ import { CONTENTS_MEDIA } from './contents.js';
12
+ /** Whether a fenced block is a `properties` block: its info string is `properties` and nothing else. */
13
+ export function isPropertiesBlock(lang, meta) {
14
+ return lang === 'properties' && (meta ?? '').trim() === '';
15
+ }
16
+ const OPTIONS = ['keys', 'title', 'fold', 'place'];
17
+ const isOption = (key) => OPTIONS.includes(key);
18
+ const isMedium = (key) => CONTENTS_MEDIA.includes(key);
19
+ /** A list of keys as written: `a, b`, or `[a, b]`, each trimmed and unquoted. */
20
+ function keysOf(value) {
21
+ const inner = value.trim().replace(/^\[(.*)\]$/, '$1');
22
+ return inner
23
+ .split(',')
24
+ .map((key) => key.trim().replace(/^(['"])(.*)\1$/, '$2').trim())
25
+ .filter((key) => key !== '');
26
+ }
27
+ /** Reads one option's value; `undefined` for a value its key cannot take. */
28
+ function optionOf(key, value) {
29
+ if (key === 'keys')
30
+ return keysOf(value);
31
+ if (key === 'title')
32
+ return value;
33
+ const folded = value.toLowerCase();
34
+ if (key === 'fold')
35
+ return folded === 'open' || folded === 'closed' ? folded : undefined;
36
+ return folded === 'start' || folded === 'end' ? folded : undefined;
37
+ }
38
+ /**
39
+ * Reads the lines of a `properties` block into its settings, and what is wrong with them. A
40
+ * mistake sets nothing and the rest is read.
41
+ */
42
+ export function readPropertiesBlock(source) {
43
+ const settings = {};
44
+ const problems = [];
45
+ let medium = null;
46
+ let rootIndent = null;
47
+ source
48
+ .replace(/\r\n?/g, '\n')
49
+ .split('\n')
50
+ .forEach((raw, index) => {
51
+ const line = index + 1;
52
+ if (raw.trim() === '')
53
+ return;
54
+ const problem = (code) => {
55
+ problems.push({ code, line });
56
+ };
57
+ const indentText = /^[ \t]*/.exec(raw)[0];
58
+ if (indentText.includes('\t'))
59
+ return problem('properties-key-unknown');
60
+ const indent = indentText.length;
61
+ if (medium && indent <= medium.keyIndent)
62
+ medium = null;
63
+ let target = settings;
64
+ if (medium) {
65
+ if (medium.childIndent === null)
66
+ medium.childIndent = indent;
67
+ else if (indent !== medium.childIndent)
68
+ return problem('properties-key-unknown');
69
+ target = medium.target;
70
+ }
71
+ else if (rootIndent === null)
72
+ rootIndent = indent;
73
+ else if (indent !== rootIndent)
74
+ return problem('properties-key-unknown');
75
+ const match = /^([^:]+):(.*)$/.exec(raw.trim());
76
+ if (!match)
77
+ return problem('properties-key-unknown');
78
+ const key = match[1].trim().toLowerCase();
79
+ const value = match[2].trim();
80
+ if (Object.hasOwn(target, key))
81
+ return problem('properties-key-unknown');
82
+ if (isOption(key)) {
83
+ if (value === '') {
84
+ target[key] = undefined;
85
+ return;
86
+ }
87
+ const read = optionOf(key, value);
88
+ if (read === undefined)
89
+ problem('properties-value-invalid');
90
+ else
91
+ target[key] = read;
92
+ return;
93
+ }
94
+ if (isMedium(key) && target === settings) {
95
+ if (value.toLowerCase() === 'none') {
96
+ settings[key] = 'none';
97
+ return;
98
+ }
99
+ if (value !== '')
100
+ return problem('properties-value-invalid');
101
+ const layer = {};
102
+ settings[key] = layer;
103
+ medium = { keyIndent: indent, childIndent: null, target: layer };
104
+ return;
105
+ }
106
+ problem('properties-key-unknown');
107
+ });
108
+ return { settings: cleanProperties(settings) ?? {}, problems };
109
+ }
110
+ /** Settings with only what they can mean: a host's, read from YAML or JSON, or a block's. */
111
+ export function cleanProperties(given, medium = false) {
112
+ if (typeof given !== 'object' || given === null || Array.isArray(given))
113
+ return null;
114
+ const out = {};
115
+ for (const [rawKey, value] of Object.entries(given)) {
116
+ const key = rawKey.toLowerCase();
117
+ if (key === 'keys') {
118
+ const keys = Array.isArray(value) ? value.map(String).map((each) => each.trim()).filter(Boolean) : typeof value === 'string' ? keysOf(value) : [];
119
+ if (keys.length > 0)
120
+ out['keys'] = keys;
121
+ }
122
+ else if (key === 'title' && typeof value === 'string' && value.trim() !== '')
123
+ out['title'] = value.trim();
124
+ else if ((key === 'fold' || key === 'place') && typeof value === 'string') {
125
+ const read = optionOf(key, value);
126
+ if (read !== undefined)
127
+ out[key] = read;
128
+ }
129
+ else if (isMedium(key) && !medium) {
130
+ if (String(value).toLowerCase() === 'none')
131
+ out[key] = 'none';
132
+ else if (value === null || value === undefined || value === '')
133
+ out[key] = {};
134
+ else {
135
+ const layer = cleanProperties(value, true);
136
+ if (layer)
137
+ out[key] = layer;
138
+ }
139
+ }
140
+ }
141
+ return out;
142
+ }
143
+ function optionAt(layers, key) {
144
+ for (const layer of layers) {
145
+ if (!layer || layer === 'none')
146
+ continue;
147
+ if (layer[key] !== undefined)
148
+ return layer[key];
149
+ }
150
+ return undefined;
151
+ }
152
+ function plan(layers, place) {
153
+ return { keys: optionAt(layers, 'keys') ?? null, title: optionAt(layers, 'title') ?? null, fold: optionAt(layers, 'fold') ?? null, place };
154
+ }
155
+ /**
156
+ * What a note's block draws in a medium, over the host's settings: `null` where the block says
157
+ * `none`. Each option is the nearest that sets it; `place` is the block's own, never the host's.
158
+ */
159
+ export function resolvePropertiesBlock(block, host, medium) {
160
+ const noteMedium = block[medium];
161
+ if (noteMedium === 'none')
162
+ return null;
163
+ const layers = [noteMedium, block, host?.[medium], host ?? undefined];
164
+ return plan(layers, noteMedium?.place ?? block.place ?? null);
165
+ }
166
+ /**
167
+ * What a note with no block draws in a medium: its properties at the start, as always, unless the
168
+ * host's settings say where, which keys, or `none`.
169
+ */
170
+ export function resolvePropertiesHost(host, medium) {
171
+ const hostMedium = host?.[medium];
172
+ if (hostMedium === 'none')
173
+ return null;
174
+ return plan([hostMedium, host ?? undefined], hostMedium?.place ?? host?.place ?? 'start');
175
+ }
package/dist/slots.js CHANGED
@@ -113,9 +113,18 @@ export function MarkdownTable({ children, node, ...rest }) {
113
113
  }
114
114
  function Heading({ level, className, children, node: _node, ...rest }) {
115
115
  const slot = useSlot('heading');
116
+ // Its number, as the style numbers the outline (#174): drawn before its text, never written.
117
+ const number = rest['data-number'];
116
118
  // The heading of the footnotes is the footnotes slot's, not a heading of the note.
117
- if (slot && !className?.split(/\s+/).includes('footnotes-label'))
118
- return drawSlot(slot, { level, children });
119
+ if (slot && !className?.split(/\s+/).includes('footnotes-label')) {
120
+ // Where a contents entry and a link to `#section` land (#173), for the slot to put on its element.
121
+ const id = typeof rest.id === 'string' ? rest.id : undefined;
122
+ const slug = rest['data-heading'];
123
+ return drawSlot(slot, { level, children, ...(id ? { id } : {}), ...(typeof slug === 'string' ? { slug } : {}), ...(typeof number === 'string' ? { number } : {}) });
124
+ }
125
+ if (typeof number === 'string') {
126
+ return createElement(`h${level}`, { className, ...rest }, createElement('span', { className: 'heading-number' }, number), ' ', children);
127
+ }
119
128
  return createElement(`h${level}`, { className, ...rest }, children);
120
129
  }
121
130
  export const headings = {