aboutsummaryrefslogtreecommitdiffstats
path: root/app/pages.ts
diff options
context:
space:
mode:
authorLeonardo Bishop <me@leonardobishop.com>2023-08-05 21:11:48 +0100
committerLeonardo Bishop <me@leonardobishop.com>2023-08-05 21:11:48 +0100
commit18cc5f69129615850e48a995f7c3406b74d8d2f4 (patch)
tree1fdc6eadae4b0a6da69319f9b6733379ced2e4c2 /app/pages.ts
parent64c36dcef8ab1c0b985d79da627cecd30fd50336 (diff)
Redesign website
Diffstat (limited to 'app/pages.ts')
-rw-r--r--app/pages.ts87
1 files changed, 87 insertions, 0 deletions
diff --git a/app/pages.ts b/app/pages.ts
new file mode 100644
index 0000000..3bef4a9
--- /dev/null
+++ b/app/pages.ts
@@ -0,0 +1,87 @@
+import { readFileSync } from 'fs';
+import glob from 'glob';
+import { logger } from './logger.js'
+import { marked } from 'marked';
+import matter from 'gray-matter';
+
+export function buildPage(page: Page) {
+ logger.info(`Building ${page.path}`);
+ try {
+ const result = matter(page.raw);
+ const metadata = result.data;
+ const html = marked.parse(result.content, { mangle: false, headerIds: false });
+
+ page.html = html;
+ page.metadata = metadata;
+ page.buildTime = Date.now();
+ } catch (e) {
+ logger.error(`Failed to build page ${page.path}: ${e.message}`);
+ }
+}
+
+export namespace PageDirectory {
+ export const pages: Record<string, Page> = {};
+ export let lastBuild: number;
+
+ export const rebuild = (pagePath: string): boolean => {
+ for (const page in pages) {
+ delete pages[page];
+ }
+
+ const localPages = glob.sync(`**/*.{md,html}`, { cwd: pagePath })
+
+ // Load page content
+ localPages.forEach(page => {
+ let route = page.replace(/\.[^.]*$/,'')
+ let name = /[^/]*$/.exec(route)[0];
+ let path = `${pagePath}/${page}`
+ let raw: string;
+ try {
+ raw = loadRaw(path);
+ } catch (e) {
+ logger.error(`Failed to read page ${path}: ${e.message}`);
+ return;
+ }
+
+ pages[route] = {
+ route: route,
+ name: name,
+ path: path,
+ raw: raw,
+ buildTime: 0,
+ metadata: {
+ title: "A Page"
+ }
+ }
+ });
+
+ // Build pages
+ Object.values(pages).forEach(page => buildPage(page));
+
+ lastBuild = Date.now();
+ return true;
+ }
+
+ export function get(name: string): Page {
+ const page = pages[name];
+ if (!page) {
+ return undefined;
+ }
+
+ return page;
+ }
+
+ function loadRaw(path: string): string {
+ return readFileSync(`${path}`, 'utf-8');
+ }
+}
+
+export type Page = {
+ html?: string;
+ raw?: string;
+ route: string;
+ name: string;
+ path: string;
+ buildTime: number;
+ metadata: any;
+};