wiris / html-integrations

The official JavaScript library for MathType, the leading formula editor and equation writer for the web by Wiris
https://wiris.com/solutions/integrations/html-editors/
MIT License
78 stars 53 forks source link

Change CKEditor4 value with the latex format of the inputted mathtype #421

Closed henok-outlier closed 3 years ago

henok-outlier commented 3 years ago

Hi, from this comment(https://github.com/wiris/html-integrations/issues/383#issuecomment-915094862), I'm suggested to use params.node.outerHTML = latex, to change the CKEditor value with the latex value.

WirisPlugin.currentInstance.core.listeners.add(Listeners.newListener('onAfterFormulaInsertion', (params) => {
    const mathml = WirisPlugin.Parser.codeImgTransform(params.node.outerHTML, 'img2mathml');
    const latex = WirisPlugin.Latex.getLatexFromMathML(mathml);
    params.node.outerHTML = latex
  }));

Butthe above code only changes the expression displayed in the CKEditor, but the actually value got in onChange event of the CKEditor is in MathML format.

<CKEditor4
        data={fieldValue}
        config={CKEDITOR_CONFIG}
        onBeforeLoad={CKEDITOR => this.handleBeforeLoad(CKEDITOR)}
        onChange={evt => {
          const data = evt.editor.getData()
          console.log({ data }) 
          this.setState({ text: data })
        }}
        onBlur={this.handleOnBlur}
      />

evt.editor.getData() is MathML, but the expression is displayed in CKEditor as Latex. I want to change the editor data as well with the latex value, when setting params.node.outerHTML = latex;.

Records - #53351155 - Edit Training Dato CMS 2021-09-26 at 8 50 24 PM

henok-outlier commented 3 years ago

As a workaround, we can replace the editor data MathML, evt.editor.getData(), to Latex in onChange event handler.

export const MATHML_REGEX = /(<math xmlns="http:\/\/www\.w3\.org\/1998\/Math\/MathML">((.|\n)*?)<\/math>)/g

export const replaceMathMLWithLatex = mathml => {
  const isWirisLoaded = window.WirisPlugin?.Latex

  if (!isWirisLoaded) return mathml

  return mathml.replace(MATHML_REGEX, (_i, match) => {
    return window.WirisPlugin.Latex.getLatexFromMathML(match)
  })
}

So on change will be,

onChange={evt => {
   const data = evt.editor.getData()
   const latex = replaceMathMLWithLatex(data)
   this.setState({ text: latex })
 }}
carla-at-wiris commented 3 years ago

Hi @henok-outlier,

You are experimenting a discordance between the content in the editor and the content obtained by the onChange event because the onAfterFormulaInsertion event gets called after the onChange, so the data retrieved by it won't be the one you modified.

The workaround you purpose can be a good idea.