@mathzetta/inlinemath 0.1.0 → 0.3.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 (57) hide show
  1. package/README.md +98 -50
  2. package/dist/cas.external.js +2 -2
  3. package/dist/cas.js +2 -2
  4. package/dist/chunks/calculate-BGMEvf3f.js +2 -0
  5. package/dist/chunks/draw-q86mDDWm.js +2 -0
  6. package/dist/chunks/edit-CTMRUElt.js +2 -0
  7. package/dist/chunks/edit-D2RO7fg0.js +2 -0
  8. package/dist/chunks/html-1wCO6EpZ.js +2 -0
  9. package/dist/chunks/html-D5QiXGXD.js +2 -0
  10. package/dist/chunks/lite-Bo8THzyq.js +2 -0
  11. package/dist/fonts/README-inlinemath-greek.txt +15 -0
  12. package/dist/fonts/fonts.css +19 -1
  13. package/dist/fonts/inlinemath-greek-italic.woff2 +0 -0
  14. package/dist/fonts/inlinemath-greek-regular.woff2 +0 -0
  15. package/dist/inlinemath-cas.external.global.min.js +2 -2
  16. package/dist/inlinemath-cas.global.min.js +2 -2
  17. package/dist/inlinemath-lite-calc.global.min.js +2 -2
  18. package/dist/inlinemath-lite.external.global.min.js +2 -2
  19. package/dist/inlinemath-lite.global.min.js +2 -2
  20. package/dist/inlinemath.css +48 -7
  21. package/dist/inlinemath.external.global.min.js +2 -2
  22. package/dist/inlinemath.external.js +2 -2
  23. package/dist/inlinemath.global.min.js +2 -2
  24. package/dist/inlinemath.js +2 -2
  25. package/dist/lite-calc.js +2 -2
  26. package/dist/lite.external.js +2 -2
  27. package/dist/lite.js +2 -2
  28. package/dist/markdown.external.js +2 -2
  29. package/dist/markdown.js +2 -2
  30. package/fonts/README-inlinemath-greek.txt +15 -0
  31. package/fonts/fonts.css +19 -1
  32. package/fonts/inlinemath-greek-italic.woff2 +0 -0
  33. package/fonts/inlinemath-greek-regular.woff2 +0 -0
  34. package/inlinemath.css +48 -7
  35. package/package.json +6 -6
  36. package/src/cas.d.ts +1 -1
  37. package/src/cas.js +38 -17
  38. package/src/draw.js +13 -9
  39. package/src/edit.js +103 -0
  40. package/src/glyphs.js +2 -0
  41. package/src/html.js +1 -1
  42. package/src/index.d.ts +2 -2
  43. package/src/index.js +2 -2
  44. package/src/layout.js +142 -41
  45. package/src/lite.js +1 -1
  46. package/src/markdown.d.ts +3 -3
  47. package/src/markdown.js +476 -79
  48. package/src/mathzetta.js +3 -2
  49. package/src/select.js +7 -0
  50. package/src/types.d.ts +86 -13
  51. package/src/variables.js +262 -0
  52. package/src/view.js +286 -15
  53. package/dist/chunks/calculate-BX9lJ7Ff.js +0 -2
  54. package/dist/chunks/draw-Cm4exbg7.js +0 -2
  55. package/dist/chunks/html-CvuSyhzk.js +0 -2
  56. package/dist/chunks/html-DWtfytjA.js +0 -2
  57. package/dist/chunks/lite-Bj_L6w2g.js +0 -2
package/src/mathzetta.js CHANGED
@@ -9,9 +9,10 @@
9
9
  */
10
10
 
11
11
  export {
12
- parse, parseTree, fromPostfix, toPostfix, asTree, walk, firstVariable,
12
+ parse, parseTree, fromPostfix, toPostfix, walk, firstVariable,
13
13
  operator, precedenceOf, isCustomFunction, VARIADIC,
14
14
  GREEK, needsBrackets, unaryNeedsBrackets, isMinusOneTimes, isImplicitProduct, isVariable,
15
15
  firstLeaf, customName, derivativeOrder, bracketedSides, bracketOp,
16
+ MATRICES, matrixRows,
16
17
  } from 'mathzetta';
17
- export { toSpeech, toSpeechSegments } from 'mathzetta/speech';
18
+ export { toSpeechSegments, toAudioSpeech } from 'mathzetta/speech';
package/src/select.js CHANGED
@@ -17,6 +17,13 @@
17
17
 
18
18
  import { parseTree, toPostfix, walk, operator, VARIADIC } from './mathzetta.js';
19
19
 
20
+ /** A tree with its ids (and where-it-came-from marks) dropped, so it can be numbered again inside another. */
21
+ export function bare(node) {
22
+ const { id, from, ...rest } = node;
23
+ if (rest.args) rest.args = rest.args.map(bare);
24
+ return rest;
25
+ }
26
+
20
27
  /** A subtree's postfix as one string: two parts look the same exactly when these match. */
21
28
  export const signature = (node) => toPostfix(node).join(' ');
22
29
 
package/src/types.d.ts CHANGED
@@ -9,7 +9,7 @@ export type { Input, Node, BlockHandler };
9
9
  * input ('x^2': every part that is x²), a path ({ path: [0, 1] }, as @mathzetta/cas reports it), a test,
10
10
  * or a list of any of these.
11
11
  */
12
- export type Target = number | string | { path: number[] } | ((node: Node) => boolean) | Target[];
12
+ export type Target = number | string | Node | { path: number[] } | ((node: Node, parent?: Node | null) => boolean) | Target[];
13
13
 
14
14
  export interface LayoutOptions {
15
15
  /** CSS class prefix (default 'mv'). */
@@ -30,6 +30,9 @@ export interface LayoutOptions {
30
30
  cases?: boolean;
31
31
  /** The accessible name: true = the spoken form, a string, a function of the tree, or false for none. */
32
32
  label?: boolean | string | ((tree: Node) => string);
33
+ /** MathZetta's toMathML (from 'mathzetta/mathml'): also write the expression as visually hidden MathML, which
34
+ * screen readers can step through and show in math braille; it takes the place of the label. Off by default. */
35
+ mathml?: ((input: Node) => string) | null;
33
36
  /** Extra attributes for a node's element. */
34
37
  attributes?: ((node: Node) => Record<string, string>) | null;
35
38
  /** Inline style for a node's element. */
@@ -37,7 +40,7 @@ export interface LayoutOptions {
37
40
  }
38
41
 
39
42
  export interface DrawOptions extends LayoutOptions {
40
- /** Colours by target: { 'x^2': 'red', 3: '#06c' } or [[target, colour], …]. */
43
+ /** Colors by target: { 'x^2': 'red', 3: '#06c' } or [[target, color], …]. */
41
44
  colors?: Record<string | number, string> | Array<[Target, string]>;
42
45
  /** Parts to mark with the `<prefix>-hl` class. */
43
46
  highlight?: Target;
@@ -47,6 +50,13 @@ export interface DrawOptions extends LayoutOptions {
47
50
  blocks?: BlockHandler;
48
51
  }
49
52
 
53
+ /** Options for a live view: everything toHTML takes, plus how steps reach a screen reader. */
54
+ export interface ViewOptions extends DrawOptions {
55
+ /** Read each new step (every set() after the first) to a screen reader: true places a polite live
56
+ * region after the element; or pass your own live-region element. Off by default. */
57
+ announce?: boolean | Element;
58
+ }
59
+
50
60
  export const DEFAULTS: Required<LayoutOptions>;
51
61
 
52
62
  /** Anything MathZetta reads, as HTML (a string; works in Node). Needs inlinemath.css on the page. */
@@ -69,27 +79,51 @@ export const PATHS: Record<string, { fill?: string; stroke?: string }>;
69
79
 
70
80
  export interface ClickInfo { node: Node; id: number; path: number[] | null; element: Element; event: Event }
71
81
 
72
- /** A live drawing: highlight, colour, listen, step with animation. */
82
+ /** A live drawing: highlight, color, listen, step with animation. */
73
83
  export class View {
74
- constructor(element: Element, input: Input, options?: DrawOptions);
84
+ constructor(element: Element, input: Input, options?: ViewOptions);
75
85
  readonly element: Element;
76
86
  readonly tree: Node;
77
- /** Show a new expression; with animate, matching parts glide over and new ones fade in. */
78
- set(input: Input, options?: { animate?: boolean; duration?: number; easing?: string }): this;
87
+ /** Show a new expression; with animate, matching parts glide over and new ones fade in. `true` is instant
88
+ * when the reader's system asks for reduced motion; `'always'` animates regardless. */
89
+ set(input: Input, options?: { animate?: boolean | 'always'; duration?: number; easing?: string }): this;
90
+ /** The expression as a listener hears it (its accessible name, else MathZetta's audio speech). */
91
+ spoken(): string;
92
+ /** Say something through the live region ({ announce } must be set); steps are announced this way. */
93
+ announce(text: string): this;
79
94
  nodes(target: Target): Node[];
80
95
  elements(target: Target): Element[];
81
96
  elementOf(node: Node): Element | null;
82
97
  highlight(target: Target, className?: string): this;
83
98
  unhighlight(target?: Target | null, className?: string): this;
84
- color(target: Target, colour: string): this;
85
- /** Listen for an event on a part; returns a function that stops listening. */
99
+ color(target: Target, color: string): this;
100
+ /** Listen for an event on the parts; returns a function that stops listening. A 'click' listener also makes the drawing work from the keyboard:
101
+ * one tab stop, arrow keys walk the parts (each spoken), Enter or Space calls the listener for the
102
+ * current part — `event` is then the KeyboardEvent. */
86
103
  on(type: string, fn: (info: ClickInfo) => void): () => void;
104
+ /**
105
+ * Let the reader edit a part at a time: double-click it (or F2 on the keyboard's part) and a
106
+ * text box opens over it; Enter puts the new text in its place, Escape leaves it.
107
+ * toText is MathZetta's (import { toText } from 'mathzetta/text'; InlineMath.toText in the <script> build).
108
+ */
109
+ editable(how: { toText: (input: Input) => string; onEdit?: (change: { tree: Node; text: string; path: number[]; part: string }) => void }): this;
110
+ /** Open the editing box over a part (editable() first). */
111
+ edit(target?: unknown, options?: { returnFocus?: boolean }): HTMLInputElement | null;
112
+ /** The part the arrow keys are on (null: the whole expression). */
113
+ readonly active: Node | null;
114
+ /** Put the keyboard on a part (null: the whole expression) and say it. */
115
+ focusPart(node: Node | null): this;
87
116
  /** The expression read aloud in pieces, each tagged with the node it describes. */
88
117
  segments(options?: SpeechOptions): { text: string; id?: number }[];
89
118
  showSegment(segment: { id?: number } | null, className?: string): this;
119
+ /** Stop listening (on() handlers, keys, double-click editing), close an open editor and remove the live
120
+ * regions this view added; the drawing stays. */
121
+ destroy(): this;
90
122
  }
91
123
  /** Draw into an element and return the live view. */
92
- export function render(element: Element, input: Input, options?: DrawOptions): View;
124
+ export function render(element: Element, input: Input, options?: ViewOptions): View;
125
+ /** Should a step animate: true honors prefers-reduced-motion, 'always' does not, false never. */
126
+ export function shouldAnimate(animate?: boolean | 'always'): boolean;
93
127
 
94
128
  // ---- inlinemath/markdown --------------------------------------------------------------------
95
129
 
@@ -104,14 +138,52 @@ export interface MarkdownOptions {
104
138
  define?: boolean;
105
139
  /** Let raw HTML through (default false: it is shown as text). */
106
140
  html?: boolean;
107
- /** Another Markdown renderer; the maths is taken out first and put back into its output. */
141
+ /** Another Markdown renderer; the math is taken out first and put back into its output. */
108
142
  render?: (markdown: string) => string;
109
- /** Which of '$$', '$', '\\[', '\\(' mark maths (default all). */
143
+ /** Which of '$$', '$', '\\[', '\\(' mark math (default all). */
110
144
  delimiters?: string[];
145
+ /**
146
+ * The saved variables ($A := 2+2$) the math may use. markdownToHTML: none by default;
147
+ * renderMarkdownInto: the page's `variables` by default, false for none.
148
+ */
149
+ variables?: Variables | false | null;
150
+ /**
151
+ * renderMarkdownInto: double-clicking a part drawn from a textbox variable edits it in place
152
+ * (toText from 'mathzetta/text'); without it the textbox is focused. Any other part fires
153
+ * 'inlinemath:select' (detail { index, start, end, raw, source, id, path }) on the element.
154
+ */
155
+ editable?: { toText: (input: Input) => string };
156
+ }
157
+ /** What a saved variable is: its expression, or the input that sets it. */
158
+ export interface VariableDefinition {
159
+ name: string;
160
+ text: string;
161
+ input: null | { kind: 'textbox'; default: string } | { kind: 'dropdown'; options: string[]; default: string } | { kind: 'slider'; min: number; max: number; step: number; default: string };
162
+ key: string;
163
+ }
164
+ /** A page's saved variables: every part drawn with renderMarkdownInto sees the others'. */
165
+ export class Variables {
166
+ /** A variable's expression now (what its input holds, for an input), or undefined. */
167
+ get(name: string): string | undefined;
168
+ /** Set a variable: what its input holds, or (with no input) a definition for the whole page. */
169
+ set(name: string, text: string | number): this;
170
+ /** Forget a variable set with set(), or everything. */
171
+ clear(name?: string): this;
172
+ /** The saved names. */
173
+ names(): string[];
174
+ /** Called whenever a variable changes; returns a function that stops it. */
175
+ subscribe(fn: (owner: unknown, name?: string) => void): () => void;
176
+ definitions(except?: unknown): Map<string, VariableDefinition>;
177
+ textOf(def: VariableDefinition): string;
178
+ own(owner: unknown, defs: Map<string, VariableDefinition> | null): void;
111
179
  }
180
+ /** A store of its own, for parts of a page that shouldn't share variables. */
181
+ export function createVariables(): Variables;
182
+ /** The page's store, renderMarkdownInto's default. */
183
+ export const variables: Variables;
112
184
  export function markdownToHTML(markdown: string, options?: MarkdownOptions): string;
113
185
  export function renderMarkdownInto<E extends Element>(element: E, markdown: string, options?: MarkdownOptions): E;
114
- export function extractMath(markdown: string, options?: { delimiters?: string[] }): { text: string; math: Array<{ source: string; display: boolean; raw: string }> };
186
+ export function extractMath(markdown: string, options?: { delimiters?: string[] }): { text: string; math: Array<{ source: string; display: boolean; raw: string; start: number; end: number }> };
115
187
  export function renderMarkdown(markdown: string, options?: MarkdownOptions): string;
116
188
 
117
189
  // ---- inlinemath/cas (needs @mathzetta/cas) --------------------------------------------------------
@@ -122,7 +194,8 @@ export interface CASStep { id: string; name: string; from: string; to: string; p
122
194
  export type CAS = Record<string, any>;
123
195
  export function mathCAS(options?: { rules?: unknown[]; names?: string[]; complex?: boolean; [option: string]: unknown }): CAS;
124
196
  /** A `{{…}}` handler: toHTML(input, { blocks: casBlocks() }). `last` holds the latest CAS result. */
125
- export function casBlocks(options?: { cas?: CAS }): BlockHandler & { last?: unknown };
197
+ /** steps: how much working each call keeps (true: every step, 'brief': the ones that carry the idea, false: none). */
198
+ export function casBlocks(options?: { cas?: CAS; steps?: boolean | 'brief' | Record<string, unknown> }): BlockHandler & { last?: { steps?: CASStep[]; text?: string; [k: string]: unknown } };
126
199
  /** Steps as an ordered list, each rewrite highlighted, with its explanation. */
127
200
  export function stepsHTML(steps: CASStep[], options?: DrawOptions): string;
128
201
  /** A CAS node → MathZetta postfix tokens. */
@@ -0,0 +1,262 @@
1
+ /**
2
+ * Saved variables for '@mathzetta/inlinemath/markdown': `$A := 2+2$` saves A, and A in any math
3
+ * after it is drawn as 2 + 2 (and `{{A}}` is 4). A store holds them for a whole page, so every
4
+ * part drawn with renderMarkdownInto sees the others' variables, and an input bound to a variable
5
+ * (`$A := [[2+2]]$`, a textbox) redraws everything that uses it.
6
+ *
7
+ * import { createVariables, variables } from '@mathzetta/inlinemath/markdown';
8
+ * variables.set('A', 'x^2'); // the page's store: A is x² everywhere
9
+ * variables.get('A'); // 'x^2'
10
+ */
11
+
12
+ /**
13
+ * Where a scope carries the saved variables' expressions, for {{…}} handlers that work with
14
+ * expressions rather than values (casBlocks: {{diff(f, x)}} with f saved): name → MathZetta
15
+ * postfix, every saved name inside already put in. A symbol, so the calculator never sees it.
16
+ */
17
+ export const EXPRESSIONS = Symbol.for('inlinemath.expressions');
18
+
19
+ // ---- names ----------------------------------------------------------------------------------
20
+
21
+ const LEAF = new Set(['symbol', 'number']);
22
+
23
+ /** The variable a node names: A, α, A_1 (a symbol with a plain subscript) — else null. */
24
+ export function nameOf(node) {
25
+ if (!node) return null;
26
+ if (node.type === 'symbol') return node.value;
27
+ if (node.type === 'op' && node.op === '_' && node.args.length === 2 && node.args[0].type === 'symbol' && LEAF.has(node.args[1].type)) {
28
+ return `${node.args[0].value}_${node.args[1].value}`;
29
+ }
30
+ return null;
31
+ }
32
+
33
+ // bare(): ids and where-it-came-from marks dropped; it lives in select.js so edit.js (and with it the
34
+ // main entry, for View.editable) doesn't pull in this store
35
+ import { bare } from './select.js';
36
+ import { firstVariable } from './mathzetta.js';
37
+ export { bare };
38
+
39
+ /** Ids dropped (to be numbered again), `from` marks kept. */
40
+ function renumber(node) {
41
+ const { id, ...rest } = node;
42
+ if (rest.args) rest.args = rest.args.map(renumber);
43
+ return rest;
44
+ }
45
+
46
+ /**
47
+ * The part of a substituted tree a variable stands for, written back in its own terms: the
48
+ * variables inside it put back as their names. `named(name)` gives a name's own tree.
49
+ */
50
+ export function unexpand(node, named) {
51
+ const visit = (n, top) => {
52
+ if (!top && n.from !== undefined) return named(n.from);
53
+ const { id, from, ...rest } = n;
54
+ if (rest.args) rest.args = rest.args.map((a) => visit(a, false));
55
+ return rest;
56
+ };
57
+ return visit(node, true);
58
+ }
59
+
60
+ const NONE = new Set();
61
+
62
+ /**
63
+ * The variable an operation binds, and which of its arguments it is bound in: d/dx (der(f, x)) and
64
+ * ∫ … dx (int(f, x, a, b)) in f and x but not the limits; lim(f, x → a) in f and x; ∑ and ∏
65
+ * (\\sumidx(f, k = 1, n), \\sumidx(f, k ∈ S)) in f and k. Null for anything else.
66
+ */
67
+ function boundBy(node) {
68
+ const [f, second] = node.args;
69
+ const symbol = (n) => (n && n.type === 'symbol' ? n.value : null);
70
+ switch (node.op) {
71
+ case 'der':
72
+ if (second?.op === '=') return symbol(second.args[0]) && { name: symbol(second.args[0]), where: (i) => i === 0, index: 1 }; // der(f, x = a): a takes values
73
+ return symbol(second) && { name: symbol(second), where: (i) => i <= 1 };
74
+ case 'int': {
75
+ const name = symbol(second) ?? (node.args.length === 3 || node.args.length === 1 ? firstVariable(f) || 'x' : null);
76
+ return name && { name, where: (i) => i === 0 || (i === 1 && symbol(second) === name) };
77
+ }
78
+ case 'lim': return second?.op === '→' && symbol(second.args[0]) && { name: symbol(second.args[0]), where: (i) => i === 0, index: 1 };
79
+ case '\\sumidx': case '\\prodidx':
80
+ return (second?.op === '=' || second?.op === '∈') && symbol(second.args[0]) && { name: symbol(second.args[0]), where: (i) => i === 0, index: 1 };
81
+ default: return null;
82
+ }
83
+ }
84
+
85
+ /**
86
+ * Every saved name in a tree replaced by its own tree (which may use other saved names).
87
+ * `lookup(name)` gives a saved name's tree, or null. A name inside its own definition is left as it is.
88
+ * @returns {{ tree: object, changed: boolean }}
89
+ */
90
+ export function substitute(tree, lookup) {
91
+ let changed = false;
92
+ const seen = new Set();
93
+ const visit = (node, bound = NONE) => {
94
+ const name = nameOf(node);
95
+ if (name !== null) {
96
+ if (!seen.has(name) && !bound.has(name)) {
97
+ const value = lookup(name);
98
+ if (value) {
99
+ changed = true;
100
+ seen.add(name);
101
+ const out = { ...visit(bare(value)), from: name }; // where it came from, for editing
102
+ seen.delete(name);
103
+ return out;
104
+ }
105
+ }
106
+ return node; // A_1 is one name: its A is not substituted
107
+ }
108
+ if (node.args) {
109
+ // d/dx, ∫ … dx, lim and ∑ bind their variable: a saved x isn't put into x³ in d/dx x³
110
+ const binds = boundBy(node);
111
+ if (!binds) return { ...node, args: node.args.map((a) => visit(a, bound)) };
112
+ const inside = new Set([...bound, binds.name]);
113
+ return { ...node, args: node.args.map((a, i) => {
114
+ // the index (x → a, k = 1, k ∈ S): its variable is bound, its value isn't
115
+ if (i === binds.index) return { ...a, args: a.args.map((c, j) => visit(c, j === 0 ? inside : bound)) };
116
+ return visit(a, binds.where(i) ? inside : bound);
117
+ }) };
118
+ }
119
+ return node;
120
+ };
121
+ const out = visit(tree);
122
+ return { tree: changed ? renumber(out) : tree, changed };
123
+ }
124
+
125
+ // ---- inputs ---------------------------------------------------------------------------------
126
+
127
+ const NUMBER = '[-+]?(?:\\d+\\.?\\d*|\\.\\d+)';
128
+ const SLIDER = new RegExp(`^(${NUMBER})\\s*\\.\\.\\s*(${NUMBER})(?:\\s+step\\s+(${NUMBER}))?(?:\\s*=\\s*(${NUMBER}))?$`);
129
+
130
+ /**
131
+ * What `[[…]]` asks for: `[[2+2]]` a textbox, `[[2+2 | x^2]]` a dropdown,
132
+ * `[[1..10]]` a slider (`[[0..1 step 0.1 = 0.5]]` with a step and a starting value). Else null.
133
+ */
134
+ export function inputOf(text) {
135
+ const m = /^\s*\[\[([\s\S]*)\]\]\s*$/.exec(text);
136
+ // [[2, 1], [1, 3]] is a matrix (rows of a list), not an input
137
+ if (!m || /\]\s*,\s*\[/.test(m[1])) return null;
138
+ const inner = m[1].trim();
139
+ const range = SLIDER.exec(inner);
140
+ if (range) {
141
+ const min = Number(range[1]);
142
+ const max = Number(range[2]);
143
+ if (!(max > min)) return null;
144
+ const step = range[3] !== undefined ? Number(range[3]) : Number.isInteger(min) && Number.isInteger(max) ? 1 : (max - min) / 100;
145
+ if (!(step > 0)) return null;
146
+ const start = range[4] !== undefined ? Math.min(max, Math.max(min, Number(range[4]))) : min;
147
+ return { kind: 'slider', min, max, step, default: String(start) };
148
+ }
149
+ if (inner.includes('|')) {
150
+ const options = inner.split('|').map((o) => o.trim()).filter(Boolean);
151
+ if (options.length) return { kind: 'dropdown', options, default: options[0] };
152
+ }
153
+ return { kind: 'textbox', default: inner };
154
+ }
155
+
156
+ // ---- the store ------------------------------------------------------------------------------
157
+
158
+ const PAGE = Symbol('set on the page');
159
+
160
+ /**
161
+ * Where a page's variables live. A part of the page owns the definitions it makes (drawing it
162
+ * again replaces them); `set` is how an input — or the page's own code — changes one.
163
+ */
164
+ export class Variables {
165
+ constructor() {
166
+ this.owners = new Map(); // owner → Map(name → definition)
167
+ this.chosen = new Map(); // name → { key, text }: what an input was set to
168
+ this.listeners = new Set();
169
+ }
170
+
171
+ /** Every definition, in the order the parts were drawn; `except` leaves one part out. */
172
+ definitions(except) {
173
+ const all = new Map();
174
+ for (const [owner, defs] of this.owners) {
175
+ if (owner === except) continue;
176
+ for (const [name, def] of defs) {
177
+ all.delete(name); // a later definition goes after the earlier ones
178
+ all.set(name, def);
179
+ }
180
+ }
181
+ return all;
182
+ }
183
+
184
+ /** The text a definition stands for now: its expression, or what its input is set to. */
185
+ textOf(def) {
186
+ const chosen = this.chosen.get(def.name);
187
+ return chosen && chosen.key === def.key ? chosen.text : def.text;
188
+ }
189
+
190
+ /** A variable's expression now, or undefined. */
191
+ get(name) {
192
+ const def = this.definitions().get(name);
193
+ return def ? this.textOf(def) : undefined;
194
+ }
195
+
196
+ /** The saved names. */
197
+ names() {
198
+ return [...this.definitions().keys()];
199
+ }
200
+
201
+ /** Set a variable: what its input holds, or (with no input) a definition for the whole page. */
202
+ set(name, text) {
203
+ text = String(text);
204
+ const def = this.definitions().get(name);
205
+ if (def && def.input) {
206
+ const chosen = this.chosen.get(name);
207
+ if (chosen && chosen.key === def.key && chosen.text === text) return this;
208
+ this.chosen.set(name, { key: def.key, text });
209
+ } else {
210
+ const defs = new Map(this.owners.get(PAGE));
211
+ defs.set(name, { name, text, key: `page:${text}`, input: null });
212
+ this.owners.delete(PAGE);
213
+ this.owners.set(PAGE, defs);
214
+ }
215
+ this.notify(null, name);
216
+ return this;
217
+ }
218
+
219
+ /** Forget a variable set with `set`, or everything (no name). */
220
+ clear(name) {
221
+ if (name === undefined) {
222
+ this.owners.clear();
223
+ this.chosen.clear();
224
+ } else {
225
+ this.owners.get(PAGE)?.delete(name);
226
+ this.chosen.delete(name);
227
+ }
228
+ this.notify(null, name);
229
+ return this;
230
+ }
231
+
232
+ /** Called with (owner, name) when something changes; returns a function that stops it. */
233
+ subscribe(fn) {
234
+ this.listeners.add(fn);
235
+ return () => this.listeners.delete(fn);
236
+ }
237
+
238
+ /** A part's definitions (null: it has none any more). Tells the others only when they change. */
239
+ own(owner, defs) {
240
+ const before = this.owners.get(owner);
241
+ const same = (a, b) => (a?.size ?? 0) === (b?.size ?? 0) && [...(a ?? [])].every(([k, d]) => b?.get(k)?.key === d.key);
242
+ if (same(before, defs)) {
243
+ if (defs) this.owners.set(owner, defs);
244
+ return;
245
+ }
246
+ if (defs && defs.size) this.owners.set(owner, defs);
247
+ else this.owners.delete(owner);
248
+ this.notify(owner);
249
+ }
250
+
251
+ notify(owner, name) {
252
+ for (const fn of [...this.listeners]) fn(owner, name);
253
+ }
254
+ }
255
+
256
+ /** A store of its own, for parts of a page that shouldn't share variables. */
257
+ export function createVariables() {
258
+ return new Variables();
259
+ }
260
+
261
+ /** The page's store: renderMarkdownInto uses it unless told otherwise. */
262
+ export const variables = createVariables();