fix: fix some issue with new generateSidebar function

This commit is contained in:
kiameow
2024-07-29 20:33:15 +08:00
parent eee42b867f
commit aa18da125a
7 changed files with 57 additions and 29 deletions

View File

@@ -51,11 +51,11 @@ export default withMermaid({
sidebar: {
'/': main_sidebar(),
'/1.杭电生存指南/': generateSidebar('1.杭电生存指南', ['static']),
'/2.编程模块/': generateSidebar('2.编程模块', ['static']),
'/3.AI模块/': generateSidebar('3.AI模块', ['static']),
'/4.WEB模块/': generateSidebar('4.WEB模块', ['static']),
'/5.安全模块/': generateSidebar('5.安全模块', ['static']),
'/1.杭电生存指南/': await generateSidebar('1.杭电生存指南'),
'/2.编程模块/': await generateSidebar('2.编程模块'),
'/3.AI模块/': await generateSidebar('3.AI模块'),
'/4.WEB模块/': await generateSidebar('4.WEB模块'),
'/5.安全模块/': await generateSidebar('5.安全模块'),
'/2023旧版内容/': main_sidebar_old(),
'/2023旧版内容/2.高效学习/': chapter2_old(),
'/2023旧版内容/3.编程思维体系构建/': chapter3_old(),

View File

@@ -1,4 +1,4 @@
import fs from 'fs';
import fs from 'fs/promises';
import path from 'path';
export function main_sidebar() {
@@ -546,31 +546,58 @@ function compareNumericPrefixes(a, b) {
return 0;
}
// Function to generate sidebar items
/**
*
* @param {String} dir the start folder to scan
* @param {String[]} excludeDir exclude unwanted folder
* @returns
*/
export function generateSidebar(dir, excludeDir = []) {
const files = fs.readdirSync(dir);
export async function generateSidebarBasic(dir, excludeDir = [], maxDepth, currentDepth = 0) {
if (currentDepth >= maxDepth)
console.warn("the file depth is beyond the maxium depth that your sidebar can show!");
const files = await fs.readdir(dir);
const sortedFiles = files.sort(compareNumericPrefixes);
return sortedFiles.map((file) => {
const fullPath = path.join(dir, file);
if (fs.statSync(fullPath).isDirectory()) {
if (excludeDir.includes(file)) {
return null; // Skip excluded directories
const sidebar = await Promise.all(
sortedFiles.map(async (file) => {
const fullPath = path.join(dir, file);
const stats = await fs.stat(fullPath);
if (stats.isDirectory()) {
if (excludeDir.includes(file)) return null; // Skip excluded directories
return {
text: file,
collapsed: true,
items: await generateSidebarBasic(fullPath, excludeDir, maxDepth, ++currentDepth),
};
} else if (file.endsWith('.md')) {
return {
text: file.replace('.md', ''),
link: `/${fullPath.replace('.md', '')}`,
};
}
return {
text: file,
collapsed: true,
items: generateSidebar(fullPath, excludeDir),
};
} else if (file.endsWith('.md')) {
return { text: file.replace('.md', ''), link: `/${fullPath.replace('.md', '')}` };
}
}).filter(Boolean);
})
);
return sidebar.filter(Boolean);
}
export async function generateSidebar(
dir,
{
excludeDir = ['static'],
previousLevel = '/',
previousLevelDescription = '返回上一层',
topLevelName,
maxDepth = 5
} = {}
) {
const sidebar = [
{
text: previousLevelDescription,
link: previousLevel,
},
{
text: topLevelName ?? dir,
collapsed: false,
items: await generateSidebarBasic(dir, excludeDir, maxDepth),
},
];
return sidebar;
}