@mathzetta/inlinemath 0.2.0 → 0.4.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 (58) hide show
  1. package/README.md +37 -33
  2. package/dist/cas.external.js +2 -2
  3. package/dist/cas.js +2 -2
  4. package/dist/chunks/calculate-DHvovDQK.js +2 -0
  5. package/dist/chunks/draw-Bw547gEd.js +2 -0
  6. package/dist/chunks/edit-BC9D1cIE.js +2 -0
  7. package/dist/chunks/edit-CCe3uoyk.js +2 -0
  8. package/dist/chunks/html-6HJlblNm.js +2 -0
  9. package/dist/chunks/html-DzjcaM8w.js +2 -0
  10. package/dist/chunks/lite-6yr4ed_k.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 +21 -9
  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 +21 -9
  35. package/package.json +6 -6
  36. package/src/cas.d.ts +1 -1
  37. package/src/cas.js +71 -13
  38. package/src/draw.js +13 -9
  39. package/src/edit.js +11 -4
  40. package/src/glyphs.js +3 -2
  41. package/src/html.js +1 -1
  42. package/src/index.js +1 -1
  43. package/src/layout.js +117 -37
  44. package/src/lite.js +1 -1
  45. package/src/markdown.d.ts +1 -1
  46. package/src/markdown.js +139 -57
  47. package/src/mathzetta.js +2 -2
  48. package/src/select.js +7 -0
  49. package/src/types.d.ts +12 -10
  50. package/src/variables.js +44 -10
  51. package/src/view.js +69 -18
  52. package/dist/chunks/calculate-Cz87Lt0N.js +0 -2
  53. package/dist/chunks/draw-Bev17BJJ.js +0 -2
  54. package/dist/chunks/edit-C65xXzo8.js +0 -2
  55. package/dist/chunks/edit-M68aRA5o.js +0 -2
  56. package/dist/chunks/html-BimAqn7x.js +0 -2
  57. package/dist/chunks/html-CupluJSh.js +0 -2
  58. package/dist/chunks/lite-3Fb-OHbt.js +0 -2
package/src/draw.js CHANGED
@@ -3,7 +3,7 @@
3
3
  * calculator for the full build; lite.js uses this as it is). No DOM needed, so this runs in Node too.
4
4
  */
5
5
 
6
- import { parseTree, fromPostfix } from './mathzetta.js';
6
+ import { parseTree, fromPostfix, walk } from './mathzetta.js';
7
7
  import { layout } from './layout.js';
8
8
  import { select, numberTree } from './select.js';
9
9
 
@@ -19,7 +19,11 @@ export function treeOf(input, options = {}) {
19
19
  if (typeof input === 'string') return parseTree(input, blocks ? { blocks: (text) => blocks(text, options.scope) } : {});
20
20
  if (Array.isArray(input)) return fromPostfix(input);
21
21
  if (input && typeof input === 'object' && input.type) {
22
- return input.id === undefined ? numberTree(structuredClone(input)) : input;
22
+ if (input.id !== undefined) return input;
23
+ // a tree made by hand: values as MathZetta writes them, text ({ type: 'number', value: 3 } is '3')
24
+ const tree = structuredClone(input);
25
+ walk(tree, (n) => { if (n.type !== 'op' && n.value !== undefined) n.value = String(n.value); });
26
+ return numberTree(tree);
23
27
  }
24
28
  throw new Error('Inline Math needs an expression, standard postfix or a tree');
25
29
  }
@@ -27,7 +31,7 @@ export function treeOf(input, options = {}) {
27
31
  /**
28
32
  * @param {string|string[]|object} input
29
33
  * @param {object} [options] layout options (see DEFAULTS in layout.js) plus:
30
- * @param {object|Array} [options.colors] { 'x^2': 'red', 3: '#06c' } or [[target, colour], …]
34
+ * @param {object|Array} [options.colors] { 'x^2': 'red', 3: '#06c' } or [[target, color], …]
31
35
  * @param {*} [options.highlight] target(s) to mark with the mv-hl class
32
36
  * @param {object} [options.scope] variable values for `{{...}}` blocks
33
37
  * @returns {string}
@@ -41,9 +45,9 @@ export function toHTML(input, options = {}) {
41
45
  export function layoutOptions(tree, options) {
42
46
  const { colors, highlight, scope, blocks, ...rest } = options;
43
47
  const styles = new Map();
44
- for (const [target, colour] of pairs(colors)) {
45
- if (!isColour(colour)) continue; // one CSS colour value, nothing more: no `;`, no url(…)
46
- for (const n of select(tree, target)) styles.set(n, `color:${colour}`);
48
+ for (const [target, color] of pairs(colors)) {
49
+ if (!isColor(color)) continue; // one CSS color value, nothing more: no `;`, no url(…)
50
+ for (const n of select(tree, target)) styles.set(n, `color:${color}`);
47
51
  }
48
52
  const marked = new Set(highlight === undefined ? [] : select(tree, highlight));
49
53
  if (!styles.size && !marked.size) return rest;
@@ -59,9 +63,9 @@ export function layoutOptions(tree, options) {
59
63
  };
60
64
  }
61
65
 
62
- /** { 'x^2': 'red', 3: 'blue' } or [[target, colour]] → [[target, colour]]; numeric keys become ids. */
63
- /** A colour a style attribute can hold on its own: red, #06c, rgb(0 102 204 / 50%), var(--accent). */
64
- function isColour(value) {
66
+ /** { 'x^2': 'red', 3: 'blue' } or [[target, color]] → [[target, color]]; numeric keys become ids. */
67
+ /** A color a style attribute can hold on its own: red, #06c, rgb(0 102 204 / 50%), var(--accent). */
68
+ function isColor(value) {
65
69
  return typeof value === 'string' && /^[#\w\s.,%()/+-]+$/.test(value) && !/url\s*\(|expression/i.test(value);
66
70
  }
67
71
 
package/src/edit.js CHANGED
@@ -9,7 +9,7 @@
9
9
  * 'mathzetta/calculate', so a buildless page's import map stays the same.
10
10
  */
11
11
 
12
- import { bare } from './variables.js';
12
+ import { bare } from './select.js';
13
13
 
14
14
  /** A copy of `tree` (ids dropped) with the node at `path` replaced by `part`. */
15
15
  export function replaceAt(tree, path, part) {
@@ -28,16 +28,17 @@ export function replaceAt(tree, path, part) {
28
28
  * @param {(tree: object, text: string) => void} how.commit called with the new part
29
29
  * @param {() => void} [how.cancel] called when nothing changed
30
30
  * @param {string} [how.label] the box's accessible name
31
- * @returns {HTMLInputElement|null}
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
32
33
  */
33
- export function openEditor(element, text, { parse, commit, cancel, label = 'Edit' }) {
34
+ export function openEditor(element, text, { parse, commit, cancel, label = 'Edit', prefix = 'mv' }) {
34
35
  const doc = element.ownerDocument;
35
36
  if (!doc || !doc.body) return null;
36
37
  const view = doc.defaultView;
37
38
  const r = element.getBoundingClientRect();
38
39
  const input = doc.createElement('input');
39
40
  input.type = 'text';
40
- input.className = 'mv-edit';
41
+ input.className = `${prefix}-edit`;
41
42
  input.value = text;
42
43
  input.spellcheck = false;
43
44
  input.autocomplete = 'off';
@@ -62,6 +63,12 @@ export function openEditor(element, text, { parse, commit, cancel, label = 'Edit
62
63
  done = true;
63
64
  input.remove();
64
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
+ };
65
72
  const finish = (keep) => {
66
73
  if (done) return true;
67
74
  if (!keep || input.value === text) {
package/src/glyphs.js CHANGED
@@ -16,8 +16,9 @@ export const PATHS = {
16
16
  ')': { fill: 'M0.08,0 C0.9,0.2 0.9,0.8 0.08,1 L0,0.975 C0.52,0.75 0.52,0.25 0,0.025 Z' },
17
17
  '{': { fill: 'M1,0 C0.45,0 0.5,0.05 0.5,0.2 L0.5,0.38 C0.5,0.46 0.35,0.49 0.05,0.5 C0.35,0.51 0.5,0.54 0.5,0.62 L0.5,0.8 C0.5,0.95 0.45,1 1,1 L1,0.985 C0.68,0.985 0.64,0.95 0.64,0.8 L0.64,0.62 C0.64,0.53 0.55,0.505 0.3,0.5 C0.55,0.495 0.64,0.47 0.64,0.38 L0.64,0.2 C0.64,0.05 0.68,0.015 1,0.015 Z' },
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
- // Radical: short tick, long down-stroke, long up-stroke to the top right.
20
- 'sqrt': { stroke: 'M0,0.62 L0.18,0.55 L0.45,0.97 L0.98,0.015' },
19
+ // Radical: short tick, long down-stroke, long up-stroke to the top right, ending at the very top
20
+ // (y = 0), which CSS puts on the center of the bar (.mv-hook).
21
+ 'sqrt': { stroke: 'M0,0.62 L0.18,0.55 L0.45,0.97 L0.98,0' },
21
22
  // \cancel: one stroke, bottom left to top right, stretched over what it crosses out.
22
23
  'cancel': { stroke: 'M0,1 L1,0' },
23
24
  // Integral: an S slanted to the right with small hooks at each end.
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.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';
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
  *
@@ -28,7 +28,7 @@ import { svg } from './glyphs.js';
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
@@ -39,7 +39,7 @@ const OP_CLASS = {
39
39
  '+': 'add', '-': 'sub', '*': 'mul', '/': 'frac', '^': 'pow', '_': 'subscript', 'neg': 'neg', 'pm': 'pm',
40
40
  '!': 'factorial', '=': 'eq', '===': 'eq', '≠': 'neq', '≠=': 'neq', '<': 'lt', '>': 'gt', '≤': 'le', '≥': 'ge',
41
41
  '≈': 'approx', '≡': 'equiv', '∈': 'in', '∉': 'notin', '∪': 'union', '∩': 'intersect', '→': 'to', '±': 'pm',
42
- '&': 'and', '|': 'or', '\\not': 'not', '\\xor': 'xor', '\\nand': 'nand', '\\nor': 'nor', '?:': 'cases',
42
+ '&': 'and', '|': 'or', '\\not': 'not', '\\xor': 'xor', '\\nand': 'nand', '\\nor': 'nor', '\\implies': 'implies', '\\iff': 'iff', '?:': 'cases',
43
43
  '()': 'tuple', '[]': 'list', '{}': 'set', '(]': 'interval', '[)': 'interval',
44
44
  '\\sumidx': 'sum', '\\prodidx': 'prod', 'mod': 'mod', 'pmod': 'pmod',
45
45
  pmatrix: 'matrix', bmatrix: 'matrix', vmatrix: 'matrix',
@@ -48,22 +48,26 @@ const OP_CLASS = {
48
48
  const RELATIONS = {
49
49
  '=': '=', '===': '=', '≠': '≠', '≠=': '≠', '<': '<', '>': '>', '≤': '≤', '≥': '≥',
50
50
  '∈': '∈', '∉': '∉', '→': '→', '≈': '≈', '≡': '≡',
51
- '&': '∧', '|': '∨', '\\xor': '⊕', '\\nand': '↑', '\\nor': '↓',
51
+ '&': '∧', '|': '∨', '\\xor': '⊕', '\\nand': '↑', '\\nor': '↓', '\\implies': '⇒', '\\iff': '⇔',
52
52
  };
53
53
  const BINARY = { '±': '±', '∪': '∪', '∩': '∩', 'mod': 'mod' };
54
54
 
55
55
  const TRIG = ['sin', 'cos', 'tan', 'csc', 'sec', 'cot', 'sinh', 'cosh', 'tanh'];
56
- const INVERSE = { arcsin: 'sin', arccos: 'cos', arctan: 'tan', arcsinh: 'sinh', arccosh: 'cosh', arctanh: 'tanh' };
56
+ const INVERSE = { arcsin: 'sin', arccos: 'cos', arctan: 'tan', arcsec: 'sec', arccsc: 'csc', arccot: 'cot', arcsinh: 'sinh', arccosh: 'cosh', arctanh: 'tanh' };
57
57
  /** Functions written with a name and, when the argument is simple, no brackets: sin x, ln x. */
58
58
  const NAMED = [...TRIG, ...Object.keys(INVERSE), 'ln', 'det'];
59
59
  /** Functions always written with brackets: max(a, b). */
60
60
  const CALLS = { atan2: 'atan2', max: 'max', min: 'min', gcd: 'gcd', mean: 'mean', round: 'round', fixed: 'fixed', expm1: 'expm1', random: 'random' };
61
61
 
62
62
  const GROUPS = { '()': ['(', ')'], '[]': ['[', ']'], '{}': ['{', '}'], '(]': ['(', ']'], '[)': ['[', ')'] };
63
+ const BIG_OPERATORS = ['int', 'lim', '\\sumidx', '\\prodidx']; // a body after them takes in whatever follows
63
64
  const LATEX_SYMBOLS = { '\\partial': '∂', '\\nabla': '∇', '\\ell': 'ℓ', '\\infty': '∞', '\\emptyset': '∅' };
64
65
 
65
66
  /** Custom functions drawn as decorations: \boxed{x} parses as boxed(x). */
66
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);
67
71
  const DECORATIONS = ['boxed', 'overline', 'bar', 'underline', 'cancel', ...Object.keys(ACCENTS)];
68
72
 
69
73
  export const DEFAULTS = {
@@ -168,11 +172,11 @@ class Layout {
168
172
  if (node.type === 'op') attrs += ` data-op="${escape(node.op)}"`;
169
173
  const extra = this.o.attributes ? this.o.attributes(node) || {} : {};
170
174
  for (const [k, v] of Object.entries(extra)) {
171
- 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
172
176
  }
173
177
  const style = [extra.style, this.o.style && this.o.style(node)].filter(Boolean).join(';');
174
178
  const all = b.leaf ? ['n', ...kinds, b.leaf.kind] : ['n', ...kinds];
175
- 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(' ');
176
180
  const content = b.leaf ? b.leaf.content : b.html;
177
181
  return { html: `<span class="${cls}"${style ? ` style="${escape(style)}"` : ''}${attrs}>${content}</span>`, h: b.h, d: b.d };
178
182
  }
@@ -187,17 +191,30 @@ class Layout {
187
191
  }
188
192
 
189
193
  number(node) {
194
+ // a repeating decimal, 0.166.. (read from 0.1\overline{6}): the block drawn once, with a bar over it
195
+ const repeating = /^(-?\d*\.)(\d*)\.\.$/.exec(node.value);
196
+ if (repeating) {
197
+ const [, head, frac] = repeating;
198
+ let L = 1;
199
+ for (let k = 1; 2 * k <= frac.length; k++) if (frac.slice(-k) === frac.slice(-2 * k, -k)) { L = k; break; }
200
+ let prefix = frac;
201
+ while (prefix.endsWith(frac.slice(-L)) && prefix.length >= L) prefix = prefix.slice(0, -L);
202
+ const first = this.text('num', (head + prefix).replace(/^-/, MINUS));
203
+ const block = this.text('num', frac.slice(-L));
204
+ return this.wrap(node, ['number'], row(first, box(this.el('over', block.html), block.h + 0.14, block.d)));
205
+ }
190
206
  return this.wrap(node, ['number'], this.text('num', node.value.replace(/^-/, MINUS)));
191
207
  }
192
208
 
193
209
  symbol(v) {
194
210
  if (GREEK[v]) v = GREEK[v];
195
- if (LATEX_SYMBOLS[v]) return this.text('ord', LATEX_SYMBOLS[v]);
211
+ if (LATEX_SYMBOLS[v]) return this.text('ord', LATEX_SYMBOLS[v]); // a null-prototype table: toString is a name
196
212
  if (v === '\\+' || v === '\\-') return this.text('ord', v[1]);
197
213
  if (v === '-∞') return this.text('ord', MINUS + '∞');
198
214
  if (/^[A-Za-z]$/.test(v) || /^[α-ω]$/.test(v)) return this.text('var', v);
199
215
  if (/^[A-Za-z]′+$/.test(v)) return box(this.el('var', escape(v[0])) + this.el('prime', escape(v.slice(1))));
200
216
  if (/^Δ[A-Za-z]$/.test(v)) return box(this.el('ord', 'Δ') + this.el('var', v[1]));
217
+ if (/^d[A-Za-zα-ω]$/.test(v)) return box(this.el('ord', 'd') + this.el('var', v[1])); // a differential: dx, dθ (the d upright)
201
218
  if (v.endsWith('⁻¹')) return this.script(this.symbol(v.slice(0, -2)), this.text('num', MINUS + '1'), { level: 0 });
202
219
  if (/^\\[A-Za-z]+$/.test(v)) return this.text('name', v.slice(1));
203
220
  if (/^[A-Za-z]{2,}$/.test(v)) return this.text('name', v); // upright, like \mathrm
@@ -209,7 +226,7 @@ class Layout {
209
226
  operation(node, ctx) {
210
227
  const { op, args } = node;
211
228
  const [a, b] = args;
212
- const r = (n, c = {}) => this.render(n, { ...ctx, ...c, forceParens: c.forceParens || false, before: c.before || false });
229
+ const r = (n, c = {}) => this.render(n, { ...ctx, ...c, forceParens: c.forceParens || false, before: c.before || false, leftFactor: false });
213
230
  const kind = OP_CLASS[op] ?? (/^[a-z0-9]+$/i.test(op) ? op : 'other');
214
231
  const wrap = (content) => this.wrap(node, ['op', `op-${kind}`], content);
215
232
  const side = (child, s) => (needsBrackets(node, child, s) && child.op !== '/' ? this.fence(r(child)) : r(child));
@@ -219,14 +236,25 @@ class Layout {
219
236
  if (isCustomFunction(op)) return wrap(this.custom(node, ctx));
220
237
  const rows = matrixRows(node); // pmatrix, bmatrix, vmatrix, and [[1, 2], [3, 4]]
221
238
  if (rows) return wrap(this.matrix(node, rows, ctx));
239
+ if (op === '{}' && !args.length) return wrap(this.text('op', '∅')); // the empty set
222
240
  if (GROUPS[op]) return wrap(this.fence(this.list(args, ctx), ...GROUPS[op]));
241
+ // a choice of equations or inequalities (a CAS's solutions) reads in words: x = 2 or x = 3
242
+ if ((op === '|' || op === '&') && args.length >= 2 && args.every(isStatement)) {
243
+ // the other word inside keeps its brackets: (x = 1 or x = 2) and y = 3
244
+ const part = (n) => ((n.op === '|' || n.op === '&') && n.op !== op ? this.fence(r(n)) : r(n));
245
+ return wrap(row(args.map((n, i) => (i ? [this.text('conj', op === '|' ? 'or' : 'and'), part(n)] : [part(n)])).flat()));
246
+ }
223
247
  if (RELATIONS[op] && args.length === 2) return wrap(row(side(a, 'left'), this.rel(RELATIONS[op]), side(b, 'right')));
224
248
  if (BINARY[op] && args.length === 2) return wrap(row(side(a, 'left'), this.bin(BINARY[op]), side(b, 'right')));
225
249
 
226
250
  switch (op) {
227
251
  case '+': {
228
252
  // a + (-1·x) and a + (-3) read as a − x and a − 3.
229
- if (isMinusOneTimes(b)) return wrap(row(side(a, 'left'), this.bin(MINUS), this.wrap(b, ['op', 'op-mul'], this.render(b.args[1], ctx))));
253
+ if (isMinusOneTimes(b)) { // bracketed as after any minus: c + (−1)(a + b) is c − (a + b)
254
+ const x = b.args[1];
255
+ const drawn = needsBrackets({ op: '-' }, x, 'right') ? this.fence(r(x)) : r(x);
256
+ return wrap(row(side(a, 'left'), this.bin(MINUS), this.wrap(b, ['op', 'op-mul'], drawn)));
257
+ }
230
258
  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)))));
231
259
  return wrap(row(side(a, 'left'), this.bin('+'), this.signed(b, side(b, 'right'))));
232
260
  }
@@ -238,8 +266,10 @@ class Layout {
238
266
  return wrap(this.fraction(node, ctx));
239
267
  case '^':
240
268
  return wrap(this.power(node, ctx));
241
- case '_':
242
- return wrap(this.script(r(a, { forceParens: true }), null, ctx, r(b, { level: ctx.level + 1 })));
269
+ case '_': { // (a + b)₁ keeps its brackets
270
+ const compound = bracketOp(a) && precedenceOf(bracketOp(a)) < 100;
271
+ return wrap(this.script(compound ? this.fence(r(a)) : r(a, { forceParens: true }), null, ctx, r(b, { level: ctx.level + 1 })));
272
+ }
243
273
  case 'neg':
244
274
  return wrap(row(this.text('sign', MINUS), unaryNeedsBrackets(op, a) ? this.fence(r(a)) : r(a, { before: ctx.before })));
245
275
  case 'pm':
@@ -271,10 +301,17 @@ class Layout {
271
301
  return wrap(this.fence(this.stack(r(a), r(b), false)));
272
302
  case '?:':
273
303
  return wrap(this.o.cases ? this.cases(node, ctx) : row(r(a), this.bin('?'), r(b), this.bin(':'), r(args[2])));
274
- case 'sum':
275
- return wrap(row(args.map((n, i) => (i ? [this.bin('+'), r(n)] : [r(n)])).flat()));
276
- case 'prod':
277
- return wrap(row(args.map((n, i) => (i ? [this.bin('·'), r(n)] : [r(n)])).flat()));
304
+ case 'sum': case 'prod': { // each term bracketed as + and · would bracket it: prod(a + b, c) is (a + b)·c
305
+ const parent = { op: op === 'sum' ? '+' : '*' };
306
+ const term = (n, i) => (needsBrackets(parent, n, i ? 'right' : 'left') ? this.fence(r(n)) : r(n));
307
+ return wrap(row(args.map((n, i) => (i ? [this.bin(op === 'sum' ? '+' : '·'), term(n, i)] : [term(n, i)])).flat()));
308
+ }
309
+ case 'setbuilder': // {x | x > 2}
310
+ return wrap(this.fence(row(r(a), this.bin('|'), r(b)), '{', '}'));
311
+ case 'evaluated': { // [F]_a^b: F in square brackets, the limits on the right (the variable isn't drawn)
312
+ const limit = (n) => this.render(n, { ...ctx, level: ctx.level + 1 });
313
+ return wrap(this.script(this.fence(r(a), '[', ']'), limit(args[3]), ctx, limit(args[2])));
314
+ }
278
315
  case 'der':
279
316
  return wrap(this.derivative(node, ctx));
280
317
  case 'int':
@@ -302,15 +339,17 @@ class Layout {
302
339
  /** 2x, x·2, (x+1)(x−2), sin x cos x. */
303
340
  product(node, ctx) {
304
341
  const [a, b] = node.args;
305
- if (isMinusOneTimes(node)) return row(this.text('sign', MINUS), this.render(b, ctx));
342
+ if (isMinusOneTimes(node)) return row(this.text('sign', MINUS), unaryNeedsBrackets('neg', b) ? this.fence(this.render(b, ctx)) : this.render(b, ctx));
306
343
  const sides = bracketedSides(node);
307
- const implicit = isImplicitProduct(a, b, sides);
344
+ if (BIG_OPERATORS.includes(a.op)) sides.left = true; // (∑ i)·x: the sum's body would take in the x
345
+ // a product typed with · or × shows it (MathZetta's node.written); otherwise a sign only where one is needed
346
+ const implicit = !node.written && isImplicitProduct(a, b, sides);
308
347
  // "sin x · y" must keep its brackets: sin(x) y. Before another function it needn't: sin x cos x.
309
348
  const nextIsCall = startsWithCall(b);
310
- const left = sides.left ? this.fence(this.render(a, ctx)) : this.render(a, { ...ctx, before: implicit && !nextIsCall });
349
+ const left = sides.left ? this.fence(this.render(a, ctx)) : this.render(a, { ...ctx, before: implicit && !nextIsCall, leftFactor: true });
311
350
  const right = sides.right ? this.fence(this.render(b, ctx)) : this.render(b, { ...ctx, before: ctx.before });
312
351
  // A thin space before a function name: 2 sin x, x² ln x.
313
- const join = !implicit ? this.bin('·') : box(this.el(nextIsCall ? 'fnspace' : 'times', ''));
352
+ const join = !implicit ? this.bin(node.written === 'cross' ? '×' : '·') : box(this.el(nextIsCall ? 'fnspace' : 'times', ''));
314
353
  return row(left, join, right);
315
354
  }
316
355
 
@@ -336,20 +375,24 @@ class Layout {
336
375
  custom(node, ctx) {
337
376
  const name = customName(node.op);
338
377
  const args = node.args;
339
- if (DECORATIONS.includes(name) && args.length === 1) return this.decorate(name, this.render(args[0], ctx));
378
+ if (DECORATIONS.includes(name) && args.length === 1) return this.decorate(name, this.render(args[0], ctx), args[0]);
340
379
  // f(x), g′(x): a one-letter function is italic like a variable; sgn(x) is upright.
341
380
  const head = /^[A-Za-z]′*(⁻¹)?$/.test(name) ? this.symbol(name) : this.word(name);
342
381
  return row(head, box(this.el('callgap', '')), this.fence(this.list(args, ctx)));
343
382
  }
344
383
 
345
- decorate(name, b) {
384
+ decorate(name, b, base) {
346
385
  switch (name) {
347
386
  case 'boxed': return box(this.el('boxed', b.html), b.h + 0.22, b.d + 0.22);
348
- // a drawn stroke, not a background: Windows high contrast drops backgrounds, and a cancelled term would look kept
387
+ // a drawn stroke, not a background: Windows high contrast drops backgrounds, and a canceled term would look kept
349
388
  case 'cancel': return box(this.el('cancel', b.html + svg('cancel', `${this.p}-cancel-line`)), b.h, b.d);
350
389
  case 'underline': return box(this.el('underline', b.html), b.h, b.d + 0.12);
351
- case 'overline': case 'bar': return box(this.el('over', b.html), b.h + 0.14, b.d);
352
- default: return box(this.el('accent', this.el('accent-mark', ACCENTS[name]) + b.html), b.h + 0.3, b.d);
390
+ case 'overline': case 'bar': return box(this.el(`over${isShortLetter(base) ? ' over-low' : ''}`, b.html), b.h + 0.14, b.d);
391
+ default: {
392
+ // over a letter with no ascender (x, u, α) the mark comes down to the letter's top
393
+ const low = isShortLetter(base);
394
+ return box(this.el(`accent${low ? ' accent-low' : ''}`, this.el(`accent-mark accent-${name}`, ACCENTS[name]) + b.html), b.h + 0.3, b.d);
395
+ }
353
396
  }
354
397
  }
355
398
 
@@ -358,8 +401,14 @@ class Layout {
358
401
  fraction(node, ctx) {
359
402
  const [a, b] = node.args;
360
403
  if (ctx.level > 0 && this.o.scriptFractions === 'slash' && isSimpleArgument(a, true) && isSimpleArgument(b, true)) {
361
- const side = (n) => (n.type === 'op' && !isSimpleArgument(n) ? this.fence(this.render(n, ctx)) : this.render(n, ctx));
362
- return row(side(a), this.text('ord', '/'), side(b));
404
+ const inner = { ...ctx, leftFactor: false };
405
+ // x^{1/(2n)} is not x^{(1/2)n}: a product below the slash keeps its brackets
406
+ const side = (n, below) => (n.type === 'op' && (!isSimpleArgument(n) || (below && n.op === '*' && !isMinusOneTimes(n)))
407
+ ? this.fence(this.render(n, inner)) : this.render(n, inner));
408
+ // a leading minus needs no brackets: e^{−x²/2} reads the same as e^{(−x²)/2}
409
+ const top = a.type === 'op' && a.op === 'neg' ? this.render(a, inner) : side(a, false);
410
+ const slash = row(top, this.text('ord', '/'), side(b, true));
411
+ return ctx.leftFactor ? this.fence(slash) : slash; // and (1/2)n keeps its own
363
412
  }
364
413
  // A fraction inside a fraction, or in running text, is set smaller.
365
414
  const k = ctx.level > 0 || ctx.inFraction || !this.o.display ? 0.8 : 1;
@@ -367,7 +416,7 @@ class Layout {
367
416
  return this.stack(this.render(a, inner), this.render(b, inner), true, k);
368
417
  }
369
418
 
370
- /** One box over another, centred on the axis; with a bar for fractions, without for binomials. */
419
+ /** One box over another, centered on the axis; with a bar for fractions, without for binomials. */
371
420
  stack(num, den, bar = true, k = 1) {
372
421
  const scale = (b) => (k === 1 ? b.html : this.el('scaled', b.html, `font-size:${em(k)}`));
373
422
  const t = bar ? RULE : 0;
@@ -382,7 +431,7 @@ class Layout {
382
431
  /** x², (x+1)³, e^{x²}, sin²x, x₁². */
383
432
  power(node, ctx) {
384
433
  const [a, b] = node.args;
385
- const up = { ...ctx, level: ctx.level + 1, forceParens: false, before: false, inFraction: false };
434
+ const up = { ...ctx, level: ctx.level + 1, forceParens: false, before: false, inFraction: false, leftFactor: false };
386
435
  const exponent = () => this.render(b, up);
387
436
  if (this.o.trigPowers && TRIG.includes(a.op) && isPositiveWhole(b)) {
388
437
  return this.wrap(a, ['op', `op-${a.op}`], this.named(a, ctx, exponent()));
@@ -392,7 +441,8 @@ class Layout {
392
441
  return this.wrap(a, ['op', 'op-subscript'], this.script(this.render(a.args[0], { ...ctx, forceParens: true }), exponent(), ctx, sub));
393
442
  }
394
443
  // (sin x)^{1/2}: a named function keeps its own name outside the brackets only as sin²x.
395
- const fenceBase = needsBrackets(node, a, 'left') || (a.type === 'number' && a.value.startsWith('-')) || a.op === '/' || NAMED.includes(a.op);
444
+ const fenceBase = needsBrackets(node, a, 'left') || (a.type === 'number' && a.value.startsWith('-')) || a.op === '/' || NAMED.includes(a.op)
445
+ || BIG_OPERATORS.includes(a.op); // (∫x dx)², (∑ i)²: the exponent would sit on the body
396
446
  const base = fenceBase ? this.fence(this.render(a, ctx)) : this.render(a, { ...ctx, forceParens: true });
397
447
  return this.script(base, exponent(), ctx);
398
448
  }
@@ -430,13 +480,16 @@ class Layout {
430
480
  const top = Math.max(inner.h, LH) + GAP + RULE;
431
481
  const depth = Math.max(inner.d, LD);
432
482
  const height = top + depth;
433
- const hook = svg('sqrt', `${this.p}-hook`, `height:${em(height)};width:${em(0.5 + 0.06 * (height - 1))};vertical-align:${em(-depth)}`);
483
+ // The hook is drawn inside the radicand's box and sized by CSS to it (inlinemath.css .mv-hook), from the
484
+ // bar's center down: its tip meets the bar whatever the font or the content. Only its width is estimated.
485
+ const width = 0.5 + 0.06 * (height - 1);
486
+ const hook = svg('sqrt', `${this.p}-hook`, `width:${em(width)};left:${em(-width)}`);
434
487
  let pre = '';
435
488
  if (index) {
436
489
  const k = SCRIPT * 0.8;
437
490
  pre = this.el('rootindex', index.html, `font-size:${em(k)};vertical-align:${em((-depth + 0.55 * height) / k)}`);
438
491
  }
439
- return box(this.el('sqrt', pre + hook + this.el('radicand', inner.html)), top, depth);
492
+ return box(this.el('sqrt', pre + this.el('radicand', hook + inner.html, `margin-left:${em(width + 0.05)}`)), top, depth);
440
493
  }
441
494
 
442
495
  /**
@@ -469,6 +522,18 @@ class Layout {
469
522
 
470
523
  /** dy/dx, d²y/dx², and d/dx [f] with the body after the fraction. */
471
524
  derivative(node, ctx) {
525
+ const drawn = this.leibniz(node, ctx);
526
+ const { by, at } = derivativeOrder(node);
527
+ if (!at) return drawn;
528
+ // at a point, der(f, x = a): a bar as tall as the derivative, the point below it (|ₓ₌₂). The x there is a
529
+ // copy, with no id: the variable's id stays on the one in dx; the point (x = a) keeps its own.
530
+ const point = node.args[1];
531
+ const below = this.render({ ...point, args: [{ ...by, id: undefined }, at] }, { ...ctx, level: ctx.level + 1 });
532
+ return this.script(this.fence(drawn, '', '|'), null, ctx, below);
533
+ }
534
+
535
+ /** d/dx f drawn: the fraction, and the body after it (or on top, dy/dx). */
536
+ leibniz(node, ctx) {
472
537
  const { n, body, by, variable } = derivativeOrder(node);
473
538
  const up = { ...ctx, level: ctx.level + 1 };
474
539
  const d = () => this.text('d', 'd');
@@ -504,7 +569,7 @@ class Layout {
504
569
  return row(this.bigSign('int', body, lo, hi, ctx), body, dx);
505
570
  }
506
571
 
507
- /** The ∫ sign, centred on the axis and at least as tall as the integrand, with limits beside it. */
572
+ /** The ∫ sign, centered on the axis and at least as tall as the integrand, with limits beside it. */
508
573
  bigSign(name, body, lo, hi, ctx) {
509
574
  const small = !this.o.display || ctx.level > 0;
510
575
  const half = Math.max(small ? 0.6 : 0.95, Math.max(body.h - AXIS, body.d + AXIS) + 0.12);
@@ -529,7 +594,7 @@ class Layout {
529
594
  const arrow = () => this.rel('→');
530
595
  let under;
531
596
  switch (args.length) {
532
- case 1: return row(this.word('lim'), box(this.el('fnspace', '')), this.render(f, ctx));
597
+ case 1: return row(this.word('lim'), box(this.el('fnspace', '')), this.body(f, ctx));
533
598
  case 2: {
534
599
  const v = firstVariable(f);
535
600
  const approaches = second.type === 'number' || (second.type === 'symbol' && second.value.includes('∞'));
@@ -542,7 +607,7 @@ class Layout {
542
607
  under = row(r(second), arrow(), this.script(r(third), this.wrap(fourth, ['symbol'], this.text('ord', sign)), below));
543
608
  }
544
609
  }
545
- return row(this.under(this.word('lim'), under, ctx), this.render(f, ctx));
610
+ return row(this.under(this.word('lim'), under, ctx), this.body(f, ctx));
546
611
  }
547
612
 
548
613
  /** A word with something set small beneath it, lim over x → 0; the word keeps the baseline. */
@@ -554,12 +619,18 @@ class Layout {
554
619
  }
555
620
 
556
621
  /** ∑ and ∏ with the index below and the end above. */
622
+ /** What a limit, sum or product applies to: a sum or anything looser is bracketed, lim (x + 1) not lim x + 1. */
623
+ body(f, ctx) {
624
+ const op = bracketOp(f);
625
+ return op && precedenceOf(op) < precedenceOf('*') ? this.fence(this.render(f, ctx)) : this.render(f, ctx);
626
+ }
627
+
557
628
  bigOperator(name, args, ctx) {
558
629
  const [f, from, to] = args;
559
630
  const up = { ...ctx, level: ctx.level + 1 };
560
631
  const lo = from ? this.render(from, up) : null;
561
632
  const hi = to ? this.render(to, up) : null;
562
- const body = this.render(f, ctx);
633
+ const body = this.body(f, ctx);
563
634
  if (!this.o.display || ctx.level > 0) {
564
635
  const half = 0.55;
565
636
  const sign = svg(name, `${this.p}-bigsign`, `height:${em(2 * half)};width:${em(0.8)};vertical-align:${em(AXIS - half)}`);
@@ -579,7 +650,7 @@ class Layout {
579
650
  }
580
651
 
581
652
  /**
582
- * A matrix: a grid of entries, centred on the maths axis, in brackets as tall as it is. Each
653
+ * A matrix: a grid of entries, centered on the math axis, in brackets as tall as it is. Each
583
654
  * row that is a list in the tree is an element of its own (display: contents), so a row can
584
655
  * be pointed at like any part.
585
656
  */
@@ -635,6 +706,11 @@ function isSimpleArgument(node, inScript = false) {
635
706
  return false;
636
707
  }
637
708
 
709
+ const STATEMENTS = ['=', '===', '≠', '≠=', '<', '>', '≤', '≥', '≈', '≡', '∈', '∉'];
710
+ /** An equation or inequality, or such statements joined by or / and. */
711
+ const isStatement = (n) => n.type === 'op' && n.args.length >= 2
712
+ && ((n.args.length === 2 && STATEMENTS.includes(n.op)) || ((n.op === '|' || n.op === '&') && n.args.every(isStatement)));
713
+
638
714
  const isShortSymbol = (n) => n.type === 'symbol' && (n.value.length === 1 || /^[α-ωΑ-Ω]$/.test(n.value) || Boolean(GREEK[n.value]));
639
715
  const isPositiveWhole = (n) => n.type === 'number' && /^[1-9]\d*$/.test(n.value) && Number(n.value) < 10;
640
716
 
@@ -647,3 +723,7 @@ function startsWithCall(node) {
647
723
  }
648
724
  return false;
649
725
  }
726
+
727
+ // Lookup tables are keyed by what an expression holds: with no prototype, a name like toString or
728
+ // constructor finds nothing rather than Object's own (and is drawn as the name it is).
729
+ 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.
1
+ // '@mathzetta/inlinemath/markdown' — Markdown with math. See types.d.ts.
2
2
  export type { MarkdownOptions, VariableDefinition } from './types.js';
3
3
  export { markdownToHTML, renderMarkdownInto, extractMath, renderMarkdown, createVariables, variables, Variables } from './types.js';