@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/edit.js ADDED
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Editing a part of a drawn expression in place: a text box opens over the part, holding the
3
+ * part as text; Enter puts what was typed back into the expression, Escape (or leaving it with
4
+ * something that doesn't read) changes nothing. Used by View.editable() and by the Markdown
5
+ * pages' textbox variables.
6
+ *
7
+ * The part is written as text by MathZetta's toText, which the caller passes in (import it
8
+ * from 'mathzetta/text'): Inline Math's core imports only 'mathzetta', 'mathzetta/speech' and
9
+ * 'mathzetta/calculate', so a buildless page's import map stays the same.
10
+ */
11
+
12
+ import { bare } from './select.js';
13
+
14
+ /** A copy of `tree` (ids dropped) with the node at `path` replaced by `part`. */
15
+ export function replaceAt(tree, path, part) {
16
+ const visit = (n, k) => (k === path.length
17
+ ? part
18
+ : { ...n, args: n.args.map((a, j) => (j === path[k] ? visit(a, k + 1) : a)) });
19
+ return bare(visit(tree, 0));
20
+ }
21
+
22
+ /**
23
+ * Open a text box over `element` holding `text`.
24
+ * @param {Element} element the drawn part
25
+ * @param {string} text what the box starts with
26
+ * @param {object} how
27
+ * @param {(text: string) => object} how.parse the typed text → a tree (throws if it doesn't read)
28
+ * @param {(tree: object, text: string) => void} how.commit called with the new part
29
+ * @param {() => void} [how.cancel] called when nothing changed
30
+ * @param {string} [how.label] the box's accessible name
31
+ * @param {string} [how.prefix] the drawing's class prefix (mv): the box is `${prefix}-edit`
32
+ * @returns {HTMLInputElement|null} the box; its cancelEdit() closes it without a change
33
+ */
34
+ export function openEditor(element, text, { parse, commit, cancel, label = 'Edit', prefix = 'mv' }) {
35
+ const doc = element.ownerDocument;
36
+ if (!doc || !doc.body) return null;
37
+ const view = doc.defaultView;
38
+ const r = element.getBoundingClientRect();
39
+ const input = doc.createElement('input');
40
+ input.type = 'text';
41
+ input.className = `${prefix}-edit`;
42
+ input.value = text;
43
+ input.spellcheck = false;
44
+ input.autocomplete = 'off';
45
+ input.setAttribute('aria-label', label);
46
+ const fit = () => { input.style.width = `${Math.max(4, input.value.length + 2)}ch`; };
47
+ const font = view.getComputedStyle(element);
48
+ Object.assign(input.style, {
49
+ position: 'absolute',
50
+ left: `${r.left + view.scrollX}px`,
51
+ top: `${r.top + view.scrollY + r.height / 2}px`,
52
+ minWidth: `${Math.max(r.width, 32)}px`,
53
+ fontSize: font.fontSize,
54
+ });
55
+ fit();
56
+ doc.body.appendChild(input);
57
+ view.getSelection?.()?.removeAllRanges(); // the double-click selected a word of the page
58
+ input.focus();
59
+ input.select();
60
+
61
+ let done = false;
62
+ const close = () => {
63
+ done = true;
64
+ input.remove();
65
+ };
66
+ // closed from outside (the view drew something else): nothing is committed
67
+ input.cancelEdit = () => {
68
+ if (done) return;
69
+ close();
70
+ if (cancel) cancel();
71
+ };
72
+ const finish = (keep) => {
73
+ if (done) return true;
74
+ if (!keep || input.value === text) {
75
+ close();
76
+ if (cancel) cancel();
77
+ return true;
78
+ }
79
+ let tree;
80
+ try {
81
+ tree = parse(input.value);
82
+ } catch (error) {
83
+ input.setAttribute('aria-invalid', 'true');
84
+ input.title = error.message;
85
+ return false;
86
+ }
87
+ close();
88
+ commit(tree, input.value);
89
+ return true;
90
+ };
91
+ input.addEventListener('keydown', (event) => {
92
+ event.stopPropagation(); // the view's arrow keys are not for the box
93
+ if (event.key === 'Enter') { event.preventDefault(); finish(true); }
94
+ if (event.key === 'Escape') { event.preventDefault(); finish(false); }
95
+ });
96
+ input.addEventListener('input', () => {
97
+ fit();
98
+ input.removeAttribute('aria-invalid');
99
+ input.removeAttribute('title');
100
+ });
101
+ input.addEventListener('blur', () => { if (!finish(true)) finish(false); });
102
+ return input;
103
+ }
package/src/glyphs.js CHANGED
@@ -18,6 +18,8 @@ export const PATHS = {
18
18
  '}': { fill: 'M0,0 C0.55,0 0.5,0.05 0.5,0.2 L0.5,0.38 C0.5,0.46 0.65,0.49 0.95,0.5 C0.65,0.51 0.5,0.54 0.5,0.62 L0.5,0.8 C0.5,0.95 0.55,1 0,1 L0,0.985 C0.32,0.985 0.36,0.95 0.36,0.8 L0.36,0.62 C0.36,0.53 0.45,0.505 0.7,0.5 C0.45,0.495 0.36,0.47 0.36,0.38 L0.36,0.2 C0.36,0.05 0.32,0.015 0,0.015 Z' },
19
19
  // Radical: short tick, long down-stroke, long up-stroke to the top right.
20
20
  'sqrt': { stroke: 'M0,0.62 L0.18,0.55 L0.45,0.97 L0.98,0.015' },
21
+ // \cancel: one stroke, bottom left to top right, stretched over what it crosses out.
22
+ 'cancel': { stroke: 'M0,1 L1,0' },
21
23
  // Integral: an S slanted to the right with small hooks at each end.
22
24
  'int': { stroke: 'M0.95,0.09 C0.9,0.01 0.72,0 0.66,0.12 C0.6,0.25 0.42,0.75 0.34,0.88 C0.28,0.99 0.1,0.99 0.05,0.91' },
23
25
  'sum': { fill: 'M0.04,0 L0.94,0 L0.98,0.24 L0.94,0.24 C0.9,0.1 0.8,0.07 0.62,0.07 L0.24,0.07 L0.58,0.5 L0.2,0.93 L0.64,0.93 C0.82,0.93 0.92,0.9 0.95,0.76 L0.99,0.76 L0.94,1 L0.02,1 L0.47,0.47 Z' },
package/src/html.js CHANGED
@@ -22,7 +22,7 @@ export function treeOf(input, options = {}) {
22
22
  /**
23
23
  * @param {string|string[]|object} input
24
24
  * @param {object} [options] layout options (see DEFAULTS in layout.js) plus:
25
- * @param {object|Array} [options.colors] { 'x^2': 'red', 3: '#06c' } or [[target, colour], …]
25
+ * @param {object|Array} [options.colors] { 'x^2': 'red', 3: '#06c' } or [[target, color], …]
26
26
  * @param {*} [options.highlight] target(s) to mark with the mv-hl class
27
27
  * @param {object} [options.scope] variable values for `{{...}}` blocks
28
28
  * @returns {string}
package/src/index.d.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  // '@mathzetta/inlinemath' — drawing, the live view, selection. See types.d.ts.
2
- export type { Input, Node, Target, LayoutOptions, DrawOptions, ClickInfo } from './types.js';
3
- export { toHTML, treeOf, layout, DEFAULTS, View, render, select, signature, nodeAt, pathOf, numberTree, PATHS } from './types.js';
2
+ export type { Input, Node, Target, LayoutOptions, DrawOptions, ViewOptions, ClickInfo } from './types.js';
3
+ export { toHTML, treeOf, layout, DEFAULTS, View, render, shouldAnimate, select, signature, nodeAt, pathOf, numberTree, PATHS } from './types.js';
package/src/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Inline Math — draws calculus-level maths as HTML and CSS, from anything
2
+ * Inline Math — draws calculus-level math as HTML and CSS, from anything
3
3
  * MathZetta can read, with every part addressable.
4
4
  *
5
5
  * import { toHTML, render } from '@mathzetta/inlinemath';
@@ -12,6 +12,6 @@
12
12
 
13
13
  export { toHTML, treeOf } from './html.js';
14
14
  export { layout, DEFAULTS } from './layout.js';
15
- export { View, render } from './view.js';
15
+ export { View, render, shouldAnimate } from './view.js';
16
16
  export { select, signature, nodeAt, pathOf, numberTree } from './select.js';
17
17
  export { PATHS } from './glyphs.js';
package/src/layout.js CHANGED
@@ -4,7 +4,7 @@
4
4
  * Every rendered piece is a box { html, h, d }: its markup, and how far it
5
5
  * reaches above (h) and below (d) the baseline, in em of the surrounding
6
6
  * text. Nothing is measured in a browser; the estimates place fractions on
7
- * the maths axis, raise exponents above tall bases and size the integral
7
+ * the math axis, raise exponents above tall bases and size the integral
8
8
  * sign, so the same string is right in Node, in a video frame or on a page.
9
9
  * Delimiters, the radical's bar and borders stretch by themselves with CSS.
10
10
  *
@@ -21,14 +21,14 @@
21
21
  import {
22
22
  GREEK, needsBrackets, unaryNeedsBrackets, isMinusOneTimes, isImplicitProduct, isVariable,
23
23
  firstLeaf, customName, derivativeOrder, bracketedSides, bracketOp, firstVariable,
24
- isCustomFunction, precedenceOf, toSpeech,
24
+ isCustomFunction, precedenceOf, toAudioSpeech, MATRICES, matrixRows,
25
25
  } from './mathzetta.js';
26
26
  import { svg } from './glyphs.js';
27
27
 
28
28
  // Metrics, in em. They match inlinemath.css; change both together.
29
29
  const LH = 0.8; // a line of text: height above the baseline (line-height 1)
30
30
  const LD = 0.2; // and depth below it
31
- const AXIS = 0.25; // the maths axis: fraction bars and big operators centre here
31
+ const AXIS = 0.25; // the math axis: fraction bars and big operators center here
32
32
  const RULE = 0.06; // fraction bar, radical bar
33
33
  const GAP = 0.1; // between a fraction bar and its numerator or denominator
34
34
  const SCRIPT = 0.7; // exponent and subscript size; deeper scripts use SCRIPT2
@@ -42,6 +42,7 @@ const OP_CLASS = {
42
42
  '&': 'and', '|': 'or', '\\not': 'not', '\\xor': 'xor', '\\nand': 'nand', '\\nor': 'nor', '?:': 'cases',
43
43
  '()': 'tuple', '[]': 'list', '{}': 'set', '(]': 'interval', '[)': 'interval',
44
44
  '\\sumidx': 'sum', '\\prodidx': 'prod', 'mod': 'mod', 'pmod': 'pmod',
45
+ pmatrix: 'matrix', bmatrix: 'matrix', vmatrix: 'matrix',
45
46
  };
46
47
 
47
48
  const RELATIONS = {
@@ -54,15 +55,19 @@ const BINARY = { '±': '±', '∪': '∪', '∩': '∩', 'mod': 'mod' };
54
55
  const TRIG = ['sin', 'cos', 'tan', 'csc', 'sec', 'cot', 'sinh', 'cosh', 'tanh'];
55
56
  const INVERSE = { arcsin: 'sin', arccos: 'cos', arctan: 'tan', arcsinh: 'sinh', arccosh: 'cosh', arctanh: 'tanh' };
56
57
  /** Functions written with a name and, when the argument is simple, no brackets: sin x, ln x. */
57
- const NAMED = [...TRIG, ...Object.keys(INVERSE), 'ln'];
58
+ const NAMED = [...TRIG, ...Object.keys(INVERSE), 'ln', 'det'];
58
59
  /** Functions always written with brackets: max(a, b). */
59
60
  const CALLS = { atan2: 'atan2', max: 'max', min: 'min', gcd: 'gcd', mean: 'mean', round: 'round', fixed: 'fixed', expm1: 'expm1', random: 'random' };
60
61
 
61
62
  const GROUPS = { '()': ['(', ')'], '[]': ['[', ']'], '{}': ['{', '}'], '(]': ['(', ']'], '[)': ['[', ')'] };
63
+ const BIG_OPERATORS = ['int', 'lim', '\\sumidx', '\\prodidx']; // a body after them takes in whatever follows
62
64
  const LATEX_SYMBOLS = { '\\partial': '∂', '\\nabla': '∇', '\\ell': 'ℓ', '\\infty': '∞', '\\emptyset': '∅' };
63
65
 
64
66
  /** Custom functions drawn as decorations: \boxed{x} parses as boxed(x). */
65
67
  const ACCENTS = { vec: '→', hat: 'ˆ', widehat: 'ˆ', tilde: '˜', dot: '˙', ddot: '¨' };
68
+ /** One letter as tall as an x: an accent over it sits lower. */
69
+ const SHORT_LETTER = /^[acegmnopqrsuvwxyzαγεημνοπρστυχω]$/;
70
+ const isShortLetter = (node) => node?.type === 'symbol' && SHORT_LETTER.test(GREEK[node.value] ?? node.value);
66
71
  const DECORATIONS = ['boxed', 'overline', 'bar', 'underline', 'cancel', ...Object.keys(ACCENTS)];
67
72
 
68
73
  export const DEFAULTS = {
@@ -74,7 +79,8 @@ export const DEFAULTS = {
74
79
  derivativeBrackets: '[', // d/dx [x² + 1], or '(' for d/dx (x² + 1)
75
80
  scriptFractions: 'slash',// x^{1/2} written x^{1/2} with a slash; 'stack' stacks it
76
81
  cases: true, // c ? a : b drawn as a piecewise brace
77
- label: true, // accessible name of the whole expression: true = the spoken form, a string, (tree) => string, or false
82
+ label: true, // accessible name of the whole expression: true = MathZetta's toAudioSpeech (the grouping in the words), a string, (tree) => string, or false
83
+ mathml: null, // MathZetta's toMathML (import it from 'mathzetta/mathml'): also write the expression as visually hidden MathML, which screen readers can step through and show in math braille; it replaces the label
78
84
  attributes: null, // (node) => ({ ... }) extra attributes for a node's element
79
85
  style: null, // (node) => 'css' inline style for a node's element
80
86
  };
@@ -102,18 +108,34 @@ export function layout(tree, options = {}) {
102
108
  const r = new Layout({ ...DEFAULTS, ...options });
103
109
  const b = r.render(tree, { level: 0 });
104
110
  const cls = `${r.p}${r.o.display ? ` ${r.p}-display` : ''}`;
105
- // Screen readers get the expression read as a teacher would; the spans and glyphs inside are not read piecemeal.
106
- const label = accessibleName(tree, r.o.label);
107
- const body = label === null ? b.html : b.html.replace(/^<span /, '<span aria-hidden="true" ');
111
+ // Screen readers get the expression as MathML they can walk (mathml: true), or read as a teacher would (the
112
+ // label); the spans and glyphs of the drawing are never read piecemeal.
113
+ const mathml = typeof r.o.mathml === 'function' ? assistiveMathML(r.o.mathml, tree, r.p, r.o.display) : '';
114
+ const label = mathml ? null : accessibleName(tree, r.o.label);
115
+ const body = label === null && !mathml ? b.html : b.html.replace(/^<span /, '<span aria-hidden="true" ');
108
116
  const attrs = label === null ? '' : ` role="math" aria-label="${escape(label)}"`;
109
- return { html: `<span class="${cls}"${attrs}>${body}</span>`, h: b.h, d: b.d };
117
+ return { html: `<span class="${cls}"${attrs}>${body}${mathml}</span>`, h: b.h, d: b.d };
118
+ }
119
+
120
+ /**
121
+ * The expression as MathML for assistive technology: no ids (two drawings on a page must not share them), hidden
122
+ * from sight. The page passes MathZetta's toMathML, so Inline Math itself imports only what every page maps.
123
+ */
124
+ function assistiveMathML(toMathML, tree, prefix, display) {
125
+ try {
126
+ return String(toMathML(tree)).replace(/ id="mz-\d+"/g, '')
127
+ .replace(/^<math>/, `<math class="${prefix}-sr-math"${display ? ' display="block"' : ''}>`);
128
+ } catch {
129
+ return ''; // nothing MathZetta can write as MathML: the label stands in
130
+ }
110
131
  }
111
132
 
112
133
  function accessibleName(tree, label) {
113
134
  if (label === false || label === null) return null;
114
135
  if (typeof label === 'string') return label;
115
136
  try {
116
- return typeof label === 'function' ? label(tree) : toSpeech(tree);
137
+ // a screen reader is speech with no drawing in view: the grouping has to be in the words
138
+ return typeof label === 'function' ? label(tree) : toAudioSpeech(tree);
117
139
  } catch {
118
140
  return null;
119
141
  }
@@ -150,11 +172,11 @@ class Layout {
150
172
  if (node.type === 'op') attrs += ` data-op="${escape(node.op)}"`;
151
173
  const extra = this.o.attributes ? this.o.attributes(node) || {} : {};
152
174
  for (const [k, v] of Object.entries(extra)) {
153
- if (k !== 'class' && k !== 'style') attrs += ` ${k}="${escape(v)}"`;
175
+ if (k !== 'class' && k !== 'style' && /^[A-Za-z_:][\w:.-]*$/.test(k)) attrs += ` ${k}="${escape(v)}"`; // a name is a name: nothing that could close the tag
154
176
  }
155
177
  const style = [extra.style, this.o.style && this.o.style(node)].filter(Boolean).join(';');
156
178
  const all = b.leaf ? ['n', ...kinds, b.leaf.kind] : ['n', ...kinds];
157
- const cls = all.map((k) => `${this.p}-${k}`).concat(extra.class ? [extra.class] : []).join(' ');
179
+ const cls = all.map((k) => `${this.p}-${k}`).concat(extra.class ? [escape(extra.class)] : []).join(' ');
158
180
  const content = b.leaf ? b.leaf.content : b.html;
159
181
  return { html: `<span class="${cls}"${style ? ` style="${escape(style)}"` : ''}${attrs}>${content}</span>`, h: b.h, d: b.d };
160
182
  }
@@ -174,7 +196,7 @@ class Layout {
174
196
 
175
197
  symbol(v) {
176
198
  if (GREEK[v]) v = GREEK[v];
177
- if (LATEX_SYMBOLS[v]) return this.text('ord', LATEX_SYMBOLS[v]);
199
+ if (LATEX_SYMBOLS[v]) return this.text('ord', LATEX_SYMBOLS[v]); // a null-prototype table: toString is a name
178
200
  if (v === '\\+' || v === '\\-') return this.text('ord', v[1]);
179
201
  if (v === '-∞') return this.text('ord', MINUS + '∞');
180
202
  if (/^[A-Za-z]$/.test(v) || /^[α-ω]$/.test(v)) return this.text('var', v);
@@ -191,7 +213,7 @@ class Layout {
191
213
  operation(node, ctx) {
192
214
  const { op, args } = node;
193
215
  const [a, b] = args;
194
- const r = (n, c = {}) => this.render(n, { ...ctx, ...c, forceParens: c.forceParens || false, before: c.before || false });
216
+ const r = (n, c = {}) => this.render(n, { ...ctx, ...c, forceParens: c.forceParens || false, before: c.before || false, leftFactor: false });
195
217
  const kind = OP_CLASS[op] ?? (/^[a-z0-9]+$/i.test(op) ? op : 'other');
196
218
  const wrap = (content) => this.wrap(node, ['op', `op-${kind}`], content);
197
219
  const side = (child, s) => (needsBrackets(node, child, s) && child.op !== '/' ? this.fence(r(child)) : r(child));
@@ -199,14 +221,26 @@ class Layout {
199
221
  if (NAMED.includes(op) || op === 'log') return wrap(this.named(node, ctx));
200
222
  if (CALLS[op]) return wrap(row(this.word(CALLS[op]), this.fence(this.list(args, ctx))));
201
223
  if (isCustomFunction(op)) return wrap(this.custom(node, ctx));
224
+ const rows = matrixRows(node); // pmatrix, bmatrix, vmatrix, and [[1, 2], [3, 4]]
225
+ if (rows) return wrap(this.matrix(node, rows, ctx));
202
226
  if (GROUPS[op]) return wrap(this.fence(this.list(args, ctx), ...GROUPS[op]));
227
+ // a choice of equations or inequalities (a CAS's solutions) reads in words: x = 2 or x = 3
228
+ if ((op === '|' || op === '&') && args.length >= 2 && args.every(isStatement)) {
229
+ // the other word inside keeps its brackets: (x = 1 or x = 2) and y = 3
230
+ const part = (n) => ((n.op === '|' || n.op === '&') && n.op !== op ? this.fence(r(n)) : r(n));
231
+ return wrap(row(args.map((n, i) => (i ? [this.text('conj', op === '|' ? 'or' : 'and'), part(n)] : [part(n)])).flat()));
232
+ }
203
233
  if (RELATIONS[op] && args.length === 2) return wrap(row(side(a, 'left'), this.rel(RELATIONS[op]), side(b, 'right')));
204
234
  if (BINARY[op] && args.length === 2) return wrap(row(side(a, 'left'), this.bin(BINARY[op]), side(b, 'right')));
205
235
 
206
236
  switch (op) {
207
237
  case '+': {
208
238
  // a + (-1·x) and a + (-3) read as a − x and a − 3.
209
- if (isMinusOneTimes(b)) return wrap(row(side(a, 'left'), this.bin(MINUS), this.wrap(b, ['op', 'op-mul'], this.render(b.args[1], ctx))));
239
+ if (isMinusOneTimes(b)) { // bracketed as after any minus: c + (−1)(a + b) is c − (a + b)
240
+ const x = b.args[1];
241
+ const drawn = needsBrackets({ op: '-' }, x, 'right') ? this.fence(r(x)) : r(x);
242
+ return wrap(row(side(a, 'left'), this.bin(MINUS), this.wrap(b, ['op', 'op-mul'], drawn)));
243
+ }
210
244
  if (b.type === 'number' && b.value.startsWith('-')) return wrap(row(side(a, 'left'), this.bin(MINUS), this.wrap(b, ['number'], this.text('num', b.value.slice(1)))));
211
245
  return wrap(row(side(a, 'left'), this.bin('+'), this.signed(b, side(b, 'right'))));
212
246
  }
@@ -218,8 +252,10 @@ class Layout {
218
252
  return wrap(this.fraction(node, ctx));
219
253
  case '^':
220
254
  return wrap(this.power(node, ctx));
221
- case '_':
222
- return wrap(this.script(r(a, { forceParens: true }), null, ctx, r(b, { level: ctx.level + 1 })));
255
+ case '_': { // (a + b)₁ keeps its brackets
256
+ const compound = bracketOp(a) && precedenceOf(bracketOp(a)) < 100;
257
+ return wrap(this.script(compound ? this.fence(r(a)) : r(a, { forceParens: true }), null, ctx, r(b, { level: ctx.level + 1 })));
258
+ }
223
259
  case 'neg':
224
260
  return wrap(row(this.text('sign', MINUS), unaryNeedsBrackets(op, a) ? this.fence(r(a)) : r(a, { before: ctx.before })));
225
261
  case 'pm':
@@ -251,10 +287,11 @@ class Layout {
251
287
  return wrap(this.fence(this.stack(r(a), r(b), false)));
252
288
  case '?:':
253
289
  return wrap(this.o.cases ? this.cases(node, ctx) : row(r(a), this.bin('?'), r(b), this.bin(':'), r(args[2])));
254
- case 'sum':
255
- return wrap(row(args.map((n, i) => (i ? [this.bin('+'), r(n)] : [r(n)])).flat()));
256
- case 'prod':
257
- return wrap(row(args.map((n, i) => (i ? [this.bin('·'), r(n)] : [r(n)])).flat()));
290
+ case 'sum': case 'prod': { // each term bracketed as + and · would bracket it: prod(a + b, c) is (a + b)·c
291
+ const parent = { op: op === 'sum' ? '+' : '*' };
292
+ const term = (n, i) => (needsBrackets(parent, n, i ? 'right' : 'left') ? this.fence(r(n)) : r(n));
293
+ return wrap(row(args.map((n, i) => (i ? [this.bin(op === 'sum' ? '+' : '·'), term(n, i)] : [term(n, i)])).flat()));
294
+ }
258
295
  case 'der':
259
296
  return wrap(this.derivative(node, ctx));
260
297
  case 'int':
@@ -282,15 +319,17 @@ class Layout {
282
319
  /** 2x, x·2, (x+1)(x−2), sin x cos x. */
283
320
  product(node, ctx) {
284
321
  const [a, b] = node.args;
285
- if (isMinusOneTimes(node)) return row(this.text('sign', MINUS), this.render(b, ctx));
322
+ if (isMinusOneTimes(node)) return row(this.text('sign', MINUS), unaryNeedsBrackets('neg', b) ? this.fence(this.render(b, ctx)) : this.render(b, ctx));
286
323
  const sides = bracketedSides(node);
287
- const implicit = isImplicitProduct(a, b, sides);
324
+ if (BIG_OPERATORS.includes(a.op)) sides.left = true; // (∑ i)·x: the sum's body would take in the x
325
+ // a product typed with · or × shows it (MathZetta's node.written); otherwise a sign only where one is needed
326
+ const implicit = !node.written && isImplicitProduct(a, b, sides);
288
327
  // "sin x · y" must keep its brackets: sin(x) y. Before another function it needn't: sin x cos x.
289
328
  const nextIsCall = startsWithCall(b);
290
- const left = sides.left ? this.fence(this.render(a, ctx)) : this.render(a, { ...ctx, before: implicit && !nextIsCall });
329
+ const left = sides.left ? this.fence(this.render(a, ctx)) : this.render(a, { ...ctx, before: implicit && !nextIsCall, leftFactor: true });
291
330
  const right = sides.right ? this.fence(this.render(b, ctx)) : this.render(b, { ...ctx, before: ctx.before });
292
331
  // A thin space before a function name: 2 sin x, x² ln x.
293
- const join = !implicit ? this.bin('·') : box(this.el(nextIsCall ? 'fnspace' : 'times', ''));
332
+ const join = !implicit ? this.bin(node.written === 'cross' ? '×' : '·') : box(this.el(nextIsCall ? 'fnspace' : 'times', ''));
294
333
  return row(left, join, right);
295
334
  }
296
335
 
@@ -316,19 +355,24 @@ class Layout {
316
355
  custom(node, ctx) {
317
356
  const name = customName(node.op);
318
357
  const args = node.args;
319
- if (DECORATIONS.includes(name) && args.length === 1) return this.decorate(name, this.render(args[0], ctx));
358
+ if (DECORATIONS.includes(name) && args.length === 1) return this.decorate(name, this.render(args[0], ctx), args[0]);
320
359
  // f(x), g′(x): a one-letter function is italic like a variable; sgn(x) is upright.
321
360
  const head = /^[A-Za-z]′*(⁻¹)?$/.test(name) ? this.symbol(name) : this.word(name);
322
361
  return row(head, box(this.el('callgap', '')), this.fence(this.list(args, ctx)));
323
362
  }
324
363
 
325
- decorate(name, b) {
364
+ decorate(name, b, base) {
326
365
  switch (name) {
327
366
  case 'boxed': return box(this.el('boxed', b.html), b.h + 0.22, b.d + 0.22);
328
- case 'cancel': return box(this.el('cancel', b.html), b.h, b.d);
367
+ // a drawn stroke, not a background: Windows high contrast drops backgrounds, and a canceled term would look kept
368
+ case 'cancel': return box(this.el('cancel', b.html + svg('cancel', `${this.p}-cancel-line`)), b.h, b.d);
329
369
  case 'underline': return box(this.el('underline', b.html), b.h, b.d + 0.12);
330
- case 'overline': case 'bar': return box(this.el('over', b.html), b.h + 0.14, b.d);
331
- default: return box(this.el('accent', this.el('accent-mark', ACCENTS[name]) + b.html), b.h + 0.3, b.d);
370
+ case 'overline': case 'bar': return box(this.el(`over${isShortLetter(base) ? ' over-low' : ''}`, b.html), b.h + 0.14, b.d);
371
+ default: {
372
+ // over a letter with no ascender (x, u, α) the mark comes down to the letter's top
373
+ const low = isShortLetter(base);
374
+ return box(this.el(`accent${low ? ' accent-low' : ''}`, this.el(`accent-mark accent-${name}`, ACCENTS[name]) + b.html), b.h + 0.3, b.d);
375
+ }
332
376
  }
333
377
  }
334
378
 
@@ -337,8 +381,14 @@ class Layout {
337
381
  fraction(node, ctx) {
338
382
  const [a, b] = node.args;
339
383
  if (ctx.level > 0 && this.o.scriptFractions === 'slash' && isSimpleArgument(a, true) && isSimpleArgument(b, true)) {
340
- const side = (n) => (n.type === 'op' && !isSimpleArgument(n) ? this.fence(this.render(n, ctx)) : this.render(n, ctx));
341
- return row(side(a), this.text('ord', '/'), side(b));
384
+ const inner = { ...ctx, leftFactor: false };
385
+ // x^{1/(2n)} is not x^{(1/2)n}: a product below the slash keeps its brackets
386
+ const side = (n, below) => (n.type === 'op' && (!isSimpleArgument(n) || (below && n.op === '*' && !isMinusOneTimes(n)))
387
+ ? this.fence(this.render(n, inner)) : this.render(n, inner));
388
+ // a leading minus needs no brackets: e^{−x²/2} reads the same as e^{(−x²)/2}
389
+ const top = a.type === 'op' && a.op === 'neg' ? this.render(a, inner) : side(a, false);
390
+ const slash = row(top, this.text('ord', '/'), side(b, true));
391
+ return ctx.leftFactor ? this.fence(slash) : slash; // and (1/2)n keeps its own
342
392
  }
343
393
  // A fraction inside a fraction, or in running text, is set smaller.
344
394
  const k = ctx.level > 0 || ctx.inFraction || !this.o.display ? 0.8 : 1;
@@ -346,7 +396,7 @@ class Layout {
346
396
  return this.stack(this.render(a, inner), this.render(b, inner), true, k);
347
397
  }
348
398
 
349
- /** One box over another, centred on the axis; with a bar for fractions, without for binomials. */
399
+ /** One box over another, centered on the axis; with a bar for fractions, without for binomials. */
350
400
  stack(num, den, bar = true, k = 1) {
351
401
  const scale = (b) => (k === 1 ? b.html : this.el('scaled', b.html, `font-size:${em(k)}`));
352
402
  const t = bar ? RULE : 0;
@@ -361,7 +411,7 @@ class Layout {
361
411
  /** x², (x+1)³, e^{x²}, sin²x, x₁². */
362
412
  power(node, ctx) {
363
413
  const [a, b] = node.args;
364
- const up = { ...ctx, level: ctx.level + 1, forceParens: false, before: false, inFraction: false };
414
+ const up = { ...ctx, level: ctx.level + 1, forceParens: false, before: false, inFraction: false, leftFactor: false };
365
415
  const exponent = () => this.render(b, up);
366
416
  if (this.o.trigPowers && TRIG.includes(a.op) && isPositiveWhole(b)) {
367
417
  return this.wrap(a, ['op', `op-${a.op}`], this.named(a, ctx, exponent()));
@@ -371,7 +421,8 @@ class Layout {
371
421
  return this.wrap(a, ['op', 'op-subscript'], this.script(this.render(a.args[0], { ...ctx, forceParens: true }), exponent(), ctx, sub));
372
422
  }
373
423
  // (sin x)^{1/2}: a named function keeps its own name outside the brackets only as sin²x.
374
- const fenceBase = needsBrackets(node, a, 'left') || (a.type === 'number' && a.value.startsWith('-')) || a.op === '/' || NAMED.includes(a.op);
424
+ const fenceBase = needsBrackets(node, a, 'left') || (a.type === 'number' && a.value.startsWith('-')) || a.op === '/' || NAMED.includes(a.op)
425
+ || BIG_OPERATORS.includes(a.op); // (∫x dx)², (∑ i)²: the exponent would sit on the body
375
426
  const base = fenceBase ? this.fence(this.render(a, ctx)) : this.render(a, { ...ctx, forceParens: true });
376
427
  return this.script(base, exponent(), ctx);
377
428
  }
@@ -448,6 +499,18 @@ class Layout {
448
499
 
449
500
  /** dy/dx, d²y/dx², and d/dx [f] with the body after the fraction. */
450
501
  derivative(node, ctx) {
502
+ const drawn = this.leibniz(node, ctx);
503
+ const { by, at } = derivativeOrder(node);
504
+ if (!at) return drawn;
505
+ // at a point, der(f, x = a): a bar as tall as the derivative, the point below it (|ₓ₌₂). The x there is a
506
+ // copy, with no id: the variable's id stays on the one in dx; the point (x = a) keeps its own.
507
+ const point = node.args[1];
508
+ const below = this.render({ ...point, args: [{ ...by, id: undefined }, at] }, { ...ctx, level: ctx.level + 1 });
509
+ return this.script(this.fence(drawn, '', '|'), null, ctx, below);
510
+ }
511
+
512
+ /** d/dx f drawn: the fraction, and the body after it (or on top, dy/dx). */
513
+ leibniz(node, ctx) {
451
514
  const { n, body, by, variable } = derivativeOrder(node);
452
515
  const up = { ...ctx, level: ctx.level + 1 };
453
516
  const d = () => this.text('d', 'd');
@@ -483,7 +546,7 @@ class Layout {
483
546
  return row(this.bigSign('int', body, lo, hi, ctx), body, dx);
484
547
  }
485
548
 
486
- /** The ∫ sign, centred on the axis and at least as tall as the integrand, with limits beside it. */
549
+ /** The ∫ sign, centered on the axis and at least as tall as the integrand, with limits beside it. */
487
550
  bigSign(name, body, lo, hi, ctx) {
488
551
  const small = !this.o.display || ctx.level > 0;
489
552
  const half = Math.max(small ? 0.6 : 0.95, Math.max(body.h - AXIS, body.d + AXIS) + 0.12);
@@ -508,7 +571,7 @@ class Layout {
508
571
  const arrow = () => this.rel('→');
509
572
  let under;
510
573
  switch (args.length) {
511
- case 1: return row(this.word('lim'), box(this.el('fnspace', '')), this.render(f, ctx));
574
+ case 1: return row(this.word('lim'), box(this.el('fnspace', '')), this.body(f, ctx));
512
575
  case 2: {
513
576
  const v = firstVariable(f);
514
577
  const approaches = second.type === 'number' || (second.type === 'symbol' && second.value.includes('∞'));
@@ -521,7 +584,7 @@ class Layout {
521
584
  under = row(r(second), arrow(), this.script(r(third), this.wrap(fourth, ['symbol'], this.text('ord', sign)), below));
522
585
  }
523
586
  }
524
- return row(this.under(this.word('lim'), under, ctx), this.render(f, ctx));
587
+ return row(this.under(this.word('lim'), under, ctx), this.body(f, ctx));
525
588
  }
526
589
 
527
590
  /** A word with something set small beneath it, lim over x → 0; the word keeps the baseline. */
@@ -533,12 +596,18 @@ class Layout {
533
596
  }
534
597
 
535
598
  /** ∑ and ∏ with the index below and the end above. */
599
+ /** What a limit, sum or product applies to: a sum or anything looser is bracketed, lim (x + 1) not lim x + 1. */
600
+ body(f, ctx) {
601
+ const op = bracketOp(f);
602
+ return op && precedenceOf(op) < precedenceOf('*') ? this.fence(this.render(f, ctx)) : this.render(f, ctx);
603
+ }
604
+
536
605
  bigOperator(name, args, ctx) {
537
606
  const [f, from, to] = args;
538
607
  const up = { ...ctx, level: ctx.level + 1 };
539
608
  const lo = from ? this.render(from, up) : null;
540
609
  const hi = to ? this.render(to, up) : null;
541
- const body = this.render(f, ctx);
610
+ const body = this.body(f, ctx);
542
611
  if (!this.o.display || ctx.level > 0) {
543
612
  const half = 0.55;
544
613
  const sign = svg(name, `${this.p}-bigsign`, `height:${em(2 * half)};width:${em(0.8)};vertical-align:${em(AXIS - half)}`);
@@ -557,6 +626,28 @@ class Layout {
557
626
  return row(op, body);
558
627
  }
559
628
 
629
+ /**
630
+ * A matrix: a grid of entries, centered on the math axis, in brackets as tall as it is. Each
631
+ * row that is a list in the tree is an element of its own (display: contents), so a row can
632
+ * be pointed at like any part.
633
+ */
634
+ matrix(node, rows, ctx) {
635
+ const ROWGAP = 0.3;
636
+ const cells = rows.map((r) => r.map((c) => this.render(c, ctx)));
637
+ const heights = cells.map((r) => ({ h: Math.max(LH, ...r.map((b) => b.h)), d: Math.max(LD, ...r.map((b) => b.d)) }));
638
+ const total = heights.reduce((s, x) => s + x.h + x.d, 0) + ROWGAP * (rows.length - 1);
639
+ const lift = AXIS + total / 2 - heights[0].h; // the first row's baseline
640
+ const html = cells.map((r, i) => {
641
+ const inner = r.map((b) => this.el('matrix-cell', b.html)).join('');
642
+ const tree = node.args[i];
643
+ return tree && tree.type === 'op' && tree.op === '[]' ? this.wrap(tree, ['op', 'op-list', 'matrix-row'], box(inner)).html : inner;
644
+ }).join('');
645
+ const columns = rows[0].length;
646
+ const grid = box(this.el('matrix', html, `grid-template-columns:repeat(${columns},auto);vertical-align:${em(lift)}`), AXIS + total / 2, total / 2 - AXIS);
647
+ const [open, close] = MATRICES[node.op] ?? ['[', ']'];
648
+ return this.fence(grid, open, close);
649
+ }
650
+
560
651
  /** c ? a : b → a brace with "a if c", "b otherwise". Nested ternaries add rows. */
561
652
  cases(node, ctx) {
562
653
  const rows = [];
@@ -565,7 +656,8 @@ class Layout {
565
656
  rows.push([this.render(n.args[1], ctx), row(this.word('if'), this.text('space', ''), this.render(n.args[0], ctx))]);
566
657
  n = n.args[2];
567
658
  }
568
- rows.push([this.render(n, ctx), this.word('otherwise')]);
659
+ // a case nobody wrote (`unchanged`: no else, no otherwise row) is not drawn
660
+ if (!(n.type === 'symbol' && n.value === 'unchanged')) rows.push([this.render(n, ctx), this.word('otherwise')]);
569
661
  const ROWGAP = 0.25;
570
662
  const heights = rows.map(([v, c]) => ({ h: Math.max(v.h, c.h), d: Math.max(v.d, c.d) }));
571
663
  const total = heights.reduce((s, x) => s + x.h + x.d, 0) + ROWGAP * (rows.length - 1);
@@ -583,7 +675,7 @@ function isSimpleArgument(node, inScript = false) {
583
675
  if (node.type === 'number') return !node.value.startsWith('-') || inScript;
584
676
  if (node.type === 'symbol') return true;
585
677
  if (node.type !== 'op') return false;
586
- if (node.op === 'abs') return !inScript;
678
+ if (node.op === 'abs' || matrixRows(node)) return !inScript; // |x| and a matrix bring their own brackets
587
679
  if (inScript && (node.op === 'neg' || node.op === '^')) return isSimpleArgument(node.args[0], true) && (node.op === 'neg' || isSimpleArgument(node.args[1], true));
588
680
  if (node.op === '*' && !isMinusOneTimes(node)) {
589
681
  return node.args.every((c) => (c.type === 'number' && !c.value.startsWith('-')) || isShortSymbol(c) || (c.op === '*' && isSimpleArgument(c, inScript)));
@@ -591,6 +683,11 @@ function isSimpleArgument(node, inScript = false) {
591
683
  return false;
592
684
  }
593
685
 
686
+ const STATEMENTS = ['=', '===', '≠', '≠=', '<', '>', '≤', '≥', '≈', '≡', '∈', '∉'];
687
+ /** An equation or inequality, or such statements joined by or / and. */
688
+ const isStatement = (n) => n.type === 'op' && n.args.length >= 2
689
+ && ((n.args.length === 2 && STATEMENTS.includes(n.op)) || ((n.op === '|' || n.op === '&') && n.args.every(isStatement)));
690
+
594
691
  const isShortSymbol = (n) => n.type === 'symbol' && (n.value.length === 1 || /^[α-ωΑ-Ω]$/.test(n.value) || Boolean(GREEK[n.value]));
595
692
  const isPositiveWhole = (n) => n.type === 'number' && /^[1-9]\d*$/.test(n.value) && Number(n.value) < 10;
596
693
 
@@ -603,3 +700,7 @@ function startsWithCall(node) {
603
700
  }
604
701
  return false;
605
702
  }
703
+
704
+ // Lookup tables are keyed by what an expression holds: with no prototype, a name like toString or
705
+ // constructor finds nothing rather than Object's own (and is drawn as the name it is).
706
+ for (const table of [OP_CLASS, RELATIONS, BINARY, INVERSE, CALLS, GROUPS, LATEX_SYMBOLS, ACCENTS]) Object.setPrototypeOf(table, null);
package/src/lite.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * '@mathzetta/inlinemath/lite' — Inline Math's drawing only: `toHTML()` and nothing live. The same layout,
3
- * glyphs, colours, highlights and accessible (spoken) labels as the full build, without the live
3
+ * glyphs, colors, highlights and accessible (spoken) labels as the full build, without the live
4
4
  * view (render, step animation, events), Markdown, the CAS or the calculator.
5
5
  *
6
6
  * import { toHTML } from '@mathzetta/inlinemath/lite';
package/src/markdown.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- // '@mathzetta/inlinemath/markdown' — Markdown with maths. See types.d.ts.
2
- export type { MarkdownOptions } from './types.js';
3
- export { markdownToHTML, renderMarkdownInto, extractMath, renderMarkdown } from './types.js';
1
+ // '@mathzetta/inlinemath/markdown' — Markdown with math. See types.d.ts.
2
+ export type { MarkdownOptions, VariableDefinition } from './types.js';
3
+ export { markdownToHTML, renderMarkdownInto, extractMath, renderMarkdown, createVariables, variables, Variables } from './types.js';