Skip to content

Commit

Permalink
fix(ck5): setData understands LaTeX
Browse files Browse the repository at this point in the history
setData now understands math LaTeX formulas
and writes them in the editor as LaTeX code
  • Loading branch information
carla-at-wiris authored and icaparros-at-wiris committed Oct 23, 2023
1 parent 418a481 commit 7e8d3b5
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
4 changes: 4 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
29 changes: 27 additions & 2 deletions packages/ckeditor5/src/plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 <math> in editor.getData()'s output.
Expand All @@ -414,6 +414,31 @@ export default class MathType extends Plugin {
let imageFormula = Parser.initParse(output);
return Parser.endParse(imageFormula);
};

/**
* Hack to transform <math> 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 = /<math(.*?)<\/math>/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);
};
}

/**
Expand Down

0 comments on commit 7e8d3b5

Please sign in to comment.