From 7e8d3b510df17a7cf6dcac70de98d60cc9ca1ff7 Mon Sep 17 00:00:00 2001 From: carla-at-wiris Date: Wed, 27 Sep 2023 16:11:39 +0200 Subject: [PATCH] fix(ck5): setData understands LaTeX setData now understands math LaTeX formulas and writes them in the editor as LaTeX code --- CHANGES.md | 4 ++++ packages/ckeditor5/src/plugin.js | 29 +++++++++++++++++++++++++++-- 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 5db00140f..091474094 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -9,6 +9,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 Last release of this project is was 30th of September 2021. +### Unreleased + + - fix(ck5): setData understanding math LaTeX. #KB-39004 + ### 8.6.0 2023-10-10 - Feat: Add branch name and commit hash to demo page diff --git a/packages/ckeditor5/src/plugin.js b/packages/ckeditor5/src/plugin.js index b5fdbd363..80d61f714 100644 --- a/packages/ckeditor5/src/plugin.js +++ b/packages/ckeditor5/src/plugin.js @@ -401,8 +401,8 @@ export default class MathType extends Plugin { viewToModelPositionOutsideModelElement(editor.model, (viewElement) => viewElement.hasClass('ck-math-widget')), ); - // Keep a reference to the original get function - const { get } = editor.data; + // Keep a reference to the original get and set function. + const { get, set } = editor.data; /** * Hack to transform $$latex$$ into in editor.getData()'s output. @@ -414,6 +414,31 @@ export default class MathType extends Plugin { let imageFormula = Parser.initParse(output); return Parser.endParse(imageFormula); }; + + /** + * Hack to transform with LaTeX into $$LaTeX$$ in editor.setData(). + */ + editor.data.set = (data) => { + // Retrieve the data to be set on the CKEditor. + let modifiedData = data; + // Regex to find all mathml formulas. + const regexp = //gm; + + // Get all MathML formulas and store them in an array. + let formulas = [...data.matchAll(regexp)]; + + // Loop to find LaTeX formulas and replace the MathML for the LaTeX notation. + formulas.forEach((formula) => { + let mathml = formula[0]; + if (mathml.includes('encoding="LaTeX"')) { // LaTeX found. + let latex = '$$$' + Latex.getLatexFromMathML(mathml) + '$$$'; // We add $$$ instead of $$ because the replace function ignores one $. + modifiedData = modifiedData.replace(mathml, latex); + } + }); + + // Run the setData code from CKEditor5 with the modified string. + set.bind(editor.data)(modifiedData); + }; } /**