]> Lady’s Gitweb - Blog/blobdiff - build.js
Add highlighting support for code blocks
[Blog] / build.js
diff --git a/build.js b/build.js
new file mode 100755 (executable)
index 0000000..641bd94
--- /dev/null
+++ b/build.js
@@ -0,0 +1,62 @@
+#!/usr/bin/env -S deno run --allow-read --allow-write
+
+// Copyright © 2023 Lady [@ Lady’s Computer].
+//
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at <https://mozilla.org/MPL/2.0/>.
+
+import hljs from "npm:highlight.js@11.8.0";
+
+const processContent = (content) => {
+  if (content == null || Object(content) instanceof String) {
+    /* do nothing */
+  } else if (Array.isArray(content)) {
+    // The provided content is an array.
+    content.forEach(processContent);
+  } else {
+    for (const child of Array.from(content)) {
+      applyHighlighting(child);
+    }
+  }
+};
+
+const applyHighlighting = (node) => {
+  if (
+    node.localName == "pre" && node.childNodes.length == 1 &&
+    node.firstChild.localName == "code"
+  ) {
+    const code = node.firstChild;
+    const language = /language-(.*)/u.exec(code.getAttribute("class"))
+      ?.[1];
+    if (language) {
+      try {
+        const { value: highlight } = hljs.highlight(
+          node.firstChild.textContent,
+          { language },
+        );
+        const nodes = new DOMParser().parseFromString(
+          `<!DOCTYPE html><html><body>${highlight}</body></html>`,
+          "text/html",
+        ).documentElement.lastChild.childNodes;
+        code.textContent = "";
+        for (const node of Array.from(nodes)) {
+          code.appendChild(code.ownerDocument.importNode(node, true));
+        }
+      } catch (e) {
+        console.warn(e);
+      }
+    }
+  } else if (node.nodeType == 1) {
+    Array.from(node.childNodes).forEach(applyHighlighting);
+  }
+};
+
+globalThis.bjørnTransformMetadata = (metadata, _type) => {
+  processContent(metadata.content);
+  processContent(metadata.summary);
+};
+
+await import(
+  "https://git.ladys.computer/Beorn/blob_plain/0.2.1:/build.js"
+);
This page took 0.026726 seconds and 4 git commands to generate.