From b80a3fdc637b19dec50dbb29f63921e0ae92d8e7 Mon Sep 17 00:00:00 2001 From: taga3s Date: Sat, 14 Sep 2024 13:34:58 +0900 Subject: [PATCH] refactor(rehype-momiji): use visit --- .../rehype-momiji/buildCodeBlockHTML.ts | 52 +++++++++++-------- 1 file changed, 31 insertions(+), 21 deletions(-) diff --git a/app/modules/rehype-momiji/buildCodeBlockHTML.ts b/app/modules/rehype-momiji/buildCodeBlockHTML.ts index 9d80a71..eaf41e7 100644 --- a/app/modules/rehype-momiji/buildCodeBlockHTML.ts +++ b/app/modules/rehype-momiji/buildCodeBlockHTML.ts @@ -3,6 +3,7 @@ import { getHighlighter } from "./highlighter"; import { toHtml } from "hast-util-to-html"; import type { Element } from "hast"; import { COLOR_SHIRONERI, COLOR_HAI } from "./colors"; +import { visit } from "unist-util-visit"; const defaultHighlighter = await getHighlighter({ themes: bundledThemes, langs: bundledLanguages }); const defaultFilenameUIColor = `color: ${COLOR_SHIRONERI}; background-color: ${COLOR_HAI};`; @@ -13,30 +14,39 @@ const buildCodeBlockHTML = (rawCode: string, lang: string, filename: string, the theme: theme, }); - const targetElem = hast.children[0] as Element; - // Add filename to the code block if it exists - if (filename !== "" && targetElem) { - targetElem.properties = { - class: targetElem.properties.class, - style: `${targetElem.properties.style}; padding-top: 0px;`, - tabindex: targetElem.properties.tabindex, - }; + if (filename === "") { + return toHtml(hast); + } + + visit(hast, "element", (node: Element) => { + if ( + node.tagName === "pre" && + node.properties.class && + typeof node.properties.class === "string" && + node.properties.class.includes("shiki") + ) { + node.properties = { + class: node.properties.class, + style: `${node.properties.style}; padding-top: 0px;`, + tabindex: node.properties.tabindex, + }; - targetElem.children.unshift({ - type: "element", - tagName: "div", - properties: { - style: `width: fit-content; margin-bottom: 16px; padding: 4px 8px; font-size: 14px; border-radius: 0 0 4px 4px; ${defaultFilenameUIColor};`, - }, - children: [ - { - type: "text", - value: filename, + node.children.unshift({ + type: "element", + tagName: "div", + properties: { + style: `width: fit-content; margin-bottom: 16px; padding: 4px 8px; font-size: 14px; border-radius: 0 0 4px 4px; ${defaultFilenameUIColor};`, }, - ], - }); - } + children: [ + { + type: "text", + value: filename, + }, + ], + }); + } + }); return toHtml(hast); };