Render JSON as HTML and escape unsupported extensions #5289
-
Hi, I am creating const plugins = [
BlockQuote,
// other extensions...
Text,
];
const html = generateHTML(JSON.parse(json) as unknown as JSONContent, plugins); But because some users are copy-pasting rich text from other places into the text editor at first, when they want to view it later, they face an error saying "HardBreak (or any other extension that is not defined in the plugins array) is not supported" or something along those lines. Is there any way to tell the generator function to skip those unknown/unsupported tags/extensions? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
You can try something like this: import { getSchema } from '@tiptap/core'
/**
* Get the invalid content from the `JSONContent`.
*/
function rewriteContent({ json, validMarks, validNodes }) {
if (json.marks && Array.isArray(json.marks)) {
json.marks = json.marks.filter(mark => {
const name = typeof mark === 'string' ? mark : mark.type
if (validMarks.has(name)) {
return true
}
// Just ignore any unknown marks
return false
})
}
if (json.content && Array.isArray(json.content)) {
json.content = Object.values(json.content).map(value => rewriteContent({
validMarks,
validNodes,
json: value,
}))
}
if (!validNodes.has(json.type)) {
// Just treat it like a paragraph and hope for the best
json.type = 'paragraph'
}
return json
}
export function rewriteUnknownContent(
json,
extensions,
) {
const schema = getSchema(extensions)
const validMarks = new Set(Object.keys(schema.marks))
const validNodes = new Set(Object.keys(schema.nodes))
return rewriteContent({
json,
validNodes,
validMarks,
})
} But I did not test it fully |
Beta Was this translation helpful? Give feedback.
You can try something like this: