-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsidebarsPapers.js
More file actions
167 lines (143 loc) · 5.35 KB
/
Copy pathsidebarsPapers.js
File metadata and controls
167 lines (143 loc) · 5.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
import fs from 'fs';
import path from 'path';
/**
* Recursively counts Markdown (.md) files in a directory and its subdirectories.
* Excludes hidden entries (names starting with '.') and '_category_.json'.
*
* @param {string} directoryPath Absolute path to the target directory.
* @return {number} Total count of Markdown files.
*/
function countMarkdownFiles(directoryPath) {
let total = 0;
const entries = fs.readdirSync(directoryPath);
for (const entry of entries) {
if (entry.startsWith('.') || entry === '_category_.json') {
continue;
}
const entryPath = path.join(directoryPath, entry);
const stats = fs.statSync(entryPath);
if (stats.isDirectory()) {
total += countMarkdownFiles(entryPath);
} else if (stats.isFile() && entry.endsWith('.md')) {
total++;
}
}
return total;
}
/**
* Encodes a relative POSIX path into a URL-friendly slug.
*
* @param {string} relativePath Relative POSIX path segments separated by '/'.
* @return {string} URL-encoded slug.
*/
function toSlug(relativePath) {
return relativePath
.replace(/\\/g, "/")
.split('/')
.map(segment => encodeURIComponent(segment))
.join('/');
}
/**
* Retrieves visible subdirectories of a directory, excluding hidden ones.
*
* @param {string} directoryPath Absolute path to the parent directory.
* @return {string[]} Alphabetically sorted list of visible subdirectory names.
*/
function getVisibleSubDirs(directoryPath) {
return fs
.readdirSync(directoryPath)
.filter(name => {
const subPath = path.join(directoryPath, name);
return !name.startsWith('.') && fs.statSync(subPath).isDirectory();
})
.sort((a, b) => {
// 檢查是否含有 _category_.json
const aHasCategory = fs.existsSync(path.join(directoryPath, a, '_category_.json'));
const bHasCategory = fs.existsSync(path.join(directoryPath, b, '_category_.json'));
// 含有 _category_.json 的資料夾排在前面
if (aHasCategory && !bHasCategory) return -1;
if (bHasCategory && !aHasCategory) return 1;
// 同類型的按字母順序排列
return a.localeCompare(b);
});
}
/**
* Builds a Docusaurus sidebar category item for a directory containing '_category_.json'.
* Subdirectories are listed first, followed by the current directory's markdown items.
*
* @param {string} absoluteDirPath Absolute path to the category directory.
* @param {string} relativeDirPath Relative POSIX path from the 'papers' base directory.
* @return {import('@docusaurus/plugin-content-docs').SidebarItem} Sidebar category item.
* @throws {Error} If the '_category_.json' file cannot be parsed.
*/
function buildCategoryItem(absoluteDirPath, relativeDirPath) {
const metaFilePath = path.join(absoluteDirPath, '_category_.json');
let metadata;
try {
metadata = JSON.parse(fs.readFileSync(metaFilePath, 'utf8'));
} catch (err) {
throw new Error(`Failed to parse ${metaFilePath}: ${err.message}`);
}
const baseLabel = metadata.label || path.basename(absoluteDirPath);
const itemCount = countMarkdownFiles(absoluteDirPath);
const label = `${baseLabel} (${itemCount})`;
const defaultSlug = `/category/${toSlug(relativeDirPath)}`;
const link = {
type: 'generated-index',
slug: metadata.link?.slug || defaultSlug,
title: metadata.link?.title || baseLabel,
...metadata.link,
};
const hasOwnMd = fs
.readdirSync(absoluteDirPath)
.some(file => file.endsWith('.md'));
const items = [
// 1. 子資料夾項目(含 _category_.json 的目錄遞迴呼叫)
...getVisibleSubDirs(absoluteDirPath).map(subDir => {
const subAbsPath = path.join(absoluteDirPath, subDir);
const subRelPath = path.posix.join(relativeDirPath, subDir);
return fs.existsSync(path.join(subAbsPath, '_category_.json'))
? buildCategoryItem(subAbsPath, subRelPath)
: { type: 'autogenerated', dirName: subRelPath };
}),
// 2. 本層 Markdown 自動產生項目(若存在 .md 檔)
...(hasOwnMd ? [{ type: 'autogenerated', dirName: relativeDirPath }] : []),
];
return { type: 'category', label, link, items };
}
/**
* Generates the Docusaurus sidebar configuration for the 'papers' directory.
*
* @return {{papersSidebar: import('@docusaurus/plugin-content-docs').SidebarItem[]}}
* Sidebar configuration object.
*/
function generateSidebarConfig() {
const baseDir = path.join(__dirname, 'papers');
const sidebarItems = ['intro'];
const subDirs = getVisibleSubDirs(baseDir);
// 優先處理有 _category_.json 的子目錄
for (const dirName of subDirs) {
const absDirPath = path.join(baseDir, dirName);
const catConfigPath = path.join(absDirPath, '_category_.json');
if (fs.existsSync(catConfigPath)) {
sidebarItems.push(buildCategoryItem(absDirPath, dirName));
}
}
// 再處理純自動產生的子目錄
for (const dirName of subDirs) {
const absDirPath = path.join(baseDir, dirName);
const catConfigPath = path.join(absDirPath, '_category_.json');
if (!fs.existsSync(catConfigPath)) {
sidebarItems.push({ type: 'autogenerated', dirName });
}
}
// 統計所有筆記數量
const totalNotes = countMarkdownFiles(baseDir);
sidebarItems.push({
type: 'link',
label: `All Notes: ${totalNotes} entries`,
href: '/papers/intro',
});
return { papersSidebar: sidebarItems };
}
export default generateSidebarConfig();