@pie-lib/math-input-mathlive 1.1.5-beta.8 → 1.1.5-beta.9

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.
@@ -292,6 +292,71 @@ var primesToApostrophes = function primesToApostrophes(primes) {
292
292
  "'".repeat((primes.match(/\\prime(?![a-zA-Z])/g) || []).length + 2 * (primes.match(BARE_DOUBLEPRIME_REGEX) || []).length)
293
293
  );
294
294
  };
295
+ var BARE_PRIME_COMMAND_REGEX = /^\\(doubleprime|prime)(?![a-zA-Z])/;
296
+
297
+ /**
298
+ * Primes that are *not* in a superscript.
299
+ *
300
+ * MathLive emits bare `\prime` / `\doubleprime` for a `′` or `″` typed or pasted
301
+ * as a character (`5′6″` serialises as `5\prime6\doubleprime`). A bare `\prime`
302
+ * is a full-size glyph in MathJax, while `''` is a superscript, so storing
303
+ * `5\prime6''` drew the single prime visibly larger than each stroke of the
304
+ * double prime. Both become apostrophes, the superscript primes MathQuill
305
+ * stored, so they always match.
306
+ *
307
+ * Inside a script (`x^{\prime 2}`, `x^\prime`) a prime is already a
308
+ * superscript, and an apostrophe there would mean something else, so
309
+ * `\prime` is kept and `\doubleprime` (unknown to MathJax) becomes
310
+ * `\prime\prime`.
311
+ *
312
+ * @param {string} latex
313
+ * @returns {string}
314
+ */
315
+ var barePrimesToApostrophes = function barePrimesToApostrophes(latex) {
316
+ if (latex.indexOf('prime') === -1) {
317
+ return latex;
318
+ }
319
+
320
+ // One entry per open brace: is that group a super/subscript?
321
+ var groups = [];
322
+ var out = '';
323
+ var i = 0;
324
+ while (i < latex.length) {
325
+ var ch = latex[i];
326
+ if (ch === '\\') {
327
+ var match = latex.slice(i).match(BARE_PRIME_COMMAND_REGEX);
328
+ if (match) {
329
+ var isDouble = match[1] === 'doubleprime';
330
+ // `x^\prime`: the command is itself the script.
331
+ var isScriptArgument = /[\^_]\s*$/.test(out);
332
+ var inScript = isScriptArgument || groups.indexOf(true) !== -1;
333
+ if (inScript) {
334
+ out += isDouble ? '\\prime\\prime' : '\\prime';
335
+ } else {
336
+ // eslint-disable-next-line quotes
337
+ out += isDouble ? "''" : "'";
338
+ }
339
+ i += match[0].length;
340
+ continue;
341
+ }
342
+
343
+ // Copy any other command, or an escaped character such as `\{`, whole.
344
+ var command = latex.slice(i).match(/^\\(?:[a-zA-Z]+|.)/);
345
+ var text = command ? command[0] : ch;
346
+ out += text;
347
+ i += text.length;
348
+ continue;
349
+ }
350
+ if (ch === '{') {
351
+ groups.push(/[\^_]\s*$/.test(out));
352
+ } else if (ch === '}') {
353
+ groups.pop();
354
+ }
355
+ out += ch;
356
+ i += 1;
357
+ }
358
+ return out;
359
+ };
295
360
 
296
361
  /**
297
362
  * Rewrite what MathLive serialises into the form MathQuill stored: alias
@@ -301,13 +366,11 @@ var primesToApostrophes = function primesToApostrophes(primes) {
301
366
  * @returns {string}
302
367
  */
303
368
  var toCanonicalCommands = exports.toCanonicalCommands = function toCanonicalCommands(latex) {
304
- return typeof latex === 'string' ? latex.replace(MATHQUILL_ALIAS_REGEX, function (m) {
369
+ return typeof latex === 'string' ? barePrimesToApostrophes(latex.replace(MATHQUILL_ALIAS_REGEX, function (m) {
305
370
  return MATHQUILL_ALIASES[m];
306
371
  }).replace(PRIME_SUPERSCRIPT_REGEX, function (_m, primes) {
307
372
  return primesToApostrophes(primes);
308
- })
309
- // eslint-disable-next-line quotes
310
- .replace(BARE_DOUBLEPRIME_REGEX, "''") : latex;
373
+ })) : latex;
311
374
  };
312
375
 
313
376
  /**
@@ -1 +1 @@
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","EMPTY_OVERLINE_REGEX","EMPTY_OVERLINE_STRUT","EMPTY_FENCE_REGEX","EMPTY_FENCE_SLOT","withVisibleEmptySlots","latex","replace","concat","_m","open","close","toNativeCommands","out","replaceAbs","escapeBareComments","indexOf","backslashes","i","length","ch","idx","depth","inner","slice","fieldIds","match","lastIndex","exec","push","toMathLive","id","content","split","join","MATHQUILL_ALIASES","MATHQUILL_ALIAS_REGEX","PRIME_SUPERSCRIPT_REGEX","BARE_DOUBLEPRIME_REGEX","primesToApostrophes","primes","repeat","toCanonicalCommands","m","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 something with real width is required.\n *\n * It must be a `\\rule`, not a unicode glyph. A glyph's width comes from font\n * metrics, and U+25AB is not in the KaTeX fonts - the browser substitutes a\n * wider fallback while MathLive still sizes surrounding accents from its own\n * metrics. That left stretchy accents (`\\overarc`, `\\overleftrightarrow`)\n * visibly narrower than the box they were meant to span. A rule carries an\n * explicit em width, so accents size correctly - and a filled box is closer to\n * MathQuill's `.mq-empty` anyway.\n *\n * Live mathfields need none of this - MathLive manages empty slots itself.\n */\nconst EMPTY_SLOT = '\\\\htmlData{pie-empty=1}{\\\\rule{0.55em}{0.55em}}';\nconst EMPTY_GROUP_REGEX = /\\{\\s*\\}/g;\n// The segment key (`\\overline{}`). A bar is a thin accent, so its label is shorter\n// than the ray and line keys' stretchy arrows. The keypad centres every label\n// in its cell, so the bar's box ended up ~0.17em higher than theirs.\nconst EMPTY_OVERLINE_REGEX = /\\\\overline\\{\\s*\\}/g;\nconst EMPTY_OVERLINE_STRUT = '\\\\rule{0em}{1.08em}';\n// Empty delimiter pairs: `\\abs{}` is converted to `\\left|\\right|`, and the\n// parenthesis / bracket keys are `\\left(\\right)` / `\\left[\\right]`. None has a\n// `{}` group for the rule above to catch, so they would render as bare fences.\nconst EMPTY_FENCE_REGEX = /\\\\left([([|])\\s*\\\\right([)\\]|])/g;\n// The same muted fill as the other slots (`pie-empty`), but a tall rectangle\n// rather than a square. It also sets the fences' height: `\\left...\\right` stretch\n// to their content, so a taller slot gives taller parentheses.\n//\n// A `\\rule` stands on the baseline, but the fences are centred on the math axis\n// (0.25em above it), so an un-lifted box sat high between them. `[-0.25em]`\n// lowers it by (axis - height / 2) = 0.25 - 1 / 2, centring it on the axis.\n//\n// Lowering it alone also shrinks the fences, which size themselves to their\n// content (MathLive switches to short bars). The zero-width `\\rule{0em}{1em}`\n// strut keeps the content as tall as before, so the bars keep their height and\n// only the box moves.\nconst EMPTY_FENCE_SLOT = '\\\\rule{0em}{1em}\\\\htmlData{pie-empty=1}{\\\\rule[-0.25em]{0.55em}{1em}}';\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) =>\n (latex || '')\n .replace(EMPTY_OVERLINE_REGEX, `\\\\overline{${EMPTY_OVERLINE_STRUT}${EMPTY_SLOT}}`)\n .replace(EMPTY_GROUP_REGEX, `{${EMPTY_SLOT}}`)\n .replace(EMPTY_FENCE_REGEX, (_m, open, close) => `\\\\left${open}${EMPTY_FENCE_SLOT}\\\\right${close}`);\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 out = escapeBareComments(out);\n\n return out;\n};\n\n/**\n * Escape an unescaped `%`.\n *\n * In real LaTeX `%` starts a comment, so MathLive discards it *and everything\n * after it*: `50%` renders as `50`, and `x%y` as just `x`. MathQuill had no\n * such notion - it treated `%` as a symbol - so latex from anywhere outside the\n * keypad may still carry a bare one.\n *\n * Only a `%` preceded by an even number of backslashes is bare: `\\%` is already\n * escaped, while the `%` in `\\\\%` (a line break, then a comment) is not.\n *\n * @param {string} latex\n * @returns {string}\n */\nconst escapeBareComments = (latex) => {\n if (latex.indexOf('%') === -1) {\n return latex;\n }\n\n let out = '';\n // Consecutive backslashes immediately before the current character.\n let backslashes = 0;\n\n for (let i = 0; i < latex.length; i++) {\n const ch = latex[i];\n\n out += ch === '%' && backslashes % 2 === 0 ? '\\\\%' : ch;\n backslashes = ch === '\\\\' ? backslashes + 1 : 0;\n }\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 * Keypad command names that MathQuill treated as ALIASES of a different command.\n *\n * MathQuill registered `\\\\divide` as another name for `\\\\div` (and\n * `\\\\perpendicular` for `\\\\perp`), so pressing the key stored the real command.\n * MathLive only knows these names through `PIE_MACROS`, and serialises a macro\n * under its own name - so `\\\\divide` reached storage verbatim, where MathJax\n * (@pie-lib/math-rendering) has no such command and renders it as red text.\n *\n * Every other keypad command already matches what MathQuill stored (`\\\\degree`,\n * `\\\\nsim`, `\\\\ncong`, `\\\\nparallel`, `\\\\square`, `\\\\napprox`,\n * `\\\\parallelogram`), and MathJax understands those.\n */\nconst MATHQUILL_ALIASES = {\n '\\\\divide': '\\\\div',\n '\\\\perpendicular': '\\\\perp',\n};\n\n// Whole command names only: `\\\\divideontimes` is a real AMS symbol.\nconst MATHQUILL_ALIAS_REGEX = /\\\\(divide|perpendicular)(?![a-zA-Z])/g;\n\n/**\n * Primes. MathLive turns a prime that follows a base into a superscript atom and\n * serialises it as `^{\\\\prime}`, or `^{\\\\doubleprime}` for the keypad's double\n * prime key (`5''` comes back out as `5^{\\\\doubleprime}`). MathJax has no\n * `\\\\doubleprime`, and two adjacent `^{\\\\prime}` groups - what typing `'` twice\n * produces - are a \"double exponent\" error. MathQuill stored plain apostrophes,\n * which both MathJax and MathLive read as primes, so store those.\n *\n * Only a superscript made of primes alone is rewritten: `x^{\\\\prime 2}` keeps\n * its group, since it holds more than primes.\n */\nconst PRIME_SUPERSCRIPT_REGEX = /\\^\\{((?:\\s*\\\\(?:prime|doubleprime)(?![a-zA-Z]))+)\\s*\\}/g;\nconst BARE_DOUBLEPRIME_REGEX = /\\\\doubleprime(?![a-zA-Z])/g;\n\nconst primesToApostrophes = (primes) =>\n // eslint-disable-next-line quotes\n \"'\".repeat(\n (primes.match(/\\\\prime(?![a-zA-Z])/g) || []).length + 2 * (primes.match(BARE_DOUBLEPRIME_REGEX) || []).length,\n );\n\n/**\n * Rewrite what MathLive serialises into the form MathQuill stored: alias\n * command names, and primes.\n *\n * @param {string} latex\n * @returns {string}\n */\nexport const toCanonicalCommands = (latex) =>\n typeof latex === 'string'\n ? latex\n .replace(MATHQUILL_ALIAS_REGEX, (m) => MATHQUILL_ALIASES[m])\n .replace(PRIME_SUPERSCRIPT_REGEX, (_m, primes) => primesToApostrophes(primes))\n // eslint-disable-next-line quotes\n .replace(BARE_DOUBLEPRIME_REGEX, \"''\")\n : latex;\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 // Store the command MathQuill stored, not the alias - also heals latex that was\n // saved with `\\\\divide` before the keypad resolved it.\n return toCanonicalCommands(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 // An explicit \"blank over blank\" key: both slots start empty.\n '\\\\frac': '\\\\frac{#?}{#?}',\n // Division, which must behave like MathQuill's `/`: whatever precedes the\n // cursor becomes the numerator and the caret lands in the denominator. `#@`\n // is MathLive's token for \"the selection, or the item before the cursor\" -\n // this is exactly the template MathLive binds to the `/` key itself. Using\n // `#?` here instead produced an empty fraction and left the typed number\n // stranded outside it.\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] || MATHQUILL_ALIASES[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, MATHQUILL_ALIASES };\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;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAMC,UAAU,GAAG,iDAAiD;AACpE,IAAMC,iBAAiB,GAAG,UAAU;AACpC;AACA;AACA;AACA,IAAMC,oBAAoB,GAAG,oBAAoB;AACjD,IAAMC,oBAAoB,GAAG,qBAAqB;AAClD;AACA;AACA;AACA,IAAMC,iBAAiB,GAAG,kCAAkC;AAC5D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAMC,gBAAgB,GAAG,uEAAuE;;AAEhG;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,IAAMC,qBAAqB,GAAAd,OAAA,CAAAc,qBAAA,GAAG,SAAxBA,qBAAqBA,CAAIC,KAAK;EAAA,OACzC,CAACA,KAAK,IAAI,EAAE,EACTC,OAAO,CAAC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ACE,OAAO,EAAE;IACf;IACA;IACA;IACA;IACA,IAAMI,KAAK,GAAGC,KAAK,CAACC,OAAO,CAACR,GAAG,CAACE,OAAO,CAAC,GAAGF,GAAG,CAACE,OAAO,GAAG,CAACF,GAAG,CAACE,OAAO,CAAC;IACtE,IAAME,KAAK,GAAGE,KAAK,CAAClB,GAAG,CAAC,UAACqB,CAAC;MAAA,OAAKnB,kBAAkB,CAACmB,CAAC,CAAC,IAAIhC,iBAAiB,CAACgC,CAAC,CAAC,IAAIA,CAAC;IAAA,EAAC,CAACjC,IAAI,CAAC,EAAE,CAAC;IAE3F,OAAO;MAAE2B,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","EMPTY_OVERLINE_REGEX","EMPTY_OVERLINE_STRUT","EMPTY_FENCE_REGEX","EMPTY_FENCE_SLOT","withVisibleEmptySlots","latex","replace","concat","_m","open","close","toNativeCommands","out","replaceAbs","escapeBareComments","indexOf","backslashes","i","length","ch","idx","depth","inner","slice","fieldIds","match","lastIndex","exec","push","toMathLive","id","content","split","join","MATHQUILL_ALIASES","MATHQUILL_ALIAS_REGEX","PRIME_SUPERSCRIPT_REGEX","BARE_DOUBLEPRIME_REGEX","primesToApostrophes","primes","repeat","BARE_PRIME_COMMAND_REGEX","barePrimesToApostrophes","groups","isDouble","isScriptArgument","test","inScript","command","text","pop","toCanonicalCommands","m","fromMathLive","trim","map","s","COMMANDS_WITH_ARGS","_","KEYSTROKES","Left","Right","Backspace","Delete","Up","Down","keyToAction","key","undefined","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 something with real width is required.\n *\n * It must be a `\\rule`, not a unicode glyph. A glyph's width comes from font\n * metrics, and U+25AB is not in the KaTeX fonts - the browser substitutes a\n * wider fallback while MathLive still sizes surrounding accents from its own\n * metrics. That left stretchy accents (`\\overarc`, `\\overleftrightarrow`)\n * visibly narrower than the box they were meant to span. A rule carries an\n * explicit em width, so accents size correctly - and a filled box is closer to\n * MathQuill's `.mq-empty` anyway.\n *\n * Live mathfields need none of this - MathLive manages empty slots itself.\n */\nconst EMPTY_SLOT = '\\\\htmlData{pie-empty=1}{\\\\rule{0.55em}{0.55em}}';\nconst EMPTY_GROUP_REGEX = /\\{\\s*\\}/g;\n// The segment key (`\\overline{}`). A bar is a thin accent, so its label is shorter\n// than the ray and line keys' stretchy arrows. The keypad centres every label\n// in its cell, so the bar's box ended up ~0.17em higher than theirs.\nconst EMPTY_OVERLINE_REGEX = /\\\\overline\\{\\s*\\}/g;\nconst EMPTY_OVERLINE_STRUT = '\\\\rule{0em}{1.08em}';\n// Empty delimiter pairs: `\\abs{}` is converted to `\\left|\\right|`, and the\n// parenthesis / bracket keys are `\\left(\\right)` / `\\left[\\right]`. None has a\n// `{}` group for the rule above to catch, so they would render as bare fences.\nconst EMPTY_FENCE_REGEX = /\\\\left([([|])\\s*\\\\right([)\\]|])/g;\n// The same muted fill as the other slots (`pie-empty`), but a tall rectangle\n// rather than a square. It also sets the fences' height: `\\left...\\right` stretch\n// to their content, so a taller slot gives taller parentheses.\n//\n// A `\\rule` stands on the baseline, but the fences are centred on the math axis\n// (0.25em above it), so an un-lifted box sat high between them. `[-0.25em]`\n// lowers it by (axis - height / 2) = 0.25 - 1 / 2, centring it on the axis.\n//\n// Lowering it alone also shrinks the fences, which size themselves to their\n// content (MathLive switches to short bars). The zero-width `\\rule{0em}{1em}`\n// strut keeps the content as tall as before, so the bars keep their height and\n// only the box moves.\nconst EMPTY_FENCE_SLOT = '\\\\rule{0em}{1em}\\\\htmlData{pie-empty=1}{\\\\rule[-0.25em]{0.55em}{1em}}';\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) =>\n (latex || '')\n .replace(EMPTY_OVERLINE_REGEX, `\\\\overline{${EMPTY_OVERLINE_STRUT}${EMPTY_SLOT}}`)\n .replace(EMPTY_GROUP_REGEX, `{${EMPTY_SLOT}}`)\n .replace(EMPTY_FENCE_REGEX, (_m, open, close) => `\\\\left${open}${EMPTY_FENCE_SLOT}\\\\right${close}`);\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 out = escapeBareComments(out);\n\n return out;\n};\n\n/**\n * Escape an unescaped `%`.\n *\n * In real LaTeX `%` starts a comment, so MathLive discards it *and everything\n * after it*: `50%` renders as `50`, and `x%y` as just `x`. MathQuill had no\n * such notion - it treated `%` as a symbol - so latex from anywhere outside the\n * keypad may still carry a bare one.\n *\n * Only a `%` preceded by an even number of backslashes is bare: `\\%` is already\n * escaped, while the `%` in `\\\\%` (a line break, then a comment) is not.\n *\n * @param {string} latex\n * @returns {string}\n */\nconst escapeBareComments = (latex) => {\n if (latex.indexOf('%') === -1) {\n return latex;\n }\n\n let out = '';\n // Consecutive backslashes immediately before the current character.\n let backslashes = 0;\n\n for (let i = 0; i < latex.length; i++) {\n const ch = latex[i];\n\n out += ch === '%' && backslashes % 2 === 0 ? '\\\\%' : ch;\n backslashes = ch === '\\\\' ? backslashes + 1 : 0;\n }\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 * Keypad command names that MathQuill treated as ALIASES of a different command.\n *\n * MathQuill registered `\\\\divide` as another name for `\\\\div` (and\n * `\\\\perpendicular` for `\\\\perp`), so pressing the key stored the real command.\n * MathLive only knows these names through `PIE_MACROS`, and serialises a macro\n * under its own name - so `\\\\divide` reached storage verbatim, where MathJax\n * (@pie-lib/math-rendering) has no such command and renders it as red text.\n *\n * Every other keypad command already matches what MathQuill stored (`\\\\degree`,\n * `\\\\nsim`, `\\\\ncong`, `\\\\nparallel`, `\\\\square`, `\\\\napprox`,\n * `\\\\parallelogram`), and MathJax understands those.\n */\nconst MATHQUILL_ALIASES = {\n '\\\\divide': '\\\\div',\n '\\\\perpendicular': '\\\\perp',\n};\n\n// Whole command names only: `\\\\divideontimes` is a real AMS symbol.\nconst MATHQUILL_ALIAS_REGEX = /\\\\(divide|perpendicular)(?![a-zA-Z])/g;\n\n/**\n * Primes. MathLive turns a prime that follows a base into a superscript atom and\n * serialises it as `^{\\\\prime}`, or `^{\\\\doubleprime}` for the keypad's double\n * prime key (`5''` comes back out as `5^{\\\\doubleprime}`). MathJax has no\n * `\\\\doubleprime`, and two adjacent `^{\\\\prime}` groups - what typing `'` twice\n * produces - are a \"double exponent\" error. MathQuill stored plain apostrophes,\n * which both MathJax and MathLive read as primes, so store those.\n *\n * Only a superscript made of primes alone is rewritten: `x^{\\\\prime 2}` keeps\n * its group, since it holds more than primes.\n */\nconst PRIME_SUPERSCRIPT_REGEX = /\\^\\{((?:\\s*\\\\(?:prime|doubleprime)(?![a-zA-Z]))+)\\s*\\}/g;\nconst BARE_DOUBLEPRIME_REGEX = /\\\\doubleprime(?![a-zA-Z])/g;\n\nconst primesToApostrophes = (primes) =>\n // eslint-disable-next-line quotes\n \"'\".repeat(\n (primes.match(/\\\\prime(?![a-zA-Z])/g) || []).length + 2 * (primes.match(BARE_DOUBLEPRIME_REGEX) || []).length,\n );\n\nconst BARE_PRIME_COMMAND_REGEX = /^\\\\(doubleprime|prime)(?![a-zA-Z])/;\n\n/**\n * Primes that are *not* in a superscript.\n *\n * MathLive emits bare `\\prime` / `\\doubleprime` for a `′` or `″` typed or pasted\n * as a character (`5′6″` serialises as `5\\prime6\\doubleprime`). A bare `\\prime`\n * is a full-size glyph in MathJax, while `''` is a superscript, so storing\n * `5\\prime6''` drew the single prime visibly larger than each stroke of the\n * double prime. Both become apostrophes, the superscript primes MathQuill\n * stored, so they always match.\n *\n * Inside a script (`x^{\\prime 2}`, `x^\\prime`) a prime is already a\n * superscript, and an apostrophe there would mean something else, so\n * `\\prime` is kept and `\\doubleprime` (unknown to MathJax) becomes\n * `\\prime\\prime`.\n *\n * @param {string} latex\n * @returns {string}\n */\nconst barePrimesToApostrophes = (latex) => {\n if (latex.indexOf('prime') === -1) {\n return latex;\n }\n\n // One entry per open brace: is that group a super/subscript?\n const groups = [];\n let out = '';\n let i = 0;\n\n while (i < latex.length) {\n const ch = latex[i];\n\n if (ch === '\\\\') {\n const match = latex.slice(i).match(BARE_PRIME_COMMAND_REGEX);\n\n if (match) {\n const isDouble = match[1] === 'doubleprime';\n // `x^\\prime`: the command is itself the script.\n const isScriptArgument = /[\\^_]\\s*$/.test(out);\n const inScript = isScriptArgument || groups.indexOf(true) !== -1;\n\n if (inScript) {\n out += isDouble ? '\\\\prime\\\\prime' : '\\\\prime';\n } else {\n // eslint-disable-next-line quotes\n out += isDouble ? \"''\" : \"'\";\n }\n\n i += match[0].length;\n continue;\n }\n\n // Copy any other command, or an escaped character such as `\\{`, whole.\n const command = latex.slice(i).match(/^\\\\(?:[a-zA-Z]+|.)/);\n const text = command ? command[0] : ch;\n\n out += text;\n i += text.length;\n continue;\n }\n\n if (ch === '{') {\n groups.push(/[\\^_]\\s*$/.test(out));\n } else if (ch === '}') {\n groups.pop();\n }\n\n out += ch;\n i += 1;\n }\n\n return out;\n};\n\n/**\n * Rewrite what MathLive serialises into the form MathQuill stored: alias\n * command names, and primes.\n *\n * @param {string} latex\n * @returns {string}\n */\nexport const toCanonicalCommands = (latex) =>\n typeof latex === 'string'\n ? barePrimesToApostrophes(\n latex\n .replace(MATHQUILL_ALIAS_REGEX, (m) => MATHQUILL_ALIASES[m])\n .replace(PRIME_SUPERSCRIPT_REGEX, (_m, primes) => primesToApostrophes(primes)),\n )\n : latex;\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 // Store the command MathQuill stored, not the alias - also heals latex that was\n // saved with `\\\\divide` before the keypad resolved it.\n return toCanonicalCommands(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 // An explicit \"blank over blank\" key: both slots start empty.\n '\\\\frac': '\\\\frac{#?}{#?}',\n // Division, which must behave like MathQuill's `/`: whatever precedes the\n // cursor becomes the numerator and the caret lands in the denominator. `#@`\n // is MathLive's token for \"the selection, or the item before the cursor\" -\n // this is exactly the template MathLive binds to the `/` key itself. Using\n // `#?` here instead produced an empty fraction and left the typed number\n // stranded outside it.\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] || MATHQUILL_ALIASES[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, MATHQUILL_ALIASES };\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,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C9D;IAAM,CAAC;EAC7C;EAEA,IAAI8D,GAAG,CAACI,KAAK,EAAE;IACb,OAAO;MAAEF,IAAI,EAAE,QAAQ;MAAEC,KAAK,EAAEH,GAAG,CAACI;IAAM,CAAC;EAC7C;EAEA,IAAIJ,GAAG,CAACnB,OAAO,EAAE;IACf;IACA;IACA;IACA;IACA,IAAMwB,KAAK,GAAGC,KAAK,CAACC,OAAO,CAACP,GAAG,CAACnB,OAAO,CAAC,GAAGmB,GAAG,CAACnB,OAAO,GAAG,CAACmB,GAAG,CAACnB,OAAO,CAAC;IACtE,IAAMsB,KAAK,GAAGE,KAAK,CAACjB,GAAG,CAAC,UAACoB,CAAC;MAAA,OAAKlB,kBAAkB,CAACkB,CAAC,CAAC,IAAIzC,iBAAiB,CAACyC,CAAC,CAAC,IAAIA,CAAC;IAAA,EAAC,CAAC1C,IAAI,CAAC,EAAE,CAAC;IAE3F,OAAO;MAAEoC,IAAI,EAAE,QAAQ;MAAEC,KAAK,EAALA;IAAM,CAAC;EAClC;EAEA,IAAIH,GAAG,CAACS,SAAS,EAAE;IACjB,IAAMC,QAAQ,GAAGlB,UAAU,CAACQ,GAAG,CAACS,SAAS,CAAC;IAE1C,OAAOC,QAAQ,GAAG;MAAER,IAAI,EAAE,SAAS;MAAEC,KAAK,EAAEO;IAAS,CAAC,GAAGT,SAAS;EACpE;EAEA,OAAOA,SAAS;AAClB,CAAC","ignoreList":[]}
package/lib/mf/input.js CHANGED
@@ -19,7 +19,6 @@ var _styles = require("@mui/material/styles");
19
19
  var _debug = _interopRequireDefault(require("debug"));
20
20
  var _mathliveInstance = require("../mathlive-instance");
21
21
  var _latexBridge = require("../latex-bridge");
22
- var _selection = require("../selection");
23
22
  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
23
  function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
25
24
  var log = (0, _debug["default"])('pie-lib:math-input-mathlive:input');
@@ -127,9 +126,6 @@ var Input = exports.Input = /*#__PURE__*/function (_React$Component) {
127
126
 
128
127
  // A selected `\placeholder{}` gets no MathLive caret; draw one.
129
128
  this.untrackCaret = (0, _mathliveInstance.trackPlaceholderCaret)(this.mathField);
130
-
131
- // Shift+Arrow would otherwise select half a fraction; snap to whole atoms.
132
- this.untrackSelection = (0, _selection.trackWholeAtomSelection)(this.mathField);
133
129
  this.mathField.addEventListener('input', this.onInputEdit);
134
130
 
135
131
  // Belt and braces: drop anything a previous mount may have left behind.
@@ -181,10 +177,6 @@ var Input = exports.Input = /*#__PURE__*/function (_React$Component) {
181
177
  this.untrackCaret();
182
178
  this.untrackCaret = undefined;
183
179
  }
184
- if (this.untrackSelection) {
185
- this.untrackSelection();
186
- this.untrackSelection = undefined;
187
- }
188
180
  if (this.mathField) {
189
181
  this.mathField.removeEventListener('input', this.onInputEdit);
190
182
  this.mathField.remove();
@@ -1 +1 @@
1
- {"version":3,"file":"input.js","names":["_react","_interopRequireDefault","require","_propTypes","_styles","_debug","_mathliveInstance","_latexBridge","_selection","_callSuper","t","o","e","_getPrototypeOf2","_possibleConstructorReturn2","_isNativeReflectConstruct","Reflect","construct","constructor","apply","Boolean","prototype","valueOf","call","log","debug","Holder","styled","display","width","Input","exports","_React$Component","props","_this","_classCallCheck2","_defineProperty2","onChange","mathField","latex","fromMathLive","getValue","lastEmitted","event","key","preventDefault","holderRef","React","createRef","undefined","_inherits2","_createClass2","value","_componentDidMount","_asyncToGenerator2","_regenerator","mark","_callee","generation","ml","wrap","_context","prev","next","mountGeneration","loadMathLive","sent","current","abrupt","MathfieldElement","macros","getMacros","toMathLive","readOnly","mathVirtualKeyboardPolicy","mathModeSpace","MATH_MODE_SPACE","smartSuperscript","applyShadowStyles","untrackCaret","trackPlaceholderCaret","untrackSelection","trackWholeAtomSelection","addEventListener","onInputEdit","replaceChildren","innerRef","stop","componentDidMount","arguments","componentDidUpdate","prevProps","_this$props","componentWillUnmount","removeEventListener","remove","get","_this2","v","setLatex","el","focus","blur","clear","command","action","keyToAction","insert","keystroke","selector","KEYSTROKES","executeCommand","message","write","_this3","values","Array","isArray","forEach","vv","render","_this$props2","className","onFocus","onBlur","onClick","createElement","onKeyDown","ref","Component","PropTypes","string","func","bool","_default"],"sources":["../../src/mf/input.jsx"],"sourcesContent":["import React from 'react';\nimport PropTypes from 'prop-types';\nimport { styled } from '@mui/material/styles';\nimport debug from 'debug';\nimport {\n loadMathLive,\n getMacros,\n MATH_MODE_SPACE,\n applyShadowStyles,\n trackPlaceholderCaret,\n} from '../mathlive-instance';\nimport { toMathLive, fromMathLive, keyToAction, KEYSTROKES } from '../latex-bridge';\nimport { trackWholeAtomSelection } from '../selection';\n\nconst log = debug('pie-lib:math-input-mathlive:input');\n\nconst Holder = styled('span')({\n display: 'inline-block',\n '& math-field': {\n display: 'block',\n width: '100%',\n },\n // MathLive ships its own virtual keyboard toggle; pie supplies its own keypad.\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 * Editable math field. Drop-in replacement for @pie-lib/math-input's `mq.Input`.\n *\n * Keeps the same imperative surface used by MathInput's keypad\n * (`write`, `command`, `keystroke`, `clear`, `focus`, `blur`) so callers do not\n * change, and the same `latex` / `onChange` props.\n */\nexport class Input extends React.Component {\n static propTypes = {\n className: PropTypes.string,\n latex: PropTypes.string,\n onChange: PropTypes.func,\n onClick: PropTypes.func,\n onFocus: PropTypes.func,\n onBlur: PropTypes.func,\n readOnly: PropTypes.bool,\n innerRef: PropTypes.func,\n };\n\n constructor(props) {\n super(props);\n this.holderRef = React.createRef();\n // Tracks the last latex we emitted, so prop echoes don't reset the cursor.\n this.lastEmitted = undefined;\n }\n\n async componentDidMount() {\n // MathLive loads asynchronously, so this method resumes after an await and\n // has to know whether it is still the current mount. React StrictMode calls\n // mount -> unmount -> mount on the SAME instance in dev, so a boolean\n // \"unmounted\" flag would latch and block the remount from ever creating a\n // field. A generation counter identifies the live mount instead: only the\n // newest one proceeds, and a real unmount invalidates all pending ones.\n const generation = (this.mountGeneration = (this.mountGeneration || 0) + 1);\n const ml = await loadMathLive();\n\n if (generation !== this.mountGeneration || !ml || !this.holderRef.current || this.mathField) {\n return;\n }\n\n this.mathField = new ml.MathfieldElement({ macros: getMacros() });\n this.mathField.value = toMathLive(this.props.latex || '');\n\n if (this.props.readOnly) {\n this.mathField.readOnly = true;\n }\n\n // pie drives input through its own keypad, so suppress MathLive's.\n this.mathField.mathVirtualKeyboardPolicy = 'manual';\n // Without this the spacebar does nothing: MathLive's mathModeSpace\n // defaults to an empty string.\n this.mathField.mathModeSpace = MATH_MODE_SPACE;\n // After the exponent key the cursor must stay in the exponent until it is moved\n // MathLive's `smartSuperscript` (on by\n // default) jumps out of an empty superscript after a single digit, which breaks\n // typing x^23 or 10^6 and is inconsistent with non-digit exponents.\n this.mathField.smartSuperscript = false;\n\n // The mathfield renders in shadow DOM, so page CSS cannot reach it - the\n // stretchy-accent fix has to be injected there directly.\n applyShadowStyles(this.mathField);\n\n // A selected `\\placeholder{}` gets no MathLive caret; draw one.\n this.untrackCaret = trackPlaceholderCaret(this.mathField);\n\n // Shift+Arrow would otherwise select half a fraction; snap to whole atoms.\n this.untrackSelection = trackWholeAtomSelection(this.mathField);\n\n this.mathField.addEventListener('input', this.onInputEdit);\n\n // Belt and braces: drop anything a previous mount may have left behind.\n this.holderRef.current.replaceChildren(this.mathField);\n\n if (this.props.innerRef) {\n this.props.innerRef(this);\n }\n }\n\n componentDidUpdate(prevProps) {\n if (!this.mathField) {\n return;\n }\n\n const { latex, readOnly } = this.props;\n\n if (readOnly !== prevProps.readOnly) {\n this.mathField.readOnly = !!readOnly;\n }\n\n // Only push the prop back into the field when it genuinely differs from\n // what the field already holds. This is the analogue of the old\n // shouldComponentUpdate latex-equality guard and prevents cursor thrash.\n if (latex !== undefined && latex !== null && latex !== this.lastEmitted) {\n const next = toMathLive(latex);\n\n if (next !== this.mathField.value) {\n this.mathField.value = next;\n }\n }\n }\n\n componentWillUnmount() {\n // Invalidate any mount still awaiting the MathLive load, so it does not\n // append a field into a holder that is going away.\n this.mountGeneration = (this.mountGeneration || 0) + 1;\n\n if (this.untrackCaret) {\n this.untrackCaret();\n this.untrackCaret = undefined;\n }\n\n if (this.untrackSelection) {\n this.untrackSelection();\n this.untrackSelection = undefined;\n }\n\n if (this.mathField) {\n this.mathField.removeEventListener('input', this.onInputEdit);\n this.mathField.remove();\n this.mathField = undefined;\n }\n\n if (this.props.innerRef) {\n this.props.innerRef(null);\n }\n }\n\n onInputEdit = () => {\n const { onChange } = this.props;\n\n if (!this.mathField) {\n return;\n }\n\n const latex = fromMathLive(this.mathField.getValue('latex'));\n\n this.lastEmitted = latex;\n\n if (onChange) {\n onChange(latex);\n }\n };\n\n /** Current latex, in stored (MathQuill-compatible) form. */\n latex() {\n return this.mathField ? fromMathLive(this.mathField.getValue('latex')) : '';\n }\n\n /**\n * The underlying `<math-field>` element, or undefined until MathLive has\n * finished loading. Exposed for callers that need the real element.\n *\n * NOTE: this is NOT a MathQuill field. Code written against\n * `@pie-lib/math-input` often did `input.mathField.latex()`; that shape is\n * provided by `mqCompat` below, and `latex()` on this component is the\n * supported replacement.\n */\n get element() {\n return this.mathField;\n }\n\n /**\n * MathQuill-shaped facade, so existing `input.mathField.latex()` /\n * `.el()` call sites keep working instead of throwing. Only the members that\n * consumers actually used are provided; MathQuill internals such as\n * `__controller` have no MathLive equivalent and are deliberately absent.\n */\n get mqCompat() {\n return {\n latex: (v) => (v === undefined ? this.latex() : (this.setLatex(v), v)),\n el: () => this.mathField,\n focus: () => this.focus(),\n blur: () => this.blur(),\n };\n }\n\n /** Programmatically replace the content. */\n setLatex(v) {\n if (this.mathField) {\n this.mathField.value = toMathLive(v || '');\n }\n }\n\n clear() {\n if (this.mathField) {\n this.mathField.value = '';\n }\n\n return '';\n }\n\n blur() {\n log('blur mathfield');\n this.mathField && this.mathField.blur();\n }\n\n focus() {\n log('focus mathfield...');\n this.mathField && this.mathField.focus();\n }\n\n /**\n * MathQuill `cmd()` equivalent.\n *\n * Callers pass MathQuill command names (`'\\\\frac'`, `'\\\\sqrt'`, `'^'`, or an\n * array of them). Those must be expanded into latex with `#?` placeholders,\n * otherwise inserting a bare `\\frac` produces no editable slots.\n */\n command(v) {\n log('command: ', v);\n\n if (!this.mathField) {\n return '';\n }\n\n const action = keyToAction({ command: v });\n\n if (action) {\n this.mathField.insert(action.value, { focus: true });\n }\n\n this.mathField.focus();\n\n return this.latex();\n }\n\n /**\n * MathQuill `keystroke()` equivalent.\n *\n * Accepts MathQuill keystroke names (`'Left'`, `'Right'`, `'Backspace'`) as\n * the keypad emits them, and passes anything else through as a MathLive\n * selector.\n */\n keystroke(v) {\n log('keystroke: ', v);\n\n if (!this.mathField) {\n return '';\n }\n\n const selector = KEYSTROKES[v] || v;\n\n try {\n this.mathField.executeCommand(selector);\n } catch (e) {\n log('unknown keystroke/selector \"%s\": %s', v, e && e.message);\n }\n\n this.mathField.focus();\n\n return this.latex();\n }\n\n /** MathQuill `write()` equivalent. Accepts an array, as `cmd()` did. */\n write(v) {\n log('write: ', v);\n\n if (!this.mathField) {\n return '';\n }\n\n const values = Array.isArray(v) ? v : [v];\n\n values.forEach((vv) => this.mathField.insert(vv, { focus: true }));\n this.mathField.focus();\n\n return this.latex();\n }\n\n /**\n * Enter must not insert a line break: math input is single-expression, and\n * the MathQuill version swallowed charCode 13 for the same reason. Newlines\n * are authored explicitly through the newLine embed, not the Enter key.\n */\n onKeyDown = (event) => {\n if (event.key === 'Enter') {\n event.preventDefault();\n }\n };\n\n render() {\n const { className, onFocus, onBlur, onClick } = this.props;\n\n return (\n <Holder\n className={className}\n onFocus={onFocus}\n onBlur={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I;EACvBT,OAAO,EAAEO,qBAAS,CAACE,IAAI;EACvBR,MAAM,EAAEM,qBAAS,CAACE,IAAI;EACtB3D,QAAQ,EAAEyD,qBAAS,CAACG,IAAI;EACxB/C,QAAQ,EAAE4C,qBAAS,CAACE;AACtB,CAAC;AAAA,IAAAE,QAAA,GAAAvG,OAAA,cAuRYD,KAAK","ignoreList":[]}
1
+ {"version":3,"file":"input.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","width","Input","exports","_React$Component","props","_this","_classCallCheck2","_defineProperty2","onChange","mathField","latex","fromMathLive","getValue","lastEmitted","event","key","preventDefault","holderRef","React","createRef","undefined","_inherits2","_createClass2","value","_componentDidMount","_asyncToGenerator2","_regenerator","mark","_callee","generation","ml","wrap","_context","prev","next","mountGeneration","loadMathLive","sent","current","abrupt","MathfieldElement","macros","getMacros","toMathLive","readOnly","mathVirtualKeyboardPolicy","mathModeSpace","MATH_MODE_SPACE","smartSuperscript","applyShadowStyles","untrackCaret","trackPlaceholderCaret","addEventListener","onInputEdit","replaceChildren","innerRef","stop","componentDidMount","arguments","componentDidUpdate","prevProps","_this$props","componentWillUnmount","removeEventListener","remove","get","_this2","v","setLatex","el","focus","blur","clear","command","action","keyToAction","insert","keystroke","selector","KEYSTROKES","executeCommand","message","write","_this3","values","Array","isArray","forEach","vv","render","_this$props2","className","onFocus","onBlur","onClick","createElement","onKeyDown","ref","Component","PropTypes","string","func","bool","_default"],"sources":["../../src/mf/input.jsx"],"sourcesContent":["import React from 'react';\nimport PropTypes from 'prop-types';\nimport { styled } from '@mui/material/styles';\nimport debug from 'debug';\nimport {\n loadMathLive,\n getMacros,\n MATH_MODE_SPACE,\n applyShadowStyles,\n trackPlaceholderCaret,\n} from '../mathlive-instance';\nimport { toMathLive, fromMathLive, keyToAction, KEYSTROKES } from '../latex-bridge';\n\nconst log = debug('pie-lib:math-input-mathlive:input');\n\nconst Holder = styled('span')({\n display: 'inline-block',\n '& math-field': {\n display: 'block',\n width: '100%',\n },\n // MathLive ships its own virtual keyboard toggle; pie supplies its own keypad.\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 * Editable math field. Drop-in replacement for @pie-lib/math-input's `mq.Input`.\n *\n * Keeps the same imperative surface used by MathInput's keypad\n * (`write`, `command`, `keystroke`, `clear`, `focus`, `blur`) so callers do not\n * change, and the same `latex` / `onChange` props.\n */\nexport class Input extends React.Component {\n static propTypes = {\n className: PropTypes.string,\n latex: PropTypes.string,\n onChange: PropTypes.func,\n onClick: PropTypes.func,\n onFocus: PropTypes.func,\n onBlur: PropTypes.func,\n readOnly: PropTypes.bool,\n innerRef: PropTypes.func,\n };\n\n constructor(props) {\n super(props);\n this.holderRef = React.createRef();\n // Tracks the last latex we emitted, so prop echoes don't reset the cursor.\n this.lastEmitted = undefined;\n }\n\n async componentDidMount() {\n // MathLive loads asynchronously, so this method resumes after an await and\n // has to know whether it is still the current mount. React StrictMode calls\n // mount -> unmount -> mount on the SAME instance in dev, so a boolean\n // \"unmounted\" flag would latch and block the remount from ever creating a\n // field. A generation counter identifies the live mount instead: only the\n // newest one proceeds, and a real unmount invalidates all pending ones.\n const generation = (this.mountGeneration = (this.mountGeneration || 0) + 1);\n const ml = await loadMathLive();\n\n if (generation !== this.mountGeneration || !ml || !this.holderRef.current || this.mathField) {\n return;\n }\n\n this.mathField = new ml.MathfieldElement({ macros: getMacros() });\n this.mathField.value = toMathLive(this.props.latex || '');\n\n if (this.props.readOnly) {\n this.mathField.readOnly = true;\n }\n\n // pie drives input through its own keypad, so suppress MathLive's.\n this.mathField.mathVirtualKeyboardPolicy = 'manual';\n // Without this the spacebar does nothing: MathLive's mathModeSpace\n // defaults to an empty string.\n this.mathField.mathModeSpace = MATH_MODE_SPACE;\n // After the exponent key the cursor must stay in the exponent until it is moved\n // MathLive's `smartSuperscript` (on by\n // default) jumps out of an empty superscript after a single digit, which breaks\n // typing x^23 or 10^6 and is inconsistent with non-digit exponents.\n this.mathField.smartSuperscript = false;\n\n // The mathfield renders in shadow DOM, so page CSS cannot reach it - the\n // stretchy-accent fix has to be injected there directly.\n applyShadowStyles(this.mathField);\n\n // A selected `\\placeholder{}` gets no MathLive caret; draw one.\n this.untrackCaret = trackPlaceholderCaret(this.mathField);\n\n this.mathField.addEventListener('input', this.onInputEdit);\n\n // Belt and braces: drop anything a previous mount may have left behind.\n this.holderRef.current.replaceChildren(this.mathField);\n\n if (this.props.innerRef) {\n this.props.innerRef(this);\n }\n }\n\n componentDidUpdate(prevProps) {\n if (!this.mathField) {\n return;\n }\n\n const { latex, readOnly } = this.props;\n\n if (readOnly !== prevProps.readOnly) {\n this.mathField.readOnly = !!readOnly;\n }\n\n // Only push the prop back into the field when it genuinely differs from\n // what the field already holds. This is the analogue of the old\n // shouldComponentUpdate latex-equality guard and prevents cursor thrash.\n if (latex !== undefined && latex !== null && latex !== this.lastEmitted) {\n const next = toMathLive(latex);\n\n if (next !== this.mathField.value) {\n this.mathField.value = next;\n }\n }\n }\n\n componentWillUnmount() {\n // Invalidate any mount still awaiting the MathLive load, so it does not\n // append a field into a holder that is going away.\n this.mountGeneration = (this.mountGeneration || 0) + 1;\n\n if (this.untrackCaret) {\n this.untrackCaret();\n this.untrackCaret = undefined;\n }\n\n if (this.mathField) {\n this.mathField.removeEventListener('input', this.onInputEdit);\n this.mathField.remove();\n this.mathField = undefined;\n }\n\n if (this.props.innerRef) {\n this.props.innerRef(null);\n }\n }\n\n onInputEdit = () => {\n const { onChange } = this.props;\n\n if (!this.mathField) {\n return;\n }\n\n const latex = fromMathLive(this.mathField.getValue('latex'));\n\n this.lastEmitted = latex;\n\n if (onChange) {\n onChange(latex);\n }\n };\n\n /** Current latex, in stored (MathQuill-compatible) form. */\n latex() {\n return this.mathField ? fromMathLive(this.mathField.getValue('latex')) : '';\n }\n\n /**\n * The underlying `<math-field>` element, or undefined until MathLive has\n * finished loading. Exposed for callers that need the real element.\n *\n * NOTE: this is NOT a MathQuill field. Code written against\n * `@pie-lib/math-input` often did `input.mathField.latex()`; that shape is\n * provided by `mqCompat` below, and `latex()` on this component is the\n * supported replacement.\n */\n get element() {\n return this.mathField;\n }\n\n /**\n * MathQuill-shaped facade, so existing `input.mathField.latex()` /\n * `.el()` call sites keep working instead of throwing. Only the members that\n * consumers actually used are provided; MathQuill internals such as\n * `__controller` have no MathLive equivalent and are deliberately absent.\n */\n get mqCompat() {\n return {\n latex: (v) => (v === undefined ? this.latex() : (this.setLatex(v), v)),\n el: () => this.mathField,\n focus: () => this.focus(),\n blur: () => this.blur(),\n };\n }\n\n /** Programmatically replace the content. */\n setLatex(v) {\n if (this.mathField) {\n this.mathField.value = toMathLive(v || '');\n }\n }\n\n clear() {\n if (this.mathField) {\n this.mathField.value = '';\n }\n\n return '';\n }\n\n blur() {\n log('blur mathfield');\n this.mathField && this.mathField.blur();\n }\n\n focus() {\n log('focus mathfield...');\n this.mathField && this.mathField.focus();\n }\n\n /**\n * MathQuill `cmd()` equivalent.\n *\n * Callers pass MathQuill command names (`'\\\\frac'`, `'\\\\sqrt'`, `'^'`, or an\n * array of them). Those must be expanded into latex with `#?` placeholders,\n * otherwise inserting a bare `\\frac` produces no editable slots.\n */\n command(v) {\n log('command: ', v);\n\n if (!this.mathField) {\n return '';\n }\n\n const action = keyToAction({ command: v });\n\n if (action) {\n this.mathField.insert(action.value, { focus: true });\n }\n\n this.mathField.focus();\n\n return this.latex();\n }\n\n /**\n * MathQuill `keystroke()` equivalent.\n *\n * Accepts MathQuill keystroke names (`'Left'`, `'Right'`, `'Backspace'`) as\n * the keypad emits them, and passes anything else through as a MathLive\n * selector.\n */\n keystroke(v) {\n log('keystroke: ', v);\n\n if (!this.mathField) {\n return '';\n }\n\n const selector = KEYSTROKES[v] || v;\n\n try {\n this.mathField.executeCommand(selector);\n } catch (e) {\n log('unknown keystroke/selector \"%s\": %s', v, e && e.message);\n }\n\n this.mathField.focus();\n\n return this.latex();\n }\n\n /** MathQuill `write()` equivalent. Accepts an array, as `cmd()` did. */\n write(v) {\n log('write: ', v);\n\n if (!this.mathField) {\n return '';\n }\n\n const values = Array.isArray(v) ? v : [v];\n\n values.forEach((vv) => this.mathField.insert(vv, { focus: true }));\n this.mathField.focus();\n\n return this.latex();\n }\n\n /**\n * Enter must not insert a line break: math input is single-expression, and\n * the MathQuill version swallowed charCode 13 for the same reason. Newlines\n * are authored explicitly through the newLine embed, not the Enter key.\n */\n onKeyDown = (event) => {\n if (event.key === 'Enter') {\n event.preventDefault();\n }\n };\n\n render() {\n const { className, onFocus, onBlur, onClick } = this.props;\n\n return (\n <Holder\n className={className}\n onFocus={onFocus}\n onBlur={onBlur}\n onClick={onClick}\n onKeyDown={this.onKeyDown}\n ref={this.holderRef}\n />\n );\n }\n}\n\nexport default Input;\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;AAOA,IAAAK,YAAA,GAAAL,OAAA;AAAoF,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,CAAA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,EAAE,IAAI,CAAChF;MAAU,CACrB,CAAC;IAEN;EAAC;AAAA,EAtRwBC,iBAAK,CAACgF,SAAS;AAAA,IAAA3F,gBAAA,aAA7BN,KAAK,eACG;EACjB0F,SAAS,EAAEQ,qBAAS,CAACC,MAAM;EAC3B1F,KAAK,EAAEyF,qBAAS,CAACC,MAAM;EACvB5F,QAAQ,EAAE2F,qBAAS,CAACE,IAAI;EACxBP,OAAO,EAAEK,qBAAS,CAACE,IAAI;EACvBT,OAAO,EAAEO,qBAAS,CAACE,IAAI;EACvBR,MAAM,EAAEM,qBAAS,CAACE,IAAI;EACtBzD,QAAQ,EAAEuD,qBAAS,CAACG,IAAI;EACxB/C,QAAQ,EAAE4C,qBAAS,CAACE;AACtB,CAAC;AAAA,IAAAE,QAAA,GAAArG,OAAA,cA+QYD,KAAK","ignoreList":[]}
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "1.1.5-beta.8",
6
+ "version": "1.1.5-beta.9",
7
7
  "description": "MathLive-based math input (drop-in alternative to @pie-lib/math-input)",
8
8
  "main": "lib/index.js",
9
9
  "module": "src/index.jsx",
@@ -252,6 +252,36 @@ describe('latex-bridge', () => {
252
252
  expect(fromMathLive("12^{\\circ}30'15''")).toEqual("12^{\\circ}30'15''");
253
253
  });
254
254
 
255
+ // `5′6″` typed or pasted as characters serialises as bare commands. A bare
256
+ // `\prime` is full size in MathJax while `''` is a superscript, so storing
257
+ // `5\prime6''` drew the single prime larger than each stroke of the double.
258
+ it('stores bare primes as apostrophes, so single and double match', () => {
259
+ expect(fromMathLive('5\\prime6\\doubleprime')).toEqual("5'6''");
260
+ expect(fromMathLive('5\\prime 6\\doubleprime')).toEqual("5' 6''");
261
+ expect(fromMathLive('\\prime')).toEqual("'");
262
+ expect(fromMathLive('\\frac{5\\prime}{2}')).toEqual("\\frac{5'}{2}");
263
+ });
264
+
265
+ // Inside a script a prime is already a superscript; an apostrophe there
266
+ // would be a prime *of* the script.
267
+ it('keeps primes that are inside a superscript or subscript', () => {
268
+ expect(fromMathLive('x^{\\prime 2}')).toEqual('x^{\\prime 2}');
269
+ expect(fromMathLive('x^\\prime')).toEqual('x^\\prime');
270
+ expect(fromMathLive('x_{\\prime}')).toEqual('x_{\\prime}');
271
+ // MathJax has no \doubleprime: spell it out rather than leave red text
272
+ expect(fromMathLive('x^{\\doubleprime 2}')).toEqual('x^{\\prime\\prime 2}');
273
+ });
274
+
275
+ it('closes the script scope at the matching brace', () => {
276
+ expect(fromMathLive('x^{2}\\prime')).toEqual("x^{2}'");
277
+ expect(fromMathLive('x^{\\frac{a}{b}}6\\doubleprime')).toEqual("x^{\\frac{a}{b}}6''");
278
+ });
279
+
280
+ it('does not touch commands that merely start with "prime"', () => {
281
+ expect(fromMathLive('\\primes')).toEqual('\\primes');
282
+ expect(fromMathLive('\\backprime')).toEqual('\\backprime');
283
+ });
284
+
255
285
  it('no keypad key inserts an alias name', () => {
256
286
  /* eslint-disable global-require */
257
287
  const fs = require('fs');
@@ -303,6 +303,81 @@ const primesToApostrophes = (primes) =>
303
303
  (primes.match(/\\prime(?![a-zA-Z])/g) || []).length + 2 * (primes.match(BARE_DOUBLEPRIME_REGEX) || []).length,
304
304
  );
305
305
 
306
+ const BARE_PRIME_COMMAND_REGEX = /^\\(doubleprime|prime)(?![a-zA-Z])/;
307
+
308
+ /**
309
+ * Primes that are *not* in a superscript.
310
+ *
311
+ * MathLive emits bare `\prime` / `\doubleprime` for a `′` or `″` typed or pasted
312
+ * as a character (`5′6″` serialises as `5\prime6\doubleprime`). A bare `\prime`
313
+ * is a full-size glyph in MathJax, while `''` is a superscript, so storing
314
+ * `5\prime6''` drew the single prime visibly larger than each stroke of the
315
+ * double prime. Both become apostrophes, the superscript primes MathQuill
316
+ * stored, so they always match.
317
+ *
318
+ * Inside a script (`x^{\prime 2}`, `x^\prime`) a prime is already a
319
+ * superscript, and an apostrophe there would mean something else, so
320
+ * `\prime` is kept and `\doubleprime` (unknown to MathJax) becomes
321
+ * `\prime\prime`.
322
+ *
323
+ * @param {string} latex
324
+ * @returns {string}
325
+ */
326
+ const barePrimesToApostrophes = (latex) => {
327
+ if (latex.indexOf('prime') === -1) {
328
+ return latex;
329
+ }
330
+
331
+ // One entry per open brace: is that group a super/subscript?
332
+ const groups = [];
333
+ let out = '';
334
+ let i = 0;
335
+
336
+ while (i < latex.length) {
337
+ const ch = latex[i];
338
+
339
+ if (ch === '\\') {
340
+ const match = latex.slice(i).match(BARE_PRIME_COMMAND_REGEX);
341
+
342
+ if (match) {
343
+ const isDouble = match[1] === 'doubleprime';
344
+ // `x^\prime`: the command is itself the script.
345
+ const isScriptArgument = /[\^_]\s*$/.test(out);
346
+ const inScript = isScriptArgument || groups.indexOf(true) !== -1;
347
+
348
+ if (inScript) {
349
+ out += isDouble ? '\\prime\\prime' : '\\prime';
350
+ } else {
351
+ // eslint-disable-next-line quotes
352
+ out += isDouble ? "''" : "'";
353
+ }
354
+
355
+ i += match[0].length;
356
+ continue;
357
+ }
358
+
359
+ // Copy any other command, or an escaped character such as `\{`, whole.
360
+ const command = latex.slice(i).match(/^\\(?:[a-zA-Z]+|.)/);
361
+ const text = command ? command[0] : ch;
362
+
363
+ out += text;
364
+ i += text.length;
365
+ continue;
366
+ }
367
+
368
+ if (ch === '{') {
369
+ groups.push(/[\^_]\s*$/.test(out));
370
+ } else if (ch === '}') {
371
+ groups.pop();
372
+ }
373
+
374
+ out += ch;
375
+ i += 1;
376
+ }
377
+
378
+ return out;
379
+ };
380
+
306
381
  /**
307
382
  * Rewrite what MathLive serialises into the form MathQuill stored: alias
308
383
  * command names, and primes.
@@ -312,11 +387,11 @@ const primesToApostrophes = (primes) =>
312
387
  */
313
388
  export const toCanonicalCommands = (latex) =>
314
389
  typeof latex === 'string'
315
- ? latex
316
- .replace(MATHQUILL_ALIAS_REGEX, (m) => MATHQUILL_ALIASES[m])
317
- .replace(PRIME_SUPERSCRIPT_REGEX, (_m, primes) => primesToApostrophes(primes))
318
- // eslint-disable-next-line quotes
319
- .replace(BARE_DOUBLEPRIME_REGEX, "''")
390
+ ? barePrimesToApostrophes(
391
+ latex
392
+ .replace(MATHQUILL_ALIAS_REGEX, (m) => MATHQUILL_ALIASES[m])
393
+ .replace(PRIME_SUPERSCRIPT_REGEX, (_m, primes) => primesToApostrophes(primes)),
394
+ )
320
395
  : latex;
321
396
 
322
397
  /**
package/src/mf/input.jsx CHANGED
@@ -10,7 +10,6 @@ import {
10
10
  trackPlaceholderCaret,
11
11
  } from '../mathlive-instance';
12
12
  import { toMathLive, fromMathLive, keyToAction, KEYSTROKES } from '../latex-bridge';
13
- import { trackWholeAtomSelection } from '../selection';
14
13
 
15
14
  const log = debug('pie-lib:math-input-mathlive:input');
16
15
 
@@ -94,9 +93,6 @@ export class Input extends React.Component {
94
93
  // A selected `\placeholder{}` gets no MathLive caret; draw one.
95
94
  this.untrackCaret = trackPlaceholderCaret(this.mathField);
96
95
 
97
- // Shift+Arrow would otherwise select half a fraction; snap to whole atoms.
98
- this.untrackSelection = trackWholeAtomSelection(this.mathField);
99
-
100
96
  this.mathField.addEventListener('input', this.onInputEdit);
101
97
 
102
98
  // Belt and braces: drop anything a previous mount may have left behind.
@@ -140,11 +136,6 @@ export class Input extends React.Component {
140
136
  this.untrackCaret = undefined;
141
137
  }
142
138
 
143
- if (this.untrackSelection) {
144
- this.untrackSelection();
145
- this.untrackSelection = undefined;
146
- }
147
-
148
139
  if (this.mathField) {
149
140
  this.mathField.removeEventListener('input', this.onInputEdit);
150
141
  this.mathField.remove();