writePage.js (view raw)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
const yaml = require("js-yaml");
import double from "./addons/double.js"; //NOTE delete from release
import rehypeDocument from "rehype-document";
import rehypeFormat from "rehype-format";
import rehypeParse from "rehype-parse";
import rehypeRaw from "rehype-raw";
import rehypeStringify from "rehype-stringify";
import rehypeWrap from "rehype-wrap";
import remarkFrontmatter from "remark-frontmatter";
import remarkParse from "remark-parse";
import remarkRehype from "remark-rehype";
import { readFile } from "fs-extra";
import { unified } from "unified";
import { writeComponent } from "./writeComponent.js";
export async function writePage(filepath) {
let page;
const processor = await unified()
.use(remarkParse)
.use(remarkFrontmatter, "yaml")
.use(() => (tree) => {
page = yaml.load(tree.children[0].value, {
schema: yaml.FAILSAFE_SCHEMA,
});
page.filename = filepath.split("/").pop().split(".").shift();
})
.use(double)
.use(remarkRehype, { allowDangerousHtml: true })
.use(rehypeRaw)
.use(rehypeWrap, { wrapper: "main" })
.use(rehypeFormat)
.use(rehypeStringify)
.process(await readFile(filepath, "utf-8"));
page.main = processor.value;
// console.log(page);
let recipe = ["before", "header", "main", "footer", "after"];
for (let i of [0, 1, 3, 4]) {
if (!Object.keys(page).includes(recipe[i])) {
recipe[i] = null;
}
}
let union = "";
for (let i of recipe.filter((x) => !!x)) {
if (i === "main") {
union += page.main;
} else {
union += await writeComponent(page[i], page);
}
}
const processor2 = unified()
.use(rehypeParse, { fragment: true })
.use(rehypeDocument, {
css: page.css ?? "style.css",
title: page?.title ?? page?.filename ?? "title",
link: [{ href: "favicon.png", rel: "icon", type: "image/png" }],
})
.use(rehypeFormat)
.use(rehypeStringify);
const output = await processor2.process(union);
return output.value;
}
|