feat: add image alignment options and enhance image handling in ArticleEditorCanvas

This commit is contained in:
2026-04-05 23:41:58 +08:00
parent b08be076b2
commit fe124b0ba4
8 changed files with 821 additions and 28 deletions
+30 -1
View File
@@ -90,6 +90,35 @@ function baseContent(article: AdapterContext["article"]): string {
return markdownToHtml(article.markdown_content ?? "");
}
function wrapStandaloneImages(html: string): string {
if (typeof DOMParser === "undefined") {
return html.replace(/<img([^>]+src="[^"]+"[^>]*)>/gi, "<figure><img$1></figure>");
}
const doc = new DOMParser().parseFromString(`<div data-root="zhihu-content">${html}</div>`, "text/html");
const root = doc.body.querySelector('[data-root="zhihu-content"]');
if (!(root instanceof HTMLElement)) {
return html;
}
for (const image of [...root.querySelectorAll("img")]) {
if (image.closest("figure")) {
continue;
}
const parent = image.parentElement;
if (parent?.tagName === "P") {
continue;
}
const figure = doc.createElement("figure");
image.parentNode?.insertBefore(figure, image);
figure.appendChild(image);
}
return root.innerHTML.trim();
}
function transformContent(html: string): string {
let next = html.trim();
@@ -99,7 +128,7 @@ function transformContent(html: string): string {
next = next.replace(/\sdata-(?!draft)[a-z-]+="[^"]*"/gi, "");
next = next.replace(/<figure[^>]*>\s*(<img[\s\S]*?>)\s*<\/figure>/gi, "$1");
next = next.replace(/<pre><code class="language-([^"]+)">/gi, '<pre lang="$1"><code>');
next = next.replace(/<img([^>]+src="[^"]+"[^>]*)>/gi, "<figure><img$1></figure>");
next = wrapStandaloneImages(next);
return next;
}