2021-11-23 08:26:02 +02:00
|
|
|
/* eslint-disable import/prefer-default-export */
|
2022-04-24 18:48:35 +03:00
|
|
|
import React, { lazy, Suspense } from 'react';
|
|
|
|
|
2021-11-23 08:26:02 +02:00
|
|
|
import linkifyHtml from 'linkifyjs/html';
|
|
|
|
import parse from 'html-react-parser';
|
|
|
|
import twemoji from 'twemoji';
|
|
|
|
import { sanitizeText } from './sanitize';
|
|
|
|
|
2022-04-24 18:48:35 +03:00
|
|
|
const Math = lazy(() => import('../app/atoms/math/Math'));
|
|
|
|
|
|
|
|
const mathOptions = {
|
|
|
|
replace: (node) => {
|
|
|
|
const maths = node.attribs?.['data-mx-maths'];
|
|
|
|
if (maths) {
|
|
|
|
return (
|
|
|
|
<Suspense fallback={<code>{maths}</code>}>
|
|
|
|
<Math
|
|
|
|
content={maths}
|
|
|
|
throwOnError={false}
|
|
|
|
errorColor="var(--tc-danger-normal)"
|
|
|
|
displayMode={node.name === 'div'}
|
|
|
|
/>
|
|
|
|
</Suspense>
|
|
|
|
);
|
|
|
|
}
|
|
|
|
return null;
|
|
|
|
},
|
|
|
|
};
|
|
|
|
|
2021-11-23 08:26:02 +02:00
|
|
|
/**
|
|
|
|
* @param {string} text - text to twemojify
|
|
|
|
* @param {object|undefined} opts - options for tweomoji.parse
|
|
|
|
* @param {boolean} [linkify=false] - convert links to html tags (default: false)
|
|
|
|
* @param {boolean} [sanitize=true] - sanitize html text (default: true)
|
2022-04-24 18:48:35 +03:00
|
|
|
* @param {boolean} [maths=false] - render maths (default: false)
|
2021-11-23 08:26:02 +02:00
|
|
|
* @returns React component
|
|
|
|
*/
|
2022-04-24 18:48:35 +03:00
|
|
|
export function twemojify(text, opts, linkify = false, sanitize = true, maths = false) {
|
2021-11-23 08:26:02 +02:00
|
|
|
if (typeof text !== 'string') return text;
|
2022-01-25 08:45:47 +02:00
|
|
|
let content = text;
|
|
|
|
|
|
|
|
if (sanitize) {
|
|
|
|
content = sanitizeText(content);
|
|
|
|
}
|
|
|
|
content = twemoji.parse(content, opts);
|
2021-11-23 08:26:02 +02:00
|
|
|
if (linkify) {
|
2022-01-25 08:45:47 +02:00
|
|
|
content = linkifyHtml(content, {
|
|
|
|
target: '_blank',
|
|
|
|
rel: 'noreferrer noopener',
|
|
|
|
});
|
2021-11-23 08:26:02 +02:00
|
|
|
}
|
2022-04-24 18:48:35 +03:00
|
|
|
return parse(content, maths ? mathOptions : null);
|
2021-11-23 08:26:02 +02:00
|
|
|
}
|