From 437268370661087dbe31323efb18dfe1a518da33 Mon Sep 17 00:00:00 2001 From: flu0r1ne Date: Wed, 21 Jul 2021 03:59:15 -0500 Subject: Dynamic markdown page generation with preloading --- utils/Posts.tsx | 40 +++++++++++++++++++++++++--------------- utils/markedOptions.js | 12 ++++++++++++ 2 files changed, 37 insertions(+), 15 deletions(-) create mode 100644 utils/markedOptions.js (limited to 'utils') diff --git a/utils/Posts.tsx b/utils/Posts.tsx index e82357a..d82467e 100644 --- a/utils/Posts.tsx +++ b/utils/Posts.tsx @@ -1,5 +1,9 @@ import { promises as fs } from 'fs'; import path from 'path'; +import marked from 'marked'; +import markedOptions from './markedOptions'; + +marked.setOptions(markedOptions); interface PostMetadata { name: string; @@ -24,21 +28,24 @@ async function getMetadata(postPath : string) : Promise { return JSON.parse(postMetadata) as PostMetadata; } -async function getPosts() : Promise { - const postsDirectory = path.join(process.cwd(), 'posts'); - const directories = await fs.readdir(postsDirectory); +const POST_PATH = path.join(process.cwd(), 'posts'); + +async function getPostFromDirectory(directory : string) { + const postPath = path.join(POST_PATH, directory); + + const meta = await getMetadata(postPath); - const posts = directories.map(async (directory) => { - const postPath = path.join(postsDirectory, directory); - - const meta = await getMetadata(postPath); + return { + directory, + path: postPath, + meta + }; +} + +async function getPosts() : Promise { + const directories = await fs.readdir(POST_PATH); - return { - directory, - path: postPath, - meta - }; - }); + const posts = directories.map(getPostFromDirectory); return await Promise.all(posts); } @@ -48,10 +55,13 @@ async function getMarkdown(post : Post) : Promise { const markdown = await fs.readFile(markdownPath, 'utf8'); - return markdown; + const html = marked(markdown); + + return html; } export { getPosts, - getMetadata, + getMarkdown, + getPostFromDirectory }; \ No newline at end of file diff --git a/utils/markedOptions.js b/utils/markedOptions.js new file mode 100644 index 0000000..ebc7a6f --- /dev/null +++ b/utils/markedOptions.js @@ -0,0 +1,12 @@ +const hljs = require('highlight.js'); + +function highlight(code, lang) { + const language = hljs.getLanguage(lang) ? lang : 'plaintext'; + + const highlighted = hljs.highlight(code, { language }).value; + return highlighted; +} + +module.exports = { + highlight +}; \ No newline at end of file -- cgit v1.2.3