tiptap: fix set title

This commit is contained in:
fantasticit 2022-06-21 21:32:59 +08:00
parent de824badee
commit 6abd21545c
1 changed files with 22 additions and 24 deletions

View File

@ -5,28 +5,35 @@ const renderer = new Renderer();
/**
* HTML prosemirror node
* @param body
* @param forceATitle
* @param needTitle
* @param defaultTitle heading paragraph
* @returns
*/
export const htmlToPromsemirror = (body, forceATitle = false, defaultTitle = '') => {
export const htmlToPromsemirror = (body, needTitle = false, defaultTitle = '') => {
const json = renderer.render(body);
// 设置标题
if (forceATitle) {
const forceTitleNode = json.content.find((node) => {
return node.type === 'heading' || node.type === 'paragraph';
});
if (needTitle) {
if (json.content[0].type !== 'title') {
const forceTitleNode = json.content.find((node) => {
return node.type === 'heading' || node.type === 'paragraph';
});
json.content.unshift({
type: 'title',
content: [
{
type: 'text',
text: defaultTitle || forceTitleNode?.content[0]?.text.slice(0, 50),
},
],
});
json.content.unshift({
type: 'title',
content: [
{
type: 'text',
text: defaultTitle || forceTitleNode?.content[0]?.text.slice(0, 50) || '未命名标题',
},
],
});
}
} else {
if (json.content[0].type === 'title') {
json.content[0].type = 'paragraph';
json.content[0].attrs = {};
}
}
const nodes = json.content;
@ -48,14 +55,5 @@ export const htmlToPromsemirror = (body, forceATitle = false, defaultTitle = '')
}
}
// trailing node
result.content.push({
type: 'paragraph',
attrs: {
indent: 0,
textAlign: 'left',
},
});
return result;
};