Skip to content

Commit

Permalink
refactor: optimize mdUtil
Browse files Browse the repository at this point in the history
  • Loading branch information
yangfuhai committed Dec 12, 2024
1 parent 010ddb6 commit 2767bd1
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 22 deletions.
25 changes: 25 additions & 0 deletions src/util/htmlUtil.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,3 +149,28 @@ export const clearDataMpSlice = (html: string) => {
tempDiv.appendChild(fragment)
return tempDiv.innerHTML;
}

export const organizeHTMLContent = (originalHtml: string) => {
if (!originalHtml) return "";
const parser = new DOMParser();
const doc = parser.parseFromString(originalHtml, 'text/html');
const lis = doc.querySelectorAll("li");

//"tiptap" does not support empty list items. Here to fill in the gaps
if (lis) lis.forEach(li => {
if (!li.innerHTML) li.innerHTML = "<p></p>"
})

let html = '';
for (let i = 0; i < doc.body.children.length; i++) {
const element = doc.body.children[i];
if (i == 0 && element.tagName === "P") {
html += element.innerHTML;
} else {
// https://gitee.com/aieditor-team/aieditor/pulls/10
html += element.querySelector("img")
? element.innerHTML : element.outerHTML;
}
}
return html;
}
24 changes: 2 additions & 22 deletions src/util/mdUtil.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import container from 'markdown-it-container';
import TurndownService from 'turndown'
// @ts-ignore
import {gfm, tables} from 'joplin-turndown-plugin-gfm';
import { organizeHTMLContent } from './htmlUtil';


const md = MarkdownIt({
Expand Down Expand Up @@ -77,30 +78,9 @@ export const mdToHtml = (markdown: string) => {
if (!markdown) return markdown;
const renderHtml = md.render(markdown).trim();
if (!renderHtml) return markdown;
const parser = new DOMParser();
const doc = parser.parseFromString(renderHtml, 'text/html');
const lis = doc.querySelectorAll("li");

//"tiptap" does not support empty list items. Here to fill in the gaps
if (lis) lis.forEach(li => {
if (!li.innerHTML) li.innerHTML = "<p></p>"
})

let html = '';
for (let i = 0; i < doc.body.children.length; i++) {
const element = doc.body.children[i];
if (i == 0 && element.tagName === "P") {
html += element.innerHTML;
} else {
// https://gitee.com/aieditor-team/aieditor/pulls/10
html += element.querySelector("img")
? element.innerHTML : element.outerHTML;
}
}
return html;
return organizeHTMLContent(renderHtml);
}


export const htmlToMd = (html: string) => {
if (!html) return html;
const parser = new DOMParser();
Expand Down

0 comments on commit 2767bd1

Please sign in to comment.