@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/markdown.js CHANGED
@@ -1,30 +1,43 @@
1
1
  /**
2
- * '@mathzetta/inlinemath/markdown' — Markdown with maths in it.
2
+ * '@mathzetta/inlinemath/markdown' — Markdown with math in it.
3
3
  *
4
4
  * import { markdownToHTML } from '@mathzetta/inlinemath/markdown';
5
5
  * el.innerHTML = markdownToHTML('The area is $\\pi r^2$, so for $r = 3$ it is ${{pi r^2}}$.');
6
6
  *
7
- * Maths: $…$ inline, $$…$$ (or a ```math fence) on its own, \(…\) and \[…\] too.
7
+ * Math: $…$ inline, $$…$$ (or a ```math fence) on its own, \(…\) and \[…\] too.
8
8
  * Each is read by MathZetta (LaTeX, plain text or code all work) and drawn by
9
9
  * Inline Math; {{…}} inside is worked out first (MathZetta's calculator, or the CAS:
10
- * { blocks: casBlocks() } from '@mathzetta/inlinemath/cas'). A definition such as $r = 3$ or
11
- * $g := 9.81$ is remembered for the {{…}} after it ({ define: false } turns that off).
10
+ * { blocks: casBlocks() } from '@mathzetta/inlinemath/cas'). A definition such as $r = 3$ is
11
+ * remembered, as a number, for the {{…}} after it ({ define: false } turns that off).
12
12
  *
13
- * A $ is maths only when it looks like it (Pandoc's rule): the opening $ is not
13
+ * Saved variables: $A := 2+2$ saves A (and draws A ≔ 2 + 2); $_A := 2+2$ saves it without drawing.
14
+ * After it, A in any math is drawn as its expression and {{A}} is its value: $A = {{A}}$ draws
15
+ * 2 + 2 = 4. $A := [[2+2]]$ is a textbox that sets A, [[2+2 | x^2]] a dropdown, [[1..10]] a slider
16
+ * ([[0..1 step 0.1 = 0.5]]). renderMarkdownInto keeps every part of a page in one store
17
+ * (`variables`), so a variable saved in one part is used in the others, and changing an input
18
+ * redraws everything that uses it.
19
+ *
20
+ * A $ is math only when it looks like it (Pandoc's rule): the opening $ is not
14
21
  * followed by a space, the closing $ is not after a space or before a digit, so
15
22
  * "$5 and $10" stays text. \$ is a dollar sign. Code spans and fences are left alone.
16
- * Maths that doesn't read is shown as written, marked, with the reason as its title.
23
+ * Math that doesn't read is shown as written, marked, with the reason as its title.
17
24
  *
18
25
  * The Markdown is a small built-in renderer (headings, emphasis, links, images,
19
26
  * lists, quotes, code, tables, rules). Raw HTML is shown as text unless { html: true }.
20
27
  * { render: (markdown) => html } uses another renderer (marked, markdown-it …):
21
- * the maths is taken out first and put back into its output.
28
+ * the math is taken out first and put back into its output.
22
29
  */
23
30
 
24
- import { toHTML } from './html.js';
31
+ import { toHTML, treeOf } from './html.js';
25
32
  import { calculate } from './calculator.js';
33
+ import { nameOf, bare, substitute, unexpand, inputOf, EXPRESSIONS, variables as pageVariables } from './variables.js';
34
+ import { toPostfix } from './mathzetta.js';
35
+ import { numberTree, select, pathOf, nodeAt } from './select.js';
36
+ import { openEditor, replaceAt } from './edit.js';
37
+
38
+ export { createVariables, variables, Variables } from './variables.js';
26
39
 
27
- // ---- finding the maths --------------------------------------------------------------------
40
+ // ---- finding the math --------------------------------------------------------------------
28
41
 
29
42
  const OPEN = '';
30
43
  const CLOSE = '';
@@ -32,22 +45,31 @@ const placeholder = (n) => `${OPEN}${n}${CLOSE}`;
32
45
  const PLACEHOLDER = new RegExp(`${OPEN}(\\d+)${CLOSE}`, 'g');
33
46
 
34
47
  /**
35
- * The maths in a Markdown text, and the text with each piece replaced by a
48
+ * The math in a Markdown text, and the text with each piece replaced by a
36
49
  * placeholder (private-use characters, which no Markdown renderer touches).
37
- * @returns {{ text: string, math: Array<{ source, display, raw }> }}
50
+ * @returns {{ text: string, math: Array<{ source, display, raw, start, end }> }} (start, end: where the raw text is)
38
51
  */
39
52
  export function extractMath(markdown, { delimiters = ['$$', '$', '\\[', '\\('] } = {}) {
40
53
  const math = [];
41
54
  let out = '';
42
55
  let i = 0;
43
- const s = String(markdown);
56
+ // the private-use characters placeholders are made of: typed ones become U+FFFD (same length, so start and end still fit)
57
+ const s = String(markdown).replace(/[\uE000-\uE003]/g, '\uFFFD');
44
58
  const atLineStart = (k) => k === 0 || s[k - 1] === '\n';
59
+ const code = indentedCode(s); // start → end of each indented code block: math there is code too
60
+ let noCloser = -1; // no $ closes inline math before this index (it doesn't depend on where the math opened)
61
+ const never = new Set(); // \) or \] found nowhere ahead: looked for once, not at every \( that follows
45
62
  const keep = (source, display, raw) => {
46
- math.push({ source, display, raw });
63
+ math.push({ source, display, raw, start: i, end: i + raw.length });
47
64
  return placeholder(math.length - 1);
48
65
  };
49
66
  while (i < s.length) {
50
- // a fenced code block: copied as is, except ```math, which is display maths
67
+ if (code.has(i)) {
68
+ out += s.slice(i, code.get(i));
69
+ i = code.get(i);
70
+ continue;
71
+ }
72
+ // a fenced code block: copied as is, except ```math, which is display math
51
73
  if (atLineStart(i)) {
52
74
  const fence = /^( {0,3})(`{3,}|~{3,})([^\n]*)\n?/.exec(s.slice(i));
53
75
  if (fence) {
@@ -82,7 +104,8 @@ export function extractMath(markdown, { delimiters = ['$$', '$', '\\[', '\\('] }
82
104
  const two = s.slice(i, i + 2);
83
105
  const closer = two === '\\[' ? '\\]' : two === '\\(' ? '\\)' : null;
84
106
  if (closer && delimiters.includes(two)) {
85
- const end = s.indexOf(closer, i + 2);
107
+ const end = never.has(closer) ? -1 : s.indexOf(closer, i + 2);
108
+ if (end < 0) never.add(closer);
86
109
  if (end > -1) {
87
110
  out += keep(s.slice(i + 2, end), two === '\\[', s.slice(i, end + 2));
88
111
  i = end + 2;
@@ -101,13 +124,14 @@ export function extractMath(markdown, { delimiters = ['$$', '$', '\\[', '\\('] }
101
124
  i = end + 2;
102
125
  continue;
103
126
  }
104
- } else if (delimiters.includes('$') && s[i + 1] && !/\s/.test(s[i + 1])) {
105
- const end = closingDollar(s, i + 1);
127
+ } else if (delimiters.includes('$') && s[i + 1] && !/\s/.test(s[i + 1]) && i + 1 >= noCloser) {
128
+ const { end, stop } = closingDollar(s, i + 1);
106
129
  if (end > -1) {
107
130
  out += keep(s.slice(i + 1, end), false, s.slice(i, end + 1));
108
131
  i = end + 1;
109
132
  continue;
110
133
  }
134
+ noCloser = stop; // every $ before `stop` opens nothing either: one scan per paragraph, not per $
111
135
  }
112
136
  }
113
137
  out += c;
@@ -116,46 +140,244 @@ export function extractMath(markdown, { delimiters = ['$$', '$', '\\[', '\\('] }
116
140
  return { text: out, math };
117
141
  }
118
142
 
119
- /** The $ that closes inline maths opened before `from`: not after a space, not before a digit, within the paragraph. */
143
+ /**
144
+ * The $ that closes inline math opened before `from`: not after a space, not before a digit, within the paragraph.
145
+ * @returns {{ end: number, stop: number }} end -1 if none; stop: where the search ended (code, a blank line, the end)
146
+ */
120
147
  function closingDollar(s, from) {
121
148
  for (let j = from; j < s.length; j++) {
122
149
  const c = s[j];
123
150
  if (c === '\\') { j++; continue; }
124
- if (c === '`') return -1; // maths doesn't run into code
125
- if (c === '\n' && /^\n[ \t]*\n/.test(s.slice(j))) return -1;
126
- if (c === '$' && !/\s/.test(s[j - 1]) && !/\d/.test(s[j + 1] ?? '') && s[j + 1] !== '$') return j;
151
+ if (c === '`') return { end: -1, stop: j }; // math doesn't run into code
152
+ if (c === '\n' && /^\n[ \t]*\n/.test(s.slice(j, j + 64))) return { end: -1, stop: j };
153
+ if (c === '$' && !/\s/.test(s[j - 1]) && !/\d/.test(s[j + 1] ?? '') && s[j + 1] !== '$') return { end: j, stop: j };
127
154
  }
128
- return -1;
155
+ return { end: -1, stop: s.length };
129
156
  }
130
157
 
131
- // ---- drawing the maths --------------------------------------------------------------------
158
+ /**
159
+ * Indented code blocks, as the renderer finds them: a line indented four spaces (or a tab) after a blank
160
+ * line or at the start, outside a list, and the indented or blank lines after it. Start → end offsets.
161
+ */
162
+ function indentedCode(s) {
163
+ const blocks = new Map();
164
+ const indented = (line) => /^( {4}|\t)/.test(line);
165
+ let at = 0;
166
+ let prevBlank = true;
167
+ let inList = false;
168
+ let start = -1;
169
+ for (const line of s.split('\n')) {
170
+ const blank = !line.trim();
171
+ if (start > -1 && !(blank || indented(line))) {
172
+ blocks.set(start, at - 1); // up to the newline before this line
173
+ start = -1;
174
+ }
175
+ if (start < 0 && !blank && indented(line) && prevBlank && !inList) start = at;
176
+ if (!blank && !indented(line)) inList = LIST_ITEM.test(line) || (inList && /^\s/.test(line));
177
+ prevBlank = blank;
178
+ at += line.length + 1;
179
+ }
180
+ if (start > -1) blocks.set(start, s.length);
181
+ return blocks;
182
+ }
183
+
184
+ // ---- drawing the math --------------------------------------------------------------------
132
185
 
133
186
  const escape = (t) => String(t).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
134
187
 
135
- /** A definition: r = 3, g := 9.81 (a single name on the left). */
136
- const DEFINITION = /^\s*([A-Za-zͰ-Ͽ](?:_\{?\w+\}?)?)\s*(?::=|=)\s*([^=<>≤≥]+)$/;
137
-
138
- function drawMath(item, options, scope) {
139
- const { source, display } = item;
140
- try {
141
- const html = toHTML(source, { ...options.math, display, blocks: options.blocks, scope });
142
- if (options.define !== false) define(source, scope);
143
- return display ? `<span class="mv-md-display">${html}</span>` : `<span class="mv-md-math">${html}</span>`;
144
- } catch (error) {
145
- return `<span class="mv-md-error" title="${escape(error.message)}"><code>${escape(item.raw)}</code></span>`;
146
- }
188
+ /** A definition: r = 3, g = 9.81 (a single name on the left) — remembered as a number for {{…}}. */
189
+ const DEFINITION = /^\s*([A-Za-z\u0370-\u03ff](?:_\{?\w+\}?)?)\s*=\s*([^=<>≤≥]+)$/;
190
+
191
+ /**
192
+ * Math that saves a variable: `A := 2+2` (drawn), `_A := 2+2` or `_A = 2+2` (not drawn),
193
+ * `A := [[…]]` (an input). Else null; `{ error }` for a `$_…$` that saves nothing.
194
+ */
195
+ function savingOf(source) {
196
+ let s = source.trim();
197
+ const hidden = s.startsWith('_');
198
+ if (hidden) s = s.slice(1).trimStart();
199
+ let at = s.indexOf(':=');
200
+ let width = 2;
201
+ if (at < 0 && hidden) {
202
+ at = s.search(/(?<![<>!≤≥=])=(?!=)/);
203
+ width = 1;
204
+ }
205
+ const nothing = hidden ? { error: 'a hidden $_…$ saves a variable: $_A := 2+2$' } : null;
206
+ if (at <= 0) return nothing;
207
+ const lhs = s.slice(0, at).trim();
208
+ const rhs = s.slice(at + width).trim();
209
+ let name = null;
210
+ try {
211
+ name = /\{\{/.test(lhs) ? null : nameOf(treeOf(lhs));
212
+ } catch {
213
+ // not a name
214
+ }
215
+ if (name === null || !rhs) return nothing;
216
+ return { hidden, lhs, name, rhs, input: inputOf(rhs) };
147
217
  }
148
218
 
149
- /** $r = 3$: remember r (exactly, as the calculator's text) for later {{…}}. */
150
- function define(source, scope) {
151
- const m = DEFINITION.exec(source);
152
- if (!m || /\{\{/.test(m[2])) return;
153
- try {
154
- const r = calculate(m[2], scope);
155
- if (typeof r.value === 'number' || typeof r.value === 'bigint') scope[m[1].replace(/[{}]/g, '')] = r.exact ? r.text : r.value;
156
- } catch {
157
- // not a number (x = y + 1): nothing to remember
158
- }
219
+ /** `A = …` drawn as `A ≔ …`: the first relation is the definition's. */
220
+ function asDefinition(html, prefix = 'mv') {
221
+ return html
222
+ .replace(`<span class="${prefix}-rel">=</span>`, `<span class="${prefix}-rel ${prefix}-rel-def">≔</span>`)
223
+ .replace(/(aria-label="[^"]*?) equals /, '$1 is defined as ')
224
+ .replace('<mo>=</mo>', '<mo>≔</mo>');
225
+ }
226
+
227
+ /** The input a definition's [[…]] asks for, holding `text`. */
228
+ function controlHTML(def, text) {
229
+ const { input, name } = def;
230
+ const attrs = `class="mv-md-input mv-md-${input.kind}" data-mv-var="${escape(name)}" aria-label="${escape(name)}"`;
231
+ if (input.kind === 'dropdown') {
232
+ const options = input.options.map((o) => `<option value="${escape(o)}"${o === text ? ' selected' : ''}>${escape(o)}</option>`);
233
+ return `<select ${attrs}>${options.join('')}</select>`;
234
+ }
235
+ if (input.kind === 'slider') {
236
+ return `<input type="range" ${attrs} min="${input.min}" max="${input.max}" step="${input.step}" value="${escape(text)}">`
237
+ + `<output class="mv-md-output" data-mv-out="${escape(name)}">${escape(text)}</output>`;
238
+ }
239
+ return `<input type="text" ${attrs} value="${escape(text)}" size="${Math.max(4, text.length + 1)}" spellcheck="false" autocomplete="off">`;
240
+ }
241
+
242
+ /**
243
+ * Every piece of math drawn, in reading order: a variable is known to the math after it, and
244
+ * the variables already in `store` (the other parts of the page) to all of it.
245
+ */
246
+ function drawAll(markdown, options, store, owner) {
247
+ const { text, math } = extractMath(markdown, options);
248
+ const defs = store ? store.definitions(owner) : new Map();
249
+ const textOf = (def) => (store ? store.textOf(def) : def.text);
250
+ const numbers = { ...(options.scope ?? {}) }; // options.scope and $r = 3$
251
+ const scope = {}; // what {{…}} sees: those and the saved variables' values
252
+ const mine = new Map();
253
+ const inputs = new Set();
254
+ const trees = []; // each piece's drawn tree, for finding what a double-click landed on
255
+ // the saved variables' values, for {{…}}: worked out until nothing more can be (B := 2A before A := 3)
256
+ const refresh = () => {
257
+ for (const k of Object.keys(scope)) delete scope[k];
258
+ Object.assign(scope, numbers);
259
+ for (const name of defs.keys()) delete scope[name]; // x^2 has no value: {{A}} draws A, drawn as x^2
260
+ let pending = [...defs.values()];
261
+ while (pending.length) {
262
+ const left = pending.filter((def) => {
263
+ try {
264
+ const r = calculate(textOf(def), scope);
265
+ // a number, or a matrix (or list): {{M^2}} works it out
266
+ if (typeof r.value === 'number' || typeof r.value === 'bigint' || Array.isArray(r.value)) {
267
+ scope[def.name] = r.exact ? r.text : r.value;
268
+ return false;
269
+ }
270
+ } catch {
271
+ // not (yet) a number
272
+ }
273
+ return true;
274
+ });
275
+ if (left.length === pending.length) break;
276
+ pending = left;
277
+ }
278
+ // and their expressions, for a CAS block: {{diff(f, x)}} differentiates what f stands for
279
+ const expressions = {};
280
+ const plain = lookupFor({});
281
+ for (const name of defs.keys()) {
282
+ const tree = plain(name);
283
+ if (!tree) continue;
284
+ try {
285
+ expressions[name] = toPostfix(substitute(tree, (n) => (n === name ? null : plain(n))).tree);
286
+ } catch {
287
+ // an expression that can't be written as postfix: the CAS sees the name
288
+ }
289
+ }
290
+ scope[EXPRESSIONS] = expressions;
291
+ };
292
+ const lookupFor = (drawOpts) => {
293
+ const trees = new Map();
294
+ return (name) => {
295
+ const def = defs.get(name);
296
+ if (!def) return null;
297
+ if (!trees.has(name)) {
298
+ let tree = null;
299
+ try {
300
+ tree = treeOf(textOf(def), drawOpts);
301
+ } catch {
302
+ // an input holding something that doesn't read: A is drawn as A
303
+ }
304
+ trees.set(name, tree);
305
+ }
306
+ return trees.get(name);
307
+ };
308
+ };
309
+
310
+ // worked out only when a {{…}} block will read them: a page of 200 definitions and no blocks is not 200 recalculations
311
+ let stale = true;
312
+
313
+ const drawItem = (item, i) => {
314
+ const { source, display } = item;
315
+ if (stale && source.includes('{{')) {
316
+ refresh();
317
+ stale = false;
318
+ }
319
+ const cls = display ? 'mv-md-display' : 'mv-md-math';
320
+ const wrap = (html, extra = '') => `<span class="${cls}${extra}" data-mv-md="${i}">${html}</span>`;
321
+ try {
322
+ const drawOpts = { ...options.math, display, blocks: options.blocks, scope };
323
+ const save = savingOf(source);
324
+ if (save && save.error) throw new Error(save.error);
325
+ if (save) {
326
+ const { name, input, hidden } = save;
327
+ const def = input
328
+ ? { name, text: input.default, input, key: `input:${JSON.stringify(input)}` }
329
+ : { name, text: save.rhs, input: null, key: `expr:${save.rhs}`, start: item.start, end: item.end };
330
+ let html = '';
331
+ if (input) {
332
+ const control = controlHTML(def, textOf(def));
333
+ html = hidden ? control : `${toHTML(save.lhs, drawOpts)}<span class="mv-md-assign" aria-hidden="true">≔</span>${control}`;
334
+ inputs.add(i);
335
+ } else {
336
+ const rhs = substitute(treeOf(save.rhs, drawOpts), lookupFor(drawOpts)).tree;
337
+ if (!hidden) {
338
+ const tree = numberTree({ type: 'op', op: '=', args: [bare(treeOf(save.lhs)), rhs.id === undefined ? rhs : bare(rhs)] });
339
+ trees[i] = tree;
340
+ html = asDefinition(toHTML(tree, drawOpts), drawOpts.prefix);
341
+ }
342
+ }
343
+ defs.delete(name);
344
+ defs.set(name, def);
345
+ mine.set(name, def);
346
+ stale = true;
347
+ if (hidden && !input) return '';
348
+ return wrap(html, input ? ' mv-md-input-def' : '');
349
+ }
350
+ const { tree, changed } = substitute(treeOf(source, drawOpts), lookupFor(drawOpts));
351
+ if (changed) numberTree(tree);
352
+ trees[i] = tree;
353
+ const html = toHTML(tree, drawOpts);
354
+ if (!changed && options.define !== false && define(source, numbers, defs)) stale = true;
355
+ return wrap(html);
356
+ } catch (error) {
357
+ return `<span class="mv-md-error" data-mv-md="${i}" title="${escape(error.message)}"><code>${escape(item.raw)}</code></span>`;
358
+ }
359
+ };
360
+ const drawn = math.map(drawItem);
361
+ return { text, math, drawn, defs: mine, inputs, trees };
362
+ }
363
+
364
+ /** $r = 3$ (or $A = \\begin{pmatrix}…$): remember r (exactly, as the calculator's text) for later {{…}} — unless r is a saved variable. */
365
+ function define(source, numbers, saved) {
366
+ const m = DEFINITION.exec(source);
367
+ if (!m || /\{\{/.test(m[2])) return false;
368
+ const name = m[1].replace(/[{}]/g, '');
369
+ if (saved.has(name)) return false;
370
+ try {
371
+ const r = calculate(m[2], numbers);
372
+ // a number, or a matrix (or list), as for saved variables
373
+ if (typeof r.value === 'number' || typeof r.value === 'bigint' || Array.isArray(r.value)) {
374
+ numbers[name] = r.exact ? r.text : r.value;
375
+ return true;
376
+ }
377
+ } catch {
378
+ // not a number (x = y + 1): nothing to remember
379
+ }
380
+ return false;
159
381
  }
160
382
 
161
383
  // ---- the Markdown renderer ----------------------------------------------------------------
@@ -163,15 +385,22 @@ function define(source, scope) {
163
385
  const SAFE_URL = /^(https?:|mailto:|#|\/|\.{0,2}\/|[^:]*$)/i;
164
386
  const safeUrl = (u) => (SAFE_URL.test(u.trim()) ? escape(u.trim()) : '#');
165
387
 
166
- /** Inline Markdown: code, links, images, emphasis, breaks. Placeholders pass through. */
167
- function inline(text, options, sourceOf) {
168
- const parts = [];
388
+ const HELD = /\uE002(\d+)\uE003/g;
389
+ const unescape = (t) => t.replace(/&quot;/g, '"').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&');
390
+
391
+ /**
392
+ * Inline Markdown: code, links, images, emphasis, breaks. Placeholders pass through. `parts` is shared with
393
+ * a link's label (read by the same function), so what was held outside it still resolves inside it.
394
+ */
395
+ function inline(text, options, sourceOf, parts = []) {
169
396
  const hold = (html) => {
170
397
  parts.push(html);
171
- return `${parts.length - 1}`;
398
+ return `\uE002${parts.length - 1}\uE003`;
172
399
  };
400
+ // an attribute or address: what was held there as its text (a\_b is a_b), math as typed — then escaped once
401
+ const plain = (s) => unescape(sourceOf(s).replace(HELD, (_, n) => (parts[Number(n)] ?? '').replace(/<[^>]*>/g, '')));
173
402
  let t = text;
174
- // code spans (maths placeholders inside are written back as their source)
403
+ // code spans (math placeholders inside are written back as their source)
175
404
  t = t.replace(/(`+)([\s\S]*?[^`])\1(?!`)/g, (_, run, code) => hold(`<code>${escape(sourceOf(code.trim()))}</code>`));
176
405
  // backslash escapes
177
406
  t = t.replace(/\\([\\`*_{}[\]()#+\-.!|~$<>"'])/g, (_, ch) => hold(escape(ch)));
@@ -179,30 +408,59 @@ function inline(text, options, sourceOf) {
179
408
  t = t.replace(/<((?:https?:\/\/|mailto:)[^\s>]+)>/g, (_, url) => hold(`<a href="${safeUrl(url)}">${escape(url)}</a>`));
180
409
  // raw HTML (only with { html: true })
181
410
  if (options.html) t = t.replace(/<\/?[A-Za-z][^>]*>/g, (tag) => hold(tag));
182
- // images and links
411
+ // images and links (a label holds no bracket of its own: a run of [[[[… was read again from every one of them)
183
412
  // an address may hold balanced brackets: wiki/Function_(mathematics)
184
- t = t.replace(/!\[([^\]]*)\]\(\s*((?:[^\s()]|\([^\s()]*\))+)(?:\s+"([^"]*)")?\s*\)/g, (_, alt, url, title) =>
185
- hold(`<img src="${safeUrl(url)}" alt="${escape(alt)}"${title ? ` title="${escape(title)}"` : ''}>`));
186
- t = t.replace(/\[([^\]]+)\]\(\s*((?:[^\s()]|\([^\s()]*\))+)(?:\s+"([^"]*)")?\s*\)/g, (_, label, url, title) =>
187
- hold(`<a href="${safeUrl(url)}"${title ? ` title="${escape(title)}"` : ''}>${inline(label, options, sourceOf)}</a>`));
188
- t = escape(t);
413
+ t = t.replace(/!\[([^\[\]]*)\]\(\s*((?:[^\s()]|\([^\s()]*\))+)(?:\s+"([^"]*)")?\s*\)/g, (_, alt, url, title) =>
414
+ hold(`<img src="${safeUrl(plain(url))}" alt="${escape(plain(alt))}"${title ? ` title="${escape(plain(title))}"` : ''}>`));
415
+ t = t.replace(/\[([^\[\]]+)\]\(\s*((?:[^\s()]|\([^\s()]*\))+)(?:\s+"([^"]*)")?\s*\)/g, (_, label, url, title) =>
416
+ hold(`<a href="${safeUrl(plain(url))}"${title ? ` title="${escape(plain(title))}"` : ''}>${inline(label, options, sourceOf, parts)}</a>`));
417
+ // escaped as text, except an entity reference written as one: &copy; &mdash; &#8212;
418
+ t = t.replace(/&(?!#\d{1,7};|#x[0-9a-f]{1,6};|[a-z][a-z0-9]{1,31};)/gi, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
419
+ t = t.replace(/(\*\*\*|___)(?=\S)([\s\S]*?\S)\1/g, '<strong><em>$2</em></strong>'); // ***both***, nested the right way round
420
+ // ***a** b* and ***a* b**: the inner run closes first
421
+ t = t.replace(/(\*\*\*|___)(?=\S)([^*_]*?\S)(\*\*|__)(?![*_])([\s\S]*?\S)(\*|_)(?![*_])/g, '<em><strong>$2</strong>$4</em>');
422
+ t = t.replace(/(\*\*\*|___)(?=\S)([^*_]*?\S)(\*|_)(?![*_])([\s\S]*?\S)(\*\*|__)(?![*_])/g, '<strong><em>$2</em>$4</strong>');
189
423
  t = t.replace(/(\*\*|__)(?=\S)([\s\S]*?\S)\1/g, '<strong>$2</strong>');
190
424
  t = t.replace(/(^|[^*\w])\*(?=\S)([\s\S]*?\S)\*(?!\*)/g, '$1<em>$2</em>');
191
425
  t = t.replace(/(^|[^_\w])_(?=\S)([\s\S]*?\S)_(?![_\w])/g, '$1<em>$2</em>');
192
426
  t = t.replace(/~~(?=\S)([\s\S]*?\S)~~/g, '<del>$1</del>');
193
427
  t = t.replace(/( {2,}|\\)\n/g, '<br>\n');
194
- return t.replace(/(\d+)/g, (_, n) => parts[Number(n)]);
428
+ // a held piece can hold another (a link's label): resolve until none is left
429
+ for (let k = 0; k < 8 && /\uE002\d+\uE003/.test(t); k++) t = t.replace(HELD, (_, n) => parts[Number(n)] ?? '');
430
+ return t;
195
431
  }
196
432
 
197
433
  const BLOCK_START = /^( {0,3})(#{1,6}\s|>|```|~~~|([-*+]|\d{1,9}[.)])\s|(\*[ \t]*){3,}$|(-[ \t]*){3,}$|(_[ \t]*){3,}$)/;
198
434
  const LIST_ITEM = /^( {0,3})([-*+]|\d{1,9}[.)])(\s+|$)/;
199
435
  const TABLE_RULE = /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/;
200
436
 
437
+ /** Does this line end a paragraph? A block starts, but an underline is a heading's and only a list from 1 interrupts:
438
+ * "The year was\n1986. What a year." stays one paragraph. */
439
+ const interrupts = (line) => BLOCK_START.test(line) && !/^ {0,3}[-=]+\s*$/.test(line)
440
+ && !/^ {0,3}(?!1[.)])\d{1,9}[.)]\s/.test(line);
441
+
442
+ const MAX_NESTING = 100;
443
+
444
+ /**
445
+ * A heading's text: without the spaces around it and a closing run of #s set off by a space (`# Title ##`).
446
+ * By hand: one pattern for all of it (\s+ … \s*#*\s*$) tried every split of a long run of spaces, cubic in its length.
447
+ */
448
+ function headingText(rest) {
449
+ const text = rest.trim();
450
+ let end = text.length;
451
+ while (end > 0 && text[end - 1] === '#') end--;
452
+ if (end === text.length) return text;
453
+ if (end === 0) return ''; // only #s
454
+ return /[ \t]/.test(text[end - 1]) ? text.slice(0, end).trimEnd() : text; // a# and \# keep theirs
455
+ }
456
+
201
457
  /** Block Markdown → HTML. */
202
- function blocks(lines, options, sourceOf) {
458
+ function blocks(lines, options, sourceOf, depth = 0) {
203
459
  const out = [];
204
460
  let i = 0;
205
461
  const para = (text) => inline(text, options, sourceOf);
462
+ // quotes in quotes, lists in lists: past any depth a person writes, the rest is a paragraph (a line of 2,500 >s overflowed the stack)
463
+ if (depth > MAX_NESTING) return `<p>${para(lines.join('\n'))}</p>`;
206
464
  while (i < lines.length) {
207
465
  const line = lines[i];
208
466
  if (!line.trim()) { i++; continue; }
@@ -218,9 +476,9 @@ function blocks(lines, options, sourceOf) {
218
476
  continue;
219
477
  }
220
478
  // ATX heading
221
- const h = /^ {0,3}(#{1,6})\s+(.*?)\s*#*\s*$/.exec(line);
479
+ const h = /^ {0,3}(#{1,6})[ \t]+/.exec(line);
222
480
  if (h) {
223
- out.push(`<h${h[1].length}>${para(h[2])}</h${h[1].length}>`);
481
+ out.push(`<h${h[1].length}>${para(headingText(line.slice(h[0].length)))}</h${h[1].length}>`);
224
482
  i++;
225
483
  continue;
226
484
  }
@@ -237,7 +495,7 @@ function blocks(lines, options, sourceOf) {
237
495
  body.push(lines[i].replace(/^ {0,3}> ?/, ''));
238
496
  i++;
239
497
  }
240
- out.push(`<blockquote>\n${blocks(body, options, sourceOf)}\n</blockquote>`);
498
+ out.push(`<blockquote>\n${blocks(body, options, sourceOf, depth + 1)}\n</blockquote>`);
241
499
  continue;
242
500
  }
243
501
  // list
@@ -277,7 +535,7 @@ function blocks(lines, options, sourceOf) {
277
535
  }
278
536
  const tag = ordered ? 'ol' : 'ul';
279
537
  const html = items.map((body) => {
280
- let inner = blocks(body, options, sourceOf);
538
+ let inner = blocks(body, options, sourceOf, depth + 1);
281
539
  if (!loose) inner = inner.replace(/^<p>([\s\S]*?)<\/p>/, '$1').replace(/\n<p>([\s\S]*?)<\/p>/g, '\n$1');
282
540
  return `<li>${inner}</li>`;
283
541
  });
@@ -306,7 +564,7 @@ function blocks(lines, options, sourceOf) {
306
564
  }
307
565
  // paragraph (or a setext heading)
308
566
  const text = [];
309
- while (i < lines.length && lines[i].trim() && !(text.length && BLOCK_START.test(lines[i]) && !/^ {0,3}[-=]+\s*$/.test(lines[i]))) {
567
+ while (i < lines.length && lines[i].trim() && !(text.length && interrupts(lines[i]))) {
310
568
  if (text.length && /^ {0,3}(=+|-+)\s*$/.test(lines[i])) {
311
569
  const level = lines[i].trim()[0] === '=' ? 1 : 2;
312
570
  out.push(`<h${level}>${para(text.join('\n'))}</h${level}>`);
@@ -324,38 +582,177 @@ function blocks(lines, options, sourceOf) {
324
582
 
325
583
  /** The built-in renderer: Markdown → HTML, raw HTML escaped unless options.html. */
326
584
  export function renderMarkdown(markdown, options = {}, sourceOf = (t) => t) {
327
- return blocks(String(markdown).replace(/\r\n?/g, '\n').split('\n'), options, sourceOf);
585
+ // typed U+E002/U+E003 would be read as held pieces: they become U+FFFD
586
+ return blocks(String(markdown).replace(/\r\n?/g, '\n').replace(/[\uE002\uE003]/g, '\uFFFD').split('\n'), options, sourceOf);
328
587
  }
329
588
 
330
589
  // ---- together ---------------------------------------------------------------------------
331
590
 
591
+ /** The Markdown around the drawn math. */
592
+ function assemble({ text, math, drawn }, options) {
593
+ const sourceOf = (t) => t.replace(PLACEHOLDER, (_, n) => math[Number(n)]?.raw ?? '');
594
+ const html = options.render ? options.render(text) : renderMarkdown(text, options, sourceOf);
595
+ return html
596
+ // display math alone in a paragraph is a block of its own
597
+ .replace(new RegExp(`<p>\\s*${OPEN}(\\d+)${CLOSE}\\s*</p>`, 'g'), (whole, n) => (math[Number(n)].display && drawn[Number(n)] ? `<div class="mv-md-block">${drawn[Number(n)]}</div>` : whole))
598
+ .replace(PLACEHOLDER, (_, n) => drawn[Number(n)] ?? '')
599
+ // a paragraph that only saved variables ($_A := 2+2$) leaves nothing behind
600
+ .replace(/<p>\s*<\/p>\n?/g, '');
601
+ }
602
+
332
603
  /**
333
- * Markdown with maths → HTML.
604
+ * Markdown with math → HTML.
334
605
  * @param {string} markdown
335
606
  * @param {object} [options]
336
607
  * @param {object} [options.math] options for each drawing (toHTML's: fnParens, colors …)
337
608
  * @param {Function} [options.blocks] the {{…}} handler (default the calculator; casBlocks() for the CAS)
338
609
  * @param {object} [options.scope] values for {{…}}: { r: 3 }
339
610
  * @param {boolean} [options.define] remember $r = 3$ for later {{…}} (default true)
611
+ * @param {object} [options.variables] a store (createVariables()) whose variables the math may use
340
612
  * @param {boolean} [options.html] let raw HTML through (default false: it is shown as text)
341
613
  * @param {(markdown: string) => string} [options.render] another Markdown renderer
342
- * @param {string[]} [options.delimiters] which of '$$', '$', '\\[', '\\(' mark maths (default all)
614
+ * @param {string[]} [options.delimiters] which of '$$', '$', '\\[', '\\(' mark math (default all)
343
615
  */
344
616
  export function markdownToHTML(markdown, options = {}) {
345
- const { text, math } = extractMath(markdown, options);
346
- const scope = { ...(options.scope ?? {}) };
347
- // drawn in reading order, so a definition is known to the maths after it
348
- const drawn = math.map((item) => drawMath(item, options, scope));
349
- const sourceOf = (t) => t.replace(PLACEHOLDER, (_, n) => math[Number(n)].raw);
350
- const html = options.render ? options.render(text) : renderMarkdown(text, options, sourceOf);
351
- return html
352
- // display maths alone in a paragraph is a block of its own
353
- .replace(new RegExp(`<p>\\s*${OPEN}(\\d+)${CLOSE}\\s*</p>`, 'g'), (whole, n) => (math[Number(n)].display ? `<div class="mv-md-block">${drawn[Number(n)]}</div>` : whole))
354
- .replace(PLACEHOLDER, (_, n) => drawn[Number(n)]);
617
+ return assemble(drawAll(markdown, options, options.variables || null), options);
618
+ }
619
+
620
+ const bindings = new WeakMap();
621
+ const live = new Set(); // every bound element's binding, to notice the ones taken off the page
622
+
623
+ /** Parts taken off the page take their variables with them. */
624
+ function sweep() {
625
+ for (const b of live) if (b.connected() && !b.element.isConnected) b.stop(true);
355
626
  }
356
627
 
357
- /** Draw Markdown with maths into an element. */
628
+ /**
629
+ * Draw Markdown with math into an element, live: its variables join the page's store
630
+ * (options.variables, default `variables`; false for none), its inputs set them, and its math is
631
+ * drawn again whenever a variable it can see changes. Drawing into the element again replaces it all.
632
+ * Double-clicking a part drawn from a textbox variable edits it ({ editable: { toText } }, toText
633
+ * from 'mathzetta/text'); any other part fires 'inlinemath:select' with where its math is in the
634
+ * Markdown ({ index, start, end, raw }).
635
+ */
358
636
  export function renderMarkdownInto(element, markdown, options = {}) {
359
- element.innerHTML = markdownToHTML(markdown, options);
360
- return element;
637
+ const store = options.variables === undefined ? pageVariables : options.variables || null;
638
+ sweep();
639
+ const old = bindings.get(element);
640
+ if (old) old.stop(old.store !== store);
641
+ let result = drawAll(markdown, options, store, element);
642
+ element.innerHTML = assemble(result, options);
643
+ if (!store) {
644
+ bindings.delete(element);
645
+ return element;
646
+ }
647
+ store.own(element, result.defs);
648
+
649
+ let connected = element.isConnected;
650
+ const redraw = () => {
651
+ const next = drawAll(markdown, options, store, element);
652
+ next.drawn.forEach((html, i) => {
653
+ if (html === result.drawn[i] || next.inputs.has(i)) return;
654
+ const at = element.querySelector(`[data-mv-md="${i}"]`);
655
+ if (at) at.outerHTML = html;
656
+ });
657
+ // inputs for the same variable agree; a slider shows its value
658
+ for (const el of element.querySelectorAll('[data-mv-var], [data-mv-out]')) {
659
+ const def = next.defs.get(el.dataset.mvVar ?? el.dataset.mvOut);
660
+ if (!def) continue;
661
+ const text = store.textOf(def);
662
+ if (el.dataset.mvOut !== undefined) el.textContent = text;
663
+ else if (el.value !== text && el !== el.ownerDocument?.activeElement) el.value = text;
664
+ }
665
+ result = next;
666
+ };
667
+ const onInput = (event) => {
668
+ const el = event.target;
669
+ const name = el && el.dataset && el.dataset.mvVar;
670
+ if (name === undefined || !element.contains(el)) return;
671
+ if (el.type === 'text') {
672
+ try {
673
+ treeOf(el.value, { blocks: options.blocks, scope: {} });
674
+ el.removeAttribute('aria-invalid');
675
+ } catch {
676
+ el.setAttribute('aria-invalid', 'true'); // keeps what it held last
677
+ return;
678
+ }
679
+ }
680
+ store.set(name, el.value);
681
+ };
682
+ // double-click a part: a part that came from a textbox variable is edited there (in place,
683
+ // with options.editable = { toText }; else the textbox is focused); anything else tells the
684
+ // page where that math is in the Markdown, as an 'inlinemath:select' event
685
+ const onDoubleClick = (event) => {
686
+ const part = event.target.closest?.('[data-node]');
687
+ const piece = part && part.closest('[data-mv-md]');
688
+ if (!piece || !element.contains(piece)) return;
689
+ const index = Number(piece.dataset.mvMd);
690
+ const tree = result.trees[index];
691
+ if (!tree) return;
692
+ const id = Number(part.dataset.node);
693
+ const path = pathOf(tree, id) || [];
694
+ // the innermost variable the part sits in
695
+ let at = null;
696
+ for (let k = path.length; k >= 0 && !at; k--) {
697
+ const n = nodeAt(tree, path.slice(0, k));
698
+ if (n && n.from !== undefined) at = { node: n, depth: k };
699
+ }
700
+ const def = at && store.definitions().get(at.node.from);
701
+ if (def && def.input && def.input.kind === 'textbox') {
702
+ event.preventDefault();
703
+ const name = def.name;
704
+ const box = element.ownerDocument.querySelector(`[data-mv-var="${CSS.escape(name)}"]`);
705
+ const toText = options.editable && options.editable.toText;
706
+ if (!toText) {
707
+ if (box) { box.focus(); box.select(); }
708
+ return;
709
+ }
710
+ const named = (n) => treeOf(n);
711
+ const node = nodeAt(tree, path);
712
+ openEditor(part, toText(unexpand(node, named)), {
713
+ label: `Edit ${name}`,
714
+ parse: (text) => treeOf(text, { blocks: options.blocks }),
715
+ commit: (typed) => {
716
+ const whole = replaceAt(unexpand(at.node, named), path.slice(at.depth), typed);
717
+ store.set(name, toText(whole));
718
+ },
719
+ });
720
+ return;
721
+ }
722
+ // a saved variable defined here: point at its definition rather than where it is used
723
+ const here = def && result.defs.get(def.name);
724
+ const item = here && here.key === def.key && here.start !== undefined
725
+ ? { ...result.math[index], start: here.start, end: here.end, raw: markdown.slice(here.start, here.end) }
726
+ : result.math[index];
727
+ element.dispatchEvent(new CustomEvent('inlinemath:select', {
728
+ bubbles: true,
729
+ detail: { index, start: item.start, end: item.end, raw: item.raw, source: item.source, id, path },
730
+ }));
731
+ };
732
+ element.addEventListener('input', onInput);
733
+ element.addEventListener('change', onInput);
734
+ element.addEventListener('dblclick', onDoubleClick);
735
+ const unsubscribe = store.subscribe((from) => {
736
+ if (from === element) return;
737
+ if (!element.isConnected) {
738
+ if (connected) stop(true); // taken off the page: its variables go with it
739
+ return;
740
+ }
741
+ connected = true;
742
+ sweep();
743
+ redraw();
744
+ });
745
+ function stop(drop) {
746
+ unsubscribe();
747
+ element.removeEventListener('input', onInput);
748
+ element.removeEventListener('change', onInput);
749
+ element.removeEventListener('dblclick', onDoubleClick);
750
+ live.delete(binding);
751
+ bindings.delete(element);
752
+ if (drop) store.own(element, null);
753
+ }
754
+ const binding = { element, store, stop, connected: () => connected };
755
+ live.add(binding);
756
+ bindings.set(element, binding);
757
+ return element;
361
758
  }