@@ -162,42 +162,50 @@ function set(obj, path, value) {
162162}
163163
164164/**
165− * getLinksinSubdirs is written to provide a recursive index of posts
166− * for nested directories for creating sidebars.
165+ * buildPageTree is written to provide a recursive index of posts
166+ * for nested directories for creating sidebars
167167 * @param {string} path Absolute path to the subdirectory.
168− * @returns {object} Nested object by directory with name of directory,
169− * child pages (as an array of objects with title, .md filename, slug, and weight),
170− * and subdirectories (named simply by the folder name). Iterate through the object
171− * recursively.
168+ * @returns {Object.<string,string|Object<string,string[]|number>>} Title of the directory, child pages, and child directories (recursive structure).
169+ *
172170 */
173171
174−export function getLinksinSubdirs(path) {
175− const allFiles = getAllFiles(path);
176− const fileTree = {};
177− allFiles.forEach((e) => {
178− const parsed = parse(e.substr(e.indexOf("content/") + 7));
179− const keys = parsed.dir.split("/").filter((e) => e !== "");
180− if (!get(fileTree, keys, false)) {
181− const fullPathofDir = join(
182− process.cwd(),
183− "/content",
184− parsed.dir,
185− "_index.md"
172+// type PageTree =
173+// { title: string,
174+// pages: [{
175+// title: string,
176+// base: string,
177+// slug: string,
178+// weight: number,
179+// }],
180+// children: { [string]: PageTree },
181+// }
182+
183+export function buildPageTree(path) {
184+ const metadata = matter(fs.readFileSync(join(path, "_index.md")), options);
185+
186+ const children = fs.readdirSync(path, { withFileTypes: true });
187+ const pages = children.filter((f) => f.isFile() && f.name !== "_index.md");
188+ const subdirs = children.filter((f) => f.isDirectory());
189+
190+ return {
191+ title: metadata.data.title,
192+ pages: pages.map((page) => {
193+ const { data: pageData } = matter(
194+ fs.readFileSync(join(path, page.name)),
195+ options
186196 );
187− const dirContents = fs.readFileSync(fullPathofDir, "utf8");
188− const { data: dirData } = matter(dirContents, options);
189− set(fileTree, keys, { title: dirData.title, pages: [] });
190− }
191− const fileContents = fs.readFileSync(e, "utf8");
192− const { data } = matter(fileContents, options);
193− if (!e.includes("_index.md")) {
194− get(fileTree, keys, false).pages.push({
195− title: data.title,
196− base: parsed.base,
197− slug: parsed.name,
198− weight: data?.weight ?? 0,
199− });
200− }
201− });
202− return fileTree;
197+ return {
198+ title: pageData.title,
199+ base: page.name,
200+ slug: page.name.replace(/.md$/, ""),
201+ weight: pageData?.weight ?? 0,
202+ };
203+ }),
204+ children: Object.fromEntries(
205+ subdirs.map((subdir) => [
206+ subdir.name,
207+ buildPageTree(join(path, subdir.name)),
208+ ])
209+ ),
210+ };
203211}