import { View, type Locale } from 'ckeditor5'; import type { KatexOptions } from '../typings-external.js'; import { renderEquation } from '../utils.js'; /** * Configuration options for the MathView. */ export interface MathViewOptions { engine: 'mathjax' | 'katex' | ( ( equation: string, element: HTMLElement, display: boolean ) => void ); lazyLoad: undefined | ( () => Promise ); previewUid: string; previewClassName: Array; katexRenderOptions: KatexOptions; } export default class MathView extends View { /** * The LaTeX equation value to render. * @observable */ public declare value: string; /** * Whether to render in display mode (centered) or inline. * @observable */ public declare display: boolean; /** * Configuration options passed during initialization. */ private options: MathViewOptions; constructor( locale: Locale, options: MathViewOptions ) { super( locale ); this.options = options; this.set( 'value', '' ); this.set( 'display', false ); // Update rendering when state changes. // Checking isRendered prevents errors during initialization. this.on( 'change', () => { if ( this.isRendered ) { this.updateMath(); } } ); this.setTemplate( { tag: 'div', attributes: { class: [ 'ck', 'ck-math-preview', 'ck-reset_all-excluded' ] } } ); } public updateMath(): void { if ( this.element ) { // This prevents the new render from appending to the old one. this.element.textContent = ''; void renderEquation( this.value, this.element, this.options.engine, this.options.lazyLoad, this.display, true, // isPreview this.options.previewUid, this.options.previewClassName, this.options.katexRenderOptions ); } } public override render(): void { super.render(); this.updateMath(); } }