From 2767bd1ebb657678d5aa6e1066c4d6315963cd0a Mon Sep 17 00:00:00 2001 From: Michael Yang Date: Thu, 12 Dec 2024 12:06:28 +0800 Subject: [PATCH] refactor: optimize mdUtil --- src/util/htmlUtil.ts | 25 +++++++++++++++++++++++++ src/util/mdUtil.ts | 24 ++---------------------- 2 files changed, 27 insertions(+), 22 deletions(-) diff --git a/src/util/htmlUtil.ts b/src/util/htmlUtil.ts index 262cb23..8de73dc 100644 --- a/src/util/htmlUtil.ts +++ b/src/util/htmlUtil.ts @@ -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 = "

" + }) + + 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; +} diff --git a/src/util/mdUtil.ts b/src/util/mdUtil.ts index 1ec456c..8925e6c 100644 --- a/src/util/mdUtil.ts +++ b/src/util/mdUtil.ts @@ -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({ @@ -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 = "

" - }) - - 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();