]> Lady’s Gitweb - GitWikiWeb/blobdiff - build.js
Render footnotes inside of doc content
[GitWikiWeb] / build.js
index 4f996a3232cf7bf195035813e872a8d05111140e..3d3a862c3f09af3e5ddc72dc9a89934a4c5263c2 100644 (file)
--- a/build.js
+++ b/build.js
@@ -20,7 +20,7 @@
 //     export GITWIKIWEB=/srv/git/GitWikiWeb
 //     git archive --remote=$GITWIKIWEB HEAD build.js \
 //       | tar -xO \
-//       | deno run -A - ~/public/wiki $GITWIKIWEB
+//       | deno run -A - ~/public/wiki $GITWIKIWEB current
 //
 // The directory `~/public/wiki` (or whatever you specify as the first
 // argument to `deno run -A -`) **will be deleted** and a new static
 import {
   emptyDir,
   ensureDir,
-} from "https://deno.land/std@0.195.0/fs/mod.ts";
+} from "https://deno.land/std@0.196.0/fs/mod.ts";
+import {
+  JSON_SCHEMA,
+  parse as parseYaml,
+} from "https://deno.land/std@0.196.0/yaml/mod.ts";
 import djot from "npm:@djot/djot@0.2.3";
 import { Parser } from "npm:htmlparser2@9.0.0";
 import { DomHandler, Element, Text } from "npm:domhandler@5.0.3";
@@ -46,6 +50,7 @@ import domSerializer from "npm:dom-serializer@2.0.0";
 
 const DESTINATION = Deno.args[0] ?? "~/public/wiki";
 const REMOTE = Deno.args[1] ?? "/srv/git/GitWikiWeb";
+const REV = Deno.args[2] ?? "HEAD";
 
 const READ_ONLY = {
   configurable: false,
@@ -53,6 +58,8 @@ const READ_ONLY = {
   writable: false,
 };
 
+const NIL = Object.preventExtensions(Object.create(null));
+
 const rawBlock = (strings, ...substitutions) => ({
   tag: "raw_block",
   format: "html",
@@ -87,7 +94,7 @@ const getDOM = (source) => {
 
 const getRemoteContent = async (pathName) => {
   const getArchive = new Deno.Command("git", {
-    args: ["archive", `--remote=${REMOTE}`, "HEAD", pathName],
+    args: ["archive", `--remote=${REMOTE}`, REV, pathName],
     stdout: "piped",
     stderr: "piped",
   }).spawn();
@@ -171,7 +178,7 @@ const listOfInternalLinks = (references, wrapper = ($) => $) => ({
   ),
 });
 
-const diffReferences = async (hash) => {
+const diffReferences = async (hash, againstHead = false) => {
   const diff = new Deno.Command("git", {
     args: [
       "diff-tree",
@@ -180,7 +187,7 @@ const diffReferences = async (hash) => {
       "--name-only",
       "--no-renames",
       "--diff-filter=AM",
-      hash,
+      ...(againstHead ? [hash, "HEAD"] : [hash]),
     ],
     stdout: "piped",
     stderr: "piped",
@@ -215,7 +222,7 @@ class GitWikiWebPage {
   #internalLinks = new Set();
   #externalLinks = new Map();
 
-  constructor(namespace, name, ast, source) {
+  constructor(namespace, name, ast, source, config) {
     const internalLinks = this.#internalLinks;
     const externalLinks = this.#externalLinks;
     const sections = Object.create(null);
@@ -228,7 +235,6 @@ class GitWikiWebPage {
             const links_section = [];
             if (internalLinks.size || externalLinks.size) {
               links_section.push(
-                rawBlock`<footer>`,
                 rawBlock`<nav id="links">`,
                 {
                   tag: "heading",
@@ -238,7 +244,7 @@ class GitWikiWebPage {
               );
               if (internalLinks.size) {
                 links_section.push(
-                  rawBlock`<details>`,
+                  rawBlock`<details open="">`,
                   rawBlock`<summary>on this wiki</summary>`,
                   listOfInternalLinks(internalLinks),
                   rawBlock`</details>`,
@@ -248,7 +254,7 @@ class GitWikiWebPage {
               }
               if (externalLinks.size) {
                 links_section.push(
-                  rawBlock`<details>`,
+                  rawBlock`<details open="">`,
                   rawBlock`<summary>elsewhere on the Web</summary>`,
                   {
                     tag: "bullet_list",
@@ -287,12 +293,16 @@ class GitWikiWebPage {
               }
               links_section.push(
                 rawBlock`</nav>`,
-                rawBlock`</footer>`,
               );
             } else {
               /* do nothing */
             }
-            e.children.push(...links_section);
+            e.children.push(
+              rawBlock`<footer>`,
+              rawBlock`${"\uFFFF"}`, // footnote placeholder
+              ...links_section,
+              rawBlock`</footer>`,
+            );
           },
         },
         hard_break: {
@@ -446,6 +456,20 @@ class GitWikiWebPage {
           },
           exit: (_) => {},
         },
+        symb: {
+          enter: (e) => {
+            const { alias } = e;
+            const codepoint = /^U\+([0-9A-Fa-f]+)$/u.exec(alias)?.[1];
+            if (codepoint) {
+              return str`${
+                String.fromCodePoint(parseInt(codepoint, 16))
+              }`;
+            } else {
+              const resolved = config.symbols?.[alias];
+              return resolved != null ? str`${resolved}` : e;
+            }
+          },
+        },
       };
     });
     Object.defineProperties(this, {
@@ -470,8 +494,43 @@ class GitWikiWebPage {
 }
 
 {
+  // Patches for Djot HTML renderer.
+  const { HTMLRenderer: { prototype: htmlRendererPrototype } } = djot;
+  const { inTags: upstreamInTags } = htmlRendererPrototype;
+  htmlRendererPrototype.inTags = function (
+    tag,
+    node,
+    newlines,
+    extraAttrs = undefined,
+  ) {
+    const attributes = node.attributes ?? NIL;
+    if ("as" in attributes) {
+      const newTag = attributes.as;
+      delete attributes.as;
+      return upstreamInTags.call(
+        this,
+        newTag,
+        node,
+        newlines,
+        extraAttrs,
+      );
+    } else {
+      return upstreamInTags.call(
+        this,
+        tag,
+        node,
+        newlines,
+        extraAttrs,
+      );
+    }
+  };
+}
+{
+  const config = await getRemoteContent("config.yaml").then((yaml) =>
+    parseYaml(yaml, { schema: JSON_SCHEMA })
+  );
   const ls = new Deno.Command("git", {
-    args: ["ls-tree", "-rz", "live"],
+    args: ["ls-tree", "-rz", "HEAD"],
     stdout: "piped",
     stderr: "piped",
   }).spawn();
@@ -543,6 +602,7 @@ class GitWikiWebPage {
                     console.warn(`Djot(${reference}): ${$.render()}`),
                 }),
                 source,
+                config,
               );
               const reference = `${namespace}:${pageName}`;
               pages.set(reference, page);
@@ -564,6 +624,7 @@ class GitWikiWebPage {
             console.warn(`Djot(${reference}): ${$.render()}`),
         }),
         source,
+        config,
       );
       pages.set(reference, page);
     }
@@ -615,7 +676,8 @@ class GitWikiWebPage {
         }
         const results = new Array(6);
         const seen = new Set();
-        let recency = 5;
+        const maxRecency = Math.max(config.max_recency | 0, 0);
+        let recency = maxRecency;
         let current;
         do {
           const show = new Deno.Command("git", {
@@ -623,7 +685,7 @@ class GitWikiWebPage {
               "show",
               "-s",
               "--format=%H%x00%cI%x00%cD",
-              recency ? `HEAD~${5 - recency}` : commit,
+              recency ? `HEAD~${maxRecency - recency}` : commit,
             ],
             stdout: "piped",
             stderr: "piped",
@@ -638,7 +700,9 @@ class GitWikiWebPage {
           ]).then(logErrorsAndCollectResults);
           const refs = [];
           current = hash;
-          for (const ref of (await diffReferences(current))) {
+          for (
+            const ref of (await diffReferences(current, !recency))
+          ) {
             if (seen.has(ref)) {
               /* do nothing */
             } else {
@@ -646,7 +710,7 @@ class GitWikiWebPage {
               seen.add(ref);
             }
           }
-          results[recency] = { dateTime, humanReadable, refs };
+          results[recency] = { dateTime, hash, humanReadable, refs };
         } while (recency-- > 0 && current && current != commit);
         return results;
       })(),
@@ -707,14 +771,16 @@ class GitWikiWebPage {
                             refs,
                           } = result;
                           yield* listOfInternalLinks(refs, (link) => ({
-                            tag: index ? "strong" : "span",
+                            tag: index == 0 ? "span" : "strong",
                             attributes: { "data-recency": `${index}` },
                             children: [
                               link,
-                              str` `,
-                              rawInline`<small>(<time dateTime="${dateTime}">`,
-                              str`${humanReadable}`,
-                              rawInline`</time>)</small>`,
+                              ...(index == 0 ? [] : [
+                                str` `,
+                                rawInline`<small>(<time dateTime="${dateTime}">`,
+                                str`${humanReadable}`,
+                                rawInline`</time>)</small>`,
+                              ]),
                             ],
                           })).children;
                         } else {
@@ -740,7 +806,9 @@ class GitWikiWebPage {
                     },
                     rawBlock`<details id="navigation-about" open="">`,
                     rawBlock`<summary>about this listing</summary>`,
+                    rawBlock`<article>`,
                     ...e.children,
+                    rawBlock`</article>`,
                     rawBlock`</details>`,
                   ],
                   navigation: [
@@ -761,7 +829,7 @@ class GitWikiWebPage {
           },
           heading: {
             enter: (e) => {
-              const attributes = e.attributes ?? Object.create(null);
+              const attributes = e.attributes ?? NIL;
               if (
                 isNavigationPage && e.level == 1 &&
                 attributes?.class == "main"
@@ -804,8 +872,7 @@ class GitWikiWebPage {
                 }
                 if (children.length == 0) {
                   const section =
-                    pages.get(reference)?.sections?.main ??
-                      Object.create(null);
+                    pages.get(reference)?.sections?.main ?? NIL;
                   const { v } = attributes;
                   if (v == null) {
                     children.push(
@@ -857,8 +924,25 @@ class GitWikiWebPage {
           },
         };
       });
+      const renderedAST = djot.renderAST(ast);
       const doc = getDOM(template);
-      const result = getDOM(`${djot.renderHTML(ast)}`);
+      const result = getDOM(djot.renderHTML(ast, {
+        overrides: {
+          raw_block: (node, context) => {
+            if (node.format == "html" && node.text == "\uFFFF") {
+              if (context.nextFootnoteIndex > 1) {
+                const result = context.renderNotes(ast.footnotes);
+                context.nextFootnoteIndex = 1;
+                return result;
+              } else {
+                return "";
+              }
+            } else {
+              return context.renderAstNodeDefault(node);
+            }
+          },
+        },
+      }));
       const headElement = domutils.findOne(
         (node) => node.name == "head",
         doc,
@@ -898,7 +982,7 @@ class GitWikiWebPage {
           "GitWikiWeb: Template did not include a <gitwikiweb-content> element.",
         );
       } else {
-        for (const node of result) {
+        for (const node of [...result]) {
           domutils.prepend(contentElement, node);
         }
         domutils.removeElement(contentElement);
@@ -915,6 +999,13 @@ class GitWikiWebPage {
           { createNew: true },
         ),
       );
+      promises.push(
+        Deno.writeTextFile(
+          `${DESTINATION}/${pageRef}/index.ast`,
+          renderedAST,
+          { createNew: true },
+        ),
+      );
       promises.push(
         Deno.writeTextFile(
           `${DESTINATION}/${pageRef}/source.djot`,
This page took 0.030969 seconds and 4 git commands to generate.