minor: add latex node in description editor (#16948)

* minor: add latex node in description editor

* minor: refactor CustomHtmlRederer to replace LaTeX content in RichTextEditorPreviewer
This commit is contained in:
Sachin Chaurasiya 2024-07-08 19:01:53 +05:30 committed by GitHub
parent 9012c738e0
commit ce1a23c3be
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 97 additions and 2 deletions

View File

@ -24,6 +24,7 @@ import {
MdNode,
} from '@toast-ui/editor';
import { t } from 'i18next';
import katex from 'katex';
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import { ReactComponent as CopyIcon } from '../../../../assets/svg/icon-copy.svg';
@ -241,4 +242,39 @@ export const customHTMLRenderer: CustomHTMLRenderer = {
{ type: 'closeTag', tagName: 'section', outerNewLine: true },
];
},
latex(node) {
const content = katex.renderToString(node.literal ?? '', {
throwOnError: false,
output: 'mathml',
});
return [
{ type: 'openTag', tagName: 'div', outerNewLine: true },
{ type: 'html', content: content },
{ type: 'closeTag', tagName: 'div', outerNewLine: true },
];
},
};
export const replaceLatex = (content: string) => {
try {
const latexPattern = /\$\$latex[\s\S]*?\$\$/g;
const latexContentPattern = /\$\$latex\s*([\s\S]*?)\s*\$\$/g;
return content.replace(latexPattern, (latex) => {
const matches = [...latex.matchAll(latexContentPattern)];
if (matches.length === 0) {
return latex;
}
return katex.renderToString(matches[0][1] ?? '', {
throwOnError: false,
output: 'mathml',
});
});
} catch (error) {
return content;
}
};

View File

@ -0,0 +1,53 @@
/*
* Copyright 2024 Collate.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* eslint-disable max-len */
import { replaceLatex } from './CustomHtmlRederer';
jest.mock('katex', () => ({
renderToString: jest.fn().mockReturnValue('latex content'),
}));
describe('replaceLatex', () => {
it('returns the original string if no LaTeX is present', () => {
const input = 'This is a test string without LaTeX.';
const output = replaceLatex(input);
expect(output).toBe(input);
});
it('replaces LaTeX content correctly', () => {
const content =
'<span class="ant-typography" data-testid="diff-normal">This dimension table contains a row for each channel or app that your customers use to create orders. Some examples of these include Facebook and Online Store. You can join this table with the sales table to measure channel performance.</span><span class="ant-typography diff-added" data-testid="diff-added"><u>\n\n$$latex\n\text{$dfrac{NetSales}{Quantity Invoiced}=Average Price, :$ If QuantityInvoiced is Null then,$: AveragePrice=Null$}\n$$</u></span>';
const output = replaceLatex(content);
expect(output).toContain('latex content');
expect(output).not.toContain('$$latex');
});
it('replaces multiple LaTeX contents correctly', () => {
const content = `$$latex \\frac{a}{b}$$ $$latex \\frac{c}{d}$$`;
const output = replaceLatex(content);
expect(output).toContain('latex content latex content');
});
it('returns the original LaTeX string if it is malformed', () => {
const malformedLatex = '$$latex \\frac{a}{b}';
const input = `This is malformed: ${malformedLatex}`;
const output = replaceLatex(input);
expect(output).toContain(malformedLatex);
});
});

View File

@ -24,6 +24,7 @@ import React, {
useState,
} from 'react';
import i18n from '../../../utils/i18next/LocalUtil';
import { customHTMLRenderer } from './CustomHtmlRederer/CustomHtmlRederer';
import { EDITOR_TOOLBAR_ITEMS } from './EditorToolBar';
import './rich-text-editor.less';
import { editorRef, RichTextEditorProp } from './RichTextEditor.interface';
@ -103,6 +104,7 @@ const RichTextEditor = forwardRef<editorRef, RichTextEditorProp>(
dir={i18n.dir()}>
<Viewer
extendedAutolinks={extendedAutolinks}
customHTMLRenderer={customHTMLRenderer}
initialValue={editorValue}
key={uniqueId()}
ref={richTextEditorRef}
@ -121,6 +123,7 @@ const RichTextEditor = forwardRef<editorRef, RichTextEditorProp>(
previewHighlight={previewHighlight}
previewStyle={previewStyle}
ref={richTextEditorRef}
customHTMLRenderer={customHTMLRenderer}
toolbarItems={[EDITOR_TOOLBAR_ITEMS]}
useCommandShortcut={useCommandShortcut}
onChange={onChangeHandler}

View File

@ -20,7 +20,10 @@ import { useTranslation } from 'react-i18next';
import { DESCRIPTION_MAX_PREVIEW_CHARACTERS } from '../../../constants/constants';
import { formatContent, isHTMLString } from '../../../utils/BlockEditorUtils';
import { getTrimmedContent } from '../../../utils/CommonUtils';
import { customHTMLRenderer } from './CustomHtmlRederer/CustomHtmlRederer';
import {
customHTMLRenderer,
replaceLatex,
} from './CustomHtmlRederer/CustomHtmlRederer';
import './rich-text-editor-previewer.less';
import { PreviewerProp } from './RichTextEditor.interface';
@ -112,7 +115,7 @@ const RichTextEditorPreviewer = ({
<Viewer
extendedAutolinks
customHTMLRenderer={customHTMLRenderer}
initialValue={viewerValue}
initialValue={replaceLatex(viewerValue)}
key={uniqueId()}
linkAttributes={{ target: '_blank' }}
/>