From edd7aed7b203b7dd324998fa0803ea1fa5de167b Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Mon, 12 Sep 2022 23:08:59 +0100 Subject: [PATCH] fix: Line breaks inside of imported HTML image src fail import --- server/utils/turndown/images.ts | 27 +++++++++++++++++++++++++++ server/utils/turndown/index.ts | 2 ++ 2 files changed, 29 insertions(+) create mode 100644 server/utils/turndown/images.ts diff --git a/server/utils/turndown/images.ts b/server/utils/turndown/images.ts new file mode 100644 index 000000000..2fd4eb027 --- /dev/null +++ b/server/utils/turndown/images.ts @@ -0,0 +1,27 @@ +import TurndownService from "turndown"; + +/** + * A turndown plugin overriding inbuilt image parsing behavior + * + * @param turndownService The TurndownService instance. + */ +export default function images(turndownService: TurndownService) { + turndownService.addRule("image", { + filter: "img", + + replacement(content, node) { + // @ts-expect-error getAttribute exists + const alt = cleanAttribute(node.getAttribute("alt")); + // @ts-expect-error getAttribute exists + const src = (node.getAttribute("src") || "").replace(/\n+/g, ""); + // @ts-expect-error getAttribute exists + const title = cleanAttribute(node.getAttribute("title")); + const titlePart = title ? ' "' + title + '"' : ""; + return src ? "![" + alt + "]" + "(" + src + titlePart + ")" : ""; + }, + }); +} + +function cleanAttribute(attribute: string) { + return attribute ? attribute.replace(/(\n+\s*)+/g, "\n") : ""; +} diff --git a/server/utils/turndown/index.ts b/server/utils/turndown/index.ts index 1f5b810d5..7b17746af 100644 --- a/server/utils/turndown/index.ts +++ b/server/utils/turndown/index.ts @@ -3,6 +3,7 @@ import TurndownService from "turndown"; import breaks from "./breaks"; import confluenceCodeBlock from "./confluence-code-block"; import confluenceTaskList from "./confluence-task-list"; +import images from "./images"; /** * Turndown converts HTML to Markdown and is used in the importer code. @@ -25,6 +26,7 @@ const service = new TurndownService({ .use(gfm) .use(confluenceTaskList) .use(confluenceCodeBlock) + .use(images) .use(breaks); export default service;