@memorysmithapp/markdown-renderer 0.12.1 → 0.13.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.
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,224 @@
1
+ /**
2
+ * The `contents` block (`SPEC.md` §7.17, #173): a table of contents the note declares, read and
3
+ * resolved, with no React and no DOM, so `diagnose` reads it on a server as the page does.
4
+ *
5
+ * A block holds settings in YAML's shape — a key alone on its line opens a group, the `key: value`
6
+ * lines indented below it belong to it — so the host's settings, `NoteHost.contents`, are the same
7
+ * structure a YAML parser gives, and one resolution reads both: the note's medium group, its root,
8
+ * the host's medium group, its root, the default. `place` is the one value not inherited: a note's
9
+ * block with none is drawn where it is written.
10
+ */
11
+ /** The lists a contents block draws, each a group of its settings. */
12
+ export const CONTENTS_LISTS = ['headings', 'figures', 'tables', 'attachments'];
13
+ /** The media a contents block tells apart. */
14
+ export const CONTENTS_MEDIA = ['screen', 'print'];
15
+ /** The default depth of the headings list. */
16
+ export const CONTENTS_DEPTH = 3;
17
+ /** Whether a fenced block is a `contents` block: its info string is `contents` and nothing else. */
18
+ export function isContentsBlock(lang, meta) {
19
+ return lang === 'contents' && (meta ?? '').trim() === '';
20
+ }
21
+ const isList = (key) => CONTENTS_LISTS.includes(key);
22
+ const isMedium = (key) => CONTENTS_MEDIA.includes(key);
23
+ /**
24
+ * Reads the lines of a `contents` block into its settings, and what is wrong with them. A mistake
25
+ * sets nothing and the rest is read: a block always draws, with its defaults where it said nothing
26
+ * that could be read.
27
+ */
28
+ export function readContents(source) {
29
+ const settings = {};
30
+ const problems = [];
31
+ const stack = [{ kind: 'root', keyIndent: -1, childIndent: null, target: settings }];
32
+ const lines = source.replace(/\r\n?/g, '\n').split('\n');
33
+ lines.forEach((raw, index) => {
34
+ const line = index + 1;
35
+ if (raw.trim() === '')
36
+ return;
37
+ const problem = (code) => {
38
+ problems.push({ code, line });
39
+ };
40
+ const indentText = /^[ \t]*/.exec(raw)[0];
41
+ if (indentText.includes('\t'))
42
+ return problem('contents-key-unknown');
43
+ const indent = indentText.length;
44
+ while (stack.length > 1 && indent <= stack[stack.length - 1].keyIndent)
45
+ stack.pop();
46
+ const group = stack[stack.length - 1];
47
+ if (group.childIndent === null)
48
+ group.childIndent = indent;
49
+ else if (indent !== group.childIndent)
50
+ return problem('contents-key-unknown');
51
+ const match = /^([^:]+):(.*)$/.exec(raw.trim());
52
+ if (!match)
53
+ return problem('contents-key-unknown');
54
+ const key = match[1].trim().toLowerCase();
55
+ const value = match[2].trim();
56
+ if (Object.hasOwn(group.target, key))
57
+ return problem('contents-key-unknown');
58
+ if (group.kind === 'list') {
59
+ if (key === 'title') {
60
+ if (value !== '')
61
+ group.target['title'] = value;
62
+ else
63
+ group.target['title'] = undefined;
64
+ return;
65
+ }
66
+ if (key === 'depth' && group.list === 'headings') {
67
+ const depth = /^[1-6]$/.test(value) ? Number(value) : null;
68
+ if (value === '')
69
+ group.target['depth'] = undefined;
70
+ else if (depth === null)
71
+ problem('contents-value-invalid');
72
+ else
73
+ group.target['depth'] = depth;
74
+ return;
75
+ }
76
+ return problem('contents-key-unknown');
77
+ }
78
+ if (key === 'place') {
79
+ const place = value.toLowerCase();
80
+ if (place === 'start' || place === 'end')
81
+ group.target['place'] = place;
82
+ else if (value === '')
83
+ group.target['place'] = undefined;
84
+ else
85
+ problem('contents-value-invalid');
86
+ return;
87
+ }
88
+ if (isList(key)) {
89
+ if (value !== '')
90
+ return problem('contents-value-invalid');
91
+ const options = {};
92
+ group.target[key] = options;
93
+ stack.push({ kind: 'list', keyIndent: indent, childIndent: null, target: options, list: key });
94
+ return;
95
+ }
96
+ if (isMedium(key) && group.kind === 'root') {
97
+ if (value.toLowerCase() === 'none') {
98
+ group.target[key] = 'none';
99
+ return;
100
+ }
101
+ if (value !== '')
102
+ return problem('contents-value-invalid');
103
+ const layer = {};
104
+ group.target[key] = layer;
105
+ stack.push({ kind: 'medium', keyIndent: indent, childIndent: null, target: layer });
106
+ return;
107
+ }
108
+ problem('contents-key-unknown');
109
+ });
110
+ return { settings: clean(settings) ?? {}, problems };
111
+ }
112
+ /**
113
+ * Settings with only what they can mean: a host's, read from YAML or JSON, or a block's. An empty
114
+ * group (`headings:`) is a list with its defaults, and anything else is left out.
115
+ */
116
+ export function cleanContents(given) {
117
+ return clean(given);
118
+ }
119
+ function clean(given, medium = false) {
120
+ if (typeof given !== 'object' || given === null || Array.isArray(given))
121
+ return null;
122
+ const out = {};
123
+ for (const [rawKey, value] of Object.entries(given)) {
124
+ const key = rawKey.toLowerCase();
125
+ if (isList(key)) {
126
+ if (value === null || value === undefined || value === '')
127
+ out[key] = {};
128
+ else if (typeof value === 'object' && !Array.isArray(value))
129
+ out[key] = cleanList(key, value);
130
+ }
131
+ else if (key === 'place') {
132
+ const place = String(value ?? '').toLowerCase();
133
+ if (place === 'start' || place === 'end')
134
+ out['place'] = place;
135
+ }
136
+ else if (isMedium(key) && !medium) {
137
+ if (String(value).toLowerCase() === 'none')
138
+ out[key] = 'none';
139
+ else if (value === null || value === undefined || value === '')
140
+ out[key] = {};
141
+ else {
142
+ const layer = clean(value, true);
143
+ if (layer)
144
+ out[key] = layer;
145
+ }
146
+ }
147
+ }
148
+ return out;
149
+ }
150
+ function cleanList(kind, given) {
151
+ const out = {};
152
+ for (const [rawKey, value] of Object.entries(given)) {
153
+ const key = rawKey.toLowerCase();
154
+ if (key === 'title' && typeof value === 'string' && value.trim() !== '')
155
+ out.title = value.trim();
156
+ if (key === 'depth' && kind === 'headings') {
157
+ const depth = Number(value);
158
+ if (Number.isInteger(depth) && depth >= 1 && depth <= 6)
159
+ out.depth = depth;
160
+ }
161
+ }
162
+ return out;
163
+ }
164
+ const layerOf = (settings, medium) => settings ? settings[medium] : undefined;
165
+ /** The lists a layer names, in the order it writes them. */
166
+ function listsOf(layer) {
167
+ if (!layer || layer === 'none')
168
+ return [];
169
+ return Object.keys(layer).filter(isList);
170
+ }
171
+ function optionOf(layers, kind, key) {
172
+ for (const layer of layers) {
173
+ if (!layer || layer === 'none')
174
+ continue;
175
+ const value = layer[kind]?.[key];
176
+ if (value !== undefined)
177
+ return value;
178
+ }
179
+ return undefined;
180
+ }
181
+ function plan(lists, layers, place) {
182
+ return {
183
+ lists: lists.map((kind) => ({ kind, title: optionOf(layers, kind, 'title') ?? null, depth: optionOf(layers, kind, 'depth') ?? CONTENTS_DEPTH })),
184
+ place,
185
+ };
186
+ }
187
+ /**
188
+ * What a note's block draws in a medium, over the host's settings: `null` when the block says
189
+ * `none` there. The lists are the first of the note's medium, the note's root, the host's medium
190
+ * and the host's root that names any, else the headings; each option the nearest that sets it.
191
+ * `place` is the block's own, never the host's.
192
+ */
193
+ export function resolveBlock(block, host, medium) {
194
+ const noteMedium = layerOf(block, medium);
195
+ if (noteMedium === 'none')
196
+ return null;
197
+ const hostMedium = layerOf(host, medium);
198
+ const layers = [noteMedium, block, hostMedium, host];
199
+ const lists = layers.map(listsOf).find((each) => each.length > 0) ?? ['headings'];
200
+ const place = noteMedium?.place ?? block.place ?? null;
201
+ return plan(lists, layers, place);
202
+ }
203
+ /**
204
+ * What the host's settings draw in a medium for a note that holds no block: `null` unless the
205
+ * host's medium group is there, or its root names a list. It is drawn where its `place` says, at
206
+ * the start when it says nothing.
207
+ */
208
+ export function resolveHost(host, medium) {
209
+ if (!host)
210
+ return null;
211
+ const hostMedium = layerOf(host, medium);
212
+ if (hostMedium === 'none')
213
+ return null;
214
+ if (hostMedium === undefined && listsOf(host).length === 0)
215
+ return null;
216
+ const layers = [hostMedium, host];
217
+ const lists = layers.map(listsOf).find((each) => each.length > 0) ?? ['headings'];
218
+ const place = (hostMedium ? hostMedium.place : undefined) ?? host.place ?? 'start';
219
+ return plan(lists, layers, place);
220
+ }
221
+ /** Whether two plans draw the same lists, so one drawing serves both media. */
222
+ export function samePlan(a, b) {
223
+ return JSON.stringify(a?.lists ?? null) === JSON.stringify(b?.lists ?? null);
224
+ }
@@ -14,8 +14,10 @@
14
14
  import type { NoteHost } from './host.js';
15
15
  import { type StyleNoticeCode } from './style-block.js';
16
16
  import { type TableNoticeCode, type TableSchema } from './table-block.js';
17
+ import { type ContentsNoticeCode } from './contents.js';
18
+ import { type PropertiesNoticeCode } from './properties-block.js';
17
19
  /** The codes of §7.13, which `spec.json` declares as `notices`. */
18
- 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 | StyleNoticeCode;
20
+ 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 | StyleNoticeCode | ContentsNoticeCode | PropertiesNoticeCode;
19
21
  /** `notice`: the page will differ from what was typed. `hint`: nothing is drawn wrong. */
20
22
  export type NoticeSeverity = 'notice' | 'hint';
21
23
  /** One place in a note, by a code of §7.13. Lines and columns count from 1 over the whole note. */
package/dist/diagnose.js CHANGED
@@ -22,6 +22,8 @@ import { hasParameterReference } from './parameters.js';
22
22
  import { readProperties } from './properties.js';
23
23
  import { readingPlugins } from './reading.js';
24
24
  import { checkTableBlock, isTableBlock, readTableBlock } from './table-block.js';
25
+ import { isContentsBlock, readContents } from './contents.js';
26
+ import { isPropertiesBlock, readPropertiesBlock } from './properties-block.js';
25
27
  /** The table of §7.13, as `spec.json` carries it: a test holds the two equal. */
26
28
  export const NOTICES = {
27
29
  '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.' },
@@ -51,6 +53,10 @@ export const NOTICES = {
51
53
  'style-key-unknown': { severity: 'notice', section: '7.16', message: 'This line of a style block is not one of its keys, or one written twice, so it sets nothing.' },
52
54
  'style-value-invalid': { severity: 'notice', section: '7.16', message: 'This value is not one its key takes, so it sets nothing.' },
53
55
  'style-unclosed': { severity: 'notice', section: '7.16', message: 'This style block is never closed by a :::, so it runs to the end of the note.' },
56
+ 'contents-key-unknown': { severity: 'notice', section: '7.17', message: 'This line of a contents block is not a key its place takes, sits under no group, or repeats a key, so it sets nothing.' },
57
+ 'properties-key-unknown': { severity: 'notice', section: '7.18', message: 'This line of a properties block is not a key its place takes, sits under no group, or repeats a key, so it sets nothing.' },
58
+ 'properties-value-invalid': { severity: 'notice', section: '7.18', message: 'This value is not one its key takes, or a group is written with a value, so it sets nothing.' },
59
+ 'contents-value-invalid': { severity: 'notice', section: '7.17', message: 'This value is not one its key takes, or a group is written with a value, so it sets nothing.' },
54
60
  };
55
61
  /** A footnote reference left as text, which is one with no definition (§7.12). */
56
62
  const UNDEFINED_REFERENCE = /\[\^[^\]\s]+\]/g;
@@ -127,6 +133,8 @@ export async function diagnose(markdown, options = {}) {
127
133
  const definitions = [];
128
134
  const images = [];
129
135
  const tables = [];
136
+ const contents = [];
137
+ const propertyBlocks = [];
130
138
  walk(tree, (node) => {
131
139
  const at = span(node);
132
140
  if (!at)
@@ -139,6 +147,10 @@ export async function diagnose(markdown, options = {}) {
139
147
  diagrams.push({ source: node.value ?? '', at });
140
148
  if (isTableBlock(node.lang, node.meta))
141
149
  tables.push({ value: node.value ?? '', at });
150
+ if (isContentsBlock(node.lang, node.meta))
151
+ contents.push({ value: node.value ?? '', at });
152
+ if (isPropertiesBlock(node.lang, node.meta))
153
+ propertyBlocks.push({ value: node.value ?? '', at });
142
154
  }
143
155
  else if (node.type === 'math') {
144
156
  if (!closes(source, /^(\${2,})/))
@@ -210,6 +222,19 @@ export async function diagnose(markdown, options = {}) {
210
222
  report(problem.code, start, next === undefined ? text.length : next - 1, problem.detail);
211
223
  }
212
224
  }
225
+ // A `contents` and a `properties` block raise their own notices, each on its line (§7.13, §7.17, §7.18).
226
+ const blockProblems = [
227
+ ...contents.map((block) => ({ block, problems: readContents(block.value).problems })),
228
+ ...propertyBlocks.map((block) => ({ block, problems: readPropertiesBlock(block.value).problems })),
229
+ ];
230
+ for (const { block, problems } of blockProblems) {
231
+ const first = pointOf(block.at[0]).line - 1;
232
+ for (const problem of problems) {
233
+ const start = lineStarts[first + problem.line] ?? block.at[0];
234
+ const next = lineStarts[first + problem.line + 1];
235
+ report(problem.code, start, next === undefined ? text.length : next - 1);
236
+ }
237
+ }
213
238
  if (diagrams.length > 0 && options.diagrams !== false) {
214
239
  const mermaid = (await import('mermaid')).default;
215
240
  for (const diagram of diagrams) {
@@ -0,0 +1,39 @@
1
+ /**
2
+ * The form of a `contents` block (`SPEC.md` §7.17, #173, #175): which lists it draws — the headings,
3
+ * the figures, the tables, the attachments — and the title of each, the levels of the headings,
4
+ * where it is drawn, and what the screen and print draw: the root's, nothing, or their own lists,
5
+ * levels and place. A field left at the notebook's writes nothing, so the host's settings stay the
6
+ * defaults. It inserts a block at the cursor, or changes the block the cursor is in; the editor
7
+ * writes the bytes.
8
+ */
9
+ import { type ContentsList, type ContentsMedium, type ContentsPlace, type ContentsSettings } from '../contents.js';
10
+ /** What the form holds for a layer: the lists it draws and their titles, the levels, and the place. */
11
+ interface LayerFields {
12
+ lists: Record<ContentsList, boolean>;
13
+ titles: Record<ContentsList, string>;
14
+ depth: string;
15
+ place: '' | ContentsPlace;
16
+ }
17
+ type MediumMode = 'same' | 'none' | 'own';
18
+ interface Fields {
19
+ root: LayerFields;
20
+ media: Record<ContentsMedium, {
21
+ mode: MediumMode;
22
+ layer: LayerFields;
23
+ }>;
24
+ }
25
+ /** The form's fields, from what a block sets. */
26
+ export declare function contentsFields(settings: ContentsSettings): Fields;
27
+ /** The settings the form's fields write. */
28
+ export declare function contentsSettings(fields: Fields): ContentsSettings;
29
+ export declare function ContentsDialog({ initial, editing, onApply, onClose, onClosed, }: {
30
+ /** What the block sets now, or nothing for a new one. */
31
+ initial: ContentsSettings;
32
+ /** Whether it changes the block the cursor is in, rather than inserting one. */
33
+ editing: boolean;
34
+ onApply: (settings: ContentsSettings) => void;
35
+ onClose: () => void;
36
+ /** Once the dialog is closed: whether the note was changed, which then has the focus. */
37
+ onClosed: (applied: boolean) => void;
38
+ }): import("react").JSX.Element;
39
+ export {};
@@ -0,0 +1,126 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ /**
3
+ * The form of a `contents` block (`SPEC.md` §7.17, #173, #175): which lists it draws — the headings,
4
+ * the figures, the tables, the attachments — and the title of each, the levels of the headings,
5
+ * where it is drawn, and what the screen and print draw: the root's, nothing, or their own lists,
6
+ * levels and place. A field left at the notebook's writes nothing, so the host's settings stay the
7
+ * defaults. It inserts a block at the cursor, or changes the block the cursor is in; the editor
8
+ * writes the bytes.
9
+ */
10
+ import { useEffect, useId, useRef, useState } from 'react';
11
+ import { useHost } from '../host.js';
12
+ import { CONTENTS_LISTS, CONTENTS_MEDIA } from '../contents.js';
13
+ import { ICONS } from './blocks.js';
14
+ const each = (value) => Object.fromEntries(CONTENTS_LISTS.map((kind) => [kind, value(kind)]));
15
+ function fieldsOf(layer, root) {
16
+ const named = CONTENTS_LISTS.filter((kind) => layer && kind in layer);
17
+ return {
18
+ // A layer that names no list draws the headings at the root, and the root's lists in a medium.
19
+ lists: each((kind) => (named.length > 0 ? named.includes(kind) : root && kind === 'headings')),
20
+ titles: each((kind) => layer?.[kind]?.title ?? ''),
21
+ depth: layer?.headings?.depth === undefined ? '' : String(layer.headings.depth),
22
+ place: layer?.place ?? '',
23
+ };
24
+ }
25
+ /** The form's fields, from what a block sets. */
26
+ export function contentsFields(settings) {
27
+ const medium = (name) => {
28
+ const layer = settings[name];
29
+ if (layer === 'none')
30
+ return { mode: 'none', layer: fieldsOf(undefined, false) };
31
+ if (layer === undefined)
32
+ return { mode: 'same', layer: fieldsOf(undefined, false) };
33
+ return { mode: 'own', layer: fieldsOf(layer, false) };
34
+ };
35
+ return { root: fieldsOf(settings, true), media: { screen: medium('screen'), print: medium('print') } };
36
+ }
37
+ function layerOf(fields, root) {
38
+ const chosen = CONTENTS_LISTS.filter((kind) => fields.lists[kind]);
39
+ // The headings alone, with nothing of their own, are what a root writes nothing for.
40
+ const classic = root && chosen.length === 1 && chosen[0] === 'headings';
41
+ const layer = {};
42
+ for (const kind of chosen) {
43
+ const options = {};
44
+ if (fields.titles[kind].trim())
45
+ options.title = fields.titles[kind].trim();
46
+ if (kind === 'headings' && fields.depth)
47
+ options.depth = Number(fields.depth);
48
+ if (!classic || Object.keys(options).length > 0)
49
+ layer[kind] = options;
50
+ }
51
+ if (fields.place)
52
+ layer['place'] = fields.place;
53
+ return layer;
54
+ }
55
+ /** The settings the form's fields write. */
56
+ export function contentsSettings(fields) {
57
+ const settings = { ...layerOf(fields.root, true) };
58
+ for (const medium of CONTENTS_MEDIA) {
59
+ const { mode, layer } = fields.media[medium];
60
+ if (mode === 'none')
61
+ settings[medium] = 'none';
62
+ else if (mode === 'own') {
63
+ // The lists the root draws are not written again: the medium names them only to differ.
64
+ const same = CONTENTS_LISTS.every((kind) => layer.lists[kind] === fields.root.lists[kind]);
65
+ const own = { ...layerOf(layer, false) };
66
+ // Naming one list in a medium replaces the root's, so they are all named or none is.
67
+ const options = CONTENTS_LISTS.some((kind) => own[kind] && Object.keys(own[kind]).length > 0);
68
+ if (same && !options)
69
+ for (const kind of CONTENTS_LISTS)
70
+ delete own[kind];
71
+ if (Object.keys(own).length > 0)
72
+ settings[medium] = own;
73
+ }
74
+ }
75
+ return settings;
76
+ }
77
+ export function ContentsDialog({ initial, editing, onApply, onClose, onClosed, }) {
78
+ const host = useHost();
79
+ const words = host.strings.editor;
80
+ const [fields, setFields] = useState(() => contentsFields(initial));
81
+ const dialog = useRef(null);
82
+ const applied = useRef(false);
83
+ const closed = useRef(onClosed);
84
+ closed.current = onClosed;
85
+ const id = useId();
86
+ useEffect(() => {
87
+ const element = dialog.current;
88
+ if (!element)
89
+ return;
90
+ if (typeof element.showModal === 'function')
91
+ element.showModal();
92
+ else
93
+ element.setAttribute('open', '');
94
+ element.querySelector('input, select')?.focus();
95
+ return () => {
96
+ if (element.open && typeof element.close === 'function')
97
+ element.close();
98
+ closed.current(applied.current);
99
+ };
100
+ }, []);
101
+ const submit = (event) => {
102
+ event.preventDefault();
103
+ applied.current = true;
104
+ onClose();
105
+ onApply(contentsSettings(fields));
106
+ };
107
+ const names = {
108
+ headings: host.strings.contentsHeadings,
109
+ figures: host.strings.contentsFigures,
110
+ tables: host.strings.contentsTables,
111
+ attachments: host.strings.contentsAttachments,
112
+ };
113
+ const layerFields = (layer, set, root) => (_jsxs(_Fragment, { children: [CONTENTS_LISTS.map((kind) => (_jsxs("div", { className: "edit-contents-list", "data-list": kind, children: [_jsxs("label", { className: "edit-contents-check", children: [_jsx("input", { type: "checkbox", name: `list-${kind}`, checked: layer.lists[kind], onChange: (event) => set({ ...layer, lists: { ...layer.lists, [kind]: event.target.checked } }) }), _jsx("span", { children: names[kind] })] }), root && layer.lists[kind] && (_jsxs("label", { children: [_jsx("span", { children: words.contentsTitle }), _jsx("input", { className: "edit-attach-input", name: kind === 'headings' ? 'title' : `title-${kind}`, value: layer.titles[kind], placeholder: host.contents?.[kind]?.title ?? names[kind], onChange: (event) => set({ ...layer, titles: { ...layer.titles, [kind]: event.target.value } }) })] }))] }, kind))), layer.lists.headings && (_jsxs("label", { children: [_jsx("span", { children: words.contentsDepth }), _jsxs("select", { className: "edit-attach-input", name: "depth", value: layer.depth, onChange: (event) => set({ ...layer, depth: event.target.value }), children: [_jsx("option", { value: "", children: words.contentsNotebook }), [1, 2, 3, 4, 5, 6].map((depth) => (_jsx("option", { value: String(depth), children: depth }, depth)))] })] })), _jsxs("label", { children: [_jsx("span", { children: words.contentsPlace }), _jsxs("select", { className: "edit-attach-input", name: "place", value: layer.place, onChange: (event) => set({ ...layer, place: event.target.value }), children: [_jsx("option", { value: "", children: root ? words.contentsHere : words.contentsSame }), _jsx("option", { value: "start", children: words.contentsStart }), _jsx("option", { value: "end", children: words.contentsEnd })] })] })] }));
114
+ return (_jsx("dialog", { ref: dialog, className: "edit-source edit-attach edit-style edit-contents", "aria-modal": "true", "aria-labelledby": `${id}-title`, onCancel: (event) => {
115
+ event.preventDefault();
116
+ onClose();
117
+ }, onClick: (event) => event.target === dialog.current && onClose(), children: _jsxs("div", { className: "edit-source-frame", children: [_jsxs("header", { className: "edit-source-header", children: [_jsx("h2", { id: `${id}-title`, className: "edit-source-title", children: words.contents }), _jsx("button", { type: "button", className: "edit-control edit-source-close", "aria-label": host.strings.close, title: host.strings.close, onClick: onClose, children: ICONS.remove })] }), _jsx("div", { className: "edit-attach-panel", children: _jsxs("form", { className: "edit-attach-form", onSubmit: submit, noValidate: true, children: [layerFields(fields.root, (root) => setFields((current) => ({ ...current, root })), true), CONTENTS_MEDIA.map((medium) => {
118
+ const { mode, layer } = fields.media[medium];
119
+ const setMedium = (next) => setFields((current) => ({ ...current, media: { ...current.media, [medium]: next } }));
120
+ return (_jsxs("fieldset", { className: "edit-contents-medium", "data-medium": medium, children: [_jsxs("label", { children: [_jsx("span", { children: medium === 'screen' ? words.contentsScreen : words.contentsPrint }), _jsxs("select", { className: "edit-attach-input", name: medium, value: mode, onChange: (event) => {
121
+ const next = event.target.value;
122
+ // A medium of its own starts from the lists the root draws.
123
+ setMedium({ mode: next, layer: next === 'own' && mode !== 'own' ? { ...layer, lists: { ...fields.root.lists } } : layer });
124
+ }, children: [_jsx("option", { value: "same", children: words.contentsSame }), _jsx("option", { value: "none", children: words.contentsNone }), _jsx("option", { value: "own", children: words.contentsOwn })] })] }), mode === 'own' && layerFields(layer, (next) => setMedium({ mode, layer: next }), false)] }, medium));
125
+ }), _jsx("div", { className: "edit-attach-actions", children: _jsx("button", { type: "submit", className: "edit-attach-button edit-attach-primary", children: editing ? words.contentsApply : words.contentsInsert }) })] }) })] }) }));
126
+ }
@@ -24,6 +24,11 @@ import { measureMetrics } from './heights.js';
24
24
  import { NoteActions } from '../NoteActions.js';
25
25
  import { AttachDialog, webImage } from './AttachDialog.js';
26
26
  import { StyleDialog } from './StyleDialog.js';
27
+ import { ContentsDialog } from './ContentsDialog.js';
28
+ import { PropertiesDialog } from './PropertiesDialog.js';
29
+ import { newPropertiesBlock, propertiesBlockAt, setProperties } from './properties.js';
30
+ import { readProperties } from '../properties.js';
31
+ import { contentsBlockAt, newContentsBlock, setContents } from './contents.js';
27
32
  import { setStyleOptions, styleBlockAt, wrapInStyle } from './style.js';
28
33
  import { ContextMenu } from './ContextMenu.js';
29
34
  import { chooseLanguageAt } from './LanguageControl.js';
@@ -135,14 +140,14 @@ function attachSays(attaching, words) {
135
140
  return attaching.queued > 0 ? `${step} (${words.attachQueued(attaching.queued)})` : step;
136
141
  }
137
142
  /** The toolbar of the editor: the marks, the blocks and the history, each a command. */
138
- function Toolbar({ view, host, end, opened, onAttach, onStyle, attaching, attachButton, }) {
143
+ function Toolbar({ view, host, end, opened, onAttach, onStyle, onContents, onProperties, attaching, attachButton, }) {
139
144
  const words = host.strings.editor;
140
145
  const disabled = !view || view.state.readOnly;
141
146
  const run = (action) => () => view && action(view);
142
147
  const button = (name, action, shortcut) => (_jsx("button", { type: "button", className: "edit-control", title: shortcut ? `${words[name]} (${shortcut})` : words[name], "aria-label": words[name], disabled: disabled, onMouseDown: (event) => event.preventDefault(), onClick: run(action), children: ICONS[name] }, name));
143
148
  const block = (name) => button(name, insertBlockCommand(name));
144
149
  const level = view ? headingLevel(view.state) : 0;
145
- return (_jsxs("div", { className: "edit-toolbar", role: "toolbar", "aria-label": words.toolbar, children: [_jsxs("div", { className: "edit-toolbar-tools", children: [_jsxs("span", { className: "edit-toolbar-group", children: [_jsx("button", { type: "button", className: "edit-control", title: words.revert, "aria-label": words.revert, disabled: !view || view.state.readOnly || view.state.doc.toString() === opened, onMouseDown: (event) => event.preventDefault(), onClick: run(command((state) => revert(state, opened))), children: ICONS.revert }), button('undo', undo, 'Mod-Z'), button('redo', redo, 'Mod-Shift-Z, Mod-Y')] }), _jsx("span", { className: "edit-toolbar-group", children: _jsxs("select", { className: "edit-heading", "aria-label": words.heading, title: words.heading, value: level, disabled: disabled, onChange: (event) => view && command((state) => setHeading(state, Number(event.target.value)))(view), children: [_jsx("option", { value: 0, children: words.paragraph }), [1, 2, 3, 4, 5, 6].map((each) => (_jsx("option", { value: each, children: `${words.heading} ${each}` }, each)))] }) }), _jsxs("span", { className: "edit-toolbar-group", children: [button('bold', command((state) => toggleMark(state, '**')), 'Mod-B'), button('italic', command((state) => toggleMark(state, '_')), 'Mod-I'), button('strikethrough', command((state) => toggleMark(state, '~~')), 'Mod-Shift-X'), button('highlight', command((state) => toggleMark(state, '==')), 'Mod-Shift-H'), button('code', command((state) => toggleMark(state, '`')), 'Mod-E')] }), _jsxs("span", { className: "edit-toolbar-group", children: [button('link', command(insertLink), 'Mod-K'), button('wikilink', command(insertWikilink), 'Mod-Shift-K'), button('footnote', command(insertFootnote)), button('comment', command(toggleComment), 'Mod-/'), _jsxs("span", { className: "edit-attach-control", children: [_jsx("button", { ref: attachButton, type: "button", className: "edit-control", title: attachSays(attaching, words), "aria-label": words.attach, "aria-busy": attaching.state === 'busy' ? true : undefined, "data-attach": attaching.state, disabled: disabled, onMouseDown: (event) => event.preventDefault(), onClick: onAttach, children: attaching.state === 'busy' ? ICONS.saving : attaching.state === 'failed' ? ICONS.notSaved : ICONS.attach }), attaching.state === 'busy' && attaching.fraction !== null && (_jsx("span", { className: "edit-attach-progress", role: "progressbar", "aria-label": words.attach, "aria-valuemin": 0, "aria-valuemax": 100, "aria-valuenow": Math.round(attaching.fraction * 100), style: { ['--edit-attach-fraction']: attaching.fraction } })), _jsx("span", { className: "visually-hidden", role: "status", "aria-live": "polite", children: attaching.state === 'idle' ? '' : attachSays(attaching, words) })] })] }), _jsxs("span", { className: "edit-toolbar-group", children: [button('bulletList', command((state) => toggleList(state, 'bullet')), 'Mod-Shift-8'), button('orderedList', command((state) => toggleList(state, 'ordered')), 'Mod-Shift-7'), button('taskList', command((state) => toggleList(state, 'task')), 'Mod-Shift-9'), button('quote', command(toggleQuote), 'Mod-Shift-.')] }), _jsxs("span", { className: "edit-toolbar-group", children: [block('callout'), block('table'), block('codeBlock'), block('math'), block('diagram'), block('rule'), _jsx("button", { type: "button", className: "edit-control", title: words.style, "aria-label": words.style, "aria-haspopup": "dialog", disabled: disabled, onMouseDown: (event) => event.preventDefault(), onClick: onStyle, children: ICONS.style })] })] }), end] }));
150
+ return (_jsxs("div", { className: "edit-toolbar", role: "toolbar", "aria-label": words.toolbar, children: [_jsxs("div", { className: "edit-toolbar-tools", children: [_jsxs("span", { className: "edit-toolbar-group", children: [_jsx("button", { type: "button", className: "edit-control", title: words.revert, "aria-label": words.revert, disabled: !view || view.state.readOnly || view.state.doc.toString() === opened, onMouseDown: (event) => event.preventDefault(), onClick: run(command((state) => revert(state, opened))), children: ICONS.revert }), button('undo', undo, 'Mod-Z'), button('redo', redo, 'Mod-Shift-Z, Mod-Y')] }), _jsx("span", { className: "edit-toolbar-group", children: _jsxs("select", { className: "edit-heading", "aria-label": words.heading, title: words.heading, value: level, disabled: disabled, onChange: (event) => view && command((state) => setHeading(state, Number(event.target.value)))(view), children: [_jsx("option", { value: 0, children: words.paragraph }), [1, 2, 3, 4, 5, 6].map((each) => (_jsx("option", { value: each, children: `${words.heading} ${each}` }, each)))] }) }), _jsxs("span", { className: "edit-toolbar-group", children: [button('bold', command((state) => toggleMark(state, '**')), 'Mod-B'), button('italic', command((state) => toggleMark(state, '_')), 'Mod-I'), button('strikethrough', command((state) => toggleMark(state, '~~')), 'Mod-Shift-X'), button('highlight', command((state) => toggleMark(state, '==')), 'Mod-Shift-H'), button('code', command((state) => toggleMark(state, '`')), 'Mod-E')] }), _jsxs("span", { className: "edit-toolbar-group", children: [button('link', command(insertLink), 'Mod-K'), button('wikilink', command(insertWikilink), 'Mod-Shift-K'), button('footnote', command(insertFootnote)), button('comment', command(toggleComment), 'Mod-/'), _jsxs("span", { className: "edit-attach-control", children: [_jsx("button", { ref: attachButton, type: "button", className: "edit-control", title: attachSays(attaching, words), "aria-label": words.attach, "aria-busy": attaching.state === 'busy' ? true : undefined, "data-attach": attaching.state, disabled: disabled, onMouseDown: (event) => event.preventDefault(), onClick: onAttach, children: attaching.state === 'busy' ? ICONS.saving : attaching.state === 'failed' ? ICONS.notSaved : ICONS.attach }), attaching.state === 'busy' && attaching.fraction !== null && (_jsx("span", { className: "edit-attach-progress", role: "progressbar", "aria-label": words.attach, "aria-valuemin": 0, "aria-valuemax": 100, "aria-valuenow": Math.round(attaching.fraction * 100), style: { ['--edit-attach-fraction']: attaching.fraction } })), _jsx("span", { className: "visually-hidden", role: "status", "aria-live": "polite", children: attaching.state === 'idle' ? '' : attachSays(attaching, words) })] })] }), _jsxs("span", { className: "edit-toolbar-group", children: [button('bulletList', command((state) => toggleList(state, 'bullet')), 'Mod-Shift-8'), button('orderedList', command((state) => toggleList(state, 'ordered')), 'Mod-Shift-7'), button('taskList', command((state) => toggleList(state, 'task')), 'Mod-Shift-9'), button('quote', command(toggleQuote), 'Mod-Shift-.')] }), _jsxs("span", { className: "edit-toolbar-group", children: [block('callout'), block('table'), block('codeBlock'), block('math'), block('diagram'), block('rule'), _jsx("button", { type: "button", className: "edit-control", title: words.style, "aria-label": words.style, "aria-haspopup": "dialog", disabled: disabled, onMouseDown: (event) => event.preventDefault(), onClick: onStyle, children: ICONS.style }), _jsx("button", { type: "button", className: "edit-control", title: words.contents, "aria-label": words.contents, "aria-haspopup": "dialog", disabled: disabled, onMouseDown: (event) => event.preventDefault(), onClick: onContents, children: ICONS.contents }), _jsx("button", { type: "button", className: "edit-control", title: words.propertiesBlock, "aria-label": words.propertiesBlock, "aria-haspopup": "dialog", disabled: disabled, onMouseDown: (event) => event.preventDefault(), onClick: onProperties, children: ICONS.propertiesBlock })] })] }), end] }));
146
151
  }
147
152
  /**
148
153
  * Where the save of the author's last change stands, in the toolbar before the switch: an icon for
@@ -295,6 +300,51 @@ export function NoteEditor({ markdown: given, onChange, editable = true, corner,
295
300
  const wrapped = wrapInStyle(text, selection.from, selection.to, style);
296
301
  current.dispatch({ changes: wrapped.changes, selection: { anchor: wrapped.cursor }, userEvent: 'input.style', scrollIntoView: true });
297
302
  };
303
+ /** The form of a contents block, open over what it sets now and whether it changes a block (#173). */
304
+ const [contentsForm, setContentsForm] = useState(null);
305
+ const openContents = () => {
306
+ const current = editorView.current;
307
+ if (!current)
308
+ return;
309
+ const block = contentsBlockAt(current.state.doc.toString(), current.state.selection.main.head);
310
+ setContentsForm({ initial: block?.settings ?? {}, editing: block !== null && block.content !== null });
311
+ };
312
+ /** Writes the form's settings: the lines of the block the cursor is in, or a new block at the cursor. */
313
+ const applyContents = (settings) => {
314
+ const current = editorView.current;
315
+ if (!current)
316
+ return;
317
+ const block = contentsBlockAt(current.state.doc.toString(), current.state.selection.main.head);
318
+ if (block && block.content) {
319
+ current.dispatch({ changes: setContents(block, settings), userEvent: 'input.contents', scrollIntoView: true });
320
+ return;
321
+ }
322
+ const written = newContentsBlock(settings);
323
+ command((state) => insertBlock(state, written, written.length + 1))(current);
324
+ };
325
+ /** The form of a properties block, open over what it sets now and the note's keys (#172). */
326
+ const [propertiesForm, setPropertiesForm] = useState(null);
327
+ const openProperties = () => {
328
+ const current = editorView.current;
329
+ if (!current)
330
+ return;
331
+ const text = current.state.doc.toString();
332
+ const block = propertiesBlockAt(text, current.state.selection.main.head);
333
+ const keys = readProperties(text).entries.map((entry) => entry.key);
334
+ setPropertiesForm({ initial: block?.settings ?? {}, editing: block !== null && block.content !== null, keys });
335
+ };
336
+ const applyProperties = (settings) => {
337
+ const current = editorView.current;
338
+ if (!current)
339
+ return;
340
+ const block = propertiesBlockAt(current.state.doc.toString(), current.state.selection.main.head);
341
+ if (block && block.content) {
342
+ current.dispatch({ changes: setProperties(block, settings), userEvent: 'input.properties', scrollIntoView: true });
343
+ return;
344
+ }
345
+ const written = newPropertiesBlock(settings);
346
+ command((state) => insertBlock(state, written, written.length + 1))(current);
347
+ };
298
348
  /** Where the editing menu is open, in the window's coordinates (#81). */
299
349
  const [menu, setMenu] = useState(null);
300
350
  const openMenu = useRef((x, y) => setMenu({ x, y }));
@@ -341,6 +391,8 @@ export function NoteEditor({ markdown: given, onChange, editable = true, corner,
341
391
  block('diagram'),
342
392
  block('rule'),
343
393
  { name: 'style', label: words.style, icon: ICONS.style, run: openStyle },
394
+ { name: 'contents', label: words.contents, icon: ICONS.contents, run: openContents },
395
+ { name: 'propertiesBlock', label: words.propertiesBlock, icon: ICONS.propertiesBlock, run: openProperties },
344
396
  item('footnote', command(insertFootnote)),
345
397
  item('comment', command(toggleComment), 'Mod-/'),
346
398
  { name: 'attach', label: words.attach, icon: ICONS.attach, run: () => setAttachOpen(true) },
@@ -576,9 +628,9 @@ export function NoteEditor({ markdown: given, onChange, editable = true, corner,
576
628
  else
577
629
  setRefusal(null);
578
630
  setAttachOpen(true);
579
- }, onStyle: openStyle, attaching: attaching, attachButton: attachButton, end: _jsxs("div", { className: "edit-corner", "aria-busy": leaving && saves.state === 'saving' ? true : undefined, "data-blocked": blocked ? '' : undefined, children: [_jsx(SaveStatus, { saves: saves, blocked: blocked, deciding: deciding, open: noticeOpen, setOpen: setNoticeOpen, host: resolved, onDecided: () => view?.focus() }), corner ?? _jsx(NoteActions, { display: buttons, text: () => (view ? output(view.state) : given) })] }, blocked ? `blocked-${refusals}` : 'corner') }) }), menu && view && (_jsx(ContextMenu, { x: menu.x, y: menu.y, label: resolved.strings.editor.menu, groups: menuGroups(view), onClose: (back) => {
631
+ }, onStyle: openStyle, onContents: openContents, onProperties: openProperties, attaching: attaching, attachButton: attachButton, end: _jsxs("div", { className: "edit-corner", "aria-busy": leaving && saves.state === 'saving' ? true : undefined, "data-blocked": blocked ? '' : undefined, children: [_jsx(SaveStatus, { saves: saves, blocked: blocked, deciding: deciding, open: noticeOpen, setOpen: setNoticeOpen, host: resolved, onDecided: () => view?.focus() }), corner ?? _jsx(NoteActions, { display: buttons, text: () => (view ? output(view.state) : given) })] }, blocked ? `blocked-${refusals}` : 'corner') }) }), menu && view && (_jsx(ContextMenu, { x: menu.x, y: menu.y, label: resolved.strings.editor.menu, groups: menuGroups(view), onClose: (back) => {
580
632
  setMenu(null);
581
633
  if (back)
582
634
  view.focus();
583
- } })), attachOpen && (_jsx(AttachDialog, { refusal: refusal, onClose: () => setAttachOpen(false), onClosed: (inserted) => !inserted && attachButton.current?.focus(), onAttach: (files) => attachFiles.current(files), onEmbed: (name) => insertLine(`![[${name}]]`), onLink: (name, address) => insertLine(webImage(name, address)) })), styling && (_jsx(StyleDialog, { initial: styling.initial, editing: styling.editing, onApply: applyStyle, onClose: () => setStyling(null), onClosed: () => editorView.current?.focus() })), lineBreak === null && _jsx("p", { className: "edit-unavailable", children: resolved.strings.editUnavailable }), _jsx("div", { ref: parent, className: "markdown-editor" })] }) }));
635
+ } })), attachOpen && (_jsx(AttachDialog, { refusal: refusal, onClose: () => setAttachOpen(false), onClosed: (inserted) => !inserted && attachButton.current?.focus(), onAttach: (files) => attachFiles.current(files), onEmbed: (name) => insertLine(`![[${name}]]`), onLink: (name, address) => insertLine(webImage(name, address)) })), styling && (_jsx(StyleDialog, { initial: styling.initial, editing: styling.editing, onApply: applyStyle, onClose: () => setStyling(null), onClosed: () => editorView.current?.focus() })), contentsForm && (_jsx(ContentsDialog, { initial: contentsForm.initial, editing: contentsForm.editing, onApply: applyContents, onClose: () => setContentsForm(null), onClosed: () => editorView.current?.focus() })), propertiesForm && (_jsx(PropertiesDialog, { initial: propertiesForm.initial, noteKeys: propertiesForm.keys, editing: propertiesForm.editing, onApply: applyProperties, onClose: () => setPropertiesForm(null), onClosed: () => editorView.current?.focus() })), lineBreak === null && _jsx("p", { className: "edit-unavailable", children: resolved.strings.editUnavailable }), _jsx("div", { ref: parent, className: "markdown-editor" })] }) }));
584
636
  }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * The form of a `properties` block (`SPEC.md` §7.18, #172): which of the note's keys it draws and in
3
+ * which order, its title, whether it starts folded, where it is drawn, and what the screen and print
4
+ * draw — the same, nothing, or their own. A field left at the notebook's writes nothing. It inserts a
5
+ * block at the cursor, or changes the block the cursor is in; the editor writes the bytes.
6
+ */
7
+ import { type ContentsMedium, type ContentsPlace } from '../contents.js';
8
+ import type { PropertiesSettings } from '../properties-block.js';
9
+ interface LayerFields {
10
+ /** Every key on offer, in the order the block draws them, each chosen or not. */
11
+ keys: {
12
+ key: string;
13
+ chosen: boolean;
14
+ }[];
15
+ /** Whether the block names its keys at all, rather than drawing every one. */
16
+ some: boolean;
17
+ title: string;
18
+ fold: '' | 'open' | 'closed';
19
+ place: '' | ContentsPlace;
20
+ }
21
+ type MediumMode = 'same' | 'none' | 'own';
22
+ interface Fields {
23
+ root: LayerFields;
24
+ media: Record<ContentsMedium, {
25
+ mode: MediumMode;
26
+ layer: LayerFields;
27
+ }>;
28
+ }
29
+ /** The form's fields, from what a block sets and the keys the note has. */
30
+ export declare function propertiesFields(settings: PropertiesSettings, noteKeys: readonly string[]): Fields;
31
+ /** The settings the form's fields write. */
32
+ export declare function propertiesSettings(fields: Fields): PropertiesSettings;
33
+ export declare function PropertiesDialog({ initial, noteKeys, editing, onApply, onClose, onClosed, }: {
34
+ initial: PropertiesSettings;
35
+ /** The keys of the note's frontmatter, in the order written. */
36
+ noteKeys: readonly string[];
37
+ editing: boolean;
38
+ onApply: (settings: PropertiesSettings) => void;
39
+ onClose: () => void;
40
+ onClosed: (applied: boolean) => void;
41
+ }): import("react").JSX.Element;
42
+ export {};