@pie-lib/math-input-mathlive 1.0.6 → 1.0.8

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 (40) hide show
  1. package/lib/__tests__/composites.test.js +255 -0
  2. package/lib/__tests__/composites.test.js.map +1 -0
  3. package/lib/__tests__/keypad-label.test.js +6 -7
  4. package/lib/__tests__/keypad-label.test.js.map +1 -1
  5. package/lib/__tests__/keypad-render.test.js +206 -0
  6. package/lib/__tests__/keypad-render.test.js.map +1 -0
  7. package/lib/__tests__/latex-bridge.test.js +65 -0
  8. package/lib/__tests__/latex-bridge.test.js.map +1 -1
  9. package/lib/__tests__/mathlive-instance.test.js +18 -0
  10. package/lib/__tests__/mathlive-instance.test.js.map +1 -1
  11. package/lib/__tests__/mount-race.test.js +194 -0
  12. package/lib/__tests__/mount-race.test.js.map +1 -0
  13. package/lib/__tests__/static-prompts.test.js +282 -0
  14. package/lib/__tests__/static-prompts.test.js.map +1 -0
  15. package/lib/keypad/index.js +4 -28
  16. package/lib/keypad/index.js.map +1 -1
  17. package/lib/latex-bridge.js +124 -4
  18. package/lib/latex-bridge.js.map +1 -1
  19. package/lib/mathlive-instance.js +28 -4
  20. package/lib/mathlive-instance.js.map +1 -1
  21. package/lib/mf/common-styles.js +13 -0
  22. package/lib/mf/common-styles.js.map +1 -1
  23. package/lib/mf/input.js +18 -5
  24. package/lib/mf/input.js.map +1 -1
  25. package/lib/mf/static.js +24 -7
  26. package/lib/mf/static.js.map +1 -1
  27. package/package.json +1 -1
  28. package/src/__tests__/composites.test.jsx +220 -0
  29. package/src/__tests__/keypad-label.test.jsx +1 -1
  30. package/src/__tests__/keypad-render.test.jsx +123 -0
  31. package/src/__tests__/latex-bridge.test.js +87 -1
  32. package/src/__tests__/mathlive-instance.test.js +20 -0
  33. package/src/__tests__/mount-race.test.jsx +129 -0
  34. package/src/__tests__/static-prompts.test.jsx +251 -0
  35. package/src/keypad/index.jsx +3 -25
  36. package/src/latex-bridge.js +128 -3
  37. package/src/mathlive-instance.js +29 -5
  38. package/src/mf/common-styles.js +13 -0
  39. package/src/mf/input.jsx +19 -5
  40. package/src/mf/static.jsx +23 -4
@@ -29,9 +29,121 @@ const DISPLAYLINES_REGEX = /^\\displaylines\{([\s\S]*)\}$/;
29
29
  const MQ_FIELD_REGEX = /\\MathQuillMathField\[([^\]]*)\]\{([^{}]*)\}/g;
30
30
  const PLACEHOLDER_REGEX = /\\placeholder\[([^\]]*)\]\{([^{}]*)\}/g;
31
31
 
32
+ /**
33
+ * Unnamed placeholders, which MathLive inserts on its own.
34
+ *
35
+ * Typing a command with empty arguments (`\longdiv{}`, `\frac{}{}`) makes
36
+ * MathLive serialise the empty slots as `\placeholder{}`. That token is
37
+ * MathLive-specific: MathJax - which @pie-lib/math-rendering uses to render
38
+ * prompts and previews - has no such command and renders it as red error text.
39
+ * Stored latex must therefore keep plain empty groups.
40
+ */
41
+ const BARE_PLACEHOLDER_REGEX = /\\placeholder\{([^{}]*)\}/g;
42
+ const BARE_PLACEHOLDER_NO_ARG_REGEX = /\\placeholder(?![[{a-zA-Z])/g;
43
+
32
44
  /** Default id used when stored latex has an unnamed field. */
33
45
  export const DEFAULT_FIELD_ID = 'r1';
34
46
 
47
+ /**
48
+ * A visible stand-in for an empty argument slot, used for STATIC rendering only.
49
+ *
50
+ * Stored latex legitimately contains empty groups - `\longdiv{}`, `\frac{}{}`,
51
+ * `x^{}` - to express a command's shape. MathQuill drew those as a shaded box
52
+ * (`.mq-empty`); MathLive renders `{}` as nothing, so `convertLatexToMarkup`
53
+ * output comes out completely blank (not even the surrounding bracket, in the
54
+ * case of `\enclose{longdiv}{}`).
55
+ *
56
+ * `\placeholder{}` is not usable here: in static markup it renders as a
57
+ * non-breaking space, because its editable box only exists inside a live
58
+ * mathfield. So an actual glyph is required.
59
+ *
60
+ * Live mathfields need none of this - MathLive manages empty slots itself.
61
+ */
62
+ const EMPTY_SLOT = '\\htmlData{pie-empty=1}{\\unicode{"25AB}}';
63
+ const EMPTY_GROUP_REGEX = /\{\s*\}/g;
64
+
65
+ /**
66
+ * Make empty argument slots visible, for static rendering.
67
+ *
68
+ * Display-only: never feed the result to a mathfield or to storage - the
69
+ * original latex is what gets typed and saved.
70
+ *
71
+ * @param {string} latex
72
+ * @returns {string}
73
+ */
74
+ export const withVisibleEmptySlots = (latex) => (latex || '').replace(EMPTY_GROUP_REGEX, `{${EMPTY_SLOT}}`);
75
+
76
+ /**
77
+ * Pie commands that take an argument, and their native MathLive equivalents.
78
+ *
79
+ * These MUST NOT be handled as MathLive macros. A macro is serialised from the
80
+ * arguments it was created with, so text typed inside its expansion never makes
81
+ * it back out: `getValue('latex')` keeps returning `\longdiv{\placeholder{}}`
82
+ * while `getValue('ascii-math')` shows the typed content. Setting
83
+ * `captureSelection: false` lets the cursor in but does not change
84
+ * serialisation.
85
+ *
86
+ * Expanding to native constructs instead gives real, editable atoms that
87
+ * round-trip. All three targets are understood by MathJax too, so stored latex
88
+ * still renders in @pie-lib/math-rendering without a reverse mapping.
89
+ */
90
+ /**
91
+ * Rewrite argument-taking pie commands into native MathLive latex.
92
+ * Applied on the way *into* a mathfield.
93
+ *
94
+ * @param {string} latex
95
+ * @returns {string}
96
+ */
97
+ export const toNativeCommands = (latex) => {
98
+ if (typeof latex !== 'string' || !latex) {
99
+ return latex || '';
100
+ }
101
+
102
+ let out = latex;
103
+
104
+ // \abs{x} -> \left|x\right| needs brace-aware handling, the rest are prefix
105
+ // swaps.
106
+ out = replaceAbs(out);
107
+ out = out.replace(/\\longdiv\{/g, '\\enclose{longdiv}{');
108
+ out = out.replace(/\\overarc\{/g, '\\overparen{');
109
+
110
+ return out;
111
+ };
112
+
113
+ /** `\abs{x}` -> `\left|x\right|`, matching balanced braces. */
114
+ const replaceAbs = (latex) => {
115
+ let out = latex;
116
+ let idx = out.indexOf('\\abs{');
117
+
118
+ while (idx !== -1) {
119
+ const open = idx + '\\abs{'.length - 1;
120
+ let depth = 0;
121
+ let close = -1;
122
+
123
+ for (let i = open; i < out.length; i++) {
124
+ if (out[i] === '{') depth++;
125
+ else if (out[i] === '}') {
126
+ depth--;
127
+ if (depth === 0) {
128
+ close = i;
129
+ break;
130
+ }
131
+ }
132
+ }
133
+
134
+ if (close === -1) {
135
+ break;
136
+ }
137
+
138
+ const inner = out.slice(open + 1, close);
139
+
140
+ out = `${out.slice(0, idx)}\\left|${inner}\\right|${out.slice(close + 1)}`;
141
+ idx = out.indexOf('\\abs{');
142
+ }
143
+
144
+ return out;
145
+ };
146
+
35
147
  /**
36
148
  * Ids of the answer blocks in a piece of stored latex, in document order.
37
149
  *
@@ -67,8 +179,12 @@ export const toMathLive = (latex) => {
67
179
  return latex || '';
68
180
  }
69
181
 
182
+ // Argument-taking pie commands -> native constructs, so their content stays
183
+ // editable and serialises back correctly (see toNativeCommands).
184
+ let out = toNativeCommands(latex);
185
+
70
186
  // Answer blocks: \MathQuillMathField[id]{x} -> \placeholder[id]{x}
71
- let out = latex.replace(MQ_FIELD_REGEX, (_m, id, content) => `\\placeholder[${id || DEFAULT_FIELD_ID}]{${content}}`);
187
+ out = out.replace(MQ_FIELD_REGEX, (_m, id, content) => `\\placeholder[${id || DEFAULT_FIELD_ID}]{${content}}`);
72
188
 
73
189
  // Newlines: \embed{newLine}[] -> a multiline environment
74
190
  if (out.indexOf(NEWLINE_EMBED) !== -1) {
@@ -108,6 +224,13 @@ export const fromMathLive = (latex) => {
108
224
  (_m, id, content) => `\\MathQuillMathField[${id || DEFAULT_FIELD_ID}]{${content}}`,
109
225
  );
110
226
 
227
+ // Unnamed placeholders are MathLive's own representation of an empty slot and
228
+ // must not reach storage or MathJax. Unwrap them: keep any content, drop the
229
+ // command itself (the surrounding braces are already part of the host latex,
230
+ // so re-adding them here would produce `\longdiv{{}}`).
231
+ out = out.replace(BARE_PLACEHOLDER_REGEX, (_m, content) => content);
232
+ out = out.replace(BARE_PLACEHOLDER_NO_ARG_REGEX, '');
233
+
111
234
  return out;
112
235
  };
113
236
 
@@ -124,8 +247,10 @@ const COMMANDS_WITH_ARGS = {
124
247
  '\\overline': '\\overline{#?}',
125
248
  '\\overrightarrow': '\\overrightarrow{#?}',
126
249
  '\\overleftrightarrow': '\\overleftrightarrow{#?}',
127
- '\\overarc': '\\overarc{#?}',
128
- '\\longdiv': '\\longdiv{#?}',
250
+ // Native forms, not the pie macros: a macro would not serialise the user's
251
+ // typed content back out (see toNativeCommands).
252
+ '\\overarc': '\\overparen{#?}',
253
+ '\\longdiv': '\\enclose{longdiv}{#?}',
129
254
  '^': '^{#?}',
130
255
  _: '_{#?}',
131
256
  '(': '\\left(#?\\right)',
@@ -1,5 +1,5 @@
1
1
  import debug from 'debug';
2
- import { NEWLINE_EMBED, toMathLive } from './latex-bridge';
2
+ import { NEWLINE_EMBED, toMathLive, withVisibleEmptySlots } from './latex-bridge';
3
3
 
4
4
  const log = debug('pie-lib:math-input-mathlive:instance');
5
5
 
@@ -66,6 +66,18 @@ export const configureFonts = (dir) => {
66
66
  }
67
67
  };
68
68
 
69
+ /**
70
+ * What the spacebar inserts in math mode.
71
+ *
72
+ * MathLive's `mathModeSpace` defaults to an empty string, which makes the
73
+ * spacebar a no-op - users cannot type a space at all. `\\ ` (a LaTeX control
74
+ * space) is what MathQuill serialised spaces as, so existing content and the
75
+ * MathJax renderer in @pie-lib/math-rendering both already understand it.
76
+ *
77
+ * A literal " " is not usable: LaTeX skips raw whitespace.
78
+ */
79
+ export const MATH_MODE_SPACE = '\\ ';
80
+
69
81
  /**
70
82
  * Custom macros for the pie-specific commands that the MathQuill fork
71
83
  * understood but stock LaTeX does not.
@@ -75,8 +87,9 @@ export const configureFonts = (dir) => {
75
87
  * way in the editor and in the static renderer.
76
88
  */
77
89
  export const PIE_MACROS = {
90
+ // Argument-less symbols. Atomic is correct here: backspace should remove the
91
+ // whole glyph, and there is nothing to type into.
78
92
  parallelogram: '\\htmlData{pie-macro=parallelogram}{\\unicode{"25B1}}',
79
- overarc: '\\overparen{#1}',
80
93
  napprox: '\\not\\approx',
81
94
  nsim: '\\not\\sim',
82
95
  ncong: '\\not\\cong',
@@ -85,7 +98,15 @@ export const PIE_MACROS = {
85
98
  divide: '\\div',
86
99
  degree: '^{\\circ}',
87
100
  square: '\\unicode{"25A1}',
88
- longdiv: '\\htmlData{pie-macro=longdiv}{#1}',
101
+
102
+ // Argument-taking commands, kept ONLY so previously authored latex still
103
+ // parses and renders. They are never used for editing: MathLive serialises a
104
+ // macro from the arguments it was created with, so text typed inside the
105
+ // expansion never comes back out of `getValue('latex')`. Anything entering a
106
+ // mathfield is rewritten to the native equivalent first - see
107
+ // `toNativeCommands` in latex-bridge.
108
+ longdiv: '\\enclose{longdiv}{#1}',
109
+ overarc: '\\overparen{#1}',
89
110
  abs: '\\left|#1\\right|',
90
111
  };
91
112
 
@@ -347,7 +368,7 @@ export function applyStaticMath(element, latex, options = {}) {
347
368
  return undefined;
348
369
  }
349
370
 
350
- element.innerHTML = ml.convertLatexToMarkup(toMathLive(source), {
371
+ element.innerHTML = ml.convertLatexToMarkup(withVisibleEmptySlots(toMathLive(source)), {
351
372
  macros: { ...getMacros(), ...(options.macros || {}) },
352
373
  });
353
374
 
@@ -372,7 +393,10 @@ export function latexToMarkup(latex, options = {}) {
372
393
  }
373
394
 
374
395
  try {
375
- return ml.convertLatexToMarkup(toMathLive(latex), {
396
+ // Empty groups render as nothing in static markup, so give them a visible
397
+ // box. This covers every static path: keypad labels, mf.Static in display
398
+ // mode, and applyStaticMath.
399
+ return ml.convertLatexToMarkup(withVisibleEmptySlots(toMathLive(latex)), {
376
400
  macros: { ...getMacros(), ...(options.macros || {}) },
377
401
  ...options,
378
402
  });
@@ -51,6 +51,19 @@ export const placeholderStyles = {
51
51
  borderBottom: '1px solid currentColor',
52
52
  minWidth: '1em',
53
53
  },
54
+ // Stand-in glyph for an empty argument slot in STATIC math (see
55
+ // `withVisibleEmptySlots`). Muted so it reads as "a slot goes here" rather
56
+ // than as part of the symbol, matching how MathQuill shaded `.mq-empty`.
57
+ '& [data-pie-empty]': {
58
+ opacity: 0.5,
59
+ },
60
+ // Stretchy accents render an <svg>; mathlive-static.css positions it
61
+ // absolutely at width:100%. Repeated here so static math cannot blow out its
62
+ // container if that stylesheet is missing.
63
+ '& svg': {
64
+ position: 'absolute',
65
+ width: '100%',
66
+ },
54
67
  };
55
68
 
56
69
  /**
package/src/mf/input.jsx CHANGED
@@ -2,7 +2,7 @@ import React from 'react';
2
2
  import PropTypes from 'prop-types';
3
3
  import { styled } from '@mui/material/styles';
4
4
  import debug from 'debug';
5
- import { loadMathLive, getMacros } from '../mathlive-instance';
5
+ import { loadMathLive, getMacros, MATH_MODE_SPACE } from '../mathlive-instance';
6
6
  import { toMathLive, fromMathLive, keyToAction, KEYSTROKES } from '../latex-bridge';
7
7
 
8
8
  const log = debug('pie-lib:math-input-mathlive:input');
@@ -49,9 +49,16 @@ export class Input extends React.Component {
49
49
  }
50
50
 
51
51
  async componentDidMount() {
52
+ // MathLive loads asynchronously, so this method resumes after an await and
53
+ // has to know whether it is still the current mount. React StrictMode calls
54
+ // mount -> unmount -> mount on the SAME instance in dev, so a boolean
55
+ // "unmounted" flag would latch and block the remount from ever creating a
56
+ // field. A generation counter identifies the live mount instead: only the
57
+ // newest one proceeds, and a real unmount invalidates all pending ones.
58
+ const generation = (this.mountGeneration = (this.mountGeneration || 0) + 1);
52
59
  const ml = await loadMathLive();
53
60
 
54
- if (!ml || !this.holderRef.current) {
61
+ if (generation !== this.mountGeneration || !ml || !this.holderRef.current || this.mathField) {
55
62
  return;
56
63
  }
57
64
 
@@ -64,15 +71,18 @@ export class Input extends React.Component {
64
71
 
65
72
  // pie drives input through its own keypad, so suppress MathLive's.
66
73
  this.mathField.mathVirtualKeyboardPolicy = 'manual';
74
+ // Without this the spacebar does nothing: MathLive's mathModeSpace
75
+ // defaults to an empty string.
76
+ this.mathField.mathModeSpace = MATH_MODE_SPACE;
67
77
 
68
78
  this.mathField.addEventListener('input', this.onInputEdit);
69
- this.holderRef.current.appendChild(this.mathField);
79
+
80
+ // Belt and braces: drop anything a previous mount may have left behind.
81
+ this.holderRef.current.replaceChildren(this.mathField);
70
82
 
71
83
  if (this.props.innerRef) {
72
84
  this.props.innerRef(this);
73
85
  }
74
-
75
- this.setState?.({});
76
86
  }
77
87
 
78
88
  componentDidUpdate(prevProps) {
@@ -99,6 +109,10 @@ export class Input extends React.Component {
99
109
  }
100
110
 
101
111
  componentWillUnmount() {
112
+ // Invalidate any mount still awaiting the MathLive load, so it does not
113
+ // append a field into a holder that is going away.
114
+ this.mountGeneration = (this.mountGeneration || 0) + 1;
115
+
102
116
  if (this.mathField) {
103
117
  this.mathField.removeEventListener('input', this.onInputEdit);
104
118
  this.mathField.remove();
package/src/mf/static.jsx CHANGED
@@ -2,13 +2,16 @@ import React from 'react';
2
2
  import PropTypes from 'prop-types';
3
3
  import { styled } from '@mui/material/styles';
4
4
  import debug from 'debug';
5
- import { loadMathLive, getMacros, latexToMarkup } from '../mathlive-instance';
5
+ import { loadMathLive, getMacros, latexToMarkup, MATH_MODE_SPACE } from '../mathlive-instance';
6
6
  import { toMathLive, fromMathLive, fieldIds } from '../latex-bridge';
7
+ import { placeholderStyles } from './common-styles';
7
8
 
8
9
  const log = debug('pie-lib:math-input-mathlive:static');
9
10
 
10
11
  const Holder = styled('span')({
11
12
  display: 'inline-block',
13
+ // Shared static-math rules: muted empty-slot glyphs and svg containment.
14
+ ...placeholderStyles,
12
15
  '& math-field': {
13
16
  display: 'inline-block',
14
17
  border: 'none',
@@ -61,28 +64,41 @@ export default class Static extends React.Component {
61
64
  }
62
65
 
63
66
  async componentDidMount() {
67
+ // See the note in mf/input.jsx: a generation counter, not a boolean, so a
68
+ // StrictMode mount -> unmount -> mount on the same instance still ends up
69
+ // with exactly one field.
70
+ const generation = (this.mountGeneration = (this.mountGeneration || 0) + 1);
71
+
64
72
  if (!this.isInteractive()) {
65
73
  await loadMathLive();
66
- this.renderMarkup();
74
+
75
+ if (generation === this.mountGeneration) {
76
+ this.renderMarkup();
77
+ }
78
+
67
79
  return;
68
80
  }
69
81
 
70
82
  const ml = await loadMathLive();
71
83
 
72
- if (!ml || !this.holderRef.current) {
84
+ if (generation !== this.mountGeneration || !ml || !this.holderRef.current || this.mathField) {
73
85
  return;
74
86
  }
75
87
 
76
88
  this.mathField = new ml.MathfieldElement({ macros: getMacros() });
77
89
  this.mathField.readOnly = true;
78
90
  this.mathField.mathVirtualKeyboardPolicy = 'manual';
91
+ // Without this the spacebar does nothing: MathLive's mathModeSpace
92
+ // defaults to an empty string.
93
+ this.mathField.mathModeSpace = MATH_MODE_SPACE;
79
94
  this.mathField.value = toMathLive(this.props.latex);
80
95
 
81
96
  this.mathField.addEventListener('input', this.onPromptInput);
82
97
  this.mathField.addEventListener('focusin', this.onPromptFocus);
83
98
  this.mathField.addEventListener('keydown', this.onKeyDown);
84
99
 
85
- this.holderRef.current.appendChild(this.mathField);
100
+ // Belt and braces: drop anything a previous mount may have left behind.
101
+ this.holderRef.current.replaceChildren(this.mathField);
86
102
 
87
103
  this.createLiveRegion();
88
104
  }
@@ -100,6 +116,9 @@ export default class Static extends React.Component {
100
116
  }
101
117
 
102
118
  componentWillUnmount() {
119
+ // Invalidate any mount still awaiting the MathLive load.
120
+ this.mountGeneration = (this.mountGeneration || 0) + 1;
121
+
103
122
  if (this.mathField) {
104
123
  this.mathField.removeEventListener('input', this.onPromptInput);
105
124
  this.mathField.removeEventListener('focusin', this.onPromptFocus);