@ohos-ports/rspress-plugin-auto-nav-sidebar 1.38.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +12 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +436 -0
- package/package.json +38 -0
- package/src/index.ts +258 -0
- package/src/modern-app-env.d.ts +1 -0
- package/src/type.ts +21 -0
- package/src/utils.ts +99 -0
- package/src/walk.ts +323 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2023-present Bytedance, Inc. and its affiliates.
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# @rspress/plugin-auto-nav-sidebar
|
|
2
|
+
|
|
3
|
+
The auto nav and sidebar plugin for [Rspress](https://rspress.dev).
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
# OpenHarmony port note
|
|
9
|
+
|
|
10
|
+
This package is the OpenHarmony (openharmony/arm64) port of `@rspress/plugin-auto-nav-sidebar`, published by the `@ohos-ports` organization as `@ohos-ports/rspress-plugin-auto-nav-sidebar@1.38.0-beta.1`.
|
|
11
|
+
|
|
12
|
+
It is content-identical to the upstream package except for the `package.json` identity/dependency redirects needed to route the runtime dependency chain to OpenHarmony-patched `@ohos-ports` packages.
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,436 @@
|
|
|
1
|
+
import * as __WEBPACK_EXTERNAL_MODULE_node_path__ from "node:path";
|
|
2
|
+
import * as __WEBPACK_EXTERNAL_MODULE__rspress_shared__ from "@rspress/shared";
|
|
3
|
+
import * as __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger__ from "@rspress/shared/logger";
|
|
4
|
+
import * as __WEBPACK_EXTERNAL_MODULE__rspress_shared_fs_extra__ from "@rspress/shared/fs-extra";
|
|
5
|
+
import * as __WEBPACK_EXTERNAL_MODULE__rspress_shared_node_utils__ from "@rspress/shared/node-utils";
|
|
6
|
+
async function detectFilePath(rawPath, extensions) {
|
|
7
|
+
// The params doesn't have extension name, so we need to try to find the file with the extension name.
|
|
8
|
+
let realPath = rawPath;
|
|
9
|
+
const fileExtname = __WEBPACK_EXTERNAL_MODULE_node_path__["default"].extname(rawPath);
|
|
10
|
+
// pathname may contain .json, see issue: https://github.com/web-infra-dev/rspress/issues/951
|
|
11
|
+
if (!extensions.includes(fileExtname)) {
|
|
12
|
+
const pathWithExtension = extensions.map((ext)=>`${rawPath}${ext}`);
|
|
13
|
+
const pathExistInfo = await Promise.all(pathWithExtension.map((p)=>__WEBPACK_EXTERNAL_MODULE__rspress_shared_fs_extra__["default"].pathExists(p)));
|
|
14
|
+
const findPath = pathWithExtension.find((_, i)=>pathExistInfo[i]);
|
|
15
|
+
// file may be public resource, see issue: https://github.com/web-infra-dev/rspress/issues/1052
|
|
16
|
+
if (!fileExtname || findPath) realPath = findPath;
|
|
17
|
+
}
|
|
18
|
+
return realPath;
|
|
19
|
+
}
|
|
20
|
+
async function extractInfoFromFrontmatter(filePath, rootDir, extensions) {
|
|
21
|
+
const realPath = await detectFilePath(filePath, extensions);
|
|
22
|
+
if (!realPath) {
|
|
23
|
+
__WEBPACK_EXTERNAL_MODULE__rspress_shared_logger__.logger.warn(`Can't find the file: ${filePath}, please check it in "${__WEBPACK_EXTERNAL_MODULE_node_path__["default"].join(__WEBPACK_EXTERNAL_MODULE_node_path__["default"].dirname(filePath), '_meta.json')}".`);
|
|
24
|
+
return {
|
|
25
|
+
realPath,
|
|
26
|
+
title: '',
|
|
27
|
+
overviewHeaders: void 0,
|
|
28
|
+
context: void 0
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
return {
|
|
32
|
+
...await extractInfoFromFrontmatterWithRealPath(realPath, rootDir),
|
|
33
|
+
realPath
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
async function extractInfoFromFrontmatterWithRealPath(realPath, rootDir) {
|
|
37
|
+
const content = await __WEBPACK_EXTERNAL_MODULE__rspress_shared_fs_extra__["default"].readFile(realPath, 'utf-8');
|
|
38
|
+
const fileNameWithoutExt = __WEBPACK_EXTERNAL_MODULE_node_path__["default"].basename(realPath, __WEBPACK_EXTERNAL_MODULE_node_path__["default"].extname(realPath));
|
|
39
|
+
const h1RegExp = /^#\s+(.*)$/m;
|
|
40
|
+
const match = content.match(h1RegExp);
|
|
41
|
+
const { frontmatter } = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_node_utils__.loadFrontMatter)(content, realPath, rootDir);
|
|
42
|
+
return {
|
|
43
|
+
title: frontmatter.title || (null == match ? void 0 : match[1]) || fileNameWithoutExt,
|
|
44
|
+
overviewHeaders: frontmatter.overviewHeaders,
|
|
45
|
+
context: frontmatter.context
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
function combineWalkResult(walks, versions) {
|
|
49
|
+
return walks.reduce((acc, cur, curIndex)=>({
|
|
50
|
+
nav: {
|
|
51
|
+
...acc.nav,
|
|
52
|
+
[versions[curIndex] || 'default']: cur.nav
|
|
53
|
+
},
|
|
54
|
+
sidebar: {
|
|
55
|
+
...acc.sidebar,
|
|
56
|
+
...cur.sidebar
|
|
57
|
+
}
|
|
58
|
+
}), {
|
|
59
|
+
nav: {},
|
|
60
|
+
sidebar: {}
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
function getHmrFileKey(realPath, docsDir) {
|
|
64
|
+
return realPath ? __WEBPACK_EXTERNAL_MODULE_node_path__["default"].relative(docsDir, realPath).replace(/\.mdx?$/, '') : '';
|
|
65
|
+
}
|
|
66
|
+
const DEFAULT_DIRNAME_PREFIX = 'rspress-dir-default-';
|
|
67
|
+
async function scanSideMeta(workDir, rootDir, docsDir, routePrefix, extensions) {
|
|
68
|
+
if (!await __WEBPACK_EXTERNAL_MODULE__rspress_shared_fs_extra__["default"].exists(workDir)) __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger__.logger.error('[plugin-auto-nav-sidebar]', `Generate sidebar meta error: ${workDir} not exists`);
|
|
69
|
+
const addRoutePrefix = (link)=>`${routePrefix}${link}`;
|
|
70
|
+
// find the `_meta.json` file
|
|
71
|
+
const metaFile = __WEBPACK_EXTERNAL_MODULE_node_path__["default"].resolve(workDir, '_meta.json');
|
|
72
|
+
// Fix the windows path
|
|
73
|
+
const relativePath = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared__.slash)(__WEBPACK_EXTERNAL_MODULE_node_path__["default"].relative(rootDir, workDir));
|
|
74
|
+
let sideMeta;
|
|
75
|
+
// Get the sidebar config from the `_meta.json` file
|
|
76
|
+
try {
|
|
77
|
+
// Don't use require to avoid require cache, which make hmr not work.
|
|
78
|
+
sideMeta = await __WEBPACK_EXTERNAL_MODULE__rspress_shared_fs_extra__["default"].readJSON(metaFile, 'utf8');
|
|
79
|
+
} catch (e) {
|
|
80
|
+
// If the `_meta.json` file doesn't exist, we will generate the sidebar config from the directory structure.
|
|
81
|
+
let subItems = await __WEBPACK_EXTERNAL_MODULE__rspress_shared_fs_extra__["default"].readdir(workDir);
|
|
82
|
+
// If there exists a file with the same name of the directory folder
|
|
83
|
+
// we don't need to generate SideMeta for this single file
|
|
84
|
+
subItems = subItems.filter((item)=>{
|
|
85
|
+
const hasExtension = extensions.some((ext)=>item.endsWith(ext));
|
|
86
|
+
const hasSameBaseName = subItems.some((elem)=>{
|
|
87
|
+
const baseName = elem.replace(/\.[^/.]+$/, '');
|
|
88
|
+
return baseName === item.replace(/\.[^/.]+$/, '') && elem !== item;
|
|
89
|
+
});
|
|
90
|
+
return !(hasExtension && hasSameBaseName);
|
|
91
|
+
});
|
|
92
|
+
sideMeta = (await Promise.all(subItems.map(async (item)=>{
|
|
93
|
+
// Fix https://github.com/web-infra-dev/rspress/issues/346
|
|
94
|
+
if ('_meta.json' === item) return null;
|
|
95
|
+
const stat = await __WEBPACK_EXTERNAL_MODULE__rspress_shared_fs_extra__["default"].stat(__WEBPACK_EXTERNAL_MODULE_node_path__["default"].join(workDir, item));
|
|
96
|
+
// If the item is a directory, we will transform it to a object with `type` and `name` property.
|
|
97
|
+
if (stat.isDirectory()) return {
|
|
98
|
+
type: 'dir',
|
|
99
|
+
name: item,
|
|
100
|
+
label: `${DEFAULT_DIRNAME_PREFIX}${item}`
|
|
101
|
+
};
|
|
102
|
+
return extensions.some((ext)=>item.endsWith(ext)) ? item : null;
|
|
103
|
+
}))).filter(Boolean);
|
|
104
|
+
}
|
|
105
|
+
const sidebarFromMeta = await Promise.all(sideMeta.map(async (metaItem)=>{
|
|
106
|
+
if ('string' == typeof metaItem) {
|
|
107
|
+
const { title, overviewHeaders, context, realPath } = await extractInfoFromFrontmatter(__WEBPACK_EXTERNAL_MODULE_node_path__["default"].resolve(workDir, metaItem), rootDir, extensions);
|
|
108
|
+
const pureLink = `${relativePath}/${metaItem.replace(/\.mdx?$/, '')}`;
|
|
109
|
+
return {
|
|
110
|
+
text: title,
|
|
111
|
+
link: addRoutePrefix(pureLink),
|
|
112
|
+
// FIXME: overviewHeaders is number[]
|
|
113
|
+
overviewHeaders,
|
|
114
|
+
context,
|
|
115
|
+
_fileKey: getHmrFileKey(realPath, docsDir)
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
const { type = 'file', name, label, collapsible, collapsed, link, tag, dashed, overviewHeaders, context } = metaItem;
|
|
119
|
+
// when type is divider, name maybe undefined, and link is not used
|
|
120
|
+
const pureLink = `${relativePath}/${null == name ? void 0 : name.replace(/\.mdx?$/, '')}`;
|
|
121
|
+
if ('file' === type) {
|
|
122
|
+
const info = await extractInfoFromFrontmatter(__WEBPACK_EXTERNAL_MODULE_node_path__["default"].resolve(workDir, name), rootDir, extensions);
|
|
123
|
+
const title = label || info.title;
|
|
124
|
+
const realPath = info.realPath;
|
|
125
|
+
return {
|
|
126
|
+
text: title,
|
|
127
|
+
link: addRoutePrefix(pureLink),
|
|
128
|
+
tag,
|
|
129
|
+
// FIXME: overviewHeaders is number[]
|
|
130
|
+
overviewHeaders: info.overviewHeaders ? info.overviewHeaders : overviewHeaders,
|
|
131
|
+
context: info.context ? info.context : context,
|
|
132
|
+
_fileKey: getHmrFileKey(realPath, docsDir)
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
if ('dir' === type) {
|
|
136
|
+
const subDir = __WEBPACK_EXTERNAL_MODULE_node_path__["default"].resolve(workDir, name);
|
|
137
|
+
const subSidebar = await scanSideMeta(subDir, rootDir, docsDir, routePrefix, extensions);
|
|
138
|
+
// Category index convention, display a document when clicking on the sidebar directory
|
|
139
|
+
// https://docusaurus.io/docs/sidebar/autogenerated#category-index-convention
|
|
140
|
+
// 1. sameName /api, /api.md or /api.mdx, (this should be removed in Rspress 2.0)
|
|
141
|
+
let realPath = await detectFilePath(subDir, extensions);
|
|
142
|
+
let link;
|
|
143
|
+
let _fileKey;
|
|
144
|
+
if (realPath) {
|
|
145
|
+
link = addRoutePrefix(pureLink);
|
|
146
|
+
_fileKey = getHmrFileKey(realPath, docsDir);
|
|
147
|
+
} else {
|
|
148
|
+
// 2. index /api, /api/index.md, /api/index.mdx
|
|
149
|
+
const indexFileRealPath = await detectFilePath((0, __WEBPACK_EXTERNAL_MODULE_node_path__.join)(subDir, 'index'), extensions);
|
|
150
|
+
link = indexFileRealPath ? addRoutePrefix(pureLink) : '';
|
|
151
|
+
_fileKey = getHmrFileKey(indexFileRealPath, docsDir);
|
|
152
|
+
realPath = indexFileRealPath;
|
|
153
|
+
// 3. if "index.mdx" or "index.md" or "index" is in _meta.json, index page should be placed to child sidebar
|
|
154
|
+
const indexItemIndex = subSidebar.findIndex((i)=>i._fileKey === _fileKey);
|
|
155
|
+
const isIndexFileInMetaItems = -1 !== indexItemIndex;
|
|
156
|
+
if (isIndexFileInMetaItems) {
|
|
157
|
+
const isMetaJsonExist = await __WEBPACK_EXTERNAL_MODULE__rspress_shared_fs_extra__["default"].exists((0, __WEBPACK_EXTERNAL_MODULE_node_path__.join)(subDir, '_meta.json'));
|
|
158
|
+
if (isMetaJsonExist) {
|
|
159
|
+
link = '';
|
|
160
|
+
_fileKey = getHmrFileKey(indexFileRealPath, docsDir);
|
|
161
|
+
realPath = void 0;
|
|
162
|
+
} else // 4. if _meta.json not exist, index page should be placed to dir sidebar
|
|
163
|
+
subSidebar.splice(indexItemIndex, 1);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
const { context: frontmatterContext = context, title } = realPath ? await extractInfoFromFrontmatterWithRealPath(realPath, rootDir) : {};
|
|
167
|
+
function getDirLabelName() {
|
|
168
|
+
let dirName;
|
|
169
|
+
if ('string' == typeof label && label.startsWith(DEFAULT_DIRNAME_PREFIX)) dirName = label.replace(DEFAULT_DIRNAME_PREFIX, '');
|
|
170
|
+
// 1. { "label": "DIR", type: "dir" } in _meta.json
|
|
171
|
+
if (!dirName && label) return label;
|
|
172
|
+
// 2. H1 or frontmatter title in md
|
|
173
|
+
if (title) return title;
|
|
174
|
+
// 3. fallback to fs dirname
|
|
175
|
+
return null != dirName ? dirName : '';
|
|
176
|
+
}
|
|
177
|
+
return {
|
|
178
|
+
text: getDirLabelName(),
|
|
179
|
+
collapsible,
|
|
180
|
+
collapsed,
|
|
181
|
+
items: subSidebar,
|
|
182
|
+
link,
|
|
183
|
+
tag,
|
|
184
|
+
// FIXME: overviewHeaders is number[]
|
|
185
|
+
overviewHeaders,
|
|
186
|
+
context: frontmatterContext,
|
|
187
|
+
_fileKey
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
if ('divider' === type) return {
|
|
191
|
+
dividerType: dashed ? 'dashed' : 'solid'
|
|
192
|
+
};
|
|
193
|
+
if ('section-header' === type) return {
|
|
194
|
+
sectionHeaderText: null != label ? label : '',
|
|
195
|
+
tag
|
|
196
|
+
};
|
|
197
|
+
return {
|
|
198
|
+
text: null != label ? label : '',
|
|
199
|
+
link: void 0 === link ? '' : (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared__.isExternalUrl)(link) ? link : (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared__.withBase)(link, routePrefix),
|
|
200
|
+
tag,
|
|
201
|
+
context
|
|
202
|
+
};
|
|
203
|
+
}));
|
|
204
|
+
return sidebarFromMeta;
|
|
205
|
+
}
|
|
206
|
+
// Start walking from the doc directory, scan the `_meta.json` file in each subdirectory
|
|
207
|
+
// and generate the nav and sidebar config
|
|
208
|
+
async function walk(workDir) {
|
|
209
|
+
let routePrefix = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : '/', docsDir = arguments.length > 2 ? arguments[2] : void 0, extensions = arguments.length > 3 ? arguments[3] : void 0;
|
|
210
|
+
// find the `_meta.json` file
|
|
211
|
+
const rootMetaFile = __WEBPACK_EXTERNAL_MODULE_node_path__["default"].resolve(workDir, '_meta.json');
|
|
212
|
+
let navConfig;
|
|
213
|
+
// Get the nav config from the `_meta.json` file
|
|
214
|
+
try {
|
|
215
|
+
navConfig = await __WEBPACK_EXTERNAL_MODULE__rspress_shared_fs_extra__["default"].readJSON(rootMetaFile, 'utf8');
|
|
216
|
+
} catch (e) {
|
|
217
|
+
navConfig = [];
|
|
218
|
+
}
|
|
219
|
+
navConfig.forEach((navItem)=>{
|
|
220
|
+
if ('items' in navItem) navItem.items.forEach((item)=>{
|
|
221
|
+
if ('link' in item && !(0, __WEBPACK_EXTERNAL_MODULE__rspress_shared__.isExternalUrl)(item.link)) item.link = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared__.withBase)(item.link, routePrefix);
|
|
222
|
+
});
|
|
223
|
+
if ('link' in navItem && !(0, __WEBPACK_EXTERNAL_MODULE__rspress_shared__.isExternalUrl)(navItem.link)) navItem.link = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared__.withBase)(navItem.link, routePrefix);
|
|
224
|
+
});
|
|
225
|
+
// find the `_meta.json` file in the subdirectory
|
|
226
|
+
const subDirs = (await __WEBPACK_EXTERNAL_MODULE__rspress_shared_fs_extra__["default"].readdir(workDir)).filter((v)=>__WEBPACK_EXTERNAL_MODULE__rspress_shared_fs_extra__["default"].statSync(__WEBPACK_EXTERNAL_MODULE_node_path__["default"].join(workDir, v)).isDirectory() && 'node_modules' !== v);
|
|
227
|
+
// Every sub dir will represent a group of sidebar
|
|
228
|
+
const sidebarConfig = {};
|
|
229
|
+
for (const subDir of subDirs){
|
|
230
|
+
const sidebarGroupKey = `${routePrefix}${subDir}`;
|
|
231
|
+
sidebarConfig[sidebarGroupKey] = await scanSideMeta(__WEBPACK_EXTERNAL_MODULE_node_path__["default"].join(workDir, subDir), workDir, docsDir, routePrefix, extensions);
|
|
232
|
+
}
|
|
233
|
+
return {
|
|
234
|
+
nav: navConfig,
|
|
235
|
+
sidebar: sidebarConfig
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
// Scan all the directories and files in the work directory(such as `docs`), and then generate the nav and sidebar configuration according to the directory structure.
|
|
239
|
+
// We will do as follows:
|
|
240
|
+
// 1. scan the directory structure, and extract all the `_meta.json` files.
|
|
241
|
+
// The `_meta.json` files will have two types:
|
|
242
|
+
// - For the `_meta.json` directly in the work directory, it will be used as the nav configuration.
|
|
243
|
+
// - For the `_meta.json` in the subdirectory, it will be used as the sidebar configuration.
|
|
244
|
+
// First, for the `_meta.json` directly in the work directory, the json content will have the following structure(see `NavMeta`):
|
|
245
|
+
// ```ts
|
|
246
|
+
// export type NavMeta = NavItem[];
|
|
247
|
+
// export type NavItem = NavItemWithLink | NavItemWithChildren;
|
|
248
|
+
// export type NavItemWithLink = {
|
|
249
|
+
// text: string;
|
|
250
|
+
// link: string;
|
|
251
|
+
// activeMatch?: string;
|
|
252
|
+
// position?: 'left' | 'right';
|
|
253
|
+
// };
|
|
254
|
+
// export type NavItemChildren = {
|
|
255
|
+
// text: string;
|
|
256
|
+
// items: NavItemWithLink[];
|
|
257
|
+
// };
|
|
258
|
+
// ```
|
|
259
|
+
// The `NavItemWithLink` will be used as the nav item, and the `NavItemChildren` will be used as the nav item with children.
|
|
260
|
+
// Second, for the `_meta.json` in the subdirectory, the json content will have the following structure(see `SideMeta`):
|
|
261
|
+
// ```ts
|
|
262
|
+
// export type SideMetaItem =
|
|
263
|
+
// | string
|
|
264
|
+
// | {
|
|
265
|
+
// type: 'file' | 'directory';
|
|
266
|
+
// name: string;
|
|
267
|
+
// // Use the h1 title as the sidebar title by default
|
|
268
|
+
// label?: string;
|
|
269
|
+
// collapsible?: boolean;
|
|
270
|
+
// collapsed?: boolean;
|
|
271
|
+
// };
|
|
272
|
+
// export type SideMeta = SideMetaItem[];
|
|
273
|
+
// ```
|
|
274
|
+
// The `SideMetaItem` can be the following types:
|
|
275
|
+
// - string: the file name, such as `home.md`, can also remove the extension name, such as `home`.
|
|
276
|
+
// - object: you can specify the `type` and `name` of the file or directory, and the `label` of the sidebar item, and whether the sidebar item is `collapsible` and `collapsed`.
|
|
277
|
+
// 2. generate the nav and sidebar configuration according to the `_meta.json` files.
|
|
278
|
+
// As you can see, every `_meta.json` file will have a corresponding file or directory, so we can get the link info from the file or directory(relative to the work directory).So we can generate the nav and sidebar config based on link info and _meta.json content.
|
|
279
|
+
// For nav config, we don't need to do anything, just use the `_meta.json` content as the nav config.
|
|
280
|
+
// For sidebar config, we need to transform every item of the array config:
|
|
281
|
+
// - string: we transform the string to a object with `text` and `link` property.Such as:
|
|
282
|
+
// ```ts
|
|
283
|
+
// {
|
|
284
|
+
// text: 'home',
|
|
285
|
+
// link: '/home'
|
|
286
|
+
// }
|
|
287
|
+
// ```
|
|
288
|
+
// - object: in this case, we will take account of the `type` property:
|
|
289
|
+
// - file: we will transform the object to a object with `text` and `link` property.Such as:
|
|
290
|
+
// ```ts
|
|
291
|
+
// {
|
|
292
|
+
// text: 'home',
|
|
293
|
+
// link: '/home'
|
|
294
|
+
// }
|
|
295
|
+
// ```
|
|
296
|
+
// - directory: we will transform the object to a object with `text` and `items` property.
|
|
297
|
+
// There is the following file structure:
|
|
298
|
+
// ```
|
|
299
|
+
// docs
|
|
300
|
+
// ├── guide
|
|
301
|
+
// │ ├── home.md
|
|
302
|
+
// │ ├── advanced
|
|
303
|
+
// │ │ └── plugin.md
|
|
304
|
+
// │ └── _meta.json
|
|
305
|
+
// └── _meta.json
|
|
306
|
+
// ```
|
|
307
|
+
// The `_meta.json` in the work directory has the following content:
|
|
308
|
+
// ```json
|
|
309
|
+
// [
|
|
310
|
+
// {
|
|
311
|
+
// "text": "guide",
|
|
312
|
+
// "link": "/guide"
|
|
313
|
+
// }
|
|
314
|
+
// ]
|
|
315
|
+
// ```
|
|
316
|
+
// The `_meta.json` in the `guide` directory has the following content:
|
|
317
|
+
// ```json
|
|
318
|
+
// [
|
|
319
|
+
// 'home',
|
|
320
|
+
// {
|
|
321
|
+
// "type": "directory",
|
|
322
|
+
// "name": "advanced",
|
|
323
|
+
// "label": "advanced",
|
|
324
|
+
// "collapsible": true,
|
|
325
|
+
// "collapsed": false
|
|
326
|
+
// }
|
|
327
|
+
// ]
|
|
328
|
+
// ```
|
|
329
|
+
// The `home.md` has the following content:
|
|
330
|
+
// ```md
|
|
331
|
+
// # home
|
|
332
|
+
// ```
|
|
333
|
+
// The `_meta.json` in the `advanced` directory has the following content:
|
|
334
|
+
// ```json
|
|
335
|
+
// [
|
|
336
|
+
// {
|
|
337
|
+
// "type": "file",
|
|
338
|
+
// "name": "plugin",
|
|
339
|
+
// "label": "plugin",
|
|
340
|
+
// "collapsible": true,
|
|
341
|
+
// "collapsed": false
|
|
342
|
+
// }
|
|
343
|
+
// ]
|
|
344
|
+
// ```
|
|
345
|
+
// The `plugin.md` has the following content:
|
|
346
|
+
// ```md
|
|
347
|
+
// # plugin
|
|
348
|
+
// ```
|
|
349
|
+
// The generated nav config will be:
|
|
350
|
+
// ```json
|
|
351
|
+
// [
|
|
352
|
+
// {
|
|
353
|
+
// "text": "guide",
|
|
354
|
+
// "link": "/guide"
|
|
355
|
+
// }
|
|
356
|
+
// ]
|
|
357
|
+
// ```
|
|
358
|
+
// The generated sidebar config will be:
|
|
359
|
+
// ```json
|
|
360
|
+
// [
|
|
361
|
+
// {
|
|
362
|
+
// "text": "home",
|
|
363
|
+
// "link": "/guide/home"
|
|
364
|
+
// },
|
|
365
|
+
// {
|
|
366
|
+
// "text": "advanced",
|
|
367
|
+
// "items": [
|
|
368
|
+
// {
|
|
369
|
+
// "text": "plugin",
|
|
370
|
+
// "link": "/guide/advanced/plugin"
|
|
371
|
+
// }
|
|
372
|
+
// ]
|
|
373
|
+
// }
|
|
374
|
+
// ]
|
|
375
|
+
// ```
|
|
376
|
+
function processLocales(langs, versions, root, defaultLang, defaultVersion, extensions) {
|
|
377
|
+
return Promise.all(langs.map(async (lang)=>{
|
|
378
|
+
const walks = versions.length ? await Promise.all(versions.map((version)=>{
|
|
379
|
+
const routePrefix = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared__.addTrailingSlash)(`${version === defaultVersion ? '' : `/${version}`}${lang === defaultLang ? '' : `/${lang}`}`);
|
|
380
|
+
return walk(__WEBPACK_EXTERNAL_MODULE_node_path__["default"].join(root, version, lang), routePrefix, root, extensions);
|
|
381
|
+
})) : [
|
|
382
|
+
await walk(__WEBPACK_EXTERNAL_MODULE_node_path__["default"].join(root, lang), (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared__.addTrailingSlash)(lang === defaultLang ? '' : `/${lang}`), root, extensions)
|
|
383
|
+
];
|
|
384
|
+
return combineWalkResult(walks, versions);
|
|
385
|
+
}));
|
|
386
|
+
}
|
|
387
|
+
const defaultExtensions = [
|
|
388
|
+
'.mdx',
|
|
389
|
+
'.md',
|
|
390
|
+
'.tsx',
|
|
391
|
+
'.jsx',
|
|
392
|
+
'.ts',
|
|
393
|
+
'.js'
|
|
394
|
+
];
|
|
395
|
+
function pluginAutoNavSidebar() {
|
|
396
|
+
return {
|
|
397
|
+
name: 'auto-nav-sidebar',
|
|
398
|
+
async config (config) {
|
|
399
|
+
var _config_multiVersion;
|
|
400
|
+
config.themeConfig = config.themeConfig || {};
|
|
401
|
+
config.themeConfig.locales = config.themeConfig.locales || config.locales || [];
|
|
402
|
+
const langs = config.themeConfig.locales.map((locale)=>locale.lang);
|
|
403
|
+
const hasLocales = langs.length > 0;
|
|
404
|
+
const hasLang = Boolean(config.lang);
|
|
405
|
+
const versions = (null === (_config_multiVersion = config.multiVersion) || void 0 === _config_multiVersion ? void 0 : _config_multiVersion.versions) || [];
|
|
406
|
+
const defaultLang = config.lang || '';
|
|
407
|
+
const { default: defaultVersion = '' } = config.multiVersion || {};
|
|
408
|
+
const { extensions = defaultExtensions } = (null == config ? void 0 : config.route) || {};
|
|
409
|
+
if (hasLocales) {
|
|
410
|
+
const metaInfo = await processLocales(langs, versions, config.root, defaultLang, defaultVersion, extensions);
|
|
411
|
+
config.themeConfig.locales = config.themeConfig.locales.map((item, index)=>({
|
|
412
|
+
...item,
|
|
413
|
+
...metaInfo[index]
|
|
414
|
+
}));
|
|
415
|
+
} else {
|
|
416
|
+
if (hasLang) {
|
|
417
|
+
__WEBPACK_EXTERNAL_MODULE__rspress_shared_logger__.logger.error("`lang` is configured but `locales` not, thus `@rspress/plugin-auto-nav-sidebar` can not auto generate navbar level config correctly!\nplease check your config file");
|
|
418
|
+
return config;
|
|
419
|
+
}
|
|
420
|
+
const walks = versions.length ? await Promise.all(versions.map((version)=>{
|
|
421
|
+
const routePrefix = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared__.addTrailingSlash)(version === defaultVersion ? '' : `/${version}`);
|
|
422
|
+
return walk(__WEBPACK_EXTERNAL_MODULE_node_path__["default"].join(config.root, version), routePrefix, config.root, extensions);
|
|
423
|
+
})) : [
|
|
424
|
+
await walk(config.root, '/', config.root, extensions)
|
|
425
|
+
];
|
|
426
|
+
const combined = combineWalkResult(walks, versions);
|
|
427
|
+
config.themeConfig = {
|
|
428
|
+
...config.themeConfig,
|
|
429
|
+
...combined
|
|
430
|
+
};
|
|
431
|
+
}
|
|
432
|
+
return config;
|
|
433
|
+
}
|
|
434
|
+
};
|
|
435
|
+
}
|
|
436
|
+
export { pluginAutoNavSidebar };
|
package/package.json
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@ohos-ports/rspress-plugin-auto-nav-sidebar",
|
|
3
|
+
"version": "1.38.0-beta.1",
|
|
4
|
+
"description": "A plugin for rspress to generate navbar and sidebar config automatically.",
|
|
5
|
+
"bugs": {
|
|
6
|
+
"url": "https://github.com/ohos-ports/ohos-ports/issues"
|
|
7
|
+
},
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "https://github.com/ohos-ports/ohos-ports.git",
|
|
11
|
+
"directory": "ports/rspress-plugin-auto-nav-sidebar/1.38.0"
|
|
12
|
+
},
|
|
13
|
+
"license": "MIT",
|
|
14
|
+
"type": "module",
|
|
15
|
+
"types": "./dist/index.d.ts",
|
|
16
|
+
"main": "./dist/index.js",
|
|
17
|
+
"module": "./dist/index.js",
|
|
18
|
+
"engines": {
|
|
19
|
+
"node": ">=14.17.6"
|
|
20
|
+
},
|
|
21
|
+
"sideEffects": [
|
|
22
|
+
"*.css",
|
|
23
|
+
"*.less",
|
|
24
|
+
"*.sass",
|
|
25
|
+
"*.scss"
|
|
26
|
+
],
|
|
27
|
+
"files": [
|
|
28
|
+
"dist",
|
|
29
|
+
"src"
|
|
30
|
+
],
|
|
31
|
+
"publishConfig": {
|
|
32
|
+
"access": "public",
|
|
33
|
+
"registry": "https://registry.npmjs.org/"
|
|
34
|
+
},
|
|
35
|
+
"dependencies": {
|
|
36
|
+
"@rspress/shared": "npm:@ohos-ports/rspress-shared@1.38.0-beta.1"
|
|
37
|
+
}
|
|
38
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { type RspressPlugin, addTrailingSlash } from '@rspress/shared';
|
|
3
|
+
import { logger } from '@rspress/shared/logger';
|
|
4
|
+
import { combineWalkResult } from './utils';
|
|
5
|
+
import { walk } from './walk';
|
|
6
|
+
|
|
7
|
+
// Scan all the directories and files in the work directory(such as `docs`), and then generate the nav and sidebar configuration according to the directory structure.
|
|
8
|
+
// We will do as follows:
|
|
9
|
+
// 1. scan the directory structure, and extract all the `_meta.json` files.
|
|
10
|
+
// The `_meta.json` files will have two types:
|
|
11
|
+
// - For the `_meta.json` directly in the work directory, it will be used as the nav configuration.
|
|
12
|
+
// - For the `_meta.json` in the subdirectory, it will be used as the sidebar configuration.
|
|
13
|
+
// First, for the `_meta.json` directly in the work directory, the json content will have the following structure(see `NavMeta`):
|
|
14
|
+
// ```ts
|
|
15
|
+
// export type NavMeta = NavItem[];
|
|
16
|
+
// export type NavItem = NavItemWithLink | NavItemWithChildren;
|
|
17
|
+
|
|
18
|
+
// export type NavItemWithLink = {
|
|
19
|
+
// text: string;
|
|
20
|
+
// link: string;
|
|
21
|
+
// activeMatch?: string;
|
|
22
|
+
// position?: 'left' | 'right';
|
|
23
|
+
// };
|
|
24
|
+
|
|
25
|
+
// export type NavItemChildren = {
|
|
26
|
+
// text: string;
|
|
27
|
+
// items: NavItemWithLink[];
|
|
28
|
+
// };
|
|
29
|
+
// ```
|
|
30
|
+
// The `NavItemWithLink` will be used as the nav item, and the `NavItemChildren` will be used as the nav item with children.
|
|
31
|
+
// Second, for the `_meta.json` in the subdirectory, the json content will have the following structure(see `SideMeta`):
|
|
32
|
+
// ```ts
|
|
33
|
+
// export type SideMetaItem =
|
|
34
|
+
// | string
|
|
35
|
+
// | {
|
|
36
|
+
// type: 'file' | 'directory';
|
|
37
|
+
// name: string;
|
|
38
|
+
// // Use the h1 title as the sidebar title by default
|
|
39
|
+
// label?: string;
|
|
40
|
+
// collapsible?: boolean;
|
|
41
|
+
// collapsed?: boolean;
|
|
42
|
+
// };
|
|
43
|
+
|
|
44
|
+
// export type SideMeta = SideMetaItem[];
|
|
45
|
+
// ```
|
|
46
|
+
// The `SideMetaItem` can be the following types:
|
|
47
|
+
// - string: the file name, such as `home.md`, can also remove the extension name, such as `home`.
|
|
48
|
+
// - object: you can specify the `type` and `name` of the file or directory, and the `label` of the sidebar item, and whether the sidebar item is `collapsible` and `collapsed`.
|
|
49
|
+
|
|
50
|
+
// 2. generate the nav and sidebar configuration according to the `_meta.json` files.
|
|
51
|
+
|
|
52
|
+
// As you can see, every `_meta.json` file will have a corresponding file or directory, so we can get the link info from the file or directory(relative to the work directory).So we can generate the nav and sidebar config based on link info and _meta.json content.
|
|
53
|
+
|
|
54
|
+
// For nav config, we don't need to do anything, just use the `_meta.json` content as the nav config.
|
|
55
|
+
// For sidebar config, we need to transform every item of the array config:
|
|
56
|
+
// - string: we transform the string to a object with `text` and `link` property.Such as:
|
|
57
|
+
// ```ts
|
|
58
|
+
// {
|
|
59
|
+
// text: 'home',
|
|
60
|
+
// link: '/home'
|
|
61
|
+
// }
|
|
62
|
+
// ```
|
|
63
|
+
// - object: in this case, we will take account of the `type` property:
|
|
64
|
+
// - file: we will transform the object to a object with `text` and `link` property.Such as:
|
|
65
|
+
// ```ts
|
|
66
|
+
// {
|
|
67
|
+
// text: 'home',
|
|
68
|
+
// link: '/home'
|
|
69
|
+
// }
|
|
70
|
+
// ```
|
|
71
|
+
// - directory: we will transform the object to a object with `text` and `items` property.
|
|
72
|
+
|
|
73
|
+
// There is the following file structure:
|
|
74
|
+
// ```
|
|
75
|
+
// docs
|
|
76
|
+
// ├── guide
|
|
77
|
+
// │ ├── home.md
|
|
78
|
+
// │ ├── advanced
|
|
79
|
+
// │ │ └── plugin.md
|
|
80
|
+
// │ └── _meta.json
|
|
81
|
+
// └── _meta.json
|
|
82
|
+
// ```
|
|
83
|
+
// The `_meta.json` in the work directory has the following content:
|
|
84
|
+
// ```json
|
|
85
|
+
// [
|
|
86
|
+
// {
|
|
87
|
+
// "text": "guide",
|
|
88
|
+
// "link": "/guide"
|
|
89
|
+
// }
|
|
90
|
+
// ]
|
|
91
|
+
// ```
|
|
92
|
+
// The `_meta.json` in the `guide` directory has the following content:
|
|
93
|
+
// ```json
|
|
94
|
+
// [
|
|
95
|
+
// 'home',
|
|
96
|
+
// {
|
|
97
|
+
// "type": "directory",
|
|
98
|
+
// "name": "advanced",
|
|
99
|
+
// "label": "advanced",
|
|
100
|
+
// "collapsible": true,
|
|
101
|
+
// "collapsed": false
|
|
102
|
+
// }
|
|
103
|
+
// ]
|
|
104
|
+
// ```
|
|
105
|
+
// The `home.md` has the following content:
|
|
106
|
+
// ```md
|
|
107
|
+
// # home
|
|
108
|
+
// ```
|
|
109
|
+
// The `_meta.json` in the `advanced` directory has the following content:
|
|
110
|
+
// ```json
|
|
111
|
+
// [
|
|
112
|
+
// {
|
|
113
|
+
// "type": "file",
|
|
114
|
+
// "name": "plugin",
|
|
115
|
+
// "label": "plugin",
|
|
116
|
+
// "collapsible": true,
|
|
117
|
+
// "collapsed": false
|
|
118
|
+
// }
|
|
119
|
+
// ]
|
|
120
|
+
// ```
|
|
121
|
+
// The `plugin.md` has the following content:
|
|
122
|
+
// ```md
|
|
123
|
+
// # plugin
|
|
124
|
+
// ```
|
|
125
|
+
|
|
126
|
+
// The generated nav config will be:
|
|
127
|
+
// ```json
|
|
128
|
+
// [
|
|
129
|
+
// {
|
|
130
|
+
// "text": "guide",
|
|
131
|
+
// "link": "/guide"
|
|
132
|
+
// }
|
|
133
|
+
// ]
|
|
134
|
+
// ```
|
|
135
|
+
// The generated sidebar config will be:
|
|
136
|
+
// ```json
|
|
137
|
+
// [
|
|
138
|
+
// {
|
|
139
|
+
// "text": "home",
|
|
140
|
+
// "link": "/guide/home"
|
|
141
|
+
// },
|
|
142
|
+
// {
|
|
143
|
+
// "text": "advanced",
|
|
144
|
+
// "items": [
|
|
145
|
+
// {
|
|
146
|
+
// "text": "plugin",
|
|
147
|
+
// "link": "/guide/advanced/plugin"
|
|
148
|
+
// }
|
|
149
|
+
// ]
|
|
150
|
+
// }
|
|
151
|
+
// ]
|
|
152
|
+
// ```
|
|
153
|
+
|
|
154
|
+
function processLocales(
|
|
155
|
+
langs: string[],
|
|
156
|
+
versions: string[],
|
|
157
|
+
root: string,
|
|
158
|
+
defaultLang: string,
|
|
159
|
+
defaultVersion: string,
|
|
160
|
+
extensions: string[],
|
|
161
|
+
) {
|
|
162
|
+
return Promise.all(
|
|
163
|
+
langs.map(async lang => {
|
|
164
|
+
const walks = versions.length
|
|
165
|
+
? await Promise.all(
|
|
166
|
+
versions.map(version => {
|
|
167
|
+
const routePrefix = addTrailingSlash(
|
|
168
|
+
`${version === defaultVersion ? '' : `/${version}`}${
|
|
169
|
+
lang === defaultLang ? '' : `/${lang}`
|
|
170
|
+
}`,
|
|
171
|
+
);
|
|
172
|
+
return walk(
|
|
173
|
+
path.join(root, version, lang),
|
|
174
|
+
routePrefix,
|
|
175
|
+
root,
|
|
176
|
+
extensions,
|
|
177
|
+
);
|
|
178
|
+
}),
|
|
179
|
+
)
|
|
180
|
+
: [
|
|
181
|
+
await walk(
|
|
182
|
+
path.join(root, lang),
|
|
183
|
+
addTrailingSlash(lang === defaultLang ? '' : `/${lang}`),
|
|
184
|
+
root,
|
|
185
|
+
extensions,
|
|
186
|
+
),
|
|
187
|
+
];
|
|
188
|
+
return combineWalkResult(walks, versions);
|
|
189
|
+
}),
|
|
190
|
+
);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
const defaultExtensions = ['.mdx', '.md', '.tsx', '.jsx', '.ts', '.js'];
|
|
194
|
+
|
|
195
|
+
export function pluginAutoNavSidebar(): RspressPlugin {
|
|
196
|
+
return {
|
|
197
|
+
name: 'auto-nav-sidebar',
|
|
198
|
+
async config(config) {
|
|
199
|
+
config.themeConfig = config.themeConfig || {};
|
|
200
|
+
config.themeConfig.locales =
|
|
201
|
+
config.themeConfig.locales || config.locales || [];
|
|
202
|
+
const langs = config.themeConfig.locales.map(locale => locale.lang);
|
|
203
|
+
const hasLocales = langs.length > 0;
|
|
204
|
+
const hasLang = Boolean(config.lang);
|
|
205
|
+
const versions = config.multiVersion?.versions || [];
|
|
206
|
+
const defaultLang = config.lang || '';
|
|
207
|
+
const { default: defaultVersion = '' } = config.multiVersion || {};
|
|
208
|
+
const { extensions = defaultExtensions } = config?.route || {};
|
|
209
|
+
if (hasLocales) {
|
|
210
|
+
const metaInfo = await processLocales(
|
|
211
|
+
langs,
|
|
212
|
+
versions,
|
|
213
|
+
config.root!,
|
|
214
|
+
defaultLang,
|
|
215
|
+
defaultVersion,
|
|
216
|
+
extensions,
|
|
217
|
+
);
|
|
218
|
+
config.themeConfig.locales = config.themeConfig.locales.map(
|
|
219
|
+
(item, index) => ({
|
|
220
|
+
...item,
|
|
221
|
+
...metaInfo[index],
|
|
222
|
+
}),
|
|
223
|
+
);
|
|
224
|
+
} else {
|
|
225
|
+
if (hasLang) {
|
|
226
|
+
logger.error(
|
|
227
|
+
'`lang` is configured but `locales` not, ' +
|
|
228
|
+
'thus `@rspress/plugin-auto-nav-sidebar` can not auto generate ' +
|
|
229
|
+
'navbar level config correctly!\n' +
|
|
230
|
+
'please check your config file',
|
|
231
|
+
);
|
|
232
|
+
return config;
|
|
233
|
+
}
|
|
234
|
+
const walks = versions.length
|
|
235
|
+
? await Promise.all(
|
|
236
|
+
versions.map(version => {
|
|
237
|
+
const routePrefix = addTrailingSlash(
|
|
238
|
+
version === defaultVersion ? '' : `/${version}`,
|
|
239
|
+
);
|
|
240
|
+
return walk(
|
|
241
|
+
path.join(config.root!, version),
|
|
242
|
+
routePrefix,
|
|
243
|
+
config.root!,
|
|
244
|
+
extensions,
|
|
245
|
+
);
|
|
246
|
+
}),
|
|
247
|
+
)
|
|
248
|
+
: [await walk(config.root!, '/', config.root!, extensions)];
|
|
249
|
+
|
|
250
|
+
const combined = combineWalkResult(walks, versions);
|
|
251
|
+
|
|
252
|
+
config.themeConfig = { ...config.themeConfig, ...combined };
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
return config;
|
|
256
|
+
},
|
|
257
|
+
};
|
|
258
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
/// <reference types='@modern-js/module-tools/types' />
|
package/src/type.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { Nav } from '@rspress/shared';
|
|
2
|
+
|
|
3
|
+
export type NavMeta = Nav;
|
|
4
|
+
|
|
5
|
+
export type SideMetaItem =
|
|
6
|
+
| string
|
|
7
|
+
| {
|
|
8
|
+
type: 'file' | 'dir' | 'divider' | 'custom-link' | 'section-header';
|
|
9
|
+
name: string;
|
|
10
|
+
link?: string;
|
|
11
|
+
// Use the h1 title as the sidebar title by default
|
|
12
|
+
label?: string;
|
|
13
|
+
collapsible?: boolean;
|
|
14
|
+
collapsed?: boolean;
|
|
15
|
+
tag?: string;
|
|
16
|
+
dashed?: boolean;
|
|
17
|
+
overviewHeaders?: number[];
|
|
18
|
+
context?: string;
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
export type SideMeta = SideMetaItem[];
|
package/src/utils.ts
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import fs from '@rspress/shared/fs-extra';
|
|
3
|
+
import type { NavItem, Sidebar } from '@rspress/shared';
|
|
4
|
+
import { logger } from '@rspress/shared/logger';
|
|
5
|
+
import { loadFrontMatter } from '@rspress/shared/node-utils';
|
|
6
|
+
|
|
7
|
+
export async function detectFilePath(
|
|
8
|
+
rawPath: string,
|
|
9
|
+
extensions: string[],
|
|
10
|
+
): Promise<string | undefined> {
|
|
11
|
+
// The params doesn't have extension name, so we need to try to find the file with the extension name.
|
|
12
|
+
let realPath: string | undefined = rawPath;
|
|
13
|
+
const fileExtname = path.extname(rawPath);
|
|
14
|
+
|
|
15
|
+
// pathname may contain .json, see issue: https://github.com/web-infra-dev/rspress/issues/951
|
|
16
|
+
if (!extensions.includes(fileExtname)) {
|
|
17
|
+
const pathWithExtension = extensions.map(ext => `${rawPath}${ext}`);
|
|
18
|
+
const pathExistInfo = await Promise.all(
|
|
19
|
+
pathWithExtension.map(p => fs.pathExists(p)),
|
|
20
|
+
);
|
|
21
|
+
const findPath = pathWithExtension.find((_, i) => pathExistInfo[i]);
|
|
22
|
+
// file may be public resource, see issue: https://github.com/web-infra-dev/rspress/issues/1052
|
|
23
|
+
if (!fileExtname || findPath) {
|
|
24
|
+
realPath = findPath;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
return realPath;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export async function extractInfoFromFrontmatter(
|
|
32
|
+
filePath: string,
|
|
33
|
+
rootDir: string,
|
|
34
|
+
extensions: string[],
|
|
35
|
+
): Promise<{
|
|
36
|
+
realPath: string | undefined;
|
|
37
|
+
title: string;
|
|
38
|
+
overviewHeaders: string | undefined;
|
|
39
|
+
context: string | undefined;
|
|
40
|
+
}> {
|
|
41
|
+
const realPath = await detectFilePath(filePath, extensions);
|
|
42
|
+
if (!realPath) {
|
|
43
|
+
logger.warn(
|
|
44
|
+
`Can't find the file: ${filePath}, please check it in "${path.join(
|
|
45
|
+
path.dirname(filePath),
|
|
46
|
+
'_meta.json',
|
|
47
|
+
)}".`,
|
|
48
|
+
);
|
|
49
|
+
return {
|
|
50
|
+
realPath,
|
|
51
|
+
title: '',
|
|
52
|
+
overviewHeaders: undefined,
|
|
53
|
+
context: undefined,
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
return {
|
|
57
|
+
...(await extractInfoFromFrontmatterWithRealPath(realPath, rootDir)),
|
|
58
|
+
realPath,
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export async function extractInfoFromFrontmatterWithRealPath(
|
|
63
|
+
realPath: string,
|
|
64
|
+
rootDir: string,
|
|
65
|
+
): Promise<{
|
|
66
|
+
title: string;
|
|
67
|
+
overviewHeaders: string | undefined;
|
|
68
|
+
context: string | undefined;
|
|
69
|
+
}> {
|
|
70
|
+
const content = await fs.readFile(realPath, 'utf-8');
|
|
71
|
+
const fileNameWithoutExt = path.basename(realPath, path.extname(realPath));
|
|
72
|
+
const h1RegExp = /^#\s+(.*)$/m;
|
|
73
|
+
const match = content.match(h1RegExp);
|
|
74
|
+
const { frontmatter } = loadFrontMatter(content, realPath, rootDir);
|
|
75
|
+
return {
|
|
76
|
+
title: frontmatter.title || match?.[1] || fileNameWithoutExt,
|
|
77
|
+
overviewHeaders: frontmatter.overviewHeaders,
|
|
78
|
+
context: frontmatter.context,
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function combineWalkResult(
|
|
83
|
+
walks: { nav: NavItem[]; sidebar: Sidebar }[],
|
|
84
|
+
versions: string[],
|
|
85
|
+
) {
|
|
86
|
+
return walks.reduce(
|
|
87
|
+
(acc, cur, curIndex) => ({
|
|
88
|
+
nav: {
|
|
89
|
+
...acc.nav,
|
|
90
|
+
[versions[curIndex] || 'default']: cur.nav,
|
|
91
|
+
},
|
|
92
|
+
sidebar: { ...acc.sidebar, ...cur.sidebar },
|
|
93
|
+
}),
|
|
94
|
+
{
|
|
95
|
+
nav: {},
|
|
96
|
+
sidebar: {},
|
|
97
|
+
},
|
|
98
|
+
);
|
|
99
|
+
}
|
package/src/walk.ts
ADDED
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
import path, { join } from 'node:path';
|
|
2
|
+
import fs from '@rspress/shared/fs-extra';
|
|
3
|
+
import {
|
|
4
|
+
type NavItem,
|
|
5
|
+
type Sidebar,
|
|
6
|
+
type SidebarGroup,
|
|
7
|
+
type SidebarItem,
|
|
8
|
+
type SidebarDivider,
|
|
9
|
+
slash,
|
|
10
|
+
withBase,
|
|
11
|
+
isExternalUrl,
|
|
12
|
+
type SidebarSectionHeader,
|
|
13
|
+
} from '@rspress/shared';
|
|
14
|
+
import type { NavMeta, SideMeta } from './type';
|
|
15
|
+
import {
|
|
16
|
+
detectFilePath,
|
|
17
|
+
extractInfoFromFrontmatter,
|
|
18
|
+
extractInfoFromFrontmatterWithRealPath,
|
|
19
|
+
} from './utils';
|
|
20
|
+
import { logger } from '@rspress/shared/logger';
|
|
21
|
+
|
|
22
|
+
function getHmrFileKey(realPath: string | undefined, docsDir: string) {
|
|
23
|
+
return realPath
|
|
24
|
+
? path.relative(docsDir, realPath).replace(/\.mdx?$/, '')
|
|
25
|
+
: '';
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const DEFAULT_DIRNAME_PREFIX = 'rspress-dir-default-';
|
|
29
|
+
export async function scanSideMeta(
|
|
30
|
+
workDir: string,
|
|
31
|
+
rootDir: string,
|
|
32
|
+
docsDir: string,
|
|
33
|
+
routePrefix: string,
|
|
34
|
+
extensions: string[],
|
|
35
|
+
): Promise<
|
|
36
|
+
(SidebarGroup | SidebarItem | SidebarDivider | SidebarSectionHeader)[]
|
|
37
|
+
> {
|
|
38
|
+
if (!(await fs.exists(workDir))) {
|
|
39
|
+
logger.error(
|
|
40
|
+
'[plugin-auto-nav-sidebar]',
|
|
41
|
+
`Generate sidebar meta error: ${workDir} not exists`,
|
|
42
|
+
);
|
|
43
|
+
}
|
|
44
|
+
const addRoutePrefix = (link: string) => `${routePrefix}${link}`;
|
|
45
|
+
// find the `_meta.json` file
|
|
46
|
+
const metaFile = path.resolve(workDir, '_meta.json');
|
|
47
|
+
// Fix the windows path
|
|
48
|
+
const relativePath = slash(path.relative(rootDir, workDir));
|
|
49
|
+
let sideMeta: SideMeta | undefined;
|
|
50
|
+
// Get the sidebar config from the `_meta.json` file
|
|
51
|
+
try {
|
|
52
|
+
// Don't use require to avoid require cache, which make hmr not work.
|
|
53
|
+
sideMeta = (await fs.readJSON(metaFile, 'utf8')) as SideMeta;
|
|
54
|
+
} catch (e) {
|
|
55
|
+
// If the `_meta.json` file doesn't exist, we will generate the sidebar config from the directory structure.
|
|
56
|
+
let subItems = await fs.readdir(workDir);
|
|
57
|
+
// If there exists a file with the same name of the directory folder
|
|
58
|
+
// we don't need to generate SideMeta for this single file
|
|
59
|
+
subItems = subItems.filter(item => {
|
|
60
|
+
const hasExtension = extensions.some(ext => item.endsWith(ext));
|
|
61
|
+
const hasSameBaseName = subItems.some(elem => {
|
|
62
|
+
const baseName = elem.replace(/\.[^/.]+$/, '');
|
|
63
|
+
return baseName === item.replace(/\.[^/.]+$/, '') && elem !== item;
|
|
64
|
+
});
|
|
65
|
+
return !(hasExtension && hasSameBaseName);
|
|
66
|
+
});
|
|
67
|
+
sideMeta = (
|
|
68
|
+
await Promise.all(
|
|
69
|
+
subItems.map(async item => {
|
|
70
|
+
// Fix https://github.com/web-infra-dev/rspress/issues/346
|
|
71
|
+
if (item === '_meta.json') {
|
|
72
|
+
return null;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const stat = await fs.stat(path.join(workDir, item));
|
|
76
|
+
// If the item is a directory, we will transform it to a object with `type` and `name` property.
|
|
77
|
+
if (stat.isDirectory()) {
|
|
78
|
+
return {
|
|
79
|
+
type: 'dir',
|
|
80
|
+
name: item,
|
|
81
|
+
label: `${DEFAULT_DIRNAME_PREFIX}${item}`, // if no _meta.json, use the dir name as default
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
return extensions.some(ext => item.endsWith(ext)) ? item : null;
|
|
85
|
+
}),
|
|
86
|
+
)
|
|
87
|
+
).filter(Boolean) as SideMeta;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const sidebarFromMeta: (
|
|
91
|
+
| SidebarGroup
|
|
92
|
+
| SidebarItem
|
|
93
|
+
| SidebarDivider
|
|
94
|
+
| SidebarSectionHeader
|
|
95
|
+
)[] = await Promise.all(
|
|
96
|
+
sideMeta.map(async metaItem => {
|
|
97
|
+
if (typeof metaItem === 'string') {
|
|
98
|
+
const { title, overviewHeaders, context, realPath } =
|
|
99
|
+
await extractInfoFromFrontmatter(
|
|
100
|
+
path.resolve(workDir, metaItem),
|
|
101
|
+
rootDir,
|
|
102
|
+
extensions,
|
|
103
|
+
);
|
|
104
|
+
const pureLink = `${relativePath}/${metaItem.replace(/\.mdx?$/, '')}`;
|
|
105
|
+
return {
|
|
106
|
+
text: title,
|
|
107
|
+
link: addRoutePrefix(pureLink),
|
|
108
|
+
// FIXME: overviewHeaders is number[]
|
|
109
|
+
overviewHeaders,
|
|
110
|
+
context,
|
|
111
|
+
_fileKey: getHmrFileKey(realPath, docsDir),
|
|
112
|
+
} as SidebarItem;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const {
|
|
116
|
+
type = 'file',
|
|
117
|
+
name,
|
|
118
|
+
label,
|
|
119
|
+
collapsible,
|
|
120
|
+
collapsed,
|
|
121
|
+
link,
|
|
122
|
+
tag,
|
|
123
|
+
dashed,
|
|
124
|
+
overviewHeaders,
|
|
125
|
+
context,
|
|
126
|
+
} = metaItem;
|
|
127
|
+
// when type is divider, name maybe undefined, and link is not used
|
|
128
|
+
const pureLink = `${relativePath}/${name?.replace(/\.mdx?$/, '')}`;
|
|
129
|
+
if (type === 'file') {
|
|
130
|
+
const info = await extractInfoFromFrontmatter(
|
|
131
|
+
path.resolve(workDir, name),
|
|
132
|
+
rootDir,
|
|
133
|
+
extensions,
|
|
134
|
+
);
|
|
135
|
+
const title = label || info.title;
|
|
136
|
+
const realPath = info.realPath;
|
|
137
|
+
return {
|
|
138
|
+
text: title,
|
|
139
|
+
link: addRoutePrefix(pureLink),
|
|
140
|
+
tag,
|
|
141
|
+
// FIXME: overviewHeaders is number[]
|
|
142
|
+
overviewHeaders: info.overviewHeaders
|
|
143
|
+
? info.overviewHeaders
|
|
144
|
+
: overviewHeaders,
|
|
145
|
+
context: info.context ? info.context : context,
|
|
146
|
+
_fileKey: getHmrFileKey(realPath, docsDir),
|
|
147
|
+
} as SidebarItem;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
if (type === 'dir') {
|
|
151
|
+
const subDir = path.resolve(workDir, name);
|
|
152
|
+
const subSidebar = await scanSideMeta(
|
|
153
|
+
subDir,
|
|
154
|
+
rootDir,
|
|
155
|
+
docsDir,
|
|
156
|
+
routePrefix,
|
|
157
|
+
extensions,
|
|
158
|
+
);
|
|
159
|
+
|
|
160
|
+
// Category index convention, display a document when clicking on the sidebar directory
|
|
161
|
+
// https://docusaurus.io/docs/sidebar/autogenerated#category-index-convention
|
|
162
|
+
|
|
163
|
+
// 1. sameName /api, /api.md or /api.mdx, (this should be removed in Rspress 2.0)
|
|
164
|
+
let realPath = await detectFilePath(subDir, extensions);
|
|
165
|
+
let link: string;
|
|
166
|
+
let _fileKey: string;
|
|
167
|
+
|
|
168
|
+
if (realPath) {
|
|
169
|
+
link = addRoutePrefix(pureLink);
|
|
170
|
+
_fileKey = getHmrFileKey(realPath, docsDir);
|
|
171
|
+
} else {
|
|
172
|
+
// 2. index /api, /api/index.md, /api/index.mdx
|
|
173
|
+
const indexFileRealPath = await detectFilePath(
|
|
174
|
+
join(subDir, 'index'),
|
|
175
|
+
extensions,
|
|
176
|
+
);
|
|
177
|
+
link = indexFileRealPath ? addRoutePrefix(pureLink) : '';
|
|
178
|
+
_fileKey = getHmrFileKey(indexFileRealPath, docsDir);
|
|
179
|
+
realPath = indexFileRealPath;
|
|
180
|
+
|
|
181
|
+
// 3. if "index.mdx" or "index.md" or "index" is in _meta.json, index page should be placed to child sidebar
|
|
182
|
+
const indexItemIndex = subSidebar.findIndex(i => {
|
|
183
|
+
return (
|
|
184
|
+
(i as { _fileKey: string | undefined })._fileKey === _fileKey
|
|
185
|
+
);
|
|
186
|
+
});
|
|
187
|
+
const isIndexFileInMetaItems = indexItemIndex !== -1;
|
|
188
|
+
|
|
189
|
+
if (isIndexFileInMetaItems) {
|
|
190
|
+
const isMetaJsonExist = await fs.exists(join(subDir, '_meta.json'));
|
|
191
|
+
if (isMetaJsonExist) {
|
|
192
|
+
link = '';
|
|
193
|
+
_fileKey = getHmrFileKey(indexFileRealPath, docsDir);
|
|
194
|
+
realPath = undefined;
|
|
195
|
+
} else {
|
|
196
|
+
// 4. if _meta.json not exist, index page should be placed to dir sidebar
|
|
197
|
+
subSidebar.splice(indexItemIndex, 1);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
const { context: frontmatterContext = context, title } = realPath
|
|
203
|
+
? await extractInfoFromFrontmatterWithRealPath(realPath, rootDir)
|
|
204
|
+
: ({} as { context: undefined; title: undefined });
|
|
205
|
+
|
|
206
|
+
function getDirLabelName(): string {
|
|
207
|
+
let dirName;
|
|
208
|
+
|
|
209
|
+
if (
|
|
210
|
+
typeof label === 'string' &&
|
|
211
|
+
label.startsWith(DEFAULT_DIRNAME_PREFIX)
|
|
212
|
+
) {
|
|
213
|
+
dirName = label.replace(DEFAULT_DIRNAME_PREFIX, '');
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// 1. { "label": "DIR", type: "dir" } in _meta.json
|
|
217
|
+
if (!dirName && label) {
|
|
218
|
+
return label;
|
|
219
|
+
}
|
|
220
|
+
// 2. H1 or frontmatter title in md
|
|
221
|
+
if (title) {
|
|
222
|
+
return title;
|
|
223
|
+
}
|
|
224
|
+
// 3. fallback to fs dirname
|
|
225
|
+
return dirName ?? '';
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
return {
|
|
229
|
+
text: getDirLabelName(),
|
|
230
|
+
collapsible,
|
|
231
|
+
collapsed,
|
|
232
|
+
items: subSidebar,
|
|
233
|
+
link,
|
|
234
|
+
tag,
|
|
235
|
+
// FIXME: overviewHeaders is number[]
|
|
236
|
+
overviewHeaders,
|
|
237
|
+
context: frontmatterContext,
|
|
238
|
+
_fileKey,
|
|
239
|
+
} as SidebarGroup;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
if (type === 'divider') {
|
|
243
|
+
return {
|
|
244
|
+
dividerType: dashed ? 'dashed' : 'solid',
|
|
245
|
+
} satisfies SidebarDivider;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
if (type === 'section-header') {
|
|
249
|
+
return {
|
|
250
|
+
sectionHeaderText: label ?? '',
|
|
251
|
+
tag,
|
|
252
|
+
} satisfies SidebarSectionHeader;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
return {
|
|
256
|
+
text: label ?? '',
|
|
257
|
+
link:
|
|
258
|
+
typeof link === 'undefined'
|
|
259
|
+
? ''
|
|
260
|
+
: isExternalUrl(link)
|
|
261
|
+
? link
|
|
262
|
+
: withBase(link, routePrefix),
|
|
263
|
+
tag,
|
|
264
|
+
context,
|
|
265
|
+
} satisfies SidebarItem;
|
|
266
|
+
}),
|
|
267
|
+
);
|
|
268
|
+
|
|
269
|
+
return sidebarFromMeta;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
// Start walking from the doc directory, scan the `_meta.json` file in each subdirectory
|
|
273
|
+
// and generate the nav and sidebar config
|
|
274
|
+
export async function walk(
|
|
275
|
+
workDir: string,
|
|
276
|
+
routePrefix = '/',
|
|
277
|
+
docsDir: string,
|
|
278
|
+
extensions: string[],
|
|
279
|
+
) {
|
|
280
|
+
// find the `_meta.json` file
|
|
281
|
+
const rootMetaFile = path.resolve(workDir, '_meta.json');
|
|
282
|
+
let navConfig: NavMeta | undefined;
|
|
283
|
+
// Get the nav config from the `_meta.json` file
|
|
284
|
+
try {
|
|
285
|
+
navConfig = (await fs.readJSON(rootMetaFile, 'utf8')) as NavItem[];
|
|
286
|
+
} catch (e) {
|
|
287
|
+
navConfig = [];
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
navConfig.forEach(navItem => {
|
|
291
|
+
if ('items' in navItem) {
|
|
292
|
+
navItem.items.forEach(item => {
|
|
293
|
+
if ('link' in item && !isExternalUrl(item.link)) {
|
|
294
|
+
item.link = withBase(item.link, routePrefix);
|
|
295
|
+
}
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
if ('link' in navItem && !isExternalUrl(navItem.link)) {
|
|
299
|
+
navItem.link = withBase(navItem.link, routePrefix);
|
|
300
|
+
}
|
|
301
|
+
});
|
|
302
|
+
// find the `_meta.json` file in the subdirectory
|
|
303
|
+
const subDirs = (await fs.readdir(workDir)).filter(
|
|
304
|
+
v =>
|
|
305
|
+
fs.statSync(path.join(workDir, v)).isDirectory() && v !== 'node_modules',
|
|
306
|
+
);
|
|
307
|
+
// Every sub dir will represent a group of sidebar
|
|
308
|
+
const sidebarConfig: Sidebar = {};
|
|
309
|
+
for (const subDir of subDirs) {
|
|
310
|
+
const sidebarGroupKey = `${routePrefix}${subDir}`;
|
|
311
|
+
sidebarConfig[sidebarGroupKey] = await scanSideMeta(
|
|
312
|
+
path.join(workDir, subDir),
|
|
313
|
+
workDir,
|
|
314
|
+
docsDir,
|
|
315
|
+
routePrefix,
|
|
316
|
+
extensions,
|
|
317
|
+
);
|
|
318
|
+
}
|
|
319
|
+
return {
|
|
320
|
+
nav: navConfig as NavItem[],
|
|
321
|
+
sidebar: sidebarConfig,
|
|
322
|
+
};
|
|
323
|
+
}
|