import {readFileSync} from 'fs' import beautify from 'js-beautify' import {join} from 'path' import {test, expect} from '../../fixtures/test' // Switching the RCE between the HTML and rich text views is setContent/getContent on // the tinymce instance; only linkedAnnotations.ts filters that path. Driving the // harness editor rather than a hand-built one keeps the whole shipped config in play, // plugins included, and gives the markup a real HTML5 foreign-content parser, which // MathML needs. // // The save-and-reopen and rendered-page workflows run the same cases through the // server in spec/selenium/rcs. const UNIT_TESTS = join(__dirname, '../../../src/__tests__') const checkerCases = JSON.parse( readFileSync(join(UNIT_TESTS, 'fixtures/mathmlCheckerCases.json'), 'utf8'), ).cases as Array<{id: string; desc: string; source: string; expectedOutput: string}> const sweep = JSON.parse( readFileSync(join(UNIT_TESTS, 'fixtures/mathmlGlobalAttributeSweep.json'), 'utf8'), ) as {attributes: Record; cases: Array<{element: string; source: string}>} const golden = JSON.parse( readFileSync(join(UNIT_TESTS, 'fixtures/mathmlDiffEngineGolden.json'), 'utf8'), ).pairs as Array<{name: string; expected: string; returned: string; findings: string[]}> // The engine is an ES module for its ruby-side twin's sake; stripping the export // makes it a plain script this page can call. const engineSource = readFileSync(join(UNIT_TESTS, 'mathmlStructuralDiff.js'), 'utf8').replace( /^export /gm, '', ) // Asserted rather than skipped so a fix is as loud as a regression: fixing one of // these reds its test and the entry has to go. // // the rest are the sanitizers' rules, and no sanitizer runs on this path const KNOWN_GAPS: Record = { t21: [ '#t21-sem children: expected [mrow], got [mrow,annotation,annotation-xml]', '#t21-annot-bad: retained, expected removal', '#t21-annot-xml-bad: retained, expected removal', ], t23: [ '#t23-sem children: expected [mrow], got [mrow,annotation,annotation-xml]', '#t23-annot-noenc: retained, expected removal', '#t23-annot-xml-noenc: retained, expected removal', ], t24: [ '#t24-sem children: expected [mrow,annotation], got [mrow,annotation,annotation]', '#t24-annot-noenc: retained, expected removal', ], } // Paste reaches the schema through the paste plugin, which linkedAnnotations.ts does // not see. const PASTE_KNOWN_GAPS: Record = { ...KNOWN_GAPS, t22: [ '#t22-sem children: expected [mrow], got [mrow,annotation]', '#t22-annot-href: retained, expected removal', ], } const SWEEP_KNOWN_GAPS: Record = { maction: ['displaystyle', 'mathsize', 'scriptlevel'], maligngroup: ['displaystyle', 'mathsize', 'scriptlevel'], malignmark: ['displaystyle', 'mathsize', 'scriptlevel'], menclose: ['displaystyle', 'mathsize', 'scriptlevel'], merror: ['displaystyle', 'mathsize', 'scriptlevel'], mfenced: ['displaystyle', 'mathsize', 'scriptlevel'], mfrac: ['mathsize'], mglyph: ['displaystyle', 'mathsize', 'scriptlevel'], mi: ['displaystyle', 'scriptlevel'], mlabeledtr: ['displaystyle', 'mathsize', 'scriptlevel'], mlongdiv: ['displaystyle', 'mathsize', 'scriptlevel'], mmultiscripts: ['mathsize'], mn: ['displaystyle', 'scriptlevel'], mo: ['displaystyle', 'scriptlevel'], mover: ['mathsize'], mpadded: ['displaystyle', 'mathsize', 'scriptlevel'], mphantom: ['displaystyle', 'mathsize', 'scriptlevel'], mprescripts: ['displaystyle', 'mathsize', 'scriptlevel'], mroot: ['mathsize'], mrow: ['mathsize'], ms: ['displaystyle', 'scriptlevel'], mscarries: ['displaystyle', 'mathsize', 'scriptlevel'], mscarry: ['displaystyle', 'mathsize', 'scriptlevel'], msgroup: ['displaystyle', 'mathsize', 'scriptlevel'], msline: ['displaystyle', 'mathsize', 'scriptlevel'], mspace: ['displaystyle', 'scriptlevel'], msqrt: ['mathsize'], msrow: ['displaystyle', 'mathsize', 'scriptlevel'], mstack: ['displaystyle', 'mathsize', 'scriptlevel'], msub: ['mathsize'], msubsup: ['mathsize'], msup: ['mathsize'], mtable: ['mathsize'], mtd: ['mathsize'], mtr: ['displaystyle', 'mathsize', 'scriptlevel'], munder: ['mathsize'], munderover: ['mathsize'], none: ['displaystyle', 'mathsize', 'scriptlevel'], semantics: ['displaystyle', 'mathbackground', 'mathcolor', 'mathsize', 'scriptlevel'], } // Fails with the message only once a gap is fully fixed; anything else gets the raw diff. const expectKnownGap = (gaps: Record, key: string, findings: string[]) => { const fixed = key in gaps && findings.length === 0 expect(fixed ? `${key} now matches its target; remove its known gap` : '').toBe('') expect(findings).toEqual(gaps[key] ?? []) } // Switching views is setContent then getContent on the tinymce instance. const pageHelpers = ` window.roundTrip = html => { window.tinymce.activeEditor.setContent(html) return window.tinymce.activeEditor.getContent() } window.missingGlobalAttributes = (html, element, attributes) => { const node = new DOMParser() .parseFromString(html, 'text/html') .querySelector('[id="sweep-' + element + '"]') if (!node) return ['(element removed)'] return Object.entries(attributes) .filter(([name, value]) => node.getAttribute(name) !== value) .map(([name]) => name) } ` test.describe('MathML through the RCE HTML/rich text view toggle', () => { test.beforeEach(async ({page, rcePage}) => { await page.goto('/scenarios/basic') await rcePage.waitForEditor() await page.addScriptTag({content: engineSource}) await page.addScriptTag({content: pageHelpers}) }) for (const testCase of checkerCases) { test(`${testCase.id}: ${testCase.desc}`, async ({page}) => { // @ts-expect-error -- helper injected by addScriptTag const rawView = await page.evaluate(source => window.roundTrip(source), testCase.source) const prettyView = beautify.html(rawView) const editedInPrettyView = await page.evaluate( // @ts-expect-error -- helper injected by addScriptTag html => window.roundTrip(html), prettyView, ) const findings = await page.evaluate( ([expected, views]) => Object.fromEntries( // @ts-expect-error -- engine injected by addScriptTag Object.entries(views).map(([view, html]) => [view, window.diffMathml(expected, html)]), ), [testCase.expectedOutput, {rawView, prettyView, editedInPrettyView}] as const, ) const gaps = KNOWN_GAPS[testCase.id] ?? [] const fixed = testCase.id in KNOWN_GAPS && Object.values(findings).every(viewFindings => !viewFindings.length) expect(fixed ? `${testCase.id} now matches its target; remove its known gap` : '').toBe('') expect(findings).toEqual({rawView: gaps, prettyView: gaps, editedInPrettyView: gaps}) }) test(`${testCase.id}: ${testCase.desc} (pasted into the rich text view)`, async ({page}) => { await page.evaluate(source => { // @ts-expect-error -- TinyMCE global const editor = window.tinymce.activeEditor editor.setContent('') editor.focus() const clipboardData = new DataTransfer() clipboardData.setData('text/html', source) editor .getBody() .dispatchEvent( new ClipboardEvent('paste', {clipboardData, bubbles: true, cancelable: true}), ) }, testCase.source) const pasted = await page.waitForFunction( // @ts-expect-error -- TinyMCE global () => window.tinymce.activeEditor.getContent() || false, ) const findings = await page.evaluate( // @ts-expect-error -- engine injected by addScriptTag ([expected, html]) => window.diffMathml(expected, html), [testCase.expectedOutput, (await pasted.jsonValue()) as string] as const, ) expectKnownGap(PASTE_KNOWN_GAPS, testCase.id, findings) }) } test('keeps every MathML global attribute on every element', async ({page}) => { const missing = await page.evaluate( ([cases, attributes]) => Object.fromEntries( cases .map(({element, source}) => [ element, // @ts-expect-error -- helpers injected by addScriptTag window.missingGlobalAttributes(window.roundTrip(source), element, attributes), ]) .filter(([, lost]) => lost.length), ), [sweep.cases, sweep.attributes] as const, ) const cleared = Object.keys(SWEEP_KNOWN_GAPS).filter(element => !(element in missing)) expect( cleared.length ? `${cleared.join(', ')} now keep every attribute; remove their known gaps` : '', ).toBe('') expect(missing).toEqual(SWEEP_KNOWN_GAPS) }) test('keeps linethickness only where MathML Core defines it', async ({page}) => { const markup = { mfrac: 'ab', mrow: 'a', msup: 'a2', mtd: 'a', } const kept = await page.evaluate( byElement => Object.fromEntries( Object.entries(byElement).map(([element, inner]) => { // @ts-expect-error -- helper injected by addScriptTag const html = window.roundTrip(`${inner}`) const node = new DOMParser().parseFromString(html, 'text/html').getElementById('e') return [element, node?.hasAttribute('linethickness') ?? false] }), ), markup, ) expect(kept).toEqual({mfrac: true, mrow: false, msup: false, mtd: false}) }) // Catches gap entries left behind when a fixture case is removed or renamed. test('has known-gap ledgers that name only cases in their fixtures', () => { const fixtureIds = checkerCases.map(c => c.id) const elements = sweep.cases.map(c => c.element) expect({ toggle: Object.keys(KNOWN_GAPS).filter(id => !fixtureIds.includes(id)), paste: Object.keys(PASTE_KNOWN_GAPS).filter(id => !fixtureIds.includes(id)), sweep: Object.keys(SWEEP_KNOWN_GAPS).filter(element => !elements.includes(element)), }).toEqual({toggle: [], paste: [], sweep: []}) }) }) // The engine is exercised here rather than under vitest so that the port is checked // against the same parser the toggle tests run it on. test.describe('the structural diff engine', () => { test.beforeEach(async ({page}) => { await page.goto('/scenarios/basic') await page.addScriptTag({content: engineSource}) }) for (const pair of golden) { test(`agrees with its ruby twin when ${pair.name}`, async ({page}) => { const findings = await page.evaluate( ([expected, returned]) => // @ts-expect-error -- engine injected by addScriptTag window.diffMathml(expected, returned), [pair.expected, pair.returned], ) expect(findings).toEqual(pair.findings) }) } })