Skip to content

Commit

Permalink
with the most recent syllabus
Browse files Browse the repository at this point in the history
  • Loading branch information
Lumi-works committed Aug 3, 2024
1 parent 102765c commit 7c5129e
Show file tree
Hide file tree
Showing 4 changed files with 553 additions and 64 deletions.
19 changes: 19 additions & 0 deletions lib/getPostMetadata.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import fs from "fs";
import matter from "gray-matter";

export default function getPostMetadata(basePath) {
const folder = basePath + "/";
const files = fs.readdirSync(folder);
const markdownPosts = files.filter((file) => file.endsWith(".md"));

// get the file data
const posts = markdownPosts.map((filename) => {
const fileContents = fs.readFileSync(`${basePath}/${filename}`, "utf8");
const matterResult = matter(fileContents);
return {
title: matterResult.data.title,
slug: filename.replace(".md", ""),
};
});
return posts;
}
55 changes: 55 additions & 0 deletions src/app/syllabus/Toc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
"use client";

import { useEffect, useState } from "react";
import { remark } from "remark";
import remarkParse from "remark-parse";
import remarkToc from "remark-toc";
import { toHAST } from "mdast-util-to-hast";
import { toString } from "hast-util-to-string";
import { visit } from "unist-util-visit";

function Toc({ markdown }) {
const [toc, setToc] = useState([]);

useEffect(() => {
const processMarkdown = async () => {
// Create a unified processor that can parse markdown
const processor = remark().use(remarkParse).use(remarkToc, {
heading: "Table of Contents",
tight: true,
maxDepth: 2,
});

// Parse the markdown and generate a table of contents
const tree = processor.parse(markdown);
const tocItems = [];

visit(tree, "listItem", (node) => {
const title = toString(toHAST(node));
const linkNode = node.children.find((child) => child.type === "link");
if (linkNode) {
const slug = linkNode.url.slice(1); // remove the leading '#'
tocItems.push({ title, slug });
}
});

setToc(tocItems);
};

processMarkdown();
}, [markdown]);

return (
<nav>
<ul>
{toc.map((item) => (
<li key={item.slug}>
<a href={`#${item.slug}`}>{item.title}</a>
</li>
))}
</ul>
</nav>
);
}

export default Toc;
Loading

0 comments on commit 7c5129e

Please sign in to comment.