Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
fix(ckeditor5-math): listen for inputTransformation on ClipboardPipeline
Elian Dorand6ef38fa6764
diff --git a/packages/ckeditor5-math/src/automath.ts b/packages/ckeditor5-math/src/automath.tsindex 4e54f78cfd..d189ac2a60 100644--- a/packages/ckeditor5-math/src/automath.ts+++ b/packages/ckeditor5-math/src/automath.ts@@ -1,9 +1,9 @@-import { Clipboard, Plugin, type Editor, ModelLivePosition, ModelLiveRange, Undo } from 'ckeditor5';+import { Clipboard, ClipboardPipeline, Plugin, type Editor, ModelLivePosition, ModelLiveRange, Undo } from 'ckeditor5';import { extractDelimiters, hasDelimiters, delimitersCounts } from './utils.js';export default class AutoMath extends Plugin {public static get requires() {- return [ Clipboard, Undo ] as const;+ return [ Clipboard, ClipboardPipeline, Undo ] as const;}public static get pluginName() {@@ -25,7 +25,9 @@ export default class AutoMath extends Plugin {const editor = this.editor;const modelDocument = editor.model.document;- this.listenTo( editor.plugins.get( Clipboard ), 'inputTransformation', () => {+ // `inputTransformation` is emitted by ClipboardPipeline, not by the Clipboard facade.+ // Listening on Clipboard silently never fires, which left this whole feature dead.+ this.listenTo( editor.plugins.get( ClipboardPipeline ), 'inputTransformation', () => {const firstRange = modelDocument.selection.getFirstRange();if ( !firstRange ) {return;diff --git a/packages/ckeditor5-math/tests/autoformatmath.ts b/packages/ckeditor5-math/tests/autoformatmath.tsnew file mode 100644index 0000000000..c676d5e627--- /dev/null+++ b/packages/ckeditor5-math/tests/autoformatmath.ts@@ -0,0 +1,108 @@+import { Autoformat, ClassicEditor, Paragraph, Typing, _setModelData as setData } from 'ckeditor5';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++// Side-effect import: declares the `math` key on EditorConfig used by the editor configs below.+import '../src/augmentation.js';++import AutoformatMath from '../src/autoformatmath.js';+import Math from '../src/math.js';+import MathUI from '../src/mathui.js';++describe( 'AutoformatMath', () => {+ let editorElement: HTMLDivElement, editor: ClassicEditor;++ async function createEditor( plugins: Array<unknown> ) {+ editorElement = document.createElement( 'div' );+ document.body.appendChild( editorElement );++ return ClassicEditor.create( editorElement, {+ plugins: plugins as never,+ licenseKey: 'GPL',+ math: {+ engine: ( equation: string, element: HTMLElement ) => {+ element.innerHTML = equation;+ }+ }+ } );+ }++ afterEach( async () => {+ editorElement.remove();+ await editor.destroy();+ vi.useRealTimers();+ vi.restoreAllMocks();+ } );++ describe( 'with the Math feature loaded', () => {+ beforeEach( async () => {+ editor = await createEditor( [ Math, AutoformatMath, Autoformat, Typing, Paragraph ] );+ } );++ it( 'has proper name and requirements', () => {+ expect( AutoformatMath.pluginName ).to.equal( 'AutoformatMath' );+ expect( AutoformatMath.requires ).to.contain( Math );+ expect( AutoformatMath.requires ).to.contain( 'Autoformat' );+ } );++ it( 'turns `$$` at the start of a block into an equation prompt', () => {+ vi.useFakeTimers();+ const showUI = vi.spyOn( editor.plugins.get( MathUI ), '_showUI' ).mockImplementation( () => undefined );++ setData( editor.model, '<paragraph>[]</paragraph>' );+ editor.execute( 'insertText', { text: '$' } );+ editor.execute( 'insertText', { text: '$' } );+ editor.execute( 'insertText', { text: ' ' } );++ // The `$$` marker is consumed and the UI is opened on a short delay, once the+ // selection has settled.+ expect( showUI ).not.toHaveBeenCalled();+ vi.advanceTimersByTime( 50 );+ expect( showUI ).toHaveBeenCalled();+ } );++ it( 'turns `\\[` at the start of a block into a display equation prompt', () => {+ vi.useFakeTimers();+ const showUI = vi.spyOn( editor.plugins.get( MathUI ), '_showUI' ).mockImplementation( () => undefined );++ setData( editor.model, '<paragraph>[]</paragraph>' );+ editor.execute( 'insertText', { text: '\\' } );+ editor.execute( 'insertText', { text: '[' } );+ editor.execute( 'insertText', { text: ' ' } );++ vi.advanceTimersByTime( 50 );+ expect( showUI ).toHaveBeenCalled();+ } );++ it( 'does nothing when the math command is disabled', () => {+ vi.useFakeTimers();+ const showUI = vi.spyOn( editor.plugins.get( MathUI ), '_showUI' ).mockImplementation( () => undefined );+ editor.commands.get( 'math' )?.forceDisabled( 'test' );++ setData( editor.model, '<paragraph>[]</paragraph>' );+ editor.execute( 'insertText', { text: '$' } );+ editor.execute( 'insertText', { text: '$' } );+ editor.execute( 'insertText', { text: ' ' } );++ vi.advanceTimersByTime( 50 );+ expect( showUI ).not.toHaveBeenCalled();+ } );+ } );++ describe( 'without the Math feature', () => {+ it( 'warns rather than throwing', async () => {+ const warn = vi.spyOn( console, 'warn' ).mockImplementation( () => undefined );++ // `requires` pulls Math in, so the missing-feature warning is only reachable by+ // removing it from the plugin map after the fact.+ editor = await createEditor( [ Math, AutoformatMath, Autoformat, Typing, Paragraph ] );+ const plugins = editor.plugins as unknown as { has( name: string ): boolean };+ const originalHas = plugins.has.bind( plugins );+ plugins.has = ( name: string ) => name === 'Math' ? false : originalHas( name );++ editor.plugins.get( AutoformatMath ).init();++ expect( warn ).toHaveBeenCalled();+ plugins.has = originalHas;+ } );+ } );+} );diff --git a/packages/ckeditor5-math/tests/automath.ts b/packages/ckeditor5-math/tests/automath.tsindex 9738ba0a22..b13941761a 100644--- a/packages/ckeditor5-math/tests/automath.ts+++ b/packages/ckeditor5-math/tests/automath.ts@@ -47,10 +47,7 @@ describe( 'AutoMath - integration', () => {expect( AutoMath.pluginName ).to.equal( 'AutoMath' );} );- // TODO: It appears that these tests are failing as the text is not replaced with its corresponding equation. What I find strange here:- // The automath plugin currently only seems to trigger a window and not allow inserting convertion a selection into an equation (either the implementation or test is broken).- // To test on the original repository.- describe.skip( 'use fake timers', () => {+ describe( 'converting pasted equations', () => {beforeEach( () => {vi.useFakeTimers();} );@@ -59,7 +56,7 @@ describe( 'AutoMath - integration', () => {vi.useRealTimers();} );- it( 'replaces pasted text with mathtex element after 100ms', () => {+ it( 'replaces pasted text with a display equation after 100ms', () => {setData( editor.model, '<paragraph>[]</paragraph>' );pasteHtml( editor, '\\[x^2\\]' );@@ -69,12 +66,11 @@ describe( 'AutoMath - integration', () => {vi.advanceTimersByTime( 100 );- expect( getData( editor.model ) ).to.equal(- '<paragraph>[<mathtex display="true" equation="x^2" type="script"></mathtex>]</paragraph>'- );+ // A display equation is a block element, so it replaces the empty paragraph outright.+ expect( getData( editor.model ) ).to.equal( '[<mathtex-display display="true" equation="x^2" type="script"></mathtex-display>]' );} );- it( 'replaces pasted text with inline mathtex element after 100ms', () => {+ it( 'replaces pasted text with an inline equation after 100ms', () => {setData( editor.model, '<paragraph>[]</paragraph>' );pasteHtml( editor, '\\(x^2\\)' );@@ -84,9 +80,16 @@ describe( 'AutoMath - integration', () => {vi.advanceTimersByTime( 100 );- expect( getData( editor.model ) ).to.equal(- '<paragraph>[<mathtex display="false" equation="x^2" type="script"></mathtex>]</paragraph>'- );+ expect( getData( editor.model ) ).to.equal( '<paragraph>[<mathtex-inline display="false" equation="x^2" type="script"></mathtex-inline>]</paragraph>' );+ } );++ it( 'does not convert before the delay elapses', () => {+ setData( editor.model, '<paragraph>[]</paragraph>' );+ pasteHtml( editor, '\\(x^2\\)' );++ vi.advanceTimersByTime( 99 );++ expect( getData( editor.model ) ).to.equal( '<paragraph>\\(x^2\\)[]</paragraph>' );} );it( 'can undo auto-mathing', () => {@@ -106,55 +109,69 @@ describe( 'AutoMath - integration', () => {);} );- it( 'works for not collapsed selection inside single element', () => {+ it( 'cancels the pending conversion when undo runs first', () => {+ setData( editor.model, '<paragraph>[]</paragraph>' );+ pasteHtml( editor, '\\(x^2\\)' );++ // Undo before the timeout fires: the scheduled conversion must be dropped, not applied.+ editor.commands.execute( 'undo' );+ vi.advanceTimersByTime( 100 );++ expect( getData( editor.model ) ).to.not.contain( 'mathtex' );+ } );++ it( 'works for a non-collapsed selection inside a single element', () => {setData( editor.model, '<paragraph>[Foo]</paragraph>' );- pasteHtml( editor, '\\[x^2\\]' );+ pasteHtml( editor, '\\(x^2\\)' );vi.advanceTimersByTime( 100 );- expect( getData( editor.model ) ).to.equal(- '<paragraph>[<mathtex display="true" equation="x^2" type="script"></mathtex>]</paragraph>'- );+ expect( getData( editor.model ) ).to.equal( '<paragraph>[<mathtex-inline display="false" equation="x^2" type="script"></mathtex-inline>]</paragraph>' );} );- it( 'works for not collapsed selection over a few elements', () => {+ it( 'works for a non-collapsed selection over a few elements', () => {setData( editor.model, '<paragraph>Fo[o</paragraph><paragraph>Ba]r</paragraph>' );- pasteHtml( editor, '\\[x^2\\]' );+ pasteHtml( editor, '\\(x^2\\)' );vi.advanceTimersByTime( 100 );- expect( getData( editor.model ) ).to.equal(- '<paragraph>Fo[<mathtex display="true" equation="x^2" type="script"></mathtex>]r</paragraph>'- );+ expect( getData( editor.model ) ).to.equal( '<paragraph>Fo[<mathtex-inline display="false" equation="x^2" type="script"></mathtex-inline>]r</paragraph>' );} );- it( 'inserts mathtex in-place (collapsed selection)', () => {+ it( 'inserts an inline equation in-place (collapsed selection)', () => {setData( editor.model, '<paragraph>Foo []Bar</paragraph>' );- pasteHtml( editor, '\\[x^2\\]' );+ pasteHtml( editor, '\\(x^2\\)' );vi.advanceTimersByTime( 100 );expect( getData( editor.model ) ).to.equal(- '<paragraph>Foo ' +- '[<mathtex display="true" equation="x^2" type="script"></mathtex>]' +- 'Bar</paragraph>'+ '<paragraph>Foo [<mathtex-inline display="false" equation="x^2" type="script"></mathtex-inline>]Bar</paragraph>');} );- it( 'inserts math in-place (non-collapsed selection)', () => {+ it( 'inserts an inline equation in-place (non-collapsed selection)', () => {setData( editor.model, '<paragraph>Foo [Bar] Baz</paragraph>' );+ pasteHtml( editor, '\\(x^2\\)' );++ vi.advanceTimersByTime( 100 );++ expect( getData( editor.model ) ).to.equal(+ '<paragraph>Foo [<mathtex-inline display="false" equation="x^2" type="script"></mathtex-inline>] Baz</paragraph>'+ );+ } );++ it( 'splits the paragraph around a pasted display equation', () => {+ setData( editor.model, '<paragraph>Foo []Bar</paragraph>' );pasteHtml( editor, '\\[x^2\\]' );vi.advanceTimersByTime( 100 );expect( getData( editor.model ) ).to.equal(- '<paragraph>Foo ' +- '[<mathtex display="true" equation="x^2" type="script"></mathtex>]' +- ' Baz</paragraph>'+ '<paragraph>Foo </paragraph>[<mathtex-display display="true" equation="x^2" type="script"></mathtex-display>]<paragraph>Bar</paragraph>');} );- it( 'does nothing if pasted two equation as text', () => {+ it( 'does nothing if two equations are pasted as text', () => {setData( editor.model, '<paragraph>[]</paragraph>' );pasteHtml( editor, '\\[x^2\\] \\[\\sqrt{x}2\\]' );@@ -164,6 +181,15 @@ describe( 'AutoMath - integration', () => {'<paragraph>\\[x^2\\] \\[\\sqrt{x}2\\][]</paragraph>');} );++ it( 'does nothing for pasted text without delimiters', () => {+ setData( editor.model, '<paragraph>[]</paragraph>' );+ pasteHtml( editor, 'x^2' );++ vi.advanceTimersByTime( 100 );++ expect( getData( editor.model ) ).to.equal( '<paragraph>x^2[]</paragraph>' );+ } );} );function pasteHtml( editor: ClassicEditor, html: string ) {diff --git a/packages/ckeditor5-math/tests/mathcommand.ts b/packages/ckeditor5-math/tests/mathcommand.tsnew file mode 100644index 0000000000..3021ab01ca--- /dev/null+++ b/packages/ckeditor5-math/tests/mathcommand.ts@@ -0,0 +1,178 @@+// Side-effect import: declares the `math` key on EditorConfig used by the editor config below.+import '../src/augmentation.js';++import { ClassicEditor, Bold, Paragraph, Typing, _getModelData as getData, _setModelData as setData } from 'ckeditor5';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import Math from '../src/math.js';+import { getBalloonPositionData } from '../src/utils.js';++const INLINE = 'mathtex-inline';+const DISPLAY = 'mathtex-display';++describe( 'MathCommand', () => {+ let editorElement: HTMLDivElement, editor: ClassicEditor;++ beforeEach( async () => {+ editorElement = document.createElement( 'div' );+ document.body.appendChild( editorElement );++ editor = await ClassicEditor.create( editorElement, {+ plugins: [ Math, Typing, Paragraph, Bold ],+ licenseKey: 'GPL',+ math: {+ engine: ( equation: string, element: HTMLElement ) => {+ element.innerHTML = equation;+ }+ }+ } );+ } );++ afterEach( async () => {+ editorElement.remove();+ await editor.destroy();+ } );++ function model() {+ return getData( editor.model, { withoutSelection: true } );+ }++ describe( 'refresh', () => {+ it( 'is enabled with a collapsed selection in a paragraph and reports no value', () => {+ setData( editor.model, '<paragraph>foo[]</paragraph>' );+ const command = editor.commands.get( 'math' );++ expect( command?.isEnabled ).toBe( true );+ expect( command?.value ).toBeNull();+ expect( command?.display ).toBe( false );+ } );++ it( 'reports the equation and display flag of a selected equation', () => {+ setData( editor.model, `<paragraph>[<${ INLINE } equation="x^2" type="script" display="false"></${ INLINE }>]</paragraph>` );+ const command = editor.commands.get( 'math' );++ expect( command?.value ).toBe( 'x^2' );+ expect( command?.display ).toBe( false );+ expect( command?.isEnabled ).toBe( true );+ } );++ it( 'reports display mode for a selected display equation', () => {+ setData( editor.model, `[<${ DISPLAY } equation="x^2" type="script" display="true"></${ DISPLAY }>]` );++ expect( editor.commands.get( 'math' )?.display ).toBe( true );+ } );+ } );++ describe( 'execute', () => {+ it( 'inserts a new inline equation at the selection', () => {+ setData( editor.model, '<paragraph>foo[]</paragraph>' );++ editor.execute( 'math', 'x^2', false, 'script' );++ expect( model() ).to.equal(+ `<paragraph>foo<${ INLINE } display="false" equation="x^2" type="script"></${ INLINE }></paragraph>`+ );+ } );++ it( 'inserts a new display equation', () => {+ setData( editor.model, '<paragraph>[]</paragraph>' );++ editor.execute( 'math', 'x^2', true, 'script' );++ expect( model() ).to.contain( `<${ DISPLAY } display="true" equation="x^2" type="script">` );+ } );++ it( 'inherits selection attributes such as bold', () => {+ setData( editor.model, '<paragraph><$text bold="true">foo[]</$text></paragraph>' );++ editor.execute( 'math', 'x^2', false, 'script' );++ expect( model() ).to.contain( 'bold="true"' );+ } );++ it( 'updates a selected equation, keeping its existing type', () => {+ setData( editor.model, `<paragraph>[<${ INLINE } equation="x^2" type="span" display="false"></${ INLINE }>]</paragraph>` );++ editor.execute( 'math', 'y^2', false, 'script' );++ expect( model() ).to.equal(+ `<paragraph><${ INLINE } display="false" equation="y^2" type="span"></${ INLINE }></paragraph>`+ );+ } );++ it( 'updates a selected equation and forces the output type when asked', () => {+ setData( editor.model, `<paragraph>[<${ INLINE } equation="x^2" type="span" display="false"></${ INLINE }>]</paragraph>` );++ editor.execute( 'math', 'y^2', false, 'script', true );++ expect( model() ).to.contain( 'type="script"' );+ } );++ it( 'falls back to the given output type when the selected equation has none', () => {+ setData( editor.model, `<paragraph>[<${ INLINE } equation="x^2" display="false"></${ INLINE }>]</paragraph>` );++ editor.execute( 'math', 'y^2', false, 'script' );++ expect( model() ).to.contain( 'type="script"' );+ } );++ it( 'converts a selected inline equation to a display one', () => {+ setData( editor.model, `<paragraph>[<${ INLINE } equation="x^2" type="script" display="false"></${ INLINE }>]</paragraph>` );++ editor.execute( 'math', 'x^2', true, 'script' );++ expect( model() ).to.contain( `<${ DISPLAY } display="true"` );+ } );+ } );+} );++describe( 'getBalloonPositionData', () => {+ let editorElement: HTMLDivElement, editor: ClassicEditor;++ beforeEach( async () => {+ editorElement = document.createElement( 'div' );+ document.body.appendChild( editorElement );++ editor = await ClassicEditor.create( editorElement, {+ plugins: [ Math, Typing, Paragraph ],+ licenseKey: 'GPL',+ math: {+ engine: ( equation: string, element: HTMLElement ) => {+ element.innerHTML = equation;+ }+ }+ } );+ } );++ afterEach( async () => {+ editorElement.remove();+ await editor.destroy();+ } );++ it( 'targets the DOM element of a selected equation widget', () => {+ setData( editor.model, `<paragraph>[<${ INLINE } equation="x^2" type="script" display="false"></${ INLINE }>]</paragraph>` );++ const { target, positions } = getBalloonPositionData( editor );++ expect( target ).toBeInstanceOf( HTMLElement );+ expect( positions ).toHaveLength( 3 );+ } );++ it( 'targets the selection range when no widget is selected', () => {+ setData( editor.model, '<paragraph>f[o]o</paragraph>' );++ const { target, positions } = getBalloonPositionData( editor );++ expect( target ).toBeInstanceOf( Range );+ expect( positions ).toHaveLength( 3 );+ } );++ it( 'throws when the view selection has no range at all', () => {+ setData( editor.model, '<paragraph>foo</paragraph>' );+ editor.editing.view.change( writer => {+ writer.setSelection( null );+ } );++ expect( () => getBalloonPositionData( editor ) ).toThrow( /math-missing-range/ );+ } );+} );diff --git a/packages/ckeditor5-math/tests/mathediting.ts b/packages/ckeditor5-math/tests/mathediting.tsnew file mode 100644index 0000000000..6ff4ed0490--- /dev/null+++ b/packages/ckeditor5-math/tests/mathediting.ts@@ -0,0 +1,226 @@+// Side-effect import: declares the `math` key on EditorConfig used by the editor configs below.+import '../src/augmentation.js';++import { ClassicEditor, CodeBlock, Paragraph, Typing, _getModelData as getData, _setModelData as setData } from 'ckeditor5';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import Math from '../src/math.js';+import MathEditing from '../src/mathediting.js';++const INLINE = 'mathtex-inline';+const DISPLAY = 'mathtex-display';++describe( 'MathEditing', () => {+ let editorElement: HTMLDivElement, editor: ClassicEditor;++ async function createEditor( mathConfig: Record<string, unknown> = {} ) {+ editorElement = document.createElement( 'div' );+ document.body.appendChild( editorElement );++ return ClassicEditor.create( editorElement, {+ plugins: [ Math, Typing, Paragraph, CodeBlock ],+ licenseKey: 'GPL',+ math: {+ engine: ( equation: string, element: HTMLElement ) => {+ element.innerHTML = equation;+ },+ ...mathConfig+ }+ } );+ }++ beforeEach( async () => {+ editor = await createEditor();+ } );++ afterEach( async () => {+ editorElement.remove();+ await editor.destroy();+ } );++ it( 'has proper name and requirements', () => {+ expect( MathEditing.pluginName ).to.equal( 'MathEditing' );+ expect( editor.plugins.get( MathEditing ) ).to.instanceOf( MathEditing );+ } );++ it( 'registers the math command', () => {+ expect( editor.commands.get( 'math' ) ).toBeDefined();+ } );++ describe( 'schema', () => {+ it( 'allows an inline equation wherever text is allowed', () => {+ expect( editor.model.schema.checkChild( [ '$root', 'paragraph' ], INLINE ) ).toBe( true );+ } );++ it( 'allows a display equation as a block', () => {+ expect( editor.model.schema.checkChild( [ '$root' ], DISPLAY ) ).toBe( true );+ } );++ it( 'forbids an inline equation inside a code block', () => {+ expect( editor.model.schema.checkChild( [ '$root', 'codeBlock' ], INLINE ) ).toBe( false );+ } );++ it( 'marks both equation elements as objects', () => {+ expect( editor.model.schema.isObject( INLINE ) ).toBe( true );+ expect( editor.model.schema.isObject( DISPLAY ) ).toBe( true );+ expect( editor.model.schema.isInline( INLINE ) ).toBe( true );+ } );+ } );++ describe( 'upcast', () => {+ it( 'reads a MathJax inline script', () => {+ editor.setData( '<p><script type="math/tex">\\sqrt{x}</script></p>' );++ expect( getData( editor.model, { withoutSelection: true } ) ).to.equal(+ `<paragraph><${ INLINE } display="false" equation="\\sqrt{x}" type="script"></${ INLINE }></paragraph>`+ );+ } );++ it( 'reads a MathJax display script', () => {+ editor.setData( '<script type="math/tex; mode=display">\\sqrt{x}</script>' );++ expect( getData( editor.model, { withoutSelection: true } ) ).to.equal(+ `<${ DISPLAY } display="true" equation="\\sqrt{x}" type="script"></${ DISPLAY }>`+ );+ } );++ it( 'ignores a MathJax script with no text child', () => {+ editor.setData( '<p><script type="math/tex"></script></p>' );++ expect( getData( editor.model, { withoutSelection: true } ) ).to.not.contain( INLINE );+ } );++ it( 'ignores a display MathJax script with no text child', () => {+ editor.setData( '<script type="math/tex; mode=display"></script>' );++ expect( getData( editor.model, { withoutSelection: true } ) ).to.not.contain( DISPLAY );+ } );++ it( 'reads the CKEditor 4 span form, inline', () => {+ editor.setData( '<p><span class="math-tex">\\(\\sqrt{x}\\)</span></p>' );++ expect( getData( editor.model, { withoutSelection: true } ) ).to.equal(+ `<paragraph><${ INLINE } display="false" equation="\\sqrt{x}" type="span"></${ INLINE }></paragraph>`+ );+ } );++ it( 'reads the CKEditor 4 span form, display', () => {+ editor.setData( '<p><span class="math-tex">\\[\\sqrt{x}\\]</span></p>' );++ expect( getData( editor.model, { withoutSelection: true } ) ).to.contain( `${ DISPLAY } display="true"` );+ } );++ it( 'restores line breaks smuggled through the data processor', () => {+ editor.setData( '<p><span class="math-tex">\\(a\nb\\)</span></p>' );++ expect( getData( editor.model, { withoutSelection: true } ) ).to.contain( 'a\nb' );+ } );++ it( 'ignores a math-tex span with no text child', () => {+ editor.setData( '<p><span class="math-tex"></span></p>' );++ expect( getData( editor.model, { withoutSelection: true } ) ).to.not.contain( INLINE );+ } );++ it( 'reads the Quill ql-formula form', () => {+ editor.setData( '<p><span class="ql-formula" data-value="\\sqrt{x}"></span></p>' );++ expect( getData( editor.model, { withoutSelection: true } ) ).to.equal(+ `<paragraph><${ INLINE } display="false" equation="\\sqrt{x}" type="script"></${ INLINE }></paragraph>`+ );+ } );++ it( 'throws when a ql-formula carries no equation', () => {+ expect( () => editor.setData( '<p><span class="ql-formula"></span></p>' ) )+ .toThrow( /missing-equation/ );+ } );++ describe( 'with forceOutputType', () => {+ beforeEach( async () => {+ editorElement.remove();+ await editor.destroy();+ editor = await createEditor( { forceOutputType: true, outputType: 'span' } );+ } );++ it( 'overrides the type of a MathJax inline script', () => {+ editor.setData( '<p><script type="math/tex">x</script></p>' );++ expect( getData( editor.model, { withoutSelection: true } ) ).to.contain( 'type="span"' );+ } );++ it( 'overrides the type of a MathJax display script', () => {+ editor.setData( '<script type="math/tex; mode=display">x</script>' );++ expect( getData( editor.model, { withoutSelection: true } ) ).to.contain( 'type="span"' );+ } );++ it( 'overrides the type of a CKEditor 4 span', () => {+ editor.setData( '<p><span class="math-tex">\\(x\\)</span></p>' );++ expect( getData( editor.model, { withoutSelection: true } ) ).to.contain( 'type="span"' );+ } );++ it( 'overrides the type of a Quill formula', () => {+ editor.setData( '<p><span class="ql-formula" data-value="x"></span></p>' );++ expect( getData( editor.model, { withoutSelection: true } ) ).to.contain( 'type="span"' );+ } );+ } );+ } );++ describe( 'data downcast', () => {+ it( 'writes a script tag for an inline script-type equation', () => {+ setData( editor.model, `<paragraph><${ INLINE } equation="x^2" type="script" display="false"></${ INLINE }></paragraph>` );++ expect( editor.getData() ).to.equal( '<p><script type="math/tex">x^2</script></p>' );+ } );++ it( 'writes a display script tag for a display equation', () => {+ setData( editor.model, `<${ DISPLAY } equation="x^2" type="script" display="true"></${ DISPLAY }>` );++ expect( editor.getData() ).to.equal( '<script type="math/tex; mode=display">x^2</script>' );+ } );++ it( 'writes a math-tex span with inline delimiters for a span-type equation', () => {+ setData( editor.model, `<paragraph><${ INLINE } equation="x^2" type="span" display="false"></${ INLINE }></paragraph>` );++ expect( editor.getData() ).to.equal( '<p><span class="math-tex">\\(x^2\\)</span></p>' );+ } );++ it( 'writes a math-tex span with display delimiters for a display span-type equation', () => {+ setData( editor.model, `<${ DISPLAY } equation="x^2" type="span" display="true"></${ DISPLAY }>` );++ expect( editor.getData() ).to.equal( '<span class="math-tex">\\[x^2\\]</span>' );+ } );++ it( 'throws when the model element carries no equation', () => {+ setData( editor.model, `<paragraph><${ INLINE } type="script" display="false"></${ INLINE }></paragraph>` );++ expect( () => editor.getData() ).toThrow( /missing-equation/ );+ } );+ } );++ describe( 'editing downcast', () => {+ it( 'renders an inline equation as an inline widget', () => {+ setData( editor.model, `<paragraph><${ INLINE } equation="x^2" type="script" display="false"></${ INLINE }></paragraph>` );++ const rendered = editorElement.nextElementSibling?.querySelector( '.ck-math-tex-inline' );+ expect( rendered ).not.toBeNull();+ expect( rendered?.tagName ).toBe( 'SPAN' );+ } );++ it( 'renders a display equation as a block widget', () => {+ setData( editor.model, `<${ DISPLAY } equation="x^2" type="script" display="true"></${ DISPLAY }>` );++ const rendered = editorElement.nextElementSibling?.querySelector( '.ck-math-tex-display' );+ expect( rendered ).not.toBeNull();+ expect( rendered?.tagName ).toBe( 'DIV' );+ } );++ it( 'passes the equation through the configured engine', () => {+ setData( editor.model, `<paragraph><${ INLINE } equation="x^2" type="script" display="false"></${ INLINE }></paragraph>` );++ expect( editorElement.nextElementSibling?.textContent ).to.contain( 'x^2' );+ } );+ } );+} );diff --git a/packages/ckeditor5-math/tests/mathinputview.ts b/packages/ckeditor5-math/tests/mathinputview.tsnew file mode 100644index 0000000000..2af512dd22--- /dev/null+++ b/packages/ckeditor5-math/tests/mathinputview.ts@@ -0,0 +1,266 @@+import { Locale } from 'ckeditor5';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import MathInputView, { LatexTextAreaView, MathFieldFocusableView } from '../src/ui/mathinputview.js';++interface MathField extends HTMLElement {+ value: string;+ readOnly: boolean;+ setValue?: ( value: string, options?: { silenceNotifications?: boolean } ) => void;+}++describe( 'MathInputView', () => {+ let view: MathInputView;++ /** Render the view into the document and wait for MathLive to mount its <math-field>. */+ async function renderAndWait(): Promise<MathField> {+ view = new MathInputView( new Locale() );+ view.render();+ document.body.appendChild( view.element as HTMLElement );++ await vi.waitFor( () => expect( view.mathfield ).not.toBeNull(), { timeout: 10000 } );+ return view.mathfield as MathField;+ }++ function textarea(): HTMLTextAreaElement {+ return view.latexTextAreaView.element;+ }++ afterEach( () => {+ view?.element?.remove();+ view?.destroy();+ vi.restoreAllMocks();+ } );++ it( 'renders a LaTeX textarea, a label and a MathLive container', async () => {+ await renderAndWait();++ expect( view.element?.querySelector( '.ck-mathlive-container' ) ).not.toBeNull();+ expect( view.element?.querySelector( '.ck-latex-label' ) ).not.toBeNull();+ expect( textarea().tagName ).toBe( 'TEXTAREA' );+ expect( textarea().spellcheck ).toBe( false );+ } );++ it( 'mounts a math-field and announces it', async () => {+ const mathfield = await renderAndWait();++ expect( mathfield.tagName.toLowerCase() ).toBe( 'math-field' );+ expect( mathfield.getAttribute( 'tabindex' ) ).toBe( '0' );+ } );++ describe( 'syncing', () => {+ it( 'pushes a model value into both the textarea and the math field', async () => {+ const mathfield = await renderAndWait();++ view.value = 'x^2';++ expect( textarea().value ).toBe( 'x^2' );+ await vi.waitFor( () => expect( mathfield.value.trim() ).toBe( 'x^2' ) );+ } );++ it( 'treats a null value as empty', async () => {+ await renderAndWait();+ view.value = 'x^2';++ view.value = null;++ expect( textarea().value ).toBe( '' );+ } );++ it( 'pushes a textarea edit into the model', async () => {+ await renderAndWait();++ textarea().value = 'y^2';+ textarea().dispatchEvent( new Event( 'input' ) );++ expect( view.value ).toBe( 'y^2' );+ } );++ it( 'rebuilds the math field when the textarea is cleared', async () => {+ const first = await renderAndWait();++ textarea().value = '';+ textarea().dispatchEvent( new Event( 'input' ) );++ expect( view.value ).toBeNull();+ await vi.waitFor( () => expect( view.mathfield ).not.toBe( first ) );+ } );++ it( 'pushes a math field edit into the textarea and the model', async () => {+ const mathfield = await renderAndWait();++ mathfield.value = 'z^2';+ mathfield.dispatchEvent( new Event( 'input' ) );++ expect( textarea().value ).toBe( 'z^2' );+ expect( view.value ).toBe( 'z^2' );+ } );++ it( 'clears the model when the math field is emptied', async () => {+ const mathfield = await renderAndWait();+ view.value = 'x^2';++ mathfield.value = '';+ mathfield.dispatchEvent( new Event( 'input' ) );++ expect( view.value ).toBeNull();+ } );++ it( 'falls back to assigning value when setValue is unavailable', async () => {+ const mathfield = await renderAndWait();+ // Older MathLive builds expose no setValue; the view must still update the field.+ delete ( mathfield as { setValue?: unknown } ).setValue;++ view.value = 'q^2';++ expect( mathfield.value ).toBe( 'q^2' );+ } );+ } );++ describe( 'read-only state', () => {+ it( 'propagates to the textarea and the math field', async () => {+ const mathfield = await renderAndWait();++ view.isReadOnly = true;++ expect( textarea().readOnly ).toBe( true );+ expect( mathfield.readOnly ).toBe( true );+ } );+ } );++ describe( 'keyboard handling', () => {+ it( 'moves focus to the LaTeX textarea on Tab', async () => {+ const mathfield = await renderAndWait();+ const focus = vi.spyOn( view.latexTextAreaView, 'focus' );++ const event = new KeyboardEvent( 'keydown', { key: 'Tab', cancelable: true, bubbles: true } );+ mathfield.dispatchEvent( event );++ expect( event.defaultPrevented ).toBe( true );+ expect( focus ).toHaveBeenCalled();+ } );++ it( 'swallows Shift+Tab without moving focus', async () => {+ const mathfield = await renderAndWait();+ const focus = vi.spyOn( view.latexTextAreaView, 'focus' );++ const event = new KeyboardEvent( 'keydown', { key: 'Tab', shiftKey: true, cancelable: true, bubbles: true } );+ mathfield.dispatchEvent( event );++ expect( event.defaultPrevented ).toBe( true );+ expect( focus ).not.toHaveBeenCalled();+ } );++ it( 'ignores other keys', async () => {+ const mathfield = await renderAndWait();++ const event = new KeyboardEvent( 'keydown', { key: 'a', cancelable: true, bubbles: true } );+ mathfield.dispatchEvent( event );++ expect( event.defaultPrevented ).toBe( false );+ } );+ } );++ describe( 'the virtual keyboard', () => {+ // MathLive owns `window.mathVirtualKeyboard` and calls into it while a <math-field> mounts,+ // so the real object stays in place and only the pieces under test are spied on.+ function captureGeometryHandler(): { handler: () => void | undefined } {+ const vk = window.mathVirtualKeyboard;+ const captured: { handler: () => void | undefined } = { handler: () => undefined };+ if ( vk ) {+ vi.spyOn( vk, 'addEventListener' ).mockImplementation( ( event: string, cb: () => void ) => {+ if ( event === 'geometrychange' ) {+ captured.handler = cb;+ }+ } );+ }+ return captured;+ }++ function setVisible( visible: boolean ): void {+ const vk = window.mathVirtualKeyboard;+ if ( vk ) {+ Object.defineProperty( vk, 'visible', { value: visible, configurable: true } );+ }+ }++ it( 'refocuses the math field when the keyboard geometry changes while visible', async () => {+ const captured = captureGeometryHandler();++ const mathfield = await renderAndWait();+ const focus = vi.spyOn( mathfield, 'focus' );+ setVisible( true );++ captured.handler();++ expect( focus ).toHaveBeenCalled();+ } );++ it( 'does nothing on geometry change while hidden', async () => {+ const captured = captureGeometryHandler();++ const mathfield = await renderAndWait();+ const focus = vi.spyOn( mathfield, 'focus' );+ setVisible( false );++ captured.handler();++ expect( focus ).not.toHaveBeenCalled();+ } );++ it( 'hides the keyboard on request and detaches its listener on destroy', async () => {+ const vk = window.mathVirtualKeyboard;+ const hide = vk ? vi.spyOn( vk, 'hide' ).mockImplementation( () => undefined ) : undefined;+ const removeEventListener = vk ? vi.spyOn( vk, 'removeEventListener' ) : undefined;++ await renderAndWait();+ view.hideKeyboard();+ expect( hide ).toHaveBeenCalled();++ view.element?.remove();+ view.destroy();++ expect( removeEventListener ).toHaveBeenCalledWith( 'geometrychange', expect.any( Function ) );+ expect( view.mathfield ).toBeNull();+ } );+ } );++ describe( 'focus delegation', () => {+ it( 'focuses the math field through the view and its focusable wrapper', async () => {+ const mathfield = await renderAndWait();+ const focus = vi.spyOn( mathfield, 'focus' );++ view.focus();+ view.mathFieldFocusableView.focus();++ expect( focus ).toHaveBeenCalledTimes( 2 );+ } );++ it( 'focuses the textarea through its own view', async () => {+ await renderAndWait();+ const focus = vi.spyOn( textarea(), 'focus' );++ view.latexTextAreaView.focus();++ expect( focus ).toHaveBeenCalled();+ } );+ } );++ describe( 'the sub-views in isolation', () => {+ it( 'LatexTextAreaView renders a textarea', () => {+ const sub = new LatexTextAreaView( new Locale() );+ sub.render();++ expect( sub.element.tagName ).toBe( 'TEXTAREA' );+ sub.destroy();+ } );++ it( 'MathFieldFocusableView tolerates focus before a field exists', () => {+ const host = new MathInputView( new Locale() );+ const sub = new MathFieldFocusableView( new Locale(), host );++ expect( () => sub.focus() ).not.toThrow();+ host.destroy();+ } );+ } );+} );diff --git a/packages/ckeditor5-math/tests/mathview.ts b/packages/ckeditor5-math/tests/mathview.tsnew file mode 100644index 0000000000..e8186295ad--- /dev/null+++ b/packages/ckeditor5-math/tests/mathview.ts@@ -0,0 +1,78 @@+import katex from 'katex';+import { Locale } from 'ckeditor5';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import MathView, { type MathViewOptions } from '../src/ui/mathview.js';++describe( 'MathView', () => {+ let view: MathView;++ const globals = window as unknown as { katex: typeof katex | undefined };+ const originalKatex = globals.katex;++ function createView( overrides: Partial<MathViewOptions> = {} ): MathView {+ return new MathView( new Locale(), {+ engine: 'katex',+ lazyLoad: undefined,+ previewUid: 'preview-mathview',+ previewClassName: [],+ katexRenderOptions: {},+ ...overrides+ } );+ }++ beforeEach( () => {+ globals.katex = katex;+ } );++ afterEach( () => {+ view?.destroy();+ globals.katex = originalKatex;+ document.getElementById( 'preview-mathview' )?.remove();+ vi.restoreAllMocks();+ } );++ it( 'renders an equation into its element', () => {+ view = createView();+ view.render();+ view.value = 'x^2';++ expect( view.element?.querySelector( '.katex' ) ?? view.element?.textContent ).toBeTruthy();+ } );++ it( 'clears the element for an empty equation', () => {+ view = createView();+ view.render();+ view.value = 'x^2';+ view.value = ' ';++ expect( view.element?.textContent ).toBe( '' );+ expect( view.element?.classList.contains( 'ck-math-render-error' ) ).toBe( false );+ } );++ it( 'does nothing before it is rendered', () => {+ view = createView();++ expect( () => view.updateMath() ).not.toThrow();+ expect( view.element ).toBeNull();+ } );++ it( 'reports a rendering failure on the element', async () => {+ const error = vi.spyOn( console, 'error' ).mockImplementation( () => undefined );+ view = createView();+ view.render();++ // Force the render to reject: no engine and no lazy loader still resolves, so make the+ // element unavailable to the renderer instead.+ const failing = view as unknown as { options: { engine: unknown } };+ failing.options.engine = () => {+ throw new Error( 'boom' );+ };++ view.value = 'x^2';+ await vi.waitFor( () => expect( error ).toHaveBeenCalled() );++ expect( view.element?.textContent ).toBe( 'Error rendering equation' );+ expect( view.element?.classList.contains( 'ck-math-render-error' ) ).toBe( true );+ } );+} );diff --git a/packages/ckeditor5-math/tests/render-equation.ts b/packages/ckeditor5-math/tests/render-equation.tsnew file mode 100644index 0000000000..7d28c6ba35--- /dev/null+++ b/packages/ckeditor5-math/tests/render-equation.ts@@ -0,0 +1,221 @@+import katex from 'katex';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import type { MathJax2, MathJax3 } from '../src/typings-external.js';+import { renderEquation } from '../src/utils.js';++/**+ * `renderEquation` reads its engines off the globals (`window.katex`, `MathJax`) and caches the+ * lazy-load promise on `window.CKEDITOR_MATH_LAZY_LOAD`, so each test installs what it needs and+ * the teardown puts the globals back.+ */+describe( 'renderEquation', () => {+ let element: HTMLDivElement;++ const globals = window as unknown as {+ katex: typeof katex | undefined;+ MathJax: MathJax2 | MathJax3 | undefined;+ CKEDITOR_MATH_LAZY_LOAD: Promise<void> | undefined;+ };++ const originalKatex = globals.katex;+ const originalMathJax = globals.MathJax;++ beforeEach( () => {+ element = document.createElement( 'div' );+ document.body.appendChild( element );+ globals.CKEDITOR_MATH_LAZY_LOAD = undefined;+ } );++ afterEach( () => {+ element.remove();+ globals.katex = originalKatex;+ globals.MathJax = originalMathJax;+ globals.CKEDITOR_MATH_LAZY_LOAD = undefined;+ document.querySelectorAll( '[id^="preview-"]' ).forEach( node => node.remove() );+ vi.restoreAllMocks();+ } );++ describe( 'the katex engine', () => {+ beforeEach( () => {+ globals.katex = katex;+ } );++ it( 'renders into the element itself when not previewing', async () => {+ await renderEquation( 'x^2', element, 'katex' );++ expect( element.querySelector( '.katex' ) ).not.toBeNull();+ } );++ it( 'renders display mode when asked', async () => {+ await renderEquation( 'x^2', element, 'katex', undefined, true );++ expect( element.querySelector( '.katex-display' ) ).not.toBeNull();+ } );++ it( 'renders into a generated preview element and reveals it', async () => {+ await renderEquation( 'x^2', element, 'katex', undefined, false, true, 'preview-a', [ 'cls-a', 'cls-b' ] );++ const preview = document.getElementById( 'preview-a' );+ expect( preview ).not.toBeNull();+ expect( preview?.classList.contains( 'cls-a' ) ).toBe( true );+ expect( preview?.classList.contains( 'cls-b' ) ).toBe( true );+ expect( preview?.style.visibility ).toBe( 'visible' );+ } );++ it( 'reuses an existing preview element rather than making a second one', async () => {+ await renderEquation( 'x^2', element, 'katex', undefined, false, true, 'preview-b', [] );+ await renderEquation( 'y^2', element, 'katex', undefined, false, true, 'preview-b', [] );++ expect( document.querySelectorAll( '#preview-b' ) ).toHaveLength( 1 );+ } );+ } );++ describe( 'a custom engine function', () => {+ it( 'is called with the equation, element and display flag', async () => {+ const engine = vi.fn();++ await renderEquation( 'x^2', element, engine, undefined, true );++ expect( engine ).toHaveBeenCalledWith( 'x^2', element, true );+ } );+ } );++ describe( 'the mathjax 3 engine', () => {+ it( 'renders through tex2chtmlPromise and replaces any previous child', async () => {+ const rendered = document.createElement( 'span' );+ rendered.textContent = 'chtml';+ const tex2chtmlPromise = vi.fn().mockResolvedValue( rendered );+ globals.MathJax = { version: '3.2.2', tex2chtmlPromise } as unknown as MathJax3;+ element.appendChild( document.createElement( 'b' ) );++ await renderEquation( 'x^2', element, 'mathjax' );+ await tex2chtmlPromise.mock.results[ 0 ]?.value;++ expect( tex2chtmlPromise ).toHaveBeenCalledWith( 'x^2', { display: false } );+ expect( element.querySelector( 'b' ) ).toBeNull();+ expect( element.textContent ).toBe( 'chtml' );+ } );++ it( 'falls back to tex2svgPromise', async () => {+ const rendered = document.createElement( 'span' );+ const tex2svgPromise = vi.fn().mockResolvedValue( rendered );+ globals.MathJax = { version: '3.2.2', tex2svgPromise } as unknown as MathJax3;++ await renderEquation( 'x^2', element, 'mathjax' );+ await tex2svgPromise.mock.results[ 0 ]?.value;++ expect( tex2svgPromise ).toHaveBeenCalled();+ } );++ it( 'reveals the preview element once rendering resolves', async () => {+ const tex2chtmlPromise = vi.fn().mockResolvedValue( document.createElement( 'span' ) );+ globals.MathJax = { version: '3.2.2', tex2chtmlPromise } as unknown as MathJax3;++ await renderEquation( 'x^2', element, 'mathjax', undefined, false, true, 'preview-c', [] );+ await tex2chtmlPromise.mock.results[ 0 ]?.value;++ expect( document.getElementById( 'preview-c' )?.style.visibility ).toBe( 'visible' );+ } );++ it( 'does nothing when neither promise function is available', async () => {+ globals.MathJax = { version: '3.2.2' } as unknown as MathJax3;++ await renderEquation( 'x^2', element, 'mathjax' );++ expect( element.innerHTML ).toBe( '' );+ } );+ } );++ describe( 'the mathjax 2 engine', () => {+ it( 'wraps the equation in inline delimiters and queues a typeset', async () => {+ const Queue = vi.fn();+ globals.MathJax = { Hub: { Queue } } as unknown as MathJax2;++ await renderEquation( 'x^2', element, 'mathjax' );+ await vi.waitFor( () => expect( Queue ).toHaveBeenCalled() );++ expect( element.innerHTML ).toBe( '\\(x^2\\)' );+ } );++ it( 'wraps the equation in display delimiters when display is set', async () => {+ const Queue = vi.fn();+ globals.MathJax = { Hub: { Queue } } as unknown as MathJax2;++ await renderEquation( 'x^2', element, 'mathjax', undefined, true );+ await vi.waitFor( () => expect( Queue ).toHaveBeenCalled() );++ expect( element.innerHTML ).toBe( '\\[x^2\\]' );+ } );++ it( 'queues the preview reveal behind the typeset', async () => {+ const queued: Array<unknown> = [];+ const Queue = vi.fn( ( arg: unknown ) => queued.push( arg ) );+ globals.MathJax = { Hub: { Queue } } as unknown as MathJax2;++ await renderEquation( 'x^2', element, 'mathjax', undefined, false, true, 'preview-d', [] );+ await vi.waitFor( () => expect( Queue ).toHaveBeenCalledTimes( 2 ) );++ // The second queued entry is the callback that reveals the preview.+ const reveal = queued[ 1 ];+ expect( typeof reveal ).toBe( 'function' );+ ( reveal as () => void )();+ expect( document.getElementById( 'preview-d' )?.style.visibility ).toBe( 'visible' );+ } );++ it( 'does nothing when MathJax is absent entirely', async () => {+ globals.MathJax = undefined;++ await renderEquation( 'x^2', element, 'mathjax' );+ await vi.waitFor( () => expect( element.innerHTML ).toBe( '' ) );+ } );+ } );++ describe( 'lazy loading', () => {+ it( 'shows the raw equation, awaits the loader, then re-renders', async () => {+ globals.katex = undefined;+ const lazyLoad = vi.fn( async () => {+ globals.katex = katex;+ } );++ await renderEquation( 'x^2', element, 'katex', lazyLoad );++ expect( lazyLoad ).toHaveBeenCalledTimes( 1 );+ expect( element.querySelector( '.katex' ) ).not.toBeNull();+ } );++ it( 'only runs the loader once across calls', async () => {+ globals.katex = undefined;+ const lazyLoad = vi.fn( async () => {+ globals.katex = katex;+ } );++ await renderEquation( 'x^2', element, 'katex', lazyLoad );+ globals.katex = undefined;+ await renderEquation( 'y^2', element, 'katex', lazyLoad );++ expect( lazyLoad ).toHaveBeenCalledTimes( 1 );+ } );++ it( 'leaves the raw equation in place and logs when the loader rejects', async () => {+ globals.katex = undefined;+ const error = vi.spyOn( console, 'error' ).mockImplementation( () => undefined );+ const lazyLoad = vi.fn( () => Promise.reject( new Error( 'boom' ) ) );++ await renderEquation( 'x^2', element, 'katex', lazyLoad );++ expect( element.innerHTML ).toBe( 'x^2' );+ expect( error ).toHaveBeenCalledWith( expect.stringContaining( 'math-tex-typesetting-lazy-load-failed' ) );+ } );++ it( 'leaves the raw equation in place and warns when there is no loader', async () => {+ globals.katex = undefined;+ const warn = vi.spyOn( console, 'warn' ).mockImplementation( () => undefined );++ await renderEquation( 'x^2', element, 'katex' );++ expect( element.innerHTML ).toBe( 'x^2' );+ expect( warn ).toHaveBeenCalledWith( expect.stringContaining( 'math-tex-typesetting-missing' ) );+ } );+ } );+} );diff --git a/packages/ckeditor5-math/tests/utils-pure.ts b/packages/ckeditor5-math/tests/utils-pure.tsnew file mode 100644index 0000000000..eb470e98d7--- /dev/null+++ b/packages/ckeditor5-math/tests/utils-pure.ts@@ -0,0 +1,83 @@+import { describe, expect, it } from 'vitest';++import {+ delimitersCounts,+ extractDelimiters,+ hasDelimiters,+ isMathJaxVersion2,+ isMathJaxVersion3+} from '../src/utils.js';++describe( 'utils: delimiter helpers', () => {+ describe( 'hasDelimiters', () => {+ it( 'matches a fully delimited display equation', () => {+ expect( hasDelimiters( '\\[x^2\\]' ) ).not.toBeNull();+ } );++ it( 'matches a fully delimited inline equation', () => {+ expect( hasDelimiters( '\\(x^2\\)' ) ).not.toBeNull();+ } );++ it( 'does not match bare or partially delimited text', () => {+ expect( hasDelimiters( 'x^2' ) ).toBeNull();+ expect( hasDelimiters( '\\[x^2' ) ).toBeNull();+ expect( hasDelimiters( 'lead \\[x^2\\]' ) ).toBeNull();+ } );+ } );++ describe( 'delimitersCounts', () => {+ it( 'counts every delimiter token', () => {+ expect( delimitersCounts( '\\[x\\]' ) ).toBe( 2 );+ expect( delimitersCounts( '\\(a\\) and \\(b\\)' ) ).toBe( 4 );+ } );++ it( 'returns undefined when there are none', () => {+ expect( delimitersCounts( 'x^2' ) ).toBeUndefined();+ } );+ } );++ describe( 'extractDelimiters', () => {+ it( 'strips display delimiters and reports display mode', () => {+ expect( extractDelimiters( '\\[x^2\\]' ) ).toEqual( { equation: 'x^2', display: true } );+ } );++ it( 'strips inline delimiters and reports inline mode', () => {+ expect( extractDelimiters( '\\(x^2\\)' ) ).toEqual( { equation: 'x^2', display: false } );+ } );++ it( 'trims surrounding and inner whitespace', () => {+ expect( extractDelimiters( ' \\[ x^2 \\] ' ) ).toEqual( { equation: 'x^2', display: true } );+ } );++ it( 'leaves an undelimited equation untouched', () => {+ expect( extractDelimiters( ' x^2 ' ) ).toEqual( { equation: 'x^2', display: false } );+ } );+ } );+} );++describe( 'utils: MathJax version detection', () => {+ it( 'recognises a MathJax 3 object by its three-part version starting with 3', () => {+ expect( isMathJaxVersion3( { version: '3.2.2' } ) ).toBe( true );+ } );++ it( 'rejects anything that is not MathJax 3', () => {+ expect( isMathJaxVersion3( undefined ) ).toBe( false );+ expect( isMathJaxVersion3( null ) ).toBe( false );+ expect( isMathJaxVersion3( '3.2.2' ) ).toBe( false );+ expect( isMathJaxVersion3( {} ) ).toBe( false );+ expect( isMathJaxVersion3( { version: 3 } ) ).toBe( false );+ expect( isMathJaxVersion3( { version: '3.2' } ) ).toBe( false );+ expect( isMathJaxVersion3( { version: '2.7.9' } ) ).toBe( false );+ } );++ it( 'recognises a MathJax 2 object by its Hub', () => {+ expect( isMathJaxVersion2( { Hub: {} } ) ).toBe( true );+ } );++ it( 'rejects anything without a Hub', () => {+ expect( isMathJaxVersion2( undefined ) ).toBe( false );+ expect( isMathJaxVersion2( null ) ).toBe( false );+ expect( isMathJaxVersion2( 'Hub' ) ).toBe( false );+ expect( isMathJaxVersion2( {} ) ).toBe( false );+ } );+} );