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

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.
@@ -3,7 +3,7 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
- exports.toMathLive = exports.keyToAction = exports.fromMathLive = exports.fieldIds = exports.NEWLINE_EMBED = exports.KEYSTROKES = exports.DEFAULT_FIELD_ID = exports.COMMANDS_WITH_ARGS = void 0;
6
+ exports.withVisibleEmptySlots = exports.toNativeCommands = exports.toMathLive = exports.keyToAction = exports.fromMathLive = exports.fieldIds = exports.NEWLINE_EMBED = exports.KEYSTROKES = exports.DEFAULT_FIELD_ID = exports.COMMANDS_WITH_ARGS = void 0;
7
7
  /**
8
8
  * LaTeX translation layer between the MathQuill-era content model and MathLive.
9
9
  *
@@ -35,9 +35,114 @@ var DISPLAYLINES_REGEX = /^\\displaylines\{([\s\S]*)\}$/;
35
35
  var MQ_FIELD_REGEX = /\\MathQuillMathField\[([^\]]*)\]\{([^{}]*)\}/g;
36
36
  var PLACEHOLDER_REGEX = /\\placeholder\[([^\]]*)\]\{([^{}]*)\}/g;
37
37
 
38
+ /**
39
+ * Unnamed placeholders, which MathLive inserts on its own.
40
+ *
41
+ * Typing a command with empty arguments (`\longdiv{}`, `\frac{}{}`) makes
42
+ * MathLive serialise the empty slots as `\placeholder{}`. That token is
43
+ * MathLive-specific: MathJax - which @pie-lib/math-rendering uses to render
44
+ * prompts and previews - has no such command and renders it as red error text.
45
+ * Stored latex must therefore keep plain empty groups.
46
+ */
47
+ var BARE_PLACEHOLDER_REGEX = /\\placeholder\{([^{}]*)\}/g;
48
+ var BARE_PLACEHOLDER_NO_ARG_REGEX = /\\placeholder(?![[{a-zA-Z])/g;
49
+
38
50
  /** Default id used when stored latex has an unnamed field. */
39
51
  var DEFAULT_FIELD_ID = exports.DEFAULT_FIELD_ID = 'r1';
40
52
 
53
+ /**
54
+ * A visible stand-in for an empty argument slot, used for STATIC rendering only.
55
+ *
56
+ * Stored latex legitimately contains empty groups - `\longdiv{}`, `\frac{}{}`,
57
+ * `x^{}` - to express a command's shape. MathQuill drew those as a shaded box
58
+ * (`.mq-empty`); MathLive renders `{}` as nothing, so `convertLatexToMarkup`
59
+ * output comes out completely blank (not even the surrounding bracket, in the
60
+ * case of `\enclose{longdiv}{}`).
61
+ *
62
+ * `\placeholder{}` is not usable here: in static markup it renders as a
63
+ * non-breaking space, because its editable box only exists inside a live
64
+ * mathfield. So an actual glyph is required.
65
+ *
66
+ * Live mathfields need none of this - MathLive manages empty slots itself.
67
+ */
68
+ var EMPTY_SLOT = "\\htmlData{pie-empty=1}{\\unicode{\"25AB}}";
69
+ var EMPTY_GROUP_REGEX = /\{\s*\}/g;
70
+
71
+ /**
72
+ * Make empty argument slots visible, for static rendering.
73
+ *
74
+ * Display-only: never feed the result to a mathfield or to storage - the
75
+ * original latex is what gets typed and saved.
76
+ *
77
+ * @param {string} latex
78
+ * @returns {string}
79
+ */
80
+ var withVisibleEmptySlots = exports.withVisibleEmptySlots = function withVisibleEmptySlots(latex) {
81
+ return (latex || '').replace(EMPTY_GROUP_REGEX, "{".concat(EMPTY_SLOT, "}"));
82
+ };
83
+
84
+ /**
85
+ * Pie commands that take an argument, and their native MathLive equivalents.
86
+ *
87
+ * These MUST NOT be handled as MathLive macros. A macro is serialised from the
88
+ * arguments it was created with, so text typed inside its expansion never makes
89
+ * it back out: `getValue('latex')` keeps returning `\longdiv{\placeholder{}}`
90
+ * while `getValue('ascii-math')` shows the typed content. Setting
91
+ * `captureSelection: false` lets the cursor in but does not change
92
+ * serialisation.
93
+ *
94
+ * Expanding to native constructs instead gives real, editable atoms that
95
+ * round-trip. All three targets are understood by MathJax too, so stored latex
96
+ * still renders in @pie-lib/math-rendering without a reverse mapping.
97
+ */
98
+ /**
99
+ * Rewrite argument-taking pie commands into native MathLive latex.
100
+ * Applied on the way *into* a mathfield.
101
+ *
102
+ * @param {string} latex
103
+ * @returns {string}
104
+ */
105
+ var toNativeCommands = exports.toNativeCommands = function toNativeCommands(latex) {
106
+ if (typeof latex !== 'string' || !latex) {
107
+ return latex || '';
108
+ }
109
+ var out = latex;
110
+
111
+ // \abs{x} -> \left|x\right| needs brace-aware handling, the rest are prefix
112
+ // swaps.
113
+ out = replaceAbs(out);
114
+ out = out.replace(/\\longdiv\{/g, '\\enclose{longdiv}{');
115
+ out = out.replace(/\\overarc\{/g, '\\overparen{');
116
+ return out;
117
+ };
118
+
119
+ /** `\abs{x}` -> `\left|x\right|`, matching balanced braces. */
120
+ var replaceAbs = function replaceAbs(latex) {
121
+ var out = latex;
122
+ var idx = out.indexOf('\\abs{');
123
+ while (idx !== -1) {
124
+ var open = idx + '\\abs{'.length - 1;
125
+ var depth = 0;
126
+ var close = -1;
127
+ for (var i = open; i < out.length; i++) {
128
+ if (out[i] === '{') depth++;else if (out[i] === '}') {
129
+ depth--;
130
+ if (depth === 0) {
131
+ close = i;
132
+ break;
133
+ }
134
+ }
135
+ }
136
+ if (close === -1) {
137
+ break;
138
+ }
139
+ var inner = out.slice(open + 1, close);
140
+ out = "".concat(out.slice(0, idx), "\\left|").concat(inner, "\\right|").concat(out.slice(close + 1));
141
+ idx = out.indexOf('\\abs{');
142
+ }
143
+ return out;
144
+ };
145
+
41
146
  /**
42
147
  * Ids of the answer blocks in a piece of stored latex, in document order.
43
148
  *
@@ -69,8 +174,12 @@ var toMathLive = exports.toMathLive = function toMathLive(latex) {
69
174
  return latex || '';
70
175
  }
71
176
 
177
+ // Argument-taking pie commands -> native constructs, so their content stays
178
+ // editable and serialises back correctly (see toNativeCommands).
179
+ var out = toNativeCommands(latex);
180
+
72
181
  // Answer blocks: \MathQuillMathField[id]{x} -> \placeholder[id]{x}
73
- var out = latex.replace(MQ_FIELD_REGEX, function (_m, id, content) {
182
+ out = out.replace(MQ_FIELD_REGEX, function (_m, id, content) {
74
183
  return "\\placeholder[".concat(id || DEFAULT_FIELD_ID, "]{").concat(content, "}");
75
184
  });
76
185
 
@@ -107,6 +216,15 @@ var fromMathLive = exports.fromMathLive = function fromMathLive(latex) {
107
216
  out = out.replace(PLACEHOLDER_REGEX, function (_m, id, content) {
108
217
  return "\\MathQuillMathField[".concat(id || DEFAULT_FIELD_ID, "]{").concat(content, "}");
109
218
  });
219
+
220
+ // Unnamed placeholders are MathLive's own representation of an empty slot and
221
+ // must not reach storage or MathJax. Unwrap them: keep any content, drop the
222
+ // command itself (the surrounding braces are already part of the host latex,
223
+ // so re-adding them here would produce `\longdiv{{}}`).
224
+ out = out.replace(BARE_PLACEHOLDER_REGEX, function (_m, content) {
225
+ return content;
226
+ });
227
+ out = out.replace(BARE_PLACEHOLDER_NO_ARG_REGEX, '');
110
228
  return out;
111
229
  };
112
230
 
@@ -123,8 +241,10 @@ var COMMANDS_WITH_ARGS = exports.COMMANDS_WITH_ARGS = {
123
241
  '\\overline': '\\overline{#?}',
124
242
  '\\overrightarrow': '\\overrightarrow{#?}',
125
243
  '\\overleftrightarrow': '\\overleftrightarrow{#?}',
126
- '\\overarc': '\\overarc{#?}',
127
- '\\longdiv': '\\longdiv{#?}',
244
+ // Native forms, not the pie macros: a macro would not serialise the user's
245
+ // typed content back out (see toNativeCommands).
246
+ '\\overarc': '\\overparen{#?}',
247
+ '\\longdiv': '\\enclose{longdiv}{#?}',
128
248
  '^': '^{#?}',
129
249
  _: '_{#?}',
130
250
  '(': '\\left(#?\\right)',
@@ -1 +1 @@
1
- {"version":3,"file":"latex-bridge.js","names":["NEWLINE_EMBED","exports","NEWLINE_EMBED_REGEX","DISPLAYLINES_REGEX","MQ_FIELD_REGEX","PLACEHOLDER_REGEX","DEFAULT_FIELD_ID","fieldIds","latex","out","match","lastIndex","exec","push","toMathLive","replace","_m","id","content","concat","indexOf","split","join","fromMathLive","trim","map","s","COMMANDS_WITH_ARGS","_","KEYSTROKES","Left","Right","Backspace","Delete","Up","Down","keyToAction","key","undefined","command","type","value","write","parts","Array","isArray","c","keystroke","selector"],"sources":["../src/latex-bridge.js"],"sourcesContent":["/**\n * LaTeX translation layer between the MathQuill-era content model and MathLive.\n *\n * Two independent concerns live here:\n *\n * 1. Newlines. MathQuill had no line break, so pie-lib registered a custom\n * `newLine` embed that serialises to `\\embed{newLine}[]`. MathLive has no\n * embed system but supports real multiline environments, so we translate\n * `\\embed{newLine}[]` <-> `\\\\` inside `\\displaylines{}`.\n *\n * Authored content keeps its `\\embed{newLine}[]` on-disk form (that is what\n * @pie-lib/math-rendering already normalises for MathJax), so each renderer\n * normalises at its own boundary and stored items stay compatible.\n *\n * 2. Keypad key -> MathLive action. MathQuill keys carry `write`/`command`/\n * `keystroke` built for `mf.write()` / `mf.cmd()` / `mf.keystroke()`.\n * MathLive has `insert()` and `executeCommand()` instead.\n */\n\nexport const NEWLINE_EMBED = '\\\\embed{newLine}[]';\nconst NEWLINE_EMBED_REGEX = /\\\\embed\\{newLine\\}\\[\\]/g;\nconst DISPLAYLINES_REGEX = /^\\\\displaylines\\{([\\s\\S]*)\\}$/;\n\n/**\n * MathQuill's editable sub-field syntax, e.g. `\\MathQuillMathField[r1]{}`.\n * These are the answer blocks in templated math items; MathLive expresses the\n * same idea as `\\placeholder[id]{}` and reads them back via the prompts API.\n */\nconst MQ_FIELD_REGEX = /\\\\MathQuillMathField\\[([^\\]]*)\\]\\{([^{}]*)\\}/g;\nconst PLACEHOLDER_REGEX = /\\\\placeholder\\[([^\\]]*)\\]\\{([^{}]*)\\}/g;\n\n/** Default id used when stored latex has an unnamed field. */\nexport const DEFAULT_FIELD_ID = 'r1';\n\n/**\n * Ids of the answer blocks in a piece of stored latex, in document order.\n *\n * @param {string} latex\n * @returns {string[]}\n */\nexport const fieldIds = (latex) => {\n if (typeof latex !== 'string') {\n return [];\n }\n\n const out = [];\n let match;\n\n MQ_FIELD_REGEX.lastIndex = 0;\n\n while ((match = MQ_FIELD_REGEX.exec(latex)) !== null) {\n out.push(match[1] || DEFAULT_FIELD_ID);\n }\n\n return out;\n};\n\n/**\n * Convert stored latex (which may contain `\\embed{newLine}[]`) into latex that\n * MathLive can parse and render as multiple lines.\n *\n * @param {string} latex\n * @returns {string}\n */\nexport const toMathLive = (latex) => {\n if (typeof latex !== 'string' || !latex) {\n return latex || '';\n }\n\n // Answer blocks: \\MathQuillMathField[id]{x} -> \\placeholder[id]{x}\n let out = latex.replace(MQ_FIELD_REGEX, (_m, id, content) => `\\\\placeholder[${id || DEFAULT_FIELD_ID}]{${content}}`);\n\n // Newlines: \\embed{newLine}[] -> a multiline environment\n if (out.indexOf(NEWLINE_EMBED) !== -1) {\n out = `\\\\displaylines{${out.split(NEWLINE_EMBED_REGEX).join(' \\\\\\\\ ')}}`;\n }\n\n return out;\n};\n\n/**\n * Convert latex out of MathLive back into the stored form, so items authored\n * with the MathLive editor remain readable by @pie-lib/math-rendering and by\n * the existing MathQuill implementation.\n *\n * @param {string} latex\n * @returns {string}\n */\nexport const fromMathLive = (latex) => {\n if (typeof latex !== 'string' || !latex) {\n return latex || '';\n }\n\n const match = latex.trim().match(DISPLAYLINES_REGEX);\n let out = match ? match[1] : latex;\n\n // `\\\\` is the line separator inside a multiline environment.\n if (out.indexOf('\\\\\\\\') !== -1) {\n out = out\n .split(/\\s*\\\\\\\\\\s*/)\n .map((s) => s.trim())\n .join(NEWLINE_EMBED);\n }\n\n // Answer blocks: \\placeholder[id]{x} -> \\MathQuillMathField[id]{x}\n out = out.replace(\n PLACEHOLDER_REGEX,\n (_m, id, content) => `\\\\MathQuillMathField[${id || DEFAULT_FIELD_ID}]{${content}}`,\n );\n\n return out;\n};\n\n/**\n * MathQuill `cmd()` semantics: commands that take arguments should land the\n * cursor inside the first argument. MathLive expresses that with `#?`\n * placeholders in the inserted latex.\n */\nconst COMMANDS_WITH_ARGS = {\n '\\\\frac': '\\\\frac{#?}{#?}',\n '/': '\\\\frac{#?}{#?}',\n '\\\\sqrt': '\\\\sqrt{#?}',\n '\\\\nthroot': '\\\\sqrt[#?]{#?}',\n '\\\\overline': '\\\\overline{#?}',\n '\\\\overrightarrow': '\\\\overrightarrow{#?}',\n '\\\\overleftrightarrow': '\\\\overleftrightarrow{#?}',\n '\\\\overarc': '\\\\overarc{#?}',\n '\\\\longdiv': '\\\\longdiv{#?}',\n '^': '^{#?}',\n _: '_{#?}',\n '(': '\\\\left(#?\\\\right)',\n '[': '\\\\left[#?\\\\right]',\n '|': '\\\\left|#?\\\\right|',\n};\n\n/**\n * MathQuill keystroke names -> MathLive command selectors.\n */\nconst KEYSTROKES = {\n Left: 'moveToPreviousChar',\n Right: 'moveToNextChar',\n Backspace: 'deleteBackward',\n Delete: 'deleteForward',\n Up: 'moveUp',\n Down: 'moveDown',\n};\n\n/**\n * Translate a keypad key definition into a MathLive action.\n *\n * Mirrors the precedence in @pie-lib/math-input's MathInput.keypadPress:\n * latex (unless a command is present) -> write -> command -> keystroke.\n *\n * @param {object} key\n * @returns {{type: 'insert'|'command', value: string}|undefined}\n */\nexport const keyToAction = (key) => {\n if (!key) {\n return undefined;\n }\n\n if (key.latex && !key.command) {\n return { type: 'insert', value: key.latex };\n }\n\n if (key.write) {\n return { type: 'insert', value: key.write };\n }\n\n if (key.command) {\n // Some keys carry an array of commands (e.g. Measured Angle is\n // ['m', '\\\\angle'], log-base-n is ['\\\\log', '_']). MathQuill's `cmd()`\n // applied them in sequence; MathLive inserts one latex string, so expand\n // each part and concatenate.\n const parts = Array.isArray(key.command) ? key.command : [key.command];\n const value = parts.map((c) => COMMANDS_WITH_ARGS[c] || c).join('');\n\n return { type: 'insert', value };\n }\n\n if (key.keystroke) {\n const selector = KEYSTROKES[key.keystroke];\n\n return selector ? { type: 'command', value: selector } : undefined;\n }\n\n return undefined;\n};\n\nexport { COMMANDS_WITH_ARGS, KEYSTROKES };\n"],"mappings":";;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEO,IAAMA,aAAa,GAAAC,OAAA,CAAAD,aAAA,GA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AAKnB,kBAAkB,CAACmB,CAAC,CAAC,IAAIA,CAAC;IAAA,EAAC,CAACxB,IAAI,CAAC,EAAE,CAAC;IAEnE,OAAO;MAAEkB,IAAI,EAAE,QAAQ;MAAEC,KAAK,EAALA;IAAM,CAAC;EAClC;EAEA,IAAIJ,GAAG,CAACU,SAAS,EAAE;IACjB,IAAMC,QAAQ,GAAGnB,UAAU,CAACQ,GAAG,CAACU,SAAS,CAAC;IAE1C,OAAOC,QAAQ,GAAG;MAAER,IAAI,EAAE,SAAS;MAAEC,KAAK,EAAEO;IAAS,CAAC,GAAGV,SAAS;EACpE;EAEA,OAAOA,SAAS;AAClB,CAAC","ignoreList":[]}
1
+ {"version":3,"file":"latex-bridge.js","names":["NEWLINE_EMBED","exports","NEWLINE_EMBED_REGEX","DISPLAYLINES_REGEX","MQ_FIELD_REGEX","PLACEHOLDER_REGEX","BARE_PLACEHOLDER_REGEX","BARE_PLACEHOLDER_NO_ARG_REGEX","DEFAULT_FIELD_ID","EMPTY_SLOT","EMPTY_GROUP_REGEX","withVisibleEmptySlots","latex","replace","concat","toNativeCommands","out","replaceAbs","idx","indexOf","open","length","depth","close","i","inner","slice","fieldIds","match","lastIndex","exec","push","toMathLive","_m","id","content","split","join","fromMathLive","trim","map","s","COMMANDS_WITH_ARGS","_","KEYSTROKES","Left","Right","Backspace","Delete","Up","Down","keyToAction","key","undefined","command","type","value","write","parts","Array","isArray","c","keystroke","selector"],"sources":["../src/latex-bridge.js"],"sourcesContent":["/**\n * LaTeX translation layer between the MathQuill-era content model and MathLive.\n *\n * Two independent concerns live here:\n *\n * 1. Newlines. MathQuill had no line break, so pie-lib registered a custom\n * `newLine` embed that serialises to `\\embed{newLine}[]`. MathLive has no\n * embed system but supports real multiline environments, so we translate\n * `\\embed{newLine}[]` <-> `\\\\` inside `\\displaylines{}`.\n *\n * Authored content keeps its `\\embed{newLine}[]` on-disk form (that is what\n * @pie-lib/math-rendering already normalises for MathJax), so each renderer\n * normalises at its own boundary and stored items stay compatible.\n *\n * 2. Keypad key -> MathLive action. MathQuill keys carry `write`/`command`/\n * `keystroke` built for `mf.write()` / `mf.cmd()` / `mf.keystroke()`.\n * MathLive has `insert()` and `executeCommand()` instead.\n */\n\nexport const NEWLINE_EMBED = '\\\\embed{newLine}[]';\nconst NEWLINE_EMBED_REGEX = /\\\\embed\\{newLine\\}\\[\\]/g;\nconst DISPLAYLINES_REGEX = /^\\\\displaylines\\{([\\s\\S]*)\\}$/;\n\n/**\n * MathQuill's editable sub-field syntax, e.g. `\\MathQuillMathField[r1]{}`.\n * These are the answer blocks in templated math items; MathLive expresses the\n * same idea as `\\placeholder[id]{}` and reads them back via the prompts API.\n */\nconst MQ_FIELD_REGEX = /\\\\MathQuillMathField\\[([^\\]]*)\\]\\{([^{}]*)\\}/g;\nconst PLACEHOLDER_REGEX = /\\\\placeholder\\[([^\\]]*)\\]\\{([^{}]*)\\}/g;\n\n/**\n * Unnamed placeholders, which MathLive inserts on its own.\n *\n * Typing a command with empty arguments (`\\longdiv{}`, `\\frac{}{}`) makes\n * MathLive serialise the empty slots as `\\placeholder{}`. That token is\n * MathLive-specific: MathJax - which @pie-lib/math-rendering uses to render\n * prompts and previews - has no such command and renders it as red error text.\n * Stored latex must therefore keep plain empty groups.\n */\nconst BARE_PLACEHOLDER_REGEX = /\\\\placeholder\\{([^{}]*)\\}/g;\nconst BARE_PLACEHOLDER_NO_ARG_REGEX = /\\\\placeholder(?![[{a-zA-Z])/g;\n\n/** Default id used when stored latex has an unnamed field. */\nexport const DEFAULT_FIELD_ID = 'r1';\n\n/**\n * A visible stand-in for an empty argument slot, used for STATIC rendering only.\n *\n * Stored latex legitimately contains empty groups - `\\longdiv{}`, `\\frac{}{}`,\n * `x^{}` - to express a command's shape. MathQuill drew those as a shaded box\n * (`.mq-empty`); MathLive renders `{}` as nothing, so `convertLatexToMarkup`\n * output comes out completely blank (not even the surrounding bracket, in the\n * case of `\\enclose{longdiv}{}`).\n *\n * `\\placeholder{}` is not usable here: in static markup it renders as a\n * non-breaking space, because its editable box only exists inside a live\n * mathfield. So an actual glyph is required.\n *\n * Live mathfields need none of this - MathLive manages empty slots itself.\n */\nconst EMPTY_SLOT = '\\\\htmlData{pie-empty=1}{\\\\unicode{\"25AB}}';\nconst EMPTY_GROUP_REGEX = /\\{\\s*\\}/g;\n\n/**\n * Make empty argument slots visible, for static rendering.\n *\n * Display-only: never feed the result to a mathfield or to storage - the\n * original latex is what gets typed and saved.\n *\n * @param {string} latex\n * @returns {string}\n */\nexport const withVisibleEmptySlots = (latex) => (latex || '').replace(EMPTY_GROUP_REGEX, `{${EMPTY_SLOT}}`);\n\n/**\n * Pie commands that take an argument, and their native MathLive equivalents.\n *\n * These MUST NOT be handled as MathLive macros. A macro is serialised from the\n * arguments it was created with, so text typed inside its expansion never makes\n * it back out: `getValue('latex')` keeps returning `\\longdiv{\\placeholder{}}`\n * while `getValue('ascii-math')` shows the typed content. Setting\n * `captureSelection: false` lets the cursor in but does not change\n * serialisation.\n *\n * Expanding to native constructs instead gives real, editable atoms that\n * round-trip. All three targets are understood by MathJax too, so stored latex\n * still renders in @pie-lib/math-rendering without a reverse mapping.\n */\n/**\n * Rewrite argument-taking pie commands into native MathLive latex.\n * Applied on the way *into* a mathfield.\n *\n * @param {string} latex\n * @returns {string}\n */\nexport const toNativeCommands = (latex) => {\n if (typeof latex !== 'string' || !latex) {\n return latex || '';\n }\n\n let out = latex;\n\n // \\abs{x} -> \\left|x\\right| needs brace-aware handling, the rest are prefix\n // swaps.\n out = replaceAbs(out);\n out = out.replace(/\\\\longdiv\\{/g, '\\\\enclose{longdiv}{');\n out = out.replace(/\\\\overarc\\{/g, '\\\\overparen{');\n\n return out;\n};\n\n/** `\\abs{x}` -> `\\left|x\\right|`, matching balanced braces. */\nconst replaceAbs = (latex) => {\n let out = latex;\n let idx = out.indexOf('\\\\abs{');\n\n while (idx !== -1) {\n const open = idx + '\\\\abs{'.length - 1;\n let depth = 0;\n let close = -1;\n\n for (let i = open; i < out.length; i++) {\n if (out[i] === '{') depth++;\n else if (out[i] === '}') {\n depth--;\n if (depth === 0) {\n close = i;\n break;\n }\n }\n }\n\n if (close === -1) {\n break;\n }\n\n const inner = out.slice(open + 1, close);\n\n out = `${out.slice(0, idx)}\\\\left|${inner}\\\\right|${out.slice(close + 1)}`;\n idx = out.indexOf('\\\\abs{');\n }\n\n return out;\n};\n\n/**\n * Ids of the answer blocks in a piece of stored latex, in document order.\n *\n * @param {string} latex\n * @returns {string[]}\n */\nexport const fieldIds = (latex) => {\n if (typeof latex !== 'string') {\n return [];\n }\n\n const out = [];\n let match;\n\n MQ_FIELD_REGEX.lastIndex = 0;\n\n while ((match = MQ_FIELD_REGEX.exec(latex)) !== null) {\n out.push(match[1] || DEFAULT_FIELD_ID);\n }\n\n return out;\n};\n\n/**\n * Convert stored latex (which may contain `\\embed{newLine}[]`) into latex that\n * MathLive can parse and render as multiple lines.\n *\n * @param {string} latex\n * @returns {string}\n */\nexport const toMathLive = (latex) => {\n if (typeof latex !== 'string' || !latex) {\n return latex || '';\n }\n\n // Argument-taking pie commands -> native constructs, so their content stays\n // editable and serialises back correctly (see toNativeCommands).\n let out = toNativeCommands(latex);\n\n // Answer blocks: \\MathQuillMathField[id]{x} -> \\placeholder[id]{x}\n out = out.replace(MQ_FIELD_REGEX, (_m, id, content) => `\\\\placeholder[${id || DEFAULT_FIELD_ID}]{${content}}`);\n\n // Newlines: \\embed{newLine}[] -> a multiline environment\n if (out.indexOf(NEWLINE_EMBED) !== -1) {\n out = `\\\\displaylines{${out.split(NEWLINE_EMBED_REGEX).join(' \\\\\\\\ ')}}`;\n }\n\n return out;\n};\n\n/**\n * Convert latex out of MathLive back into the stored form, so items authored\n * with the MathLive editor remain readable by @pie-lib/math-rendering and by\n * the existing MathQuill implementation.\n *\n * @param {string} latex\n * @returns {string}\n */\nexport const fromMathLive = (latex) => {\n if (typeof latex !== 'string' || !latex) {\n return latex || '';\n }\n\n const match = latex.trim().match(DISPLAYLINES_REGEX);\n let out = match ? match[1] : latex;\n\n // `\\\\` is the line separator inside a multiline environment.\n if (out.indexOf('\\\\\\\\') !== -1) {\n out = out\n .split(/\\s*\\\\\\\\\\s*/)\n .map((s) => s.trim())\n .join(NEWLINE_EMBED);\n }\n\n // Answer blocks: \\placeholder[id]{x} -> \\MathQuillMathField[id]{x}\n out = out.replace(\n PLACEHOLDER_REGEX,\n (_m, id, content) => `\\\\MathQuillMathField[${id || DEFAULT_FIELD_ID}]{${content}}`,\n );\n\n // Unnamed placeholders are MathLive's own representation of an empty slot and\n // must not reach storage or MathJax. Unwrap them: keep any content, drop the\n // command itself (the surrounding braces are already part of the host latex,\n // so re-adding them here would produce `\\longdiv{{}}`).\n out = out.replace(BARE_PLACEHOLDER_REGEX, (_m, content) => content);\n out = out.replace(BARE_PLACEHOLDER_NO_ARG_REGEX, '');\n\n return out;\n};\n\n/**\n * MathQuill `cmd()` semantics: commands that take arguments should land the\n * cursor inside the first argument. MathLive expresses that with `#?`\n * placeholders in the inserted latex.\n */\nconst COMMANDS_WITH_ARGS = {\n '\\\\frac': '\\\\frac{#?}{#?}',\n '/': '\\\\frac{#?}{#?}',\n '\\\\sqrt': '\\\\sqrt{#?}',\n '\\\\nthroot': '\\\\sqrt[#?]{#?}',\n '\\\\overline': '\\\\overline{#?}',\n '\\\\overrightarrow': '\\\\overrightarrow{#?}',\n '\\\\overleftrightarrow': '\\\\overleftrightarrow{#?}',\n // Native forms, not the pie macros: a macro would not serialise the user's\n // typed content back out (see toNativeCommands).\n '\\\\overarc': '\\\\overparen{#?}',\n '\\\\longdiv': '\\\\enclose{longdiv}{#?}',\n '^': '^{#?}',\n _: '_{#?}',\n '(': '\\\\left(#?\\\\right)',\n '[': '\\\\left[#?\\\\right]',\n '|': '\\\\left|#?\\\\right|',\n};\n\n/**\n * MathQuill keystroke names -> MathLive command selectors.\n */\nconst KEYSTROKES = {\n Left: 'moveToPreviousChar',\n Right: 'moveToNextChar',\n Backspace: 'deleteBackward',\n Delete: 'deleteForward',\n Up: 'moveUp',\n Down: 'moveDown',\n};\n\n/**\n * Translate a keypad key definition into a MathLive action.\n *\n * Mirrors the precedence in @pie-lib/math-input's MathInput.keypadPress:\n * latex (unless a command is present) -> write -> command -> keystroke.\n *\n * @param {object} key\n * @returns {{type: 'insert'|'command', value: string}|undefined}\n */\nexport const keyToAction = (key) => {\n if (!key) {\n return undefined;\n }\n\n if (key.latex && !key.command) {\n return { type: 'insert', value: key.latex };\n }\n\n if (key.write) {\n return { type: 'insert', value: key.write };\n }\n\n if (key.command) {\n // Some keys carry an array of commands (e.g. Measured Angle is\n // ['m', '\\\\angle'], log-base-n is ['\\\\log', '_']). MathQuill's `cmd()`\n // applied them in sequence; MathLive inserts one latex string, so expand\n // each part and concatenate.\n const parts = Array.isArray(key.command) ? key.command : [key.command];\n const value = parts.map((c) => COMMANDS_WITH_ARGS[c] || c).join('');\n\n return { type: 'insert', value };\n }\n\n if (key.keystroke) {\n const selector = KEYSTROKES[key.keystroke];\n\n return selector ? { type: 'command', value: selector } : undefined;\n }\n\n return undefined;\n};\n\nexport { COMMANDS_WITH_ARGS, KEYSTROKES };\n"],"mappings":";;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEO,IAAMA,aAAa,GAAAC,OAAA,CAAAD,aAAA,GAAG,oBAAoB;AACjD,IAAME,mBAAmB,GAAG,yBAAyB;AACrD,IAAMC,kBAAkB,GAAG,+BAA+B;;AAE1D;AACA;AACA;AACA;AACA;AACA,IAAMC,cAAc,GAAG,+CAA+C;AACtE,IAAMC,iBAAiB,GAAG,wCAAwC;;AAElE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAMC,sBAAsB,GAAG,4BAA4B;AAC3D,IAAMC,6BAA6B,GAAG,8BAA8B;;AAEpE;AACO,IAAMC,gBAAgB,GAAAP,OAAA,CAAAO,gBAAA,GAAG,IAAI;;AAEpC;AAC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;EACpE;EAEA,OAAOA,SAAS;AAClB,CAAC","ignoreList":[]}
@@ -98,8 +98,9 @@ var configureFonts = exports.configureFonts = function configureFonts(dir) {
98
98
  * way in the editor and in the static renderer.
99
99
  */
100
100
  var PIE_MACROS = exports.PIE_MACROS = {
101
+ // Argument-less symbols. Atomic is correct here: backspace should remove the
102
+ // whole glyph, and there is nothing to type into.
101
103
  parallelogram: "\\htmlData{pie-macro=parallelogram}{\\unicode{\"25B1}}",
102
- overarc: '\\overparen{#1}',
103
104
  napprox: '\\not\\approx',
104
105
  nsim: '\\not\\sim',
105
106
  ncong: '\\not\\cong',
@@ -108,7 +109,14 @@ var PIE_MACROS = exports.PIE_MACROS = {
108
109
  divide: '\\div',
109
110
  degree: '^{\\circ}',
110
111
  square: "\\unicode{\"25A1}",
111
- longdiv: '\\htmlData{pie-macro=longdiv}{#1}',
112
+ // Argument-taking commands, kept ONLY so previously authored latex still
113
+ // parses and renders. They are never used for editing: MathLive serialises a
114
+ // macro from the arguments it was created with, so text typed inside the
115
+ // expansion never comes back out of `getValue('latex')`. Anything entering a
116
+ // mathfield is rewritten to the native equivalent first - see
117
+ // `toNativeCommands` in latex-bridge.
118
+ longdiv: '\\enclose{longdiv}{#1}',
119
+ overarc: '\\overparen{#1}',
112
120
  abs: '\\left|#1\\right|'
113
121
  };
114
122
 
@@ -376,7 +384,7 @@ function applyStaticMath(element, latex) {
376
384
  });
377
385
  return undefined;
378
386
  }
379
- element.innerHTML = ml.convertLatexToMarkup((0, _latexBridge.toMathLive)(source), {
387
+ element.innerHTML = ml.convertLatexToMarkup((0, _latexBridge.withVisibleEmptySlots)((0, _latexBridge.toMathLive)(source)), {
380
388
  macros: _objectSpread(_objectSpread({}, getMacros()), options.macros || {})
381
389
  });
382
390
  return element;
@@ -399,7 +407,10 @@ function latexToMarkup(latex) {
399
407
  return '';
400
408
  }
401
409
  try {
402
- return ml.convertLatexToMarkup((0, _latexBridge.toMathLive)(latex), _objectSpread({
410
+ // Empty groups render as nothing in static markup, so give them a visible
411
+ // box. This covers every static path: keypad labels, mf.Static in display
412
+ // mode, and applyStaticMath.
413
+ return ml.convertLatexToMarkup((0, _latexBridge.withVisibleEmptySlots)((0, _latexBridge.toMathLive)(latex)), _objectSpread({
403
414
  macros: _objectSpread(_objectSpread({}, getMacros()), options.macros || {})
404
415
  }, options));
405
416
  } catch (e) {
@@ -1 +1 @@
1
- {"version":3,"file":"mathlive-instance.js","names":["_debug","_interopRequireDefault","require","_latexBridge","ownKeys","e","r","t","Object","keys","getOwnPropertySymbols","o","filter","getOwnPropertyDescriptor","enumerable","push","apply","_objectSpread","arguments","length","forEach","_defineProperty2","getOwnPropertyDescriptors","defineProperties","defineProperty","_interopRequireWildcard","WeakMap","n","__esModule","i","f","__proto__","_typeof","has","get","set","_t2","hasOwnProperty","call","log","debug","mathlive","fontsDirectory","absoluteFontsDirectory","dir","test","URL","document","baseURI","href","message","configureFonts","exports","MathfieldElement","PIE_MACROS","parallelogram","overarc","napprox","nsim","ncong","nparallel","perpendicular","divide","degree","square","longdiv","abs","embeds","Map","KNOWN_EMBED_LATEX","newLine","answerBlock","loadWarned","configureLoaded","undefined","injectCoreStylesheet","renderMathInElement","createElement","loadMathLiveSync","window","loadMathLive","_ref","_asyncToGenerator2","_regenerator","mark","_callee","_t","wrap","_context","prev","next","abrupt","Promise","resolve","then","sent","process","env","NODE_ENV","console","warn","stop","getMathLive","getMacros","out","_ref2","name","latex","concat","registerEmbed","factory","definition","prototype","mathliveLatex","registeredEmbeds","Array","from","__resetEmbeds","clear","__setMathLiveForTest","stub","applyStaticMath","element","options","source","textContent","ml","loaded","isConnected","innerHTML","convertLatexToMarkup","toMathLive","macros","latexToMarkup"],"sources":["../src/mathlive-instance.js"],"sourcesContent":["import debug from 'debug';\nimport { NEWLINE_EMBED, toMathLive } from './latex-bridge';\n\nconst log = debug('pie-lib:math-input-mathlive:instance');\n\n/**\n * MathLive bootstrap + compatibility shims for @pie-lib/math-input's public API.\n *\n * MathLive is loaded lazily and only in the browser: the editor bundle is\n * ~227KB gzip and registers custom elements, so it must never run during SSR.\n */\n\nlet mathlive;\n\n/**\n * Where the KaTeX woff2 fonts are served from, as configured by the host app.\n * `undefined` means \"not configured\"; `null` means \"explicitly disabled\".\n */\nlet fontsDirectory;\n\n/**\n * Turn a fonts path into a fully-qualified URL.\n *\n * MathLive's default `fontsDirectory` is the relative `'./fonts/'`, which it\n * resolves against its own script URL. Under a bundler (webpack/Next) that\n * script URL is empty, so `new URL('./fonts/', '')` throws\n * \"Failed to construct 'URL': Invalid base URL\" from `loadFonts`.\n * Resolving against `document.baseURI` avoids that entirely and honours any\n * <base href> / asset prefix the host app uses.\n */\nconst absoluteFontsDirectory = (dir) => {\n if (!dir) {\n return dir;\n }\n\n // Already absolute (http://, https://, //cdn...) - MathLive handles these.\n if (/^(?:[a-z+]+:)?\\/\\//i.test(dir)) {\n return dir;\n }\n\n try {\n return new URL(dir, document.baseURI).href;\n } catch (e) {\n log('could not resolve fontsDirectory \"%s\": %s', dir, e && e.message);\n return null;\n }\n};\n\n/**\n * Tell the package where the MathLive fonts are served from.\n *\n * Call before `loadMathLive()`. Accepts an absolute URL, a root-relative path\n * (`/mathlive-fonts`) or a relative one; pass `null` to skip font loading and\n * fall back to system fonts.\n *\n * The fonts ship inside the `mathlive` package (`node_modules/mathlive/fonts`)\n * and must be copied into whatever the host app serves statically.\n *\n * @param {string|null} dir\n */\nexport const configureFonts = (dir) => {\n fontsDirectory = dir;\n\n if (mathlive) {\n mathlive.MathfieldElement.fontsDirectory = absoluteFontsDirectory(dir);\n }\n};\n\n/**\n * Custom macros for the pie-specific commands that the MathQuill fork\n * understood but stock LaTeX does not.\n *\n * Kept deliberately in sync with the MathJax macros in\n * @pie-lib/math-rendering (`render-math.js`) so the same latex renders the same\n * way in the editor and in the static renderer.\n */\nexport const PIE_MACROS = {\n parallelogram: '\\\\htmlData{pie-macro=parallelogram}{\\\\unicode{\"25B1}}',\n overarc: '\\\\overparen{#1}',\n napprox: '\\\\not\\\\approx',\n nsim: '\\\\not\\\\sim',\n ncong: '\\\\not\\\\cong',\n nparallel: '\\\\not\\\\parallel',\n perpendicular: '\\\\perp',\n divide: '\\\\div',\n degree: '^{\\\\circ}',\n square: '\\\\unicode{\"25A1}',\n longdiv: '\\\\htmlData{pie-macro=longdiv}{#1}',\n abs: '\\\\left|#1\\\\right|',\n};\n\n/**\n * Registry for `registerEmbed`.\n *\n * MathLive has no embed plugin system, so an embed is expressed as a macro that\n * expands to real LaTeX. `\\htmlData{embed=<name>}` tags the rendered output so\n * consumers can target it with CSS exactly as they targeted the old\n * `htmlString` markup.\n *\n * Known embeds map to native constructs:\n * - `newLine` -> structural, handled by latex-bridge (`\\displaylines` + `\\\\`)\n * - `answerBlock`-> `\\placeholder{}` (interactive, read via the prompts API)\n *\n * @type {Map<string, {factory: Function, latex: string}>}\n */\nconst embeds = new Map();\n\nconst KNOWN_EMBED_LATEX = {\n // newLine is structural: it is translated by latex-bridge before it ever\n // reaches MathLive, so the macro only needs to be harmless.\n newLine: '',\n answerBlock: '\\\\placeholder{}',\n};\n\nlet loadWarned = false;\n\n/** Apply post-load configuration exactly once. */\nconst configureLoaded = () => {\n // Always replace MathLive's relative `'./fonts/'` default: it throws\n // \"Invalid base URL\" when bundled. Either point at the host app's copy or\n // disable font loading, both of which are safe.\n if (fontsDirectory === undefined) {\n log(\n 'no fontsDirectory configured - MathLive will use fallback fonts. ' +\n 'Call configureFonts(\"/path/to/fonts\") with a copy of node_modules/mathlive/fonts to enable them.',\n );\n }\n\n mathlive.MathfieldElement.fontsDirectory =\n fontsDirectory === undefined ? null : absoluteFontsDirectory(fontsDirectory);\n\n injectCoreStylesheet();\n};\n\n/**\n * Ensure MathLive's \"core\" stylesheet is in the document.\n *\n * `convertLatexToMarkup` - which renders keypad labels and static math - does\n * NOT inject it, while `renderMathInElement` and live mathfields do. Without it\n * the generated markup is unstyled: glyphs misalign and the <svg> used by\n * stretchy accents lays out statically at an unbounded width.\n *\n * Hosts that can import CSS should `import 'mathlive/static.css'`. For bundles\n * that cannot handle CSS imports (pie-elements ships JS-only web components),\n * this triggers MathLive's own injection against a detached element, so the\n * styles come from MathLive itself rather than being duplicated here.\n */\nconst injectCoreStylesheet = () => {\n if (typeof document === 'undefined' || !mathlive || !mathlive.renderMathInElement) {\n return;\n }\n\n try {\n mathlive.renderMathInElement(document.createElement('span'));\n } catch (e) {\n log('could not trigger MathLive core stylesheet injection: %s', e && e.message);\n }\n};\n\n/**\n * Load MathLive synchronously when the bundler allows it.\n *\n * `require` keeps MathLive inside the host's bundle. An `import()` would make\n * webpack emit a separate chunk, and a deployment that does not serve that\n * chunk fails with a 404 at runtime - leaving every mathfield and keypad label\n * blank with no obvious cause. Being in the main bundle also makes the engine\n * available on first render, so callers that run synchronously (applyStaticMath,\n * keypad labels) work without a second pass.\n *\n * Returns undefined during SSR or if the module is genuinely unavailable.\n *\n * @returns {object|undefined}\n */\nexport const loadMathLiveSync = () => {\n if (typeof window === 'undefined') {\n return undefined;\n }\n\n if (!mathlive) {\n try {\n // eslint-disable-next-line global-require\n mathlive = require('mathlive');\n configureLoaded();\n } catch (e) {\n log('synchronous MathLive load unavailable: %s', e && e.message);\n return undefined;\n }\n }\n\n return mathlive;\n};\n\n/**\n * Load MathLive. Prefers the synchronous path; falls back to a dynamic import.\n * Resolves to undefined during SSR.\n *\n * @returns {Promise<object|undefined>}\n */\nexport const loadMathLive = async () => {\n if (typeof window === 'undefined') {\n return undefined;\n }\n\n if (mathlive) {\n return mathlive;\n }\n\n if (loadMathLiveSync()) {\n return mathlive;\n }\n\n try {\n mathlive = await import('mathlive');\n configureLoaded();\n } catch (e) {\n // Surface this once: a silent failure here renders every field and keypad\n // label blank, which is very hard to trace back to a module load.\n // Skipped under test, where jsdom cannot load the browser build.\n if (!loadWarned && process.env.NODE_ENV !== 'test') {\n loadWarned = true;\n // eslint-disable-next-line no-console\n console.warn(\n '[@pie-lib/math-input-mathlive] MathLive could not be loaded; math input will not render. ' +\n 'If this is a bundling issue, ensure \"mathlive\" is resolvable from the host bundle. Cause: ' +\n (e && e.message),\n );\n }\n\n return undefined;\n }\n\n return mathlive;\n};\n\n/**\n * Synchronous accessor for an already-loaded MathLive.\n * @returns {object|undefined}\n */\nexport const getMathLive = () => mathlive;\n\n/**\n * The macro dictionary to hand to a mathfield: pie macros plus anything\n * registered through `registerEmbed`.\n *\n * @returns {object}\n */\nexport const getMacros = () => {\n const out = { ...PIE_MACROS };\n\n embeds.forEach(({ latex }, name) => {\n out[name] = `\\\\htmlData{embed=${name}}{${latex}}`;\n });\n\n return out;\n};\n\n/**\n * Register an embed. API-compatible with @pie-lib/math-input's `registerEmbed`\n * so existing callers do not change.\n *\n * MathQuill's factory returns `{ htmlString, text, latex }`. Only the\n * declarative parts survive: `latex` round-trips through a macro and the\n * styling hook becomes a `data-embed` attribute. Arbitrary DOM injection via\n * `htmlString` has no MathLive equivalent and is ignored.\n *\n * @param {string} name\n * @param {Function} factory\n */\nexport function registerEmbed(name, factory) {\n if (!name || typeof factory !== 'function') {\n return;\n }\n\n let definition = {};\n\n try {\n definition = factory() || {};\n } catch (e) {\n log('embed factory threw for \"%s\": %s', name, e.message);\n }\n\n const latex = Object.prototype.hasOwnProperty.call(KNOWN_EMBED_LATEX, name)\n ? KNOWN_EMBED_LATEX[name]\n : definition.mathliveLatex || '\\\\placeholder{}';\n\n if (!Object.prototype.hasOwnProperty.call(KNOWN_EMBED_LATEX, name) && !definition.mathliveLatex) {\n // Unknown third-party embed: degrade instead of throwing. `htmlString`\n // cannot be reproduced, so it renders as an editable slot.\n log(\n 'embed \"%s\" is not natively supported by MathLive; rendering as a placeholder. ' +\n 'Provide `mathliveLatex` in the factory result to control this.',\n name,\n );\n }\n\n embeds.set(name, { factory, latex });\n}\n\n/**\n * Embeds registered so far. Exposed for tests/diagnostics.\n * @returns {string[]}\n */\nexport const registeredEmbeds = () => Array.from(embeds.keys());\n\n/** Reset the embed registry. Test helper. */\nexport const __resetEmbeds = () => embeds.clear();\n\n/** Inject a stub MathLive instance. Test helper. */\nexport const __setMathLiveForTest = (stub) => {\n mathlive = stub;\n};\n\n/**\n * Render static math into an element. API-compatible with\n * @pie-lib/math-input's `applyStaticMath`.\n *\n * Callers written against MathQuill invoke this synchronously from lifecycle\n * methods, where MathLive (a dynamic import) may not have loaded yet. Rather\n * than silently rendering nothing, this kicks off the load and re-applies once\n * the engine is ready, so the element fills in on the next tick.\n *\n * @param {HTMLElement} element\n * @param {string} [latex] assigned to the element before rendering\n * @param {object} [options] `{ macros }` overrides\n * @returns {HTMLElement|undefined} the element, or undefined if deferred\n */\nexport function applyStaticMath(element, latex, options = {}) {\n if (!element || typeof window === 'undefined') {\n return undefined;\n }\n\n // Capture the source now: if we defer, the element's textContent may have\n // been overwritten by the time MathLive is ready.\n const source = latex === undefined || latex === null ? element.textContent : latex;\n const ml = getMathLive() || loadMathLiveSync();\n\n if (!ml) {\n log('applyStaticMath called before MathLive loaded - deferring until it is ready');\n\n loadMathLive().then((loaded) => {\n // The element may have been unmounted while loading.\n if (loaded && element.isConnected !== false) {\n applyStaticMath(element, source, options);\n }\n });\n\n return undefined;\n }\n\n element.innerHTML = ml.convertLatexToMarkup(toMathLive(source), {\n macros: { ...getMacros(), ...(options.macros || {}) },\n });\n\n return element;\n}\n\n/**\n * Convert latex to markup using the pie macro set. Used for keypad labels and\n * any read-only rendering that does not need a live mathfield.\n *\n * @param {string} latex\n * @param {object} [options]\n * @returns {string} HTML markup, or '' if MathLive is not loaded\n */\nexport function latexToMarkup(latex, options = {}) {\n // Try the synchronous load so the very first render can produce markup\n // instead of falling back to raw latex.\n const ml = getMathLive() || loadMathLiveSync();\n\n if (!ml || !latex) {\n return '';\n }\n\n try {\n return ml.convertLatexToMarkup(toMathLive(latex), {\n macros: { ...getMacros(), ...(options.macros || {}) },\n ...options,\n });\n } catch (e) {\n log('convertLatexToMarkup failed for \"%s\": %s', latex, e.message);\n return '';\n }\n}\n\nexport { NEWLINE_EMBED };\n"],"mappings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I,CAACnB,KAAK,EAAE;IACjB,OAAO,EAAE;EACX;EAEA,IAAI;IACF,OAAOmB,EAAE,CAACI,oBAAoB,CAAC,IAAAC,uBAAU,EAACxB,KAAK,CAAC,EAAA1F,aAAA;MAC9CmH,MAAM,EAAAnH,aAAA,CAAAA,aAAA,KAAOsF,SAAS,CAAC,CAAC,GAAMoB,OAAO,CAACS,MAAM,IAAI,CAAC,CAAC;IAAG,GAClDT,OAAO,CACX,CAAC;EACJ,CAAC,CAAC,OAAOtH,CAAC,EAAE;IACVkC,GAAG,CAAC,0CAA0C,EAAEoE,KAAK,EAAEtG,CAAC,CAAC6C,OAAO,CAAC;IACjE,OAAO,EAAE;EACX;AACF","ignoreList":[]}
1
+ {"version":3,"file":"mathlive-instance.js","names":["_debug","_interopRequireDefault","require","_latexBridge","ownKeys","e","r","t","Object","keys","getOwnPropertySymbols","o","filter","getOwnPropertyDescriptor","enumerable","push","apply","_objectSpread","arguments","length","forEach","_defineProperty2","getOwnPropertyDescriptors","defineProperties","defineProperty","_interopRequireWildcard","WeakMap","n","__esModule","i","f","__proto__","_typeof","has","get","set","_t2","hasOwnProperty","call","log","debug","mathlive","fontsDirectory","absoluteFontsDirectory","dir","test","URL","document","baseURI","href","message","configureFonts","exports","MathfieldElement","PIE_MACROS","parallelogram","napprox","nsim","ncong","nparallel","perpendicular","divide","degree","square","longdiv","overarc","abs","embeds","Map","KNOWN_EMBED_LATEX","newLine","answerBlock","loadWarned","configureLoaded","undefined","injectCoreStylesheet","renderMathInElement","createElement","loadMathLiveSync","window","loadMathLive","_ref","_asyncToGenerator2","_regenerator","mark","_callee","_t","wrap","_context","prev","next","abrupt","Promise","resolve","then","sent","process","env","NODE_ENV","console","warn","stop","getMathLive","getMacros","out","_ref2","name","latex","concat","registerEmbed","factory","definition","prototype","mathliveLatex","registeredEmbeds","Array","from","__resetEmbeds","clear","__setMathLiveForTest","stub","applyStaticMath","element","options","source","textContent","ml","loaded","isConnected","innerHTML","convertLatexToMarkup","withVisibleEmptySlots","toMathLive","macros","latexToMarkup"],"sources":["../src/mathlive-instance.js"],"sourcesContent":["import debug from 'debug';\nimport { NEWLINE_EMBED, toMathLive, withVisibleEmptySlots } from './latex-bridge';\n\nconst log = debug('pie-lib:math-input-mathlive:instance');\n\n/**\n * MathLive bootstrap + compatibility shims for @pie-lib/math-input's public API.\n *\n * MathLive is loaded lazily and only in the browser: the editor bundle is\n * ~227KB gzip and registers custom elements, so it must never run during SSR.\n */\n\nlet mathlive;\n\n/**\n * Where the KaTeX woff2 fonts are served from, as configured by the host app.\n * `undefined` means \"not configured\"; `null` means \"explicitly disabled\".\n */\nlet fontsDirectory;\n\n/**\n * Turn a fonts path into a fully-qualified URL.\n *\n * MathLive's default `fontsDirectory` is the relative `'./fonts/'`, which it\n * resolves against its own script URL. Under a bundler (webpack/Next) that\n * script URL is empty, so `new URL('./fonts/', '')` throws\n * \"Failed to construct 'URL': Invalid base URL\" from `loadFonts`.\n * Resolving against `document.baseURI` avoids that entirely and honours any\n * <base href> / asset prefix the host app uses.\n */\nconst absoluteFontsDirectory = (dir) => {\n if (!dir) {\n return dir;\n }\n\n // Already absolute (http://, https://, //cdn...) - MathLive handles these.\n if (/^(?:[a-z+]+:)?\\/\\//i.test(dir)) {\n return dir;\n }\n\n try {\n return new URL(dir, document.baseURI).href;\n } catch (e) {\n log('could not resolve fontsDirectory \"%s\": %s', dir, e && e.message);\n return null;\n }\n};\n\n/**\n * Tell the package where the MathLive fonts are served from.\n *\n * Call before `loadMathLive()`. Accepts an absolute URL, a root-relative path\n * (`/mathlive-fonts`) or a relative one; pass `null` to skip font loading and\n * fall back to system fonts.\n *\n * The fonts ship inside the `mathlive` package (`node_modules/mathlive/fonts`)\n * and must be copied into whatever the host app serves statically.\n *\n * @param {string|null} dir\n */\nexport const configureFonts = (dir) => {\n fontsDirectory = dir;\n\n if (mathlive) {\n mathlive.MathfieldElement.fontsDirectory = absoluteFontsDirectory(dir);\n }\n};\n\n/**\n * Custom macros for the pie-specific commands that the MathQuill fork\n * understood but stock LaTeX does not.\n *\n * Kept deliberately in sync with the MathJax macros in\n * @pie-lib/math-rendering (`render-math.js`) so the same latex renders the same\n * way in the editor and in the static renderer.\n */\nexport const PIE_MACROS = {\n // Argument-less symbols. Atomic is correct here: backspace should remove the\n // whole glyph, and there is nothing to type into.\n parallelogram: '\\\\htmlData{pie-macro=parallelogram}{\\\\unicode{\"25B1}}',\n napprox: '\\\\not\\\\approx',\n nsim: '\\\\not\\\\sim',\n ncong: '\\\\not\\\\cong',\n nparallel: '\\\\not\\\\parallel',\n perpendicular: '\\\\perp',\n divide: '\\\\div',\n degree: '^{\\\\circ}',\n square: '\\\\unicode{\"25A1}',\n\n // Argument-taking commands, kept ONLY so previously authored latex still\n // parses and renders. They are never used for editing: MathLive serialises a\n // macro from the arguments it was created with, so text typed inside the\n // expansion never comes back out of `getValue('latex')`. Anything entering a\n // mathfield is rewritten to the native equivalent first - see\n // `toNativeCommands` in latex-bridge.\n longdiv: '\\\\enclose{longdiv}{#1}',\n overarc: '\\\\overparen{#1}',\n abs: '\\\\left|#1\\\\right|',\n};\n\n/**\n * Registry for `registerEmbed`.\n *\n * MathLive has no embed plugin system, so an embed is expressed as a macro that\n * expands to real LaTeX. `\\htmlData{embed=<name>}` tags the rendered output so\n * consumers can target it with CSS exactly as they targeted the old\n * `htmlString` markup.\n *\n * Known embeds map to native constructs:\n * - `newLine` -> structural, handled by latex-bridge (`\\displaylines` + `\\\\`)\n * - `answerBlock`-> `\\placeholder{}` (interactive, read via the prompts API)\n *\n * @type {Map<string, {factory: Function, latex: string}>}\n */\nconst embeds = new Map();\n\nconst KNOWN_EMBED_LATEX = {\n // newLine is structural: it is translated by latex-bridge before it ever\n // reaches MathLive, so the macro only needs to be harmless.\n newLine: '',\n answerBlock: '\\\\placeholder{}',\n};\n\nlet loadWarned = false;\n\n/** Apply post-load configuration exactly once. */\nconst configureLoaded = () => {\n // Always replace MathLive's relative `'./fonts/'` default: it throws\n // \"Invalid base URL\" when bundled. Either point at the host app's copy or\n // disable font loading, both of which are safe.\n if (fontsDirectory === undefined) {\n log(\n 'no fontsDirectory configured - MathLive will use fallback fonts. ' +\n 'Call configureFonts(\"/path/to/fonts\") with a copy of node_modules/mathlive/fonts to enable them.',\n );\n }\n\n mathlive.MathfieldElement.fontsDirectory =\n fontsDirectory === undefined ? null : absoluteFontsDirectory(fontsDirectory);\n\n injectCoreStylesheet();\n};\n\n/**\n * Ensure MathLive's \"core\" stylesheet is in the document.\n *\n * `convertLatexToMarkup` - which renders keypad labels and static math - does\n * NOT inject it, while `renderMathInElement` and live mathfields do. Without it\n * the generated markup is unstyled: glyphs misalign and the <svg> used by\n * stretchy accents lays out statically at an unbounded width.\n *\n * Hosts that can import CSS should `import 'mathlive/static.css'`. For bundles\n * that cannot handle CSS imports (pie-elements ships JS-only web components),\n * this triggers MathLive's own injection against a detached element, so the\n * styles come from MathLive itself rather than being duplicated here.\n */\nconst injectCoreStylesheet = () => {\n if (typeof document === 'undefined' || !mathlive || !mathlive.renderMathInElement) {\n return;\n }\n\n try {\n mathlive.renderMathInElement(document.createElement('span'));\n } catch (e) {\n log('could not trigger MathLive core stylesheet injection: %s', e && e.message);\n }\n};\n\n/**\n * Load MathLive synchronously when the bundler allows it.\n *\n * `require` keeps MathLive inside the host's bundle. An `import()` would make\n * webpack emit a separate chunk, and a deployment that does not serve that\n * chunk fails with a 404 at runtime - leaving every mathfield and keypad label\n * blank with no obvious cause. Being in the main bundle also makes the engine\n * available on first render, so callers that run synchronously (applyStaticMath,\n * keypad labels) work without a second pass.\n *\n * Returns undefined during SSR or if the module is genuinely unavailable.\n *\n * @returns {object|undefined}\n */\nexport const loadMathLiveSync = () => {\n if (typeof window === 'undefined') {\n return undefined;\n }\n\n if (!mathlive) {\n try {\n // eslint-disable-next-line global-require\n mathlive = require('mathlive');\n configureLoaded();\n } catch (e) {\n log('synchronous MathLive load unavailable: %s', e && e.message);\n return undefined;\n }\n }\n\n return mathlive;\n};\n\n/**\n * Load MathLive. Prefers the synchronous path; falls back to a dynamic import.\n * Resolves to undefined during SSR.\n *\n * @returns {Promise<object|undefined>}\n */\nexport const loadMathLive = async () => {\n if (typeof window === 'undefined') {\n return undefined;\n }\n\n if (mathlive) {\n return mathlive;\n }\n\n if (loadMathLiveSync()) {\n return mathlive;\n }\n\n try {\n mathlive = await import('mathlive');\n configureLoaded();\n } catch (e) {\n // Surface this once: a silent failure here renders every field and keypad\n // label blank, which is very hard to trace back to a module load.\n // Skipped under test, where jsdom cannot load the browser build.\n if (!loadWarned && process.env.NODE_ENV !== 'test') {\n loadWarned = true;\n // eslint-disable-next-line no-console\n console.warn(\n '[@pie-lib/math-input-mathlive] MathLive could not be loaded; math input will not render. ' +\n 'If this is a bundling issue, ensure \"mathlive\" is resolvable from the host bundle. Cause: ' +\n (e && e.message),\n );\n }\n\n return undefined;\n }\n\n return mathlive;\n};\n\n/**\n * Synchronous accessor for an already-loaded MathLive.\n * @returns {object|undefined}\n */\nexport const getMathLive = () => mathlive;\n\n/**\n * The macro dictionary to hand to a mathfield: pie macros plus anything\n * registered through `registerEmbed`.\n *\n * @returns {object}\n */\nexport const getMacros = () => {\n const out = { ...PIE_MACROS };\n\n embeds.forEach(({ latex }, name) => {\n out[name] = `\\\\htmlData{embed=${name}}{${latex}}`;\n });\n\n return out;\n};\n\n/**\n * Register an embed. API-compatible with @pie-lib/math-input's `registerEmbed`\n * so existing callers do not change.\n *\n * MathQuill's factory returns `{ htmlString, text, latex }`. Only the\n * declarative parts survive: `latex` round-trips through a macro and the\n * styling hook becomes a `data-embed` attribute. Arbitrary DOM injection via\n * `htmlString` has no MathLive equivalent and is ignored.\n *\n * @param {string} name\n * @param {Function} factory\n */\nexport function registerEmbed(name, factory) {\n if (!name || typeof factory !== 'function') {\n return;\n }\n\n let definition = {};\n\n try {\n definition = factory() || {};\n } catch (e) {\n log('embed factory threw for \"%s\": %s', name, e.message);\n }\n\n const latex = Object.prototype.hasOwnProperty.call(KNOWN_EMBED_LATEX, name)\n ? KNOWN_EMBED_LATEX[name]\n : definition.mathliveLatex || '\\\\placeholder{}';\n\n if (!Object.prototype.hasOwnProperty.call(KNOWN_EMBED_LATEX, name) && !definition.mathliveLatex) {\n // Unknown third-party embed: degrade instead of throwing. `htmlString`\n // cannot be reproduced, so it renders as an editable slot.\n log(\n 'embed \"%s\" is not natively supported by MathLive; rendering as a placeholder. ' +\n 'Provide `mathliveLatex` in the factory result to control this.',\n name,\n );\n }\n\n embeds.set(name, { factory, latex });\n}\n\n/**\n * Embeds registered so far. Exposed for tests/diagnostics.\n * @returns {string[]}\n */\nexport const registeredEmbeds = () => Array.from(embeds.keys());\n\n/** Reset the embed registry. Test helper. */\nexport const __resetEmbeds = () => embeds.clear();\n\n/** Inject a stub MathLive instance. Test helper. */\nexport const __setMathLiveForTest = (stub) => {\n mathlive = stub;\n};\n\n/**\n * Render static math into an element. API-compatible with\n * @pie-lib/math-input's `applyStaticMath`.\n *\n * Callers written against MathQuill invoke this synchronously from lifecycle\n * methods, where MathLive (a dynamic import) may not have loaded yet. Rather\n * than silently rendering nothing, this kicks off the load and re-applies once\n * the engine is ready, so the element fills in on the next tick.\n *\n * @param {HTMLElement} element\n * @param {string} [latex] assigned to the element before rendering\n * @param {object} [options] `{ macros }` overrides\n * @returns {HTMLElement|undefined} the element, or undefined if deferred\n */\nexport function applyStaticMath(element, latex, options = {}) {\n if (!element || typeof window === 'undefined') {\n return undefined;\n }\n\n // Capture the source now: if we defer, the element's textContent may have\n // been overwritten by the time MathLive is ready.\n const source = latex === undefined || latex === null ? element.textContent : latex;\n const ml = getMathLive() || loadMathLiveSync();\n\n if (!ml) {\n log('applyStaticMath called before MathLive loaded - deferring until it is ready');\n\n loadMathLive().then((loaded) => {\n // The element may have been unmounted while loading.\n if (loaded && element.isConnected !== false) {\n applyStaticMath(element, source, options);\n }\n });\n\n return undefined;\n }\n\n element.innerHTML = ml.convertLatexToMarkup(withVisibleEmptySlots(toMathLive(source)), {\n macros: { ...getMacros(), ...(options.macros || {}) },\n });\n\n return element;\n}\n\n/**\n * Convert latex to markup using the pie macro set. Used for keypad labels and\n * any read-only rendering that does not need a live mathfield.\n *\n * @param {string} latex\n * @param {object} [options]\n * @returns {string} HTML markup, or '' if MathLive is not loaded\n */\nexport function latexToMarkup(latex, options = {}) {\n // Try the synchronous load so the very first render can produce markup\n // instead of falling back to raw latex.\n const ml = getMathLive() || loadMathLiveSync();\n\n if (!ml || !latex) {\n return '';\n }\n\n try {\n // Empty groups render as nothing in static markup, so give them a visible\n // box. This covers every static path: keypad labels, mf.Static in display\n // mode, and applyStaticMath.\n return ml.convertLatexToMarkup(withVisibleEmptySlots(toMathLive(latex)), {\n macros: { ...getMacros(), ...(options.macros || {}) },\n ...options,\n });\n } catch (e) {\n log('convertLatexToMarkup failed for \"%s\": %s', latex, e.message);\n return '';\n }\n}\n\nexport { NEWLINE_EMBED };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAAA,MAAA,GAAAC,sBAAA,CAAAC,OAAA;AACA,IAAAC,YAAA,GAAAD,OAAA;AAAkF,SAAAE,QAAAC,CAAA,EAAAC,CAAA,QAAAC,CAAA,GAAAC,MAAA,CAAAC,IAAA,CAAAJ,CAAA,OAAAG,MAAA,CAAAE,qBAAA,QAAAC,CAAA,GAAAH,MAAA,CAAAE,qBAAA,CAAAL,CAAA,GAAAC,CAAA,KAAAK,CAAA,GAAAA,CAAA,CAAAC,MAAA,WAAAN,CAAA,WAAAE,MAAA,CAAAK,wBAAA,CAAAR,CAAA,EAAAC,CAAA,EAAAQ,UAAA,OAAAP,CAAA,CAAAQ,IAAA,CAAAC,KAAA,CAAAT,CAAA,EAAAI,CAAA,YAAAJ,CAAA;AAAA,SAAAU,cAAAZ,CAAA,aAAAC,CAAA,MAAAA,CAAA,GAAAY,SAAA,CAAAC,MAAA,EAAAb,CAAA,UAAAC,CAAA,WAAAW,SAAA,CAAAZ,CAAA,IAAAY,SAAA,CAAAZ,CAAA,QAAAA,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AC,CAAC;IAEF,OAAOjD,SAAS;EAClB;EAEAgD,OAAO,CAACO,SAAS,GAAGH,EAAE,CAACI,oBAAoB,CAAC,IAAAC,kCAAqB,EAAC,IAAAC,uBAAU,EAACR,MAAM,CAAC,CAAC,EAAE;IACrFS,MAAM,EAAApH,aAAA,CAAAA,aAAA,KAAOsF,SAAS,CAAC,CAAC,GAAMoB,OAAO,CAACU,MAAM,IAAI,CAAC,CAAC;EACpD,CAAC,CAAC;EAEF,OAAOX,OAAO;AAChB;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAASY,aAAaA,CAAC3B,KAAK,EAAgB;EAAA,IAAdgB,OAAO,GAAAzG,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAwD,SAAA,GAAAxD,SAAA,MAAG,CAAC,CAAC;EAC/C;EACA;EACA,IAAM4G,EAAE,GAAGxB,WAAW,CAAC,CAAC,IAAIxB,gBAAgB,CAAC,CAAC;EAE9C,IAAI,CAACgD,EAAE,IAAI,CAACnB,KAAK,EAAE;IACjB,OAAO,EAAE;EACX;EAEA,IAAI;IACF;IACA;IACA;IACA,OAAOmB,EAAE,CAACI,oBAAoB,CAAC,IAAAC,kCAAqB,EAAC,IAAAC,uBAAU,EAACzB,KAAK,CAAC,CAAC,EAAA1F,aAAA;MACrEoH,MAAM,EAAApH,aAAA,CAAAA,aAAA,KAAOsF,SAAS,CAAC,CAAC,GAAMoB,OAAO,CAACU,MAAM,IAAI,CAAC,CAAC;IAAG,GAClDV,OAAO,CACX,CAAC;EACJ,CAAC,CAAC,OAAOtH,CAAC,EAAE;IACVkC,GAAG,CAAC,0CAA0C,EAAEoE,KAAK,EAAEtG,CAAC,CAAC6C,OAAO,CAAC;IACjE,OAAO,EAAE;EACX;AACF","ignoreList":[]}
@@ -60,6 +60,19 @@ var placeholderStyles = exports.placeholderStyles = {
60
60
  '& .ML__placeholder': {
61
61
  borderBottom: '1px solid currentColor',
62
62
  minWidth: '1em'
63
+ },
64
+ // Stand-in glyph for an empty argument slot in STATIC math (see
65
+ // `withVisibleEmptySlots`). Muted so it reads as "a slot goes here" rather
66
+ // than as part of the symbol, matching how MathQuill shaded `.mq-empty`.
67
+ '& [data-pie-empty]': {
68
+ opacity: 0.5
69
+ },
70
+ // Stretchy accents render an <svg>; mathlive-static.css positions it
71
+ // absolutely at width:100%. Repeated here so static math cannot blow out its
72
+ // container if that stylesheet is missing.
73
+ '& svg': {
74
+ position: 'absolute',
75
+ width: '100%'
63
76
  }
64
77
  };
65
78
 
@@ -1 +1 @@
1
- {"version":3,"file":"common-styles.js","names":["commonMqFontStyles","exports","fontFamily","longdivStyles","display","supsubStyles","placeholderStyles","borderBottom","minWidth","commonMqKeyboardStyles","_objectSpread","touchAction","fontSize","outline","commonMathLiveStyles","commonKeyboardStyles","_default"],"sources":["../../src/mf/common-styles.js"],"sourcesContent":["/**\n * Shared MathLive styling.\n *\n * Replaces @pie-lib/math-input's `common-mq-styles.js`. That file was built\n * around MathQuill's `.mq-*` class names, none of which exist in MathLive\n * output, so the selectors here target MathLive's own structure instead.\n *\n * The four named groups are kept because consumers destructure them:\n *\n * const { commonMqFontStyles, commonMqKeyboardStyles, longdivStyles, supsubStyles }\n * = mq.CommonMqStyles; // math-toolbar/src/editor-and-pad.jsx, math-preview.jsx\n *\n * Most are intentionally near-empty: MathLive sizes scripts, radicals and\n * fences correctly on its own, so the MathQuill-era corrections are not needed.\n * They stay as documented extension points rather than being deleted, so the\n * destructuring above keeps working.\n */\n\n/**\n * Font styling. MathQuill needed explicit MathJax font families to match the\n * static renderer; MathLive ships the KaTeX fonts it renders with, so this only\n * smooths rendering and lets the host override the family.\n */\nexport const commonMqFontStyles = {\n '-webkit-font-smoothing': 'antialiased',\n '& math-field': {\n fontFamily: 'inherit',\n },\n};\n\n/**\n * Long division. The MathQuill fork drew this with nested `.mq-longdiv-*`\n * elements that needed manual offsets; here it comes from the `\\longdiv` macro\n * (see `PIE_MACROS`), tagged with `data-pie-macro=\"longdiv\"`.\n */\nexport const longdivStyles = {\n '& [data-pie-macro=\"longdiv\"]': {\n display: 'inline-flex',\n },\n};\n\n/**\n * Superscript/subscript sizing. MathLive follows TeX metrics, so no overrides\n * are required.\n */\nexport const supsubStyles = {};\n\n/** Empty placeholder boxes (answer blocks / open slots). */\nexport const placeholderStyles = {\n '& .ML__placeholder': {\n borderBottom: '1px solid currentColor',\n minWidth: '1em',\n },\n};\n\n/**\n * Styling for the on-screen keyboard and any container rendering math labels.\n * Also hides MathLive's own affordances, since pie supplies its own keypad.\n */\nexport const commonMqKeyboardStyles = {\n ...commonMqFontStyles,\n ...longdivStyles,\n ...placeholderStyles,\n touchAction: 'manipulation',\n '& math-field': {\n fontSize: 'inherit',\n outline: 'none',\n },\n '& math-field::part(virtual-keyboard-toggle)': {\n display: 'none',\n },\n '& math-field::part(menu-toggle)': {\n display: 'none',\n },\n};\n\n/** Everything combined - the common case for a container of math. */\nexport const commonMathLiveStyles = {\n ...commonMqFontStyles,\n ...longdivStyles,\n ...supsubStyles,\n ...placeholderStyles,\n '& math-field': {\n fontSize: 'inherit',\n outline: 'none',\n },\n '& math-field::part(virtual-keyboard-toggle)': {\n display: 'none',\n },\n '& math-field::part(menu-toggle)': {\n display: 'none',\n },\n};\n\nexport const commonKeyboardStyles = commonMqKeyboardStyles;\n\n/**\n * Default export mirrors @pie-lib/math-input's `CommonMqStyles` object so\n * existing destructuring keeps working.\n */\nexport default {\n commonMqFontStyles,\n longdivStyles,\n supsubStyles,\n commonMqKeyboardStyles,\n placeholderStyles,\n commonMathLiveStyles,\n};\n"],"mappings":";;;;;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACO,IAAMA,kBAAkB,GAAAC,OAAA,CAAAD,kBAAA,GAAG;EAChC,wBAAwB,EAAE,aAAa;EACvC,cAAc,EAAE;IACdE,UAAU,EAAE;EACd;AACF,CAAC;;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B,EAAlBA,kBAAkB;EAClBG,aAAa,EAAbA,aAAa;EACbE,YAAY,EAAZA,YAAY;EACZI,sBAAsB,EAAtBA,sBAAsB;EACtBH,iBAAiB,EAAjBA,iBAAiB;EACjBQ,oBAAoB,EAApBA;AACF,CAAC","ignoreList":[]}
1
+ {"version":3,"file":"common-styles.js","names":["commonMqFontStyles","exports","fontFamily","longdivStyles","display","supsubStyles","placeholderStyles","borderBottom","minWidth","opacity","position","width","commonMqKeyboardStyles","_objectSpread","touchAction","fontSize","outline","commonMathLiveStyles","commonKeyboardStyles","_default"],"sources":["../../src/mf/common-styles.js"],"sourcesContent":["/**\n * Shared MathLive styling.\n *\n * Replaces @pie-lib/math-input's `common-mq-styles.js`. That file was built\n * around MathQuill's `.mq-*` class names, none of which exist in MathLive\n * output, so the selectors here target MathLive's own structure instead.\n *\n * The four named groups are kept because consumers destructure them:\n *\n * const { commonMqFontStyles, commonMqKeyboardStyles, longdivStyles, supsubStyles }\n * = mq.CommonMqStyles; // math-toolbar/src/editor-and-pad.jsx, math-preview.jsx\n *\n * Most are intentionally near-empty: MathLive sizes scripts, radicals and\n * fences correctly on its own, so the MathQuill-era corrections are not needed.\n * They stay as documented extension points rather than being deleted, so the\n * destructuring above keeps working.\n */\n\n/**\n * Font styling. MathQuill needed explicit MathJax font families to match the\n * static renderer; MathLive ships the KaTeX fonts it renders with, so this only\n * smooths rendering and lets the host override the family.\n */\nexport const commonMqFontStyles = {\n '-webkit-font-smoothing': 'antialiased',\n '& math-field': {\n fontFamily: 'inherit',\n },\n};\n\n/**\n * Long division. The MathQuill fork drew this with nested `.mq-longdiv-*`\n * elements that needed manual offsets; here it comes from the `\\longdiv` macro\n * (see `PIE_MACROS`), tagged with `data-pie-macro=\"longdiv\"`.\n */\nexport const longdivStyles = {\n '& [data-pie-macro=\"longdiv\"]': {\n display: 'inline-flex',\n },\n};\n\n/**\n * Superscript/subscript sizing. MathLive follows TeX metrics, so no overrides\n * are required.\n */\nexport const supsubStyles = {};\n\n/** Empty placeholder boxes (answer blocks / open slots). */\nexport const placeholderStyles = {\n '& .ML__placeholder': {\n borderBottom: '1px solid currentColor',\n minWidth: '1em',\n },\n // Stand-in glyph for an empty argument slot in STATIC math (see\n // `withVisibleEmptySlots`). Muted so it reads as \"a slot goes here\" rather\n // than as part of the symbol, matching how MathQuill shaded `.mq-empty`.\n '& [data-pie-empty]': {\n opacity: 0.5,\n },\n // Stretchy accents render an <svg>; mathlive-static.css positions it\n // absolutely at width:100%. Repeated here so static math cannot blow out its\n // container if that stylesheet is missing.\n '& svg': {\n position: 'absolute',\n width: '100%',\n },\n};\n\n/**\n * Styling for the on-screen keyboard and any container rendering math labels.\n * Also hides MathLive's own affordances, since pie supplies its own keypad.\n */\nexport const commonMqKeyboardStyles = {\n ...commonMqFontStyles,\n ...longdivStyles,\n ...placeholderStyles,\n touchAction: 'manipulation',\n '& math-field': {\n fontSize: 'inherit',\n outline: 'none',\n },\n '& math-field::part(virtual-keyboard-toggle)': {\n display: 'none',\n },\n '& math-field::part(menu-toggle)': {\n display: 'none',\n },\n};\n\n/** Everything combined - the common case for a container of math. */\nexport const commonMathLiveStyles = {\n ...commonMqFontStyles,\n ...longdivStyles,\n ...supsubStyles,\n ...placeholderStyles,\n '& math-field': {\n fontSize: 'inherit',\n outline: 'none',\n },\n '& math-field::part(virtual-keyboard-toggle)': {\n display: 'none',\n },\n '& math-field::part(menu-toggle)': {\n display: 'none',\n },\n};\n\nexport const commonKeyboardStyles = commonMqKeyboardStyles;\n\n/**\n * Default export mirrors @pie-lib/math-input's `CommonMqStyles` object so\n * existing destructuring keeps working.\n */\nexport default {\n commonMqFontStyles,\n longdivStyles,\n supsubStyles,\n commonMqKeyboardStyles,\n placeholderStyles,\n commonMathLiveStyles,\n};\n"],"mappings":";;;;;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACO,IAA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E,SAAS;IACnBC,OAAO,EAAE;EACX,CAAC;EACD,6CAA6C,EAAE;IAC7CZ,OAAO,EAAE;EACX,CAAC;EACD,iCAAiC,EAAE;IACjCA,OAAO,EAAE;EACX;AAAC,EACF;AAEM,IAAMc,oBAAoB,GAAAjB,OAAA,CAAAiB,oBAAA,GAAGN,sBAAsB;;AAE1D;AACA;AACA;AACA;AAHA,IAAAO,QAAA,GAAAlB,OAAA,cAIe;EACbD,kBAAkB,EAAlBA,kBAAkB;EAClBG,aAAa,EAAbA,aAAa;EACbE,YAAY,EAAZA,YAAY;EACZO,sBAAsB,EAAtBA,sBAAsB;EACtBN,iBAAiB,EAAjBA,iBAAiB;EACjBW,oBAAoB,EAApBA;AACF,CAAC","ignoreList":[]}
package/lib/mf/static.js CHANGED
@@ -20,11 +20,15 @@ var _styles = require("@mui/material/styles");
20
20
  var _debug = _interopRequireDefault(require("debug"));
21
21
  var _mathliveInstance = require("../mathlive-instance");
22
22
  var _latexBridge = require("../latex-bridge");
23
+ var _commonStyles = require("./common-styles");
23
24
  function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2["default"])(o), (0, _possibleConstructorReturn2["default"])(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2["default"])(t).constructor) : o.apply(t, e)); }
24
25
  function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
26
+ function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
27
+ function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { (0, _defineProperty2["default"])(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
25
28
  var log = (0, _debug["default"])('pie-lib:math-input-mathlive:static');
26
- var Holder = (0, _styles.styled)('span')({
27
- display: 'inline-block',
29
+ var Holder = (0, _styles.styled)('span')(_objectSpread(_objectSpread({
30
+ display: 'inline-block'
31
+ }, _commonStyles.placeholderStyles), {}, {
28
32
  '& math-field': {
29
33
  display: 'inline-block',
30
34
  border: 'none',
@@ -36,7 +40,7 @@ var Holder = (0, _styles.styled)('span')({
36
40
  '& math-field::part(menu-toggle)': {
37
41
  display: 'none'
38
42
  }
39
- });
43
+ }));
40
44
 
41
45
  /**
42
46
  * Static math. Drop-in replacement for @pie-lib/math-input's `mq.Static`.
@@ -1 +1 @@
1
- {"version":3,"file":"static.js","names":["_react","_interopRequireDefault","require","_propTypes","_styles","_debug","_mathliveInstance","_latexBridge","_callSuper","t","o","e","_getPrototypeOf2","_possibleConstructorReturn2","_isNativeReflectConstruct","Reflect","construct","constructor","apply","Boolean","prototype","valueOf","call","log","debug","Holder","styled","display","border","background","Static","exports","_React$Component","props","_this","_classCallCheck2","_defineProperty2","document","liveRegion","createElement","Object","assign","style","position","width","height","marginTop","clip","overflow","setAttribute","body","appendChild","parentNode","removeChild","undefined","message","textContent","clearTimeout","announceTimeout","setTimeout","event","isDeleting","key","next","converted","keys","some","id","before","promptValues","after","length","test","slice","announce","_this$props","onSubFieldChange","getFieldName","mathField","values","announceConversion","fields","innerFields","forEach","name","promptHandle","_this$props2","onSubFieldFocus","ids","getPrompts","focused","find","range","getPromptRange","selection","ranges","_range","_slicedToArray2","start","end","_selection$ranges$","selStart","handle","setInput","holderRef","React","createRef","state","markup","_inherits2","_createClass2","value","_componentDidMount","_asyncToGenerator2","_regenerator","mark","_callee","ml","wrap","_context","prev","isInteractive","loadMathLive","renderMarkup","abrupt","sent","current","MathfieldElement","macros","getMacros","readOnly","mathVirtualKeyboardPolicy","toMathLive","latex","addEventListener","onPromptInput","onPromptFocus","onKeyDown","createLiveRegion","stop","componentDidMount","arguments","componentDidUpdate","prevProps","componentWillUnmount","removeEventListener","remove","removeLiveRegion","fieldIds","indexOf","latexToMarkup","setState","_this2","out","fromMathLive","getPromptValue","_this3","setPromptValue","get","_this4","map","focus","blur","render","_this$props3","className","onFocus","onBlur","ref","dangerouslySetInnerHTML","__html","Component","PropTypes","string","isRequired","func"],"sources":["../../src/mf/static.jsx"],"sourcesContent":["import React from 'react';\nimport PropTypes from 'prop-types';\nimport { styled } from '@mui/material/styles';\nimport debug from 'debug';\nimport { loadMathLive, getMacros, latexToMarkup } from '../mathlive-instance';\nimport { toMathLive, fromMathLive, fieldIds } from '../latex-bridge';\n\nconst log = debug('pie-lib:math-input-mathlive:static');\n\nconst Holder = styled('span')({\n display: 'inline-block',\n '& math-field': {\n display: 'inline-block',\n border: 'none',\n background: 'transparent',\n },\n '& math-field::part(virtual-keyboard-toggle)': {\n display: 'none',\n },\n '& math-field::part(menu-toggle)': {\n display: 'none',\n },\n});\n\n/**\n * Static math. Drop-in replacement for @pie-lib/math-input's `mq.Static`.\n *\n * Two modes, chosen automatically:\n *\n * - **display** (no answer blocks in the latex): rendered with\n * `convertLatexToMarkup`. No mathfield instance, so it is cheap enough for\n * keypad labels - the old implementation created a full MathQuill\n * StaticMath per button.\n *\n * - **interactive** (latex contains `\\MathQuillMathField[..]{}` /\n * `\\placeholder[..]{}`): a read-only `<math-field>` whose placeholders stay\n * editable. Sub-field values are surfaced through the prompts API, replacing\n * MathQuill's `innerFields`.\n */\nexport default class Static extends React.Component {\n static propTypes = {\n latex: PropTypes.string.isRequired,\n className: PropTypes.string,\n onFocus: PropTypes.func,\n onBlur: PropTypes.func,\n getFieldName: PropTypes.func,\n onSubFieldChange: PropTypes.func,\n onSubFieldFocus: PropTypes.func,\n setInput: PropTypes.func,\n };\n\n static defaultProps = {\n getFieldName: () => {},\n };\n\n constructor(props) {\n super(props);\n this.holderRef = React.createRef();\n this.state = { markup: '' };\n this.promptValues = {};\n }\n\n async componentDidMount() {\n if (!this.isInteractive()) {\n await loadMathLive();\n this.renderMarkup();\n return;\n }\n\n const ml = await loadMathLive();\n\n if (!ml || !this.holderRef.current) {\n return;\n }\n\n this.mathField = new ml.MathfieldElement({ macros: getMacros() });\n this.mathField.readOnly = true;\n this.mathField.mathVirtualKeyboardPolicy = 'manual';\n this.mathField.value = toMathLive(this.props.latex);\n\n this.mathField.addEventListener('input', this.onPromptInput);\n this.mathField.addEventListener('focusin', this.onPromptFocus);\n this.mathField.addEventListener('keydown', this.onKeyDown);\n\n this.holderRef.current.appendChild(this.mathField);\n\n this.createLiveRegion();\n }\n\n componentDidUpdate(prevProps) {\n if (prevProps.latex === this.props.latex) {\n return;\n }\n\n if (this.mathField) {\n this.mathField.value = toMathLive(this.props.latex);\n } else {\n this.renderMarkup();\n }\n }\n\n componentWillUnmount() {\n if (this.mathField) {\n this.mathField.removeEventListener('input', this.onPromptInput);\n this.mathField.removeEventListener('focusin', this.onPromptFocus);\n this.mathField.removeEventListener('keydown', this.onKeyDown);\n this.mathField.remove();\n this.mathField = undefined;\n }\n\n this.removeLiveRegion();\n }\n\n /**\n * Off-screen aria-live region, ported from @pie-lib/math-input's Static.\n *\n * MathLive has its own accessibility layer, but it does not announce that\n * typed input was converted into a math symbol, which screen-reader users\n * relied on in the MathQuill implementation.\n */\n createLiveRegion = () => {\n if (typeof document === 'undefined' || this.liveRegion) {\n return;\n }\n\n this.liveRegion = document.createElement('div');\n Object.assign(this.liveRegion.style, {\n position: 'absolute',\n width: '1px',\n height: '1px',\n marginTop: '-1px',\n clip: 'rect(1px, 1px, 1px, 1px)',\n overflow: 'hidden',\n });\n this.liveRegion.setAttribute('aria-live', 'polite');\n this.liveRegion.setAttribute('aria-atomic', 'true');\n\n document.body.appendChild(this.liveRegion);\n };\n\n removeLiveRegion = () => {\n if (this.liveRegion && this.liveRegion.parentNode) {\n this.liveRegion.parentNode.removeChild(this.liveRegion);\n }\n\n this.liveRegion = undefined;\n };\n\n announce = (message) => {\n if (!this.liveRegion) {\n return;\n }\n\n this.liveRegion.textContent = message;\n\n // Clear once announced, so the same message can be announced again.\n clearTimeout(this.announceTimeout);\n this.announceTimeout = setTimeout(() => {\n if (this.liveRegion) {\n this.liveRegion.textContent = '';\n }\n }, 500);\n };\n\n onKeyDown = (event) => {\n // Deletions should not be announced as conversions.\n this.isDeleting = event?.key === 'Backspace' || event?.key === 'Delete';\n };\n\n /**\n * Announce when typed input became a math symbol. The MathQuill version\n * inferred this by counting braces; here a prompt whose latex grew by more\n * than the single character typed means a command was expanded.\n */\n announceConversion = (next) => {\n if (this.isDeleting) {\n this.isDeleting = false;\n return;\n }\n\n const converted = Object.keys(next).some((id) => {\n const before = this.promptValues[id] || '';\n const after = next[id] || '';\n\n return after.length > before.length + 1 && /\\\\/.test(after.slice(before.length));\n });\n\n if (converted) {\n this.announce('Converted to math symbol');\n }\n };\n\n /** Does this latex contain answer blocks? */\n isInteractive() {\n const latex = this.props.latex || '';\n\n return fieldIds(latex).length > 0 || latex.indexOf('\\\\placeholder') !== -1;\n }\n\n renderMarkup() {\n const markup = latexToMarkup(this.props.latex);\n\n if (markup !== this.state.markup) {\n this.setState({ markup });\n }\n }\n\n /** MathQuill's `innerFields` equivalent, keyed by prompt id. */\n values() {\n if (!this.mathField) {\n return {};\n }\n\n const out = {};\n\n (this.mathField.getPrompts() || []).forEach((id) => {\n out[id] = fromMathLive(this.mathField.getPromptValue(id));\n });\n\n return out;\n }\n\n /**\n * A MathQuill-inner-field-like handle for a prompt.\n *\n * The old API handed callers a MathQuill field object, and consumers commonly\n * called `field.latex()` on it. There is no equivalent object in MathLive -\n * prompts are addressed by id - so this adapter exposes the parts that were\n * actually used: `id` and a get/set `latex()`.\n */\n promptHandle(id) {\n return {\n id,\n latex: (value) => {\n if (!this.mathField) {\n return '';\n }\n\n if (value === undefined) {\n return fromMathLive(this.mathField.getPromptValue(id));\n }\n\n this.mathField.setPromptValue(id, toMathLive(value), {});\n\n return value;\n },\n };\n }\n\n /** All prompt handles, the analogue of `mathField.innerFields`. */\n get innerFields() {\n if (!this.mathField) {\n return [];\n }\n\n return (this.mathField.getPrompts() || []).map((id) => this.promptHandle(id));\n }\n\n onPromptInput = () => {\n const { onSubFieldChange, getFieldName } = this.props;\n\n if (!this.mathField) {\n return;\n }\n\n const next = this.values();\n\n this.announceConversion(next);\n\n if (!onSubFieldChange) {\n this.promptValues = next;\n return;\n }\n\n const fields = this.innerFields;\n\n // Emit only the prompts whose value actually changed, mirroring the\n // per-field granularity of the old onSubFieldChange(name, latex).\n Object.keys(next).forEach((id) => {\n if (next[id] === this.promptValues[id]) {\n return;\n }\n\n const name = getFieldName(this.promptHandle(id), fields) || id;\n\n onSubFieldChange(name, next[id]);\n });\n\n this.promptValues = next;\n };\n\n onPromptFocus = () => {\n const { onSubFieldFocus, getFieldName } = this.props;\n\n if (!this.mathField || !onSubFieldFocus) {\n return;\n }\n\n try {\n const ids = this.mathField.getPrompts() || [];\n // The focused prompt is the one containing the current selection.\n const focused = ids.find((id) => {\n const range = this.mathField.getPromptRange(id);\n const selection = this.mathField.selection;\n\n if (!range || !selection || !selection.ranges || !selection.ranges.length) {\n return false;\n }\n\n const [start, end] = range;\n const [selStart] = selection.ranges[0];\n\n return selStart >= start && selStart <= end;\n });\n\n if (focused) {\n const handle = this.promptHandle(focused);\n const name = getFieldName(handle, this.innerFields) || focused;\n\n if (this.props.setInput) {\n this.props.setInput(handle);\n }\n\n onSubFieldFocus(name, handle);\n }\n } catch (e) {\n log('error resolving focused prompt: %s', e.message);\n }\n };\n\n focus() {\n this.mathField && this.mathField.focus();\n }\n\n blur() {\n this.mathField && this.mathField.blur();\n }\n\n render() {\n const { className, onFocus, onBlur } = this.props;\n const { markup } = this.state;\n\n if (this.mathField || this.isInteractive()) {\n return <Holder className={className} onFocus={onFocus} onBlur={onBlur} ref={this.holderRef} />;\n }\n\n return (\n <Holder\n className={className}\n onFocus={onFocus}\n onBlur={onBlur}\n ref={this.holderRef}\n // eslint-disable-next-line react/no-danger\n dangerouslySetInnerHTML={{ __html: markup }}\n />\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAAA,IAAAA,MAAA,GAAAC,sBAAA,CAAAC,OAAA;AACA,IAAAC,UAAA,GAAAF,sBAAA,CAAAC,OAAA;AACA,IAAAE,OAAA,GAAAF,OAAA;AACA,IAAAG,MAAA,GAAAJ,sBAAA,CAAAC,OAAA;AACA,IAAAI,iBAAA,GAAAJ,OAAA;AACA,IAAAK,YAAA,GAAAL,OAAA;AAAqE,SAAAM,WAAAC,CAAA,EAAAC,CAAA,EAAAC,CAAA,WAAAD,CAAA,OAAAE,gBAAA,aAAAF,CAAA,OAAAG,2BAAA,aAAAJ,CAAA,EAAAK,yBAAA,KAAAC,OAAA,CAAAC,SAAA,CAAAN,CAAA,EAAAC,CAAA,YAAAC,gBAAA,aAAAH,CAAA,EAAAQ,WAAA,IAAAP,CAAA,CAAAQ,KAAA,CAAAT,CAAA,EAAAE,CAAA;AAAA,SAAAG,0BAAA,cAAAL,CAAA,IAAAU,OAAA,CAAAC,SAAA,CAAAC,OAAA,CAAAC,IAAA,CAAAP,OAAA,CAAAC,SAAA,CAAAG,OAAA,iCAAAV,CAAA,aAAAK,yBAAA,YAAAA,0BAAA,aAAAL,CAAA;AAErE,IAAMc,GAAG,GAAG,IAAAC,iBAAK,EAAC,oCAAoC,CAAC;AAEvD,IAAMC,MAAM,GAAG,IAAAC,cAAM,EAAC,MAAM,CAAC,CAAC;EAC5BC,OAAO,EAAE,cAAc;EACvB,cAAc,EAAE;IACdA,OAAO,EAAE,cAAc;IACvBC,MAAM,EAAE,MAAM;IACdC,UAAU,EAAE;EACd,CAAC;EACD,6CAA6C,EAAE;IAC7CF,OAAO,EAAE;EACX,CAAC;EACD,iCAAiC,EAAE;IACjCA,OAAO,EAAE;EACX;AACF,CAAC,CAAC;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SAAS,EAAEO,qBAAS,CAACC,MAAM;EAC3BP,OAAO,EAAEM,qBAAS,CAACG,IAAI;EACvBR,MAAM,EAAEK,qBAAS,CAACG,IAAI;EACtBlG,YAAY,EAAE+F,qBAAS,CAACG,IAAI;EAC5BnG,gBAAgB,EAAEgG,qBAAS,CAACG,IAAI;EAChCxF,eAAe,EAAEqF,qBAAS,CAACG,IAAI;EAC/BxE,QAAQ,EAAEqE,qBAAS,CAACG;AACtB,CAAC;AAAA,IAAA3I,gBAAA,aAVkBN,MAAM,kBAYH;EACpB+C,YAAY,EAAE,SAAdA,YAAYA,CAAA,EAAQ,CAAC;AACvB,CAAC","ignoreList":[]}
1
+ {"version":3,"file":"static.js","names":["_react","_interopRequireDefault","require","_propTypes","_styles","_debug","_mathliveInstance","_latexBridge","_commonStyles","_callSuper","t","o","e","_getPrototypeOf2","_possibleConstructorReturn2","_isNativeReflectConstruct","Reflect","construct","constructor","apply","Boolean","prototype","valueOf","call","ownKeys","r","Object","keys","getOwnPropertySymbols","filter","getOwnPropertyDescriptor","enumerable","push","_objectSpread","arguments","length","forEach","_defineProperty2","getOwnPropertyDescriptors","defineProperties","defineProperty","log","debug","Holder","styled","display","placeholderStyles","border","background","Static","exports","_React$Component","props","_this","_classCallCheck2","document","liveRegion","createElement","assign","style","position","width","height","marginTop","clip","overflow","setAttribute","body","appendChild","parentNode","removeChild","undefined","message","textContent","clearTimeout","announceTimeout","setTimeout","event","isDeleting","key","next","converted","some","id","before","promptValues","after","test","slice","announce","_this$props","onSubFieldChange","getFieldName","mathField","values","announceConversion","fields","innerFields","name","promptHandle","_this$props2","onSubFieldFocus","ids","getPrompts","focused","find","range","getPromptRange","selection","ranges","_range","_slicedToArray2","start","end","_selection$ranges$","selStart","handle","setInput","holderRef","React","createRef","state","markup","_inherits2","_createClass2","value","_componentDidMount","_asyncToGenerator2","_regenerator","mark","_callee","ml","wrap","_context","prev","isInteractive","loadMathLive","renderMarkup","abrupt","sent","current","MathfieldElement","macros","getMacros","readOnly","mathVirtualKeyboardPolicy","toMathLive","latex","addEventListener","onPromptInput","onPromptFocus","onKeyDown","createLiveRegion","stop","componentDidMount","componentDidUpdate","prevProps","componentWillUnmount","removeEventListener","remove","removeLiveRegion","fieldIds","indexOf","latexToMarkup","setState","_this2","out","fromMathLive","getPromptValue","_this3","setPromptValue","get","_this4","map","focus","blur","render","_this$props3","className","onFocus","onBlur","ref","dangerouslySetInnerHTML","__html","Component","PropTypes","string","isRequired","func"],"sources":["../../src/mf/static.jsx"],"sourcesContent":["import React from 'react';\nimport PropTypes from 'prop-types';\nimport { styled } from '@mui/material/styles';\nimport debug from 'debug';\nimport { loadMathLive, getMacros, latexToMarkup } from '../mathlive-instance';\nimport { toMathLive, fromMathLive, fieldIds } from '../latex-bridge';\nimport { placeholderStyles } from './common-styles';\n\nconst log = debug('pie-lib:math-input-mathlive:static');\n\nconst Holder = styled('span')({\n display: 'inline-block',\n // Shared static-math rules: muted empty-slot glyphs and svg containment.\n ...placeholderStyles,\n '& math-field': {\n display: 'inline-block',\n border: 'none',\n background: 'transparent',\n },\n '& math-field::part(virtual-keyboard-toggle)': {\n display: 'none',\n },\n '& math-field::part(menu-toggle)': {\n display: 'none',\n },\n});\n\n/**\n * Static math. Drop-in replacement for @pie-lib/math-input's `mq.Static`.\n *\n * Two modes, chosen automatically:\n *\n * - **display** (no answer blocks in the latex): rendered with\n * `convertLatexToMarkup`. No mathfield instance, so it is cheap enough for\n * keypad labels - the old implementation created a full MathQuill\n * StaticMath per button.\n *\n * - **interactive** (latex contains `\\MathQuillMathField[..]{}` /\n * `\\placeholder[..]{}`): a read-only `<math-field>` whose placeholders stay\n * editable. Sub-field values are surfaced through the prompts API, replacing\n * MathQuill's `innerFields`.\n */\nexport default class Static extends React.Component {\n static propTypes = {\n latex: PropTypes.string.isRequired,\n className: PropTypes.string,\n onFocus: PropTypes.func,\n onBlur: PropTypes.func,\n getFieldName: PropTypes.func,\n onSubFieldChange: PropTypes.func,\n onSubFieldFocus: PropTypes.func,\n setInput: PropTypes.func,\n };\n\n static defaultProps = {\n getFieldName: () => {},\n };\n\n constructor(props) {\n super(props);\n this.holderRef = React.createRef();\n this.state = { markup: '' };\n this.promptValues = {};\n }\n\n async componentDidMount() {\n if (!this.isInteractive()) {\n await loadMathLive();\n this.renderMarkup();\n return;\n }\n\n const ml = await loadMathLive();\n\n if (!ml || !this.holderRef.current) {\n return;\n }\n\n this.mathField = new ml.MathfieldElement({ macros: getMacros() });\n this.mathField.readOnly = true;\n this.mathField.mathVirtualKeyboardPolicy = 'manual';\n this.mathField.value = toMathLive(this.props.latex);\n\n this.mathField.addEventListener('input', this.onPromptInput);\n this.mathField.addEventListener('focusin', this.onPromptFocus);\n this.mathField.addEventListener('keydown', this.onKeyDown);\n\n this.holderRef.current.appendChild(this.mathField);\n\n this.createLiveRegion();\n }\n\n componentDidUpdate(prevProps) {\n if (prevProps.latex === this.props.latex) {\n return;\n }\n\n if (this.mathField) {\n this.mathField.value = toMathLive(this.props.latex);\n } else {\n this.renderMarkup();\n }\n }\n\n componentWillUnmount() {\n if (this.mathField) {\n this.mathField.removeEventListener('input', this.onPromptInput);\n this.mathField.removeEventListener('focusin', this.onPromptFocus);\n this.mathField.removeEventListener('keydown', this.onKeyDown);\n this.mathField.remove();\n this.mathField = undefined;\n }\n\n this.removeLiveRegion();\n }\n\n /**\n * Off-screen aria-live region, ported from @pie-lib/math-input's Static.\n *\n * MathLive has its own accessibility layer, but it does not announce that\n * typed input was converted into a math symbol, which screen-reader users\n * relied on in the MathQuill implementation.\n */\n createLiveRegion = () => {\n if (typeof document === 'undefined' || this.liveRegion) {\n return;\n }\n\n this.liveRegion = document.createElement('div');\n Object.assign(this.liveRegion.style, {\n position: 'absolute',\n width: '1px',\n height: '1px',\n marginTop: '-1px',\n clip: 'rect(1px, 1px, 1px, 1px)',\n overflow: 'hidden',\n });\n this.liveRegion.setAttribute('aria-live', 'polite');\n this.liveRegion.setAttribute('aria-atomic', 'true');\n\n document.body.appendChild(this.liveRegion);\n };\n\n removeLiveRegion = () => {\n if (this.liveRegion && this.liveRegion.parentNode) {\n this.liveRegion.parentNode.removeChild(this.liveRegion);\n }\n\n this.liveRegion = undefined;\n };\n\n announce = (message) => {\n if (!this.liveRegion) {\n return;\n }\n\n this.liveRegion.textContent = message;\n\n // Clear once announced, so the same message can be announced again.\n clearTimeout(this.announceTimeout);\n this.announceTimeout = setTimeout(() => {\n if (this.liveRegion) {\n this.liveRegion.textContent = '';\n }\n }, 500);\n };\n\n onKeyDown = (event) => {\n // Deletions should not be announced as conversions.\n this.isDeleting = event?.key === 'Backspace' || event?.key === 'Delete';\n };\n\n /**\n * Announce when typed input became a math symbol. The MathQuill version\n * inferred this by counting braces; here a prompt whose latex grew by more\n * than the single character typed means a command was expanded.\n */\n announceConversion = (next) => {\n if (this.isDeleting) {\n this.isDeleting = false;\n return;\n }\n\n const converted = Object.keys(next).some((id) => {\n const before = this.promptValues[id] || '';\n const after = next[id] || '';\n\n return after.length > before.length + 1 && /\\\\/.test(after.slice(before.length));\n });\n\n if (converted) {\n this.announce('Converted to math symbol');\n }\n };\n\n /** Does this latex contain answer blocks? */\n isInteractive() {\n const latex = this.props.latex || '';\n\n return fieldIds(latex).length > 0 || latex.indexOf('\\\\placeholder') !== -1;\n }\n\n renderMarkup() {\n const markup = latexToMarkup(this.props.latex);\n\n if (markup !== this.state.markup) {\n this.setState({ markup });\n }\n }\n\n /** MathQuill's `innerFields` equivalent, keyed by prompt id. */\n values() {\n if (!this.mathField) {\n return {};\n }\n\n const out = {};\n\n (this.mathField.getPrompts() || []).forEach((id) => {\n out[id] = fromMathLive(this.mathField.getPromptValue(id));\n });\n\n return out;\n }\n\n /**\n * A MathQuill-inner-field-like handle for a prompt.\n *\n * The old API handed callers a MathQuill field object, and consumers commonly\n * called `field.latex()` on it. There is no equivalent object in MathLive -\n * prompts are addressed by id - so this adapter exposes the parts that were\n * actually used: `id` and a get/set `latex()`.\n */\n promptHandle(id) {\n return {\n id,\n latex: (value) => {\n if (!this.mathField) {\n return '';\n }\n\n if (value === undefined) {\n return fromMathLive(this.mathField.getPromptValue(id));\n }\n\n this.mathField.setPromptValue(id, toMathLive(value), {});\n\n return value;\n },\n };\n }\n\n /** All prompt handles, the analogue of `mathField.innerFields`. */\n get innerFields() {\n if (!this.mathField) {\n return [];\n }\n\n return (this.mathField.getPrompts() || []).map((id) => this.promptHandle(id));\n }\n\n onPromptInput = () => {\n const { onSubFieldChange, getFieldName } = this.props;\n\n if (!this.mathField) {\n return;\n }\n\n const next = this.values();\n\n this.announceConversion(next);\n\n if (!onSubFieldChange) {\n this.promptValues = next;\n return;\n }\n\n const fields = this.innerFields;\n\n // Emit only the prompts whose value actually changed, mirroring the\n // per-field granularity of the old onSubFieldChange(name, latex).\n Object.keys(next).forEach((id) => {\n if (next[id] === this.promptValues[id]) {\n return;\n }\n\n const name = getFieldName(this.promptHandle(id), fields) || id;\n\n onSubFieldChange(name, next[id]);\n });\n\n this.promptValues = next;\n };\n\n onPromptFocus = () => {\n const { onSubFieldFocus, getFieldName } = this.props;\n\n if (!this.mathField || !onSubFieldFocus) {\n return;\n }\n\n try {\n const ids = this.mathField.getPrompts() || [];\n // The focused prompt is the one containing the current selection.\n const focused = ids.find((id) => {\n const range = this.mathField.getPromptRange(id);\n const selection = this.mathField.selection;\n\n if (!range || !selection || !selection.ranges || !selection.ranges.length) {\n return false;\n }\n\n const [start, end] = range;\n const [selStart] = selection.ranges[0];\n\n return selStart >= start && selStart <= end;\n });\n\n if (focused) {\n const handle = this.promptHandle(focused);\n const name = getFieldName(handle, this.innerFields) || focused;\n\n if (this.props.setInput) {\n this.props.setInput(handle);\n }\n\n onSubFieldFocus(name, handle);\n }\n } catch (e) {\n log('error resolving focused prompt: %s', e.message);\n }\n };\n\n focus() {\n this.mathField && this.mathField.focus();\n }\n\n blur() {\n this.mathField && this.mathField.blur();\n }\n\n render() {\n const { className, onFocus, onBlur } = this.props;\n const { markup } = this.state;\n\n if (this.mathField || this.isInteractive()) {\n return <Holder className={className} onFocus={onFocus} onBlur={onBlur} ref={this.holderRef} />;\n }\n\n return (\n <Holder\n className={className}\n onFocus={onFocus}\n onBlur={onBlur}\n ref={this.holderRef}\n // eslint-disable-next-line react/no-danger\n dangerouslySetInnerHTML={{ __html: markup }}\n />\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAAA,IAAAA,MAAA,GAAAC,sBAAA,CAAAC,OAAA;AACA,IAAAC,UAAA,GAAAF,sBAAA,CAAAC,OAAA;AACA,IAAAE,OAAA,GAAAF,OAAA;AACA,IAAAG,MAAA,GAAAJ,sBAAA,CAAAC,OAAA;AACA,IAAAI,iBAAA,GAAAJ,OAAA;AACA,IAAAK,YAAA,GAAAL,OAAA;AACA,IAAAM,aAAA,GAAAN,OAAA;AAAoD,SAAAO,WAAAC,CAAA,EAAAC,CAAA,EAAAC,CAAA,WAAAD,CAAA,OAAAE,gBAAA,aAAAF,CAAA,OAAAG,2BAAA,aAAAJ,CAAA,EAAAK,yBAAA,KAAAC,OAAA,CAAAC,SAAA,CAAAN,CAAA,EAAAC,CAAA,YAAAC,gBAAA,aAAAH,CAAA,EAAAQ,WAAA,IAAAP,CAAA,CAAAQ,KAAA,CAAAT,CAAA,EAAAE,CAAA;AAAA,SAAAG,0BAAA,cAAAL,CAAA,IAAAU,OAAA,CAAAC,SAAA,CAAAC,OAAA,CAAAC,IAAA,CAAAP,OAAA,CAAAC,SAAA,CAAAG,OAAA,iCAAAV,CAAA,aAAAK,yBAAA,YAAAA,0BAAA,aAAAL,CAAA;AAAA,SAAAc,QAAAZ,CAAA,EAAAa,CAAA,QAAAf,CAAA,GAAAgB,MAAA,CAAAC,IAAA,CAAAf,CAAA,OAAAc,MAAA,CAAAE,qBAAA,QAAAjB,CAAA,GAAAe,MAAA,CAAAE,qBAAA,CAAAhB,CAAA,GAAAa,CAAA,KAAAd,CAAA,GAAAA,CAAA,CAAAkB,MAAA,WAAAJ,CAAA,WAAAC,MAAA,CAAAI,wBA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