@alauda/doom 0.0.0-alpha.2 → 0.0.0-alpha.3

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.
@@ -0,0 +1,4 @@
1
+ import type { UserConfig } from '@rspress/core';
2
+ export interface DoomConfig extends UserConfig {
3
+ }
4
+ export declare const defineConfig: (config: DoomConfig) => DoomConfig;
@@ -0,0 +1 @@
1
+ export const defineConfig = (config) => config;
@@ -0,0 +1,5 @@
1
+ export declare const DEFAULT_CONFIG_NAME = "doom.config";
2
+ export declare const YAML_EXTENSIONS: readonly [".yaml", ".yml"];
3
+ export declare const JS_EXTENSIONS: readonly [".js", ".ts", ".mjs", ".mts", ".cjs", ".cts"];
4
+ export declare const DEFAULT_EXTENSIONS: readonly [".yaml", ".yml", ".js", ".ts", ".mjs", ".mts", ".cjs", ".cts"];
5
+ export declare const DEFAULT_CONFIGS: ("doom.config.yaml" | "doom.config.yml" | "doom.config.js" | "doom.config.ts" | "doom.config.mjs" | "doom.config.mts" | "doom.config.cjs" | "doom.config.cts")[];
@@ -0,0 +1,15 @@
1
+ export const DEFAULT_CONFIG_NAME = 'doom.config';
2
+ export const YAML_EXTENSIONS = ['.yaml', '.yml'];
3
+ export const JS_EXTENSIONS = [
4
+ '.js',
5
+ '.ts',
6
+ '.mjs',
7
+ '.mts',
8
+ '.cjs',
9
+ '.cts',
10
+ ];
11
+ export const DEFAULT_EXTENSIONS = [
12
+ ...YAML_EXTENSIONS,
13
+ ...JS_EXTENSIONS,
14
+ ];
15
+ export const DEFAULT_CONFIGS = DEFAULT_EXTENSIONS.map((ext) => `${DEFAULT_CONFIG_NAME}${ext}`);
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Adopted from @see https://github.com/web-infra-dev/rspress/blob/main/packages/cli/src/index.ts
4
+ */
5
+ export {};
@@ -0,0 +1,123 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Adopted from @see https://github.com/web-infra-dev/rspress/blob/main/packages/cli/src/index.ts
4
+ */
5
+ import path from 'node:path';
6
+ import { logger } from '@rsbuild/core';
7
+ import { build, dev, serve } from '@rspress/core';
8
+ import { watch } from 'chokidar';
9
+ import { program } from 'commander';
10
+ import { green } from 'yoctocolors';
11
+ import module from 'node:module';
12
+ import { DEFAULT_CONFIGS } from './constants.js';
13
+ import { loadConfig, resolveDocRoot } from './load-config.js';
14
+ const I18N_FILE = 'i18n.json';
15
+ const META_FILE = '_meta.json';
16
+ const CONFIG_FILES = [...DEFAULT_CONFIGS, I18N_FILE];
17
+ const cwd = process.cwd();
18
+ const setNodeEnv = (env) => {
19
+ process.env.NODE_ENV = env;
20
+ };
21
+ const cjsRequire = module.createRequire(import.meta.url);
22
+ const pkg = cjsRequire('../../package.json');
23
+ program
24
+ .name('doom')
25
+ .description(pkg.description)
26
+ .version(pkg.version)
27
+ .option('-c, --config [config]', 'Specify the path to the config file')
28
+ .command('dev', { isDefault: true })
29
+ .description('Start the development server')
30
+ .argument('[root]', 'Root directory of the documentation')
31
+ .option('--port [port]', 'Port number')
32
+ .option('--host [host]', 'Host name')
33
+ .action(async (root, { config: configFile, ...server }) => {
34
+ setNodeEnv('development');
35
+ let devServer;
36
+ let cliWatcher;
37
+ const startDevServer = async () => {
38
+ const { config, filepath } = await loadConfig(configFile);
39
+ config.root = resolveDocRoot(cwd, root, config.root);
40
+ config.i18nSourcePath = path.resolve(config.root, I18N_FILE);
41
+ const docDirectory = config.root;
42
+ try {
43
+ devServer = await dev({
44
+ config,
45
+ appDirectory: cwd,
46
+ docDirectory,
47
+ extraBuilderConfig: {
48
+ server,
49
+ },
50
+ });
51
+ }
52
+ catch (err) {
53
+ logger.error(err);
54
+ devServer = undefined;
55
+ }
56
+ cliWatcher = watch(filepath ? [filepath, docDirectory] : [...CONFIG_FILES, docDirectory], {
57
+ ignoreInitial: true,
58
+ ignored: ['**/node_modules/**', '**/.git/**', '**/.DS_Store/**'],
59
+ cwd,
60
+ });
61
+ let isRestarting = false;
62
+ cliWatcher.on('all', async (eventName, filepath) => {
63
+ if (eventName === 'add' ||
64
+ eventName === 'unlink' ||
65
+ (eventName === 'change' &&
66
+ (CONFIG_FILES.includes(path.basename(filepath)) ||
67
+ path.basename(filepath) === META_FILE))) {
68
+ if (isRestarting) {
69
+ return;
70
+ }
71
+ isRestarting = true;
72
+ console.log(`\n✨ ${eventName} ${green(path.relative(cwd, filepath))}, dev server will restart...\n`);
73
+ await devServer?.close();
74
+ await cliWatcher.close();
75
+ await startDevServer();
76
+ isRestarting = false;
77
+ }
78
+ });
79
+ };
80
+ await startDevServer();
81
+ const exitProcess = async () => {
82
+ try {
83
+ await devServer?.close();
84
+ await cliWatcher.close();
85
+ }
86
+ finally {
87
+ process.exit(0);
88
+ }
89
+ };
90
+ process.on('SIGINT', exitProcess);
91
+ process.on('SIGTERM', exitProcess);
92
+ })
93
+ .parent.command('build [root]')
94
+ .description('Build the documentation')
95
+ .action(async (root, { config: configFile }) => {
96
+ setNodeEnv('production');
97
+ const { config } = await loadConfig(configFile);
98
+ config.root = resolveDocRoot(cwd, root, config.root);
99
+ config.i18nSourcePath = path.resolve(config.root, I18N_FILE);
100
+ const docDirectory = config.root;
101
+ await build({
102
+ config,
103
+ appDirectory: cwd,
104
+ docDirectory,
105
+ });
106
+ })
107
+ .parent.command('preview')
108
+ .alias('serve')
109
+ .description('Preview the built documentation')
110
+ .argument('[root]', 'Root directory of the documentation')
111
+ .option('--port [port]', 'Port number', '4173')
112
+ .option('--host [host]', 'Host name')
113
+ .action(async (root, { config: configFile, ...server }) => {
114
+ setNodeEnv('production');
115
+ const { config } = await loadConfig(configFile);
116
+ config.root = resolveDocRoot(cwd, root, config.root);
117
+ config.i18nSourcePath = path.resolve(config.root, I18N_FILE);
118
+ await serve({
119
+ config,
120
+ ...server,
121
+ });
122
+ })
123
+ .parent.parse();
@@ -0,0 +1,6 @@
1
+ import type { UserConfig } from '@rspress/core';
2
+ export declare function loadConfig(configFile?: string): Promise<{
3
+ config: UserConfig;
4
+ filepath?: string;
5
+ }>;
6
+ export declare function resolveDocRoot(cwd: string, cliRoot?: string, configRoot?: string): string;
@@ -0,0 +1,99 @@
1
+ import { nodeTypes } from '@mdx-js/mdx';
2
+ import { logger } from '@rspress/shared/logger';
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import rehypeRaw from 'rehype-raw';
6
+ import { parse } from 'yaml';
7
+ import { autoSidebarPlugin, globalPlugin } from '../plugins/index.js';
8
+ import { DEFAULT_CONFIG_NAME, DEFAULT_EXTENSIONS, YAML_EXTENSIONS, } from './constants.js';
9
+ const COMMON_CONFIG = {
10
+ base: '/docs',
11
+ lang: 'en',
12
+ logo: '/logo.svg',
13
+ icon: '/logo.svg',
14
+ outDir: 'dist',
15
+ markdown: {
16
+ checkDeadLinks: true,
17
+ mdxRs: false,
18
+ rehypePlugins: [[rehypeRaw, { passThrough: nodeTypes }]],
19
+ },
20
+ ssg: {
21
+ strict: true,
22
+ },
23
+ themeConfig: {
24
+ locales: [
25
+ {
26
+ lang: 'zh',
27
+ label: '简体中文',
28
+ searchPlaceholderText: '搜索文档',
29
+ searchNoResultsText: '未搜索到相关结果',
30
+ searchSuggestedQueryText: '可更换不同的关键字后重试',
31
+ outlineTitle: '本页概览',
32
+ },
33
+ {
34
+ lang: 'en',
35
+ label: 'English',
36
+ },
37
+ ],
38
+ },
39
+ plugins: [autoSidebarPlugin(), globalPlugin()],
40
+ builderConfig: {
41
+ dev: {
42
+ lazyCompilation: true,
43
+ },
44
+ server: {
45
+ open: '/docs/',
46
+ },
47
+ },
48
+ };
49
+ const findConfig = (basePath) => {
50
+ return DEFAULT_EXTENSIONS.map((ext) => basePath + ext).find(fs.existsSync);
51
+ };
52
+ export async function loadConfig(configFile) {
53
+ let configFilePath;
54
+ if (configFile) {
55
+ configFilePath = path.resolve(configFile);
56
+ }
57
+ else {
58
+ configFilePath = findConfig(path.resolve(DEFAULT_CONFIG_NAME));
59
+ }
60
+ if (!configFilePath) {
61
+ logger.info(`No doom config file found in ${process.cwd()}`);
62
+ return {
63
+ config: {},
64
+ };
65
+ }
66
+ const { loadConfig, mergeRsbuildConfig } = await import('@rsbuild/core');
67
+ let config;
68
+ try {
69
+ if (YAML_EXTENSIONS.includes(path.extname(configFilePath))) {
70
+ config = parse(fs.readFileSync(configFilePath, 'utf-8'));
71
+ }
72
+ else {
73
+ const { content } = await loadConfig({
74
+ cwd: path.dirname(configFilePath),
75
+ path: configFilePath,
76
+ });
77
+ config = content;
78
+ }
79
+ }
80
+ catch {
81
+ logger.error(`Failed to load config from ${configFilePath}`);
82
+ }
83
+ return {
84
+ config: mergeRsbuildConfig(COMMON_CONFIG, config ?? {}),
85
+ filepath: configFilePath,
86
+ };
87
+ }
88
+ export function resolveDocRoot(cwd, cliRoot, configRoot) {
89
+ // CLI root has highest priority
90
+ if (cliRoot) {
91
+ return path.join(cwd, cliRoot);
92
+ }
93
+ // Config root is next in priority
94
+ if (configRoot) {
95
+ return path.isAbsolute(configRoot) ? configRoot : path.join(cwd, configRoot);
96
+ }
97
+ // Default to 'docs' if no root is specified
98
+ return path.join(cwd, 'docs');
99
+ }
@@ -0,0 +1,2 @@
1
+ import { type RspressPlugin } from '@rspress/core';
2
+ export declare const autoSidebarPlugin: () => RspressPlugin;
@@ -0,0 +1,200 @@
1
+ import { addTrailingSlash } from '@rspress/core';
2
+ import { logger } from '@rspress/shared/logger';
3
+ import path from 'node:path';
4
+ import { combineWalkResult } from './utils.js';
5
+ import { walk } from './walk.js';
6
+ // 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.
7
+ // We will do as follows:
8
+ // 1. scan the directory structure, and extract all the `_meta.json` files.
9
+ // The `_meta.json` files will have two types:
10
+ // - For the `_meta.json` directly in the work directory, it will be used as the nav configuration.
11
+ // - For the `_meta.json` in the subdirectory, it will be used as the sidebar configuration.
12
+ // First, for the `_meta.json` directly in the work directory, the json content will have the following structure(see `NavMeta`):
13
+ // ```ts
14
+ // export type NavMeta = NavItem[];
15
+ // export type NavItem = NavItemWithLink | NavItemWithChildren;
16
+ // export type NavItemWithLink = {
17
+ // text: string;
18
+ // link: string;
19
+ // activeMatch?: string;
20
+ // position?: 'left' | 'right';
21
+ // };
22
+ // export type NavItemChildren = {
23
+ // text: string;
24
+ // items: NavItemWithLink[];
25
+ // };
26
+ // ```
27
+ // The `NavItemWithLink` will be used as the nav item, and the `NavItemChildren` will be used as the nav item with children.
28
+ // Second, for the `_meta.json` in the subdirectory, the json content will have the following structure(see `SideMeta`):
29
+ // ```ts
30
+ // export type SideMetaItem =
31
+ // | string
32
+ // | {
33
+ // type: 'file' | 'directory';
34
+ // name: string;
35
+ // // Use the h1 title as the sidebar title by default
36
+ // label?: string;
37
+ // collapsible?: boolean;
38
+ // collapsed?: boolean;
39
+ // };
40
+ // export type SideMeta = SideMetaItem[];
41
+ // ```
42
+ // The `SideMetaItem` can be the following types:
43
+ // - string: the file name, such as `home.md`, can also remove the extension name, such as `home`.
44
+ // - 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`.
45
+ // 2. generate the nav and sidebar configuration according to the `_meta.json` files.
46
+ // 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.
47
+ // For nav config, we don't need to do anything, just use the `_meta.json` content as the nav config.
48
+ // For sidebar config, we need to transform every item of the array config:
49
+ // - string: we transform the string to a object with `text` and `link` property.Such as:
50
+ // ```ts
51
+ // {
52
+ // text: 'home',
53
+ // link: '/home'
54
+ // }
55
+ // ```
56
+ // - object: in this case, we will take account of the `type` property:
57
+ // - file: we will transform the object to a object with `text` and `link` property.Such as:
58
+ // ```ts
59
+ // {
60
+ // text: 'home',
61
+ // link: '/home'
62
+ // }
63
+ // ```
64
+ // - directory: we will transform the object to a object with `text` and `items` property.
65
+ // There is the following file structure:
66
+ // ```
67
+ // docs
68
+ // ├── guide
69
+ // │ ├── home.md
70
+ // │ ├── advanced
71
+ // │ │ └── plugin.md
72
+ // │ └── _meta.json
73
+ // └── _meta.json
74
+ // ```
75
+ // The `_meta.json` in the work directory has the following content:
76
+ // ```json
77
+ // [
78
+ // {
79
+ // "text": "guide",
80
+ // "link": "/guide"
81
+ // }
82
+ // ]
83
+ // ```
84
+ // The `_meta.json` in the `guide` directory has the following content:
85
+ // ```json
86
+ // [
87
+ // 'home',
88
+ // {
89
+ // "type": "directory",
90
+ // "name": "advanced",
91
+ // "label": "advanced",
92
+ // "collapsible": true,
93
+ // "collapsed": false
94
+ // }
95
+ // ]
96
+ // ```
97
+ // The `home.md` has the following content:
98
+ // ```md
99
+ // # home
100
+ // ```
101
+ // The `_meta.json` in the `advanced` directory has the following content:
102
+ // ```json
103
+ // [
104
+ // {
105
+ // "type": "file",
106
+ // "name": "plugin",
107
+ // "label": "plugin",
108
+ // "collapsible": true,
109
+ // "collapsed": false
110
+ // }
111
+ // ]
112
+ // ```
113
+ // The `plugin.md` has the following content:
114
+ // ```md
115
+ // # plugin
116
+ // ```
117
+ // The generated nav config will be:
118
+ // ```json
119
+ // [
120
+ // {
121
+ // "text": "guide",
122
+ // "link": "/guide"
123
+ // }
124
+ // ]
125
+ // ```
126
+ // The generated sidebar config will be:
127
+ // ```json
128
+ // [
129
+ // {
130
+ // "text": "home",
131
+ // "link": "/guide/home"
132
+ // },
133
+ // {
134
+ // "text": "advanced",
135
+ // "items": [
136
+ // {
137
+ // "text": "plugin",
138
+ // "link": "/guide/advanced/plugin"
139
+ // }
140
+ // ]
141
+ // }
142
+ // ]
143
+ // ```
144
+ function processLocales(langs, versions, root, defaultLang, defaultVersion, extensions) {
145
+ return Promise.all(langs.map(async (lang) => {
146
+ const walks = versions.length
147
+ ? await Promise.all(versions.map((version) => {
148
+ const routePrefix = addTrailingSlash(`${version === defaultVersion ? '' : `/${version}`}${lang === defaultLang ? '' : `/${lang}`}`);
149
+ return walk(path.join(root, version, lang), routePrefix, root, extensions);
150
+ }))
151
+ : [
152
+ await walk(path.join(root, lang), addTrailingSlash(lang === defaultLang ? '' : `/${lang}`), root, extensions),
153
+ ];
154
+ return combineWalkResult(walks, versions);
155
+ }));
156
+ }
157
+ const defaultExtensions = ['.mdx', '.md', '.tsx', '.jsx', '.ts', '.js'];
158
+ export const autoSidebarPlugin = () => {
159
+ return {
160
+ name: 'doom-auto-sidebar',
161
+ async config(config, utils) {
162
+ utils.removePlugin('auto-nav-sidebar');
163
+ config.themeConfig = config.themeConfig || {};
164
+ config.themeConfig.locales =
165
+ config.themeConfig.locales || config.locales || [];
166
+ const langs = config.themeConfig.locales.map((locale) => locale.lang);
167
+ const hasLocales = langs.length > 0;
168
+ const hasLang = Boolean(config.lang);
169
+ const versions = config.multiVersion?.versions || [];
170
+ const defaultLang = config.lang || '';
171
+ const { default: defaultVersion = '' } = config.multiVersion || {};
172
+ const { extensions = defaultExtensions } = config.route || {};
173
+ if (hasLocales) {
174
+ const metaInfo = await processLocales(langs, versions, config.root, defaultLang, defaultVersion, extensions);
175
+ config.themeConfig.locales = config.themeConfig.locales.map((item, index) => ({
176
+ ...item,
177
+ ...metaInfo[index],
178
+ }));
179
+ }
180
+ else {
181
+ if (hasLang) {
182
+ logger.error('`lang` is configured but `locales` not, ' +
183
+ 'thus `@rspress/plugin-auto-nav-sidebar` can not auto generate ' +
184
+ 'navbar level config correctly!\n' +
185
+ 'please check your config file');
186
+ return config;
187
+ }
188
+ const walks = versions.length
189
+ ? await Promise.all(versions.map((version) => {
190
+ const routePrefix = addTrailingSlash(version === defaultVersion ? '' : `/${version}`);
191
+ return walk(path.join(config.root, version), routePrefix, config.root, extensions);
192
+ }))
193
+ : [await walk(config.root, '/', config.root, extensions)];
194
+ const combined = combineWalkResult(walks, versions);
195
+ config.themeConfig = { ...config.themeConfig, ...combined };
196
+ }
197
+ return config;
198
+ },
199
+ };
200
+ };
@@ -0,0 +1,15 @@
1
+ import type { Nav } from '@rspress/shared';
2
+ export type NavMeta = Nav;
3
+ export type SideMetaItem = string | {
4
+ type: 'file' | 'dir' | 'divider' | 'custom-link' | 'section-header';
5
+ name: string;
6
+ link?: string;
7
+ label?: string;
8
+ collapsible?: boolean;
9
+ collapsed?: boolean;
10
+ tag?: string;
11
+ dashed?: boolean;
12
+ overviewHeaders?: number[];
13
+ context?: string;
14
+ };
15
+ export type SideMeta = SideMetaItem[];
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,17 @@
1
+ import type { NavItem } from '@rspress/shared';
2
+ import { DoomSidebar } from './walk.js';
3
+ export declare function detectFilePath(rawPath: string, extensions: string[]): Promise<string | undefined>;
4
+ export declare function extractInfoFromFrontmatter(filePath: string, rootDir: string, extensions: string[]): Promise<{
5
+ realPath: string | undefined;
6
+ title: string;
7
+ overviewHeaders: number[] | undefined;
8
+ context: string | undefined;
9
+ weight?: number;
10
+ }>;
11
+ export declare function combineWalkResult(walks: {
12
+ nav: NavItem[];
13
+ sidebar: Record<string, DoomSidebar[]>;
14
+ }[], versions: string[]): {
15
+ nav: {};
16
+ sidebar: {};
17
+ };
@@ -0,0 +1,56 @@
1
+ import fs from '@rspress/shared/fs-extra';
2
+ import { logger } from '@rspress/shared/logger';
3
+ import { loadFrontMatter } from '@rspress/shared/node-utils';
4
+ import path from 'node:path';
5
+ export async function detectFilePath(rawPath, extensions) {
6
+ // The params doesn't have extension name, so we need to try to find the file with the extension name.
7
+ let realPath = rawPath;
8
+ const fileExtname = path.extname(rawPath);
9
+ // pathname may contain .json, see issue: https://github.com/web-infra-dev/rspress/issues/951
10
+ if (!extensions.includes(fileExtname)) {
11
+ const pathWithExtension = extensions.map((ext) => `${rawPath}${ext}`);
12
+ const pathExistInfo = await Promise.all(pathWithExtension.map((p) => fs.pathExists(p)));
13
+ const findPath = pathWithExtension.find((_, i) => pathExistInfo[i]);
14
+ // file may be public resource, see issue: https://github.com/web-infra-dev/rspress/issues/1052
15
+ if (!fileExtname || findPath) {
16
+ realPath = findPath;
17
+ }
18
+ }
19
+ return realPath;
20
+ }
21
+ export async function extractInfoFromFrontmatter(filePath, rootDir, extensions) {
22
+ const realPath = await detectFilePath(filePath, extensions);
23
+ if (!realPath) {
24
+ logger.warn(`Can't find the file: ${filePath}, please check it in "${path.join(path.dirname(filePath), '_meta.json')}".`);
25
+ return {
26
+ realPath,
27
+ title: '',
28
+ overviewHeaders: undefined,
29
+ context: undefined,
30
+ };
31
+ }
32
+ const content = await fs.readFile(realPath, 'utf-8');
33
+ const fileNameWithoutExt = path.basename(realPath, path.extname(realPath));
34
+ const h1RegExp = /^#\s+(.*)$/m;
35
+ const match = content.match(h1RegExp);
36
+ const { frontmatter } = loadFrontMatter(content, filePath, rootDir);
37
+ return {
38
+ realPath,
39
+ title: frontmatter.title || match?.[1] || fileNameWithoutExt,
40
+ overviewHeaders: frontmatter.overviewHeaders,
41
+ context: frontmatter.context,
42
+ weight: frontmatter.weight,
43
+ };
44
+ }
45
+ export function combineWalkResult(walks, versions) {
46
+ return walks.reduce((acc, cur, curIndex) => ({
47
+ nav: {
48
+ ...acc.nav,
49
+ [versions[curIndex] || 'default']: cur.nav,
50
+ },
51
+ sidebar: { ...acc.sidebar, ...cur.sidebar },
52
+ }), {
53
+ nav: {},
54
+ sidebar: {},
55
+ });
56
+ }
@@ -0,0 +1,19 @@
1
+ import { type NavItem, type SidebarDivider, type SidebarGroup, type SidebarItem, type SidebarSectionHeader } from '@rspress/shared';
2
+ export interface DoomSidebarItem extends SidebarItem {
3
+ weight?: number;
4
+ }
5
+ export type DoomSidebar = DoomSidebarGroup | DoomSidebarItem | SidebarDivider | SidebarSectionHeader;
6
+ export interface DoomSidebarGroup extends Omit<SidebarGroup, 'items'> {
7
+ items: DoomSidebar[];
8
+ weight?: number;
9
+ }
10
+ export declare function scanSideMeta(workDir: string, rootDir: string, docsDir: string, routePrefix: string, extensions: string[]): Promise<{
11
+ index?: DoomSidebarItem;
12
+ others: DoomSidebar[];
13
+ }>;
14
+ export declare function walk(workDir: string, routePrefix: string | undefined, docsDir: string, extensions: string[]): Promise<{
15
+ nav: NavItem[];
16
+ sidebar: {
17
+ [x: string]: DoomSidebar[];
18
+ };
19
+ }>;
@@ -0,0 +1,209 @@
1
+ import { isExternalUrl, removeTrailingSlash, slash, withBase, } from '@rspress/shared';
2
+ import fs from '@rspress/shared/fs-extra';
3
+ import { logger } from '@rspress/shared/logger';
4
+ import path from 'node:path';
5
+ import { detectFilePath, extractInfoFromFrontmatter } from './utils.js';
6
+ const sidebarSorter = (a, b) => {
7
+ if ('weight' in a && 'weight' in b) {
8
+ return a.weight - b.weight;
9
+ }
10
+ return 0;
11
+ };
12
+ /**
13
+ * Split sideMeta into two parts: `index` and `others` and sort `others` by weight
14
+ */
15
+ const splitSideMeta = (sideMeta, extensions) => {
16
+ const result = sideMeta.reduce((acc, curr) => {
17
+ if ('_fileKey' in curr &&
18
+ !('items' in curr) &&
19
+ !acc.index &&
20
+ extensions.some((ext) => curr._fileKey?.endsWith(`/index${ext}`))) {
21
+ acc.index = curr;
22
+ }
23
+ else {
24
+ acc.others.push(curr);
25
+ }
26
+ return acc;
27
+ }, { others: [] });
28
+ result.others.sort(sidebarSorter);
29
+ return result;
30
+ };
31
+ export async function scanSideMeta(workDir, rootDir, docsDir, routePrefix, extensions) {
32
+ if (!(await fs.exists(workDir))) {
33
+ logger.error('[plugin-auto-sidebar]', `Generate sidebar meta error: ${workDir} not exists`);
34
+ }
35
+ const addRoutePrefix = (link) => `${routePrefix}${link}`;
36
+ // find the `_meta.json` file
37
+ const metaFile = path.resolve(workDir, '_meta.json');
38
+ // Fix the windows path
39
+ const relativePath = slash(path.relative(rootDir, workDir));
40
+ let sideMeta;
41
+ // Get the sidebar config from the `_meta.json` file
42
+ try {
43
+ // Don't use require to avoid require cache, which make hmr not work.
44
+ sideMeta = (await fs.readJSON(metaFile, 'utf8'));
45
+ }
46
+ catch {
47
+ // If the `_meta.json` file doesn't exist, we will generate the sidebar config from the directory structure.
48
+ let subItems = await fs.readdir(workDir);
49
+ // If there exists a file with the same name of the directory folder
50
+ // we don't need to generate SideMeta for this single file
51
+ subItems = subItems.filter((item) => {
52
+ const hasExtension = extensions.some((ext) => item.endsWith(ext));
53
+ const hasSameBaseName = subItems.some((elem) => {
54
+ const baseName = elem.replace(/\.[^/.]+$/, '');
55
+ return baseName === item.replace(/\.[^/.]+$/, '') && elem !== item;
56
+ });
57
+ return !(hasExtension && hasSameBaseName);
58
+ });
59
+ sideMeta = (await Promise.all(subItems.map(async (item) => {
60
+ // Fix https://github.com/web-infra-dev/rspress/issues/346
61
+ if (item === '_meta.json') {
62
+ return null;
63
+ }
64
+ const stat = await fs.stat(path.join(workDir, item));
65
+ // If the item is a directory, we will transform it to a object with `type` and `name` property.
66
+ if (stat.isDirectory()) {
67
+ // set H1 title to sidebar label when have same name md/mdx file
68
+ const mdFilePath = path.join(workDir, `${item}.md`);
69
+ const mdxFilePath = path.join(workDir, `${item}.mdx`);
70
+ let label = item;
71
+ const setLabelFromFilePath = async (filePath) => {
72
+ const { title } = await extractInfoFromFrontmatter(filePath, rootDir, extensions);
73
+ label = title;
74
+ };
75
+ if (fs.existsSync(mdxFilePath)) {
76
+ await setLabelFromFilePath(mdxFilePath);
77
+ }
78
+ else if (fs.existsSync(mdFilePath)) {
79
+ await setLabelFromFilePath(mdFilePath);
80
+ }
81
+ return {
82
+ type: 'dir',
83
+ name: item,
84
+ label,
85
+ };
86
+ }
87
+ return extensions.some((ext) => item.endsWith(ext)) ? item : null;
88
+ }))).filter(Boolean);
89
+ }
90
+ const sidebarFromMeta = await Promise.all(sideMeta.map(async (metaItem) => {
91
+ if (typeof metaItem === 'string') {
92
+ const { title, overviewHeaders, context, weight } = await extractInfoFromFrontmatter(path.resolve(workDir, metaItem), rootDir, extensions);
93
+ const pureLink = `${relativePath}/${metaItem.replace(/\.mdx?$/, '')}`;
94
+ return {
95
+ text: title,
96
+ link: addRoutePrefix(pureLink),
97
+ overviewHeaders,
98
+ context,
99
+ weight,
100
+ _fileKey: path.relative(docsDir, path.join(workDir, metaItem)),
101
+ };
102
+ }
103
+ const { type = 'file', name, label = '', collapsible, collapsed, link, tag, dashed, overviewHeaders, context, } = metaItem;
104
+ // when type is divider, name maybe undefined, and link is not used
105
+ const pureLink = `${relativePath}/${name.replace(/\.mdx?$/, '')}`;
106
+ if (type === 'file') {
107
+ const info = await extractInfoFromFrontmatter(path.resolve(workDir, name), rootDir, extensions);
108
+ const title = label || info.title;
109
+ const realPath = info.realPath;
110
+ return {
111
+ text: title,
112
+ link: addRoutePrefix(pureLink),
113
+ tag,
114
+ overviewHeaders: info.overviewHeaders
115
+ ? info.overviewHeaders
116
+ : overviewHeaders,
117
+ context: info.context ? info.context : context,
118
+ weight: info.weight,
119
+ _fileKey: realPath ? path.relative(docsDir, realPath) : '',
120
+ };
121
+ }
122
+ if (type === 'dir') {
123
+ const subDir = path.resolve(workDir, name);
124
+ const { index, others: subSidebar } = await scanSideMeta(subDir, rootDir, docsDir, routePrefix, extensions);
125
+ const realPath = await detectFilePath(subDir, extensions);
126
+ const group = {
127
+ text: label,
128
+ collapsible,
129
+ collapsed,
130
+ items: subSidebar,
131
+ link: realPath ? addRoutePrefix(pureLink) : '',
132
+ tag,
133
+ overviewHeaders,
134
+ context,
135
+ _fileKey: realPath ? path.relative(docsDir, realPath) : '',
136
+ };
137
+ return index ? { ...group, ...index } : group;
138
+ }
139
+ if (type === 'divider') {
140
+ return {
141
+ dividerType: dashed ? 'dashed' : 'solid',
142
+ };
143
+ }
144
+ if (type === 'section-header') {
145
+ return {
146
+ sectionHeaderText: label,
147
+ tag,
148
+ };
149
+ }
150
+ return {
151
+ text: label,
152
+ link: isExternalUrl(link) ? link : withBase(link, routePrefix),
153
+ tag,
154
+ };
155
+ }));
156
+ return splitSideMeta(sidebarFromMeta, extensions);
157
+ }
158
+ // Start walking from the doc directory, scan the `_meta.json` file in each subdirectory
159
+ // and generate the nav and sidebar config
160
+ export async function walk(workDir, routePrefix = '/', docsDir, extensions) {
161
+ // find the `_meta.json` file
162
+ const rootMetaFile = path.resolve(workDir, '_meta.json');
163
+ let navConfig;
164
+ // Get the nav config from the `_meta.json` file
165
+ try {
166
+ navConfig = (await fs.readJSON(rootMetaFile, 'utf8'));
167
+ }
168
+ catch {
169
+ navConfig = [];
170
+ }
171
+ navConfig.forEach((navItem) => {
172
+ if ('items' in navItem) {
173
+ navItem.items.forEach((item) => {
174
+ if ('link' in item && !isExternalUrl(item.link)) {
175
+ item.link = withBase(item.link, routePrefix);
176
+ }
177
+ });
178
+ }
179
+ if ('link' in navItem && !isExternalUrl(navItem.link)) {
180
+ navItem.link = withBase(navItem.link, routePrefix);
181
+ }
182
+ });
183
+ // find the `_meta.json` file in the subdirectory
184
+ const subDirs = (await fs.readdir(workDir)).filter((v) => fs.statSync(path.join(workDir, v)).isDirectory() && v !== 'node_modules');
185
+ const sidebars = [];
186
+ // Every sub dir will represent a group of sidebar
187
+ const sidebarConfig = {
188
+ [routePrefix]: sidebars,
189
+ };
190
+ for (const subDir of subDirs) {
191
+ const { index, others } = await scanSideMeta(path.join(workDir, subDir), workDir, docsDir, routePrefix, extensions);
192
+ const sidebar = index
193
+ ? { ...index, collapsed: true, items: others }
194
+ : { text: subDir, collapsed: true, items: others };
195
+ if (!sidebar.items.length) {
196
+ // @ts-expect-error -- FIXME: rspress should handle `undefined` items
197
+ delete sidebar.items;
198
+ }
199
+ sidebars.push(sidebar);
200
+ }
201
+ sidebars.sort(sidebarSorter);
202
+ if (removeTrailingSlash(routePrefix)) {
203
+ sidebarConfig[removeTrailingSlash(routePrefix)] = sidebars;
204
+ }
205
+ return {
206
+ nav: navConfig,
207
+ sidebar: sidebarConfig,
208
+ };
209
+ }
@@ -0,0 +1,2 @@
1
+ import type { RspressPlugin } from '@rspress/core';
2
+ export declare const globalPlugin: () => RspressPlugin;
@@ -0,0 +1,15 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ const componentsDir = path.resolve(import.meta.dirname, '../../runtime/components');
4
+ export const globalPlugin = () => {
5
+ return {
6
+ name: 'doom-global',
7
+ globalStyles: path.resolve(import.meta.dirname, '../../../styles/global.scss'),
8
+ markdown: {
9
+ globalComponents: fs
10
+ .readdirSync(componentsDir)
11
+ .filter((file) => path.basename(file, path.extname(file)) !== 'index')
12
+ .map((file) => path.resolve(componentsDir, file)),
13
+ },
14
+ };
15
+ };
@@ -0,0 +1,2 @@
1
+ export * from './auto-sidebar/index.js';
2
+ export * from './global/index.js';
@@ -0,0 +1,2 @@
1
+ export * from './auto-sidebar/index.js';
2
+ export * from './global/index.js';
@@ -0,0 +1,18 @@
1
+ import type { Header } from '@rspress/shared';
2
+ interface GroupItem {
3
+ text: string;
4
+ description?: string;
5
+ link: string;
6
+ headers?: Header[];
7
+ }
8
+ interface Group {
9
+ name: string;
10
+ items: GroupItem[];
11
+ }
12
+ export declare function Overview(props: {
13
+ content?: React.ReactNode;
14
+ groups?: Group[];
15
+ defaultGroupTitle?: string;
16
+ overviewHeaders?: number[];
17
+ }): import("react/jsx-runtime").JSX.Element;
18
+ export default Overview;
@@ -0,0 +1,128 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { Link, renderInlineMarkdown, useSidebarData } from '@rspress/core/theme';
3
+ import { isEqualPath, normalizeHrefInRuntime as normalizeHref, usePageData, withBase, } from '@rspress/runtime';
4
+ import { Fragment, useMemo } from 'react';
5
+ import classes from '../../../styles/overview.module.scss';
6
+ // The sidebar data include two types: sidebar item and sidebar group.
7
+ // In overpage page, we select all the related sidebar groups and show the groups in the page.
8
+ // In the meantime, some sidebar items also should be shown in the page, we collect them in the group named 'Others' and show them in the page.
9
+ export function Overview(props) {
10
+ const { siteData, page: { routePath, frontmatter, title }, } = usePageData();
11
+ const { content, groups: customGroups, defaultGroupTitle = 'Others' } = props;
12
+ const subFilter = (link) =>
13
+ // sidebar items link without base path
14
+ // pages route path with base path
15
+ withBase(link).startsWith(routePath.replace(/overview$/, '')) &&
16
+ !isEqualPath(withBase(link), routePath);
17
+ const getChildLink = (traverseItem) => {
18
+ if ('link' in traverseItem && traverseItem.link) {
19
+ return traverseItem.link;
20
+ }
21
+ if ('items' in traverseItem) {
22
+ return getChildLink(traverseItem.items[0]);
23
+ }
24
+ return '';
25
+ };
26
+ const findItemByRoutePath = (items, routePath, originalItems) => {
27
+ for (const item of items) {
28
+ if ('link' in item && withBase(item.link) === routePath) {
29
+ return [item];
30
+ }
31
+ if ('items' in item) {
32
+ return findItemByRoutePath(item.items, routePath, originalItems);
33
+ }
34
+ }
35
+ return originalItems;
36
+ };
37
+ const { pages } = siteData;
38
+ const overviewModules = pages.filter((page) => subFilter(page.routePath));
39
+ let { items: overviewSidebarGroups } = useSidebarData();
40
+ if (overviewSidebarGroups[0] &&
41
+ 'link' in overviewSidebarGroups[0] &&
42
+ overviewSidebarGroups[0]?.link !== routePath) {
43
+ overviewSidebarGroups = findItemByRoutePath(overviewSidebarGroups, routePath, overviewSidebarGroups);
44
+ }
45
+ function normalizeSidebarItem(item, sidebarGroup, frontmatter) {
46
+ if ('dividerType' in item) {
47
+ return item;
48
+ }
49
+ // do not display overview title in sub pages overview
50
+ if (withBase(item.link) === `${routePath}index` &&
51
+ frontmatter?.overview === true) {
52
+ return false;
53
+ }
54
+ // props > frontmatter in single file > _meta.json config in a file > frontmatter in overview page > _meta.json config in sidebar
55
+ const overviewHeaders = props.overviewHeaders ??
56
+ item.overviewHeaders ??
57
+ frontmatter?.overviewHeaders ??
58
+ sidebarGroup?.overviewHeaders ?? [2];
59
+ // sidebar items link without base path
60
+ const pageModule = overviewModules.find((m) => isEqualPath(m.routePath, withBase(item.link || '')));
61
+ const link = getChildLink(item);
62
+ return {
63
+ ...item,
64
+ description: pageModule?.frontmatter.description,
65
+ link,
66
+ headers: pageModule?.toc.filter((header) => overviewHeaders.some((depth) => header.depth === depth)) || [],
67
+ };
68
+ }
69
+ const isSingleFile = (item) => !('items' in item) && 'link' in item;
70
+ const getGroup = (sidebarGroups) => {
71
+ const group = sidebarGroups
72
+ .filter((sidebarGroup) => {
73
+ if ('items' in sidebarGroup) {
74
+ return (sidebarGroup.items.filter((item) => subFilter(getChildLink(item)))
75
+ .length > 0);
76
+ }
77
+ if (isSingleFile(sidebarGroup) &&
78
+ subFilter(getChildLink(sidebarGroup))) {
79
+ return true;
80
+ }
81
+ return false;
82
+ })
83
+ .map((sidebarGroup) => {
84
+ let items = [];
85
+ if ('items' in sidebarGroup) {
86
+ items = sidebarGroup.items
87
+ .map((item) => normalizeSidebarItem(item, sidebarGroup, frontmatter))
88
+ .filter((_) => !!_);
89
+ }
90
+ else if (isSingleFile(sidebarGroup)) {
91
+ items = [
92
+ normalizeSidebarItem({
93
+ link: sidebarGroup.link,
94
+ text: sidebarGroup.text || '',
95
+ tag: sidebarGroup.tag,
96
+ _fileKey: sidebarGroup._fileKey,
97
+ overviewHeaders: sidebarGroup.overviewHeaders,
98
+ }, undefined, frontmatter),
99
+ ].filter((_) => !!_);
100
+ }
101
+ return {
102
+ name: ('text' in sidebarGroup && sidebarGroup.text) || '',
103
+ items,
104
+ };
105
+ });
106
+ return group;
107
+ };
108
+ const groups = customGroups ??
109
+ useMemo(() => {
110
+ const group = getGroup(overviewSidebarGroups);
111
+ if (group.length) {
112
+ return group;
113
+ }
114
+ for (const sidebarGroup of overviewSidebarGroups) {
115
+ if (!('items' in sidebarGroup)) {
116
+ continue;
117
+ }
118
+ const group = getGroup(sidebarGroup.items);
119
+ if (group.length) {
120
+ return group;
121
+ }
122
+ }
123
+ return [];
124
+ }, [overviewSidebarGroups, routePath, frontmatter]);
125
+ return (_jsxs("div", { className: "overview-index mx-auto", children: [content, groups.map((group) => (_jsxs(Fragment, { children: [(group.name === title || group.name === defaultGroupTitle) &&
126
+ groups.length === 1 ? (_jsx("h2", { style: { paddingTop: 0 } })) : (_jsx("h2", { children: renderInlineMarkdown(group.name) })), _jsx("div", { className: classes.overviewGroups, children: group.items.map((item) => (_jsxs("div", { className: classes.overviewGroup, children: [_jsx("div", { className: "flex", children: _jsx("h3", { style: { marginBottom: 8 }, children: _jsx(Link, { href: normalizeHref(item.link), children: renderInlineMarkdown(item.text) }) }) }), _jsx("div", { className: classes.overviewDescription, children: item.description }), _jsx("ul", { className: "list-none", children: item.headers?.map((header) => (_jsx("li", { className: `${classes.overviewGroupLi} ${classes[`level${header.depth}`]} first:mt-2`, children: _jsx(Link, { href: `${normalizeHref(item.link)}#${header.id}`, children: renderInlineMarkdown(header.text) }) }, header.id))) })] }, item.link))) })] }, group.name)))] }));
127
+ }
128
+ export default Overview;
@@ -0,0 +1,13 @@
1
+ export interface QuickNavItem {
2
+ icon: string;
3
+ title: string;
4
+ links: Array<{
5
+ title: string;
6
+ href: string;
7
+ }>;
8
+ }
9
+ export interface QuickNavProps {
10
+ items: QuickNavItem[];
11
+ }
12
+ export declare const QuickNav: ({ items }: QuickNavProps) => import("react/jsx-runtime").JSX.Element;
13
+ export default QuickNav;
@@ -0,0 +1,8 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { Link } from '@rspress/core/theme';
3
+ import { normalizeImagePath } from '@rspress/core/runtime';
4
+ import classes from '../../../styles/quick-nav.module.scss';
5
+ export const QuickNav = ({ items }) => {
6
+ return (_jsx("ul", { className: classes.container, children: items.map((item, index) => (_jsxs("li", { className: classes.item, children: [_jsxs("div", { className: classes.title, title: item.title, children: [_jsx("img", { src: normalizeImagePath(item.icon), alt: item.title }), item.title] }), _jsx("hr", { className: classes.divider }), _jsx("ul", { className: classes.links, children: item.links.map((link, index) => (_jsx("li", { children: _jsx(Link, { href: link.href, title: link.title, children: link.title }) }, index))) })] }, index))) }));
7
+ };
8
+ export default QuickNav;
@@ -0,0 +1,2 @@
1
+ export * from './Overview.js';
2
+ export * from './QuickNav.js';
@@ -0,0 +1,2 @@
1
+ export * from './Overview.js';
2
+ export * from './QuickNav.js';
@@ -0,0 +1 @@
1
+ export * from './components/index.js';
@@ -0,0 +1,3 @@
1
+ // eslint-disable-next-line @typescript-eslint/triple-slash-reference
2
+ /// <reference path="../../global.d.ts" />
3
+ export * from './components/index.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alauda/doom",
3
- "version": "0.0.0-alpha.2",
3
+ "version": "0.0.0-alpha.3",
4
4
  "type": "module",
5
5
  "description": "Doctor Doom making docs.",
6
6
  "repository": "https://gitlab-ce.alauda.cn/idp/Doom",
@@ -28,6 +28,7 @@
28
28
  "lint:es": "eslint .",
29
29
  "lint:tsc": "tsc -b --noEmit",
30
30
  "prepare": "simple-git-hooks",
31
+ "prepublishOnly": "yarn build",
31
32
  "swc-node": "node --enable-source-maps --import @swc-node/register/esm-register"
32
33
  },
33
34
  "dependencies": {