Files
monkey-ai-web/src/components/common/ui/richTextContent.js
T

87 lines
2.3 KiB
JavaScript

/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { articleImageSource } from './richTextImages.js';
const TAGS = new Set([
'P',
'DIV',
'H2',
'H3',
'BR',
'B',
'STRONG',
'I',
'EM',
'U',
'UL',
'OL',
'LI',
'IMG',
'SPAN',
'BLOCKQUOTE',
]);
export function sanitizeArticleHtml(html) {
const template = document.createElement('template');
template.innerHTML = String(html || '');
const clean = (node) => {
for (const child of [...node.children]) {
if (
[
'SCRIPT',
'STYLE',
'IFRAME',
'OBJECT',
'SVG',
'MATH',
'LINK',
'META',
].includes(child.tagName)
) {
child.remove();
continue;
}
clean(child);
if (!TAGS.has(child.tagName)) {
child.replaceWith(...child.childNodes);
continue;
}
const src = child.getAttribute('src');
for (const attribute of [...child.attributes])
child.removeAttribute(attribute.name);
if (child.tagName === 'IMG') {
const source = articleImageSource(src);
if (source) {
child.setAttribute('src', source);
child.setAttribute('alt', '文章配图');
} else child.remove();
}
}
};
clean(template.content);
// Quill images are inline embeds; standalone images need their own paragraph.
for (const child of [...template.content.children]) {
if (child.tagName !== 'IMG') continue;
const paragraph = document.createElement('p');
child.replaceWith(paragraph);
paragraph.append(child);
}
return template.innerHTML;
}