@umijs/plugin-docs 4.0.0-canary.20220429.3 → 4.0.0-canary.20220429.4

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,6 @@
1
+ export declare function compile(opts: {
2
+ content: string;
3
+ fileName: string;
4
+ }): Promise<{
5
+ result: string;
6
+ }>;
@@ -0,0 +1,87 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.compile = void 0;
16
+ const plugin_utils_1 = require("umi/plugin-utils");
17
+ const rehype_pretty_code_1 = __importDefault(require("rehype-pretty-code"));
18
+ // @ts-ignore
19
+ const mdx_1 = require("../compiled/@mdx-js/mdx");
20
+ // @ts-ignore
21
+ const rehype_slug_1 = __importDefault(require("../compiled/rehype-slug"));
22
+ // @ts-ignore
23
+ const remark_gfm_1 = __importDefault(require("../compiled/remark-gfm"));
24
+ // https://rehype-pretty-code.netlify.app
25
+ const rehypePrettyCodeOptions = {
26
+ theme: 'dark-plus',
27
+ onVisitLine(node) {
28
+ // Prevent lines from collapsing in `display: grid` mode, and
29
+ // allow empty lines to be copy/pasted
30
+ if (node.children.length === 0) {
31
+ node.children = [{ type: 'text', value: ' ' }];
32
+ }
33
+ },
34
+ // 允许高亮代码行
35
+ // 对于高亮的代码行,设置为 highlighted 样式表类
36
+ onVisitHighlightedLine(node) {
37
+ node.properties.className.push('highlighted');
38
+ },
39
+ // 允许高亮代码文字
40
+ // 对于高亮的代码文字,设置为 word 样式表类
41
+ onVisitHighlightedWord(node) {
42
+ node.properties.className = ['word'];
43
+ },
44
+ };
45
+ function compile(opts) {
46
+ return __awaiter(this, void 0, void 0, function* () {
47
+ const compiler = (0, mdx_1.createProcessor)({
48
+ jsx: true,
49
+ remarkPlugins: [remark_gfm_1.default],
50
+ rehypePlugins: [rehype_slug_1.default, [rehype_pretty_code_1.default, rehypePrettyCodeOptions]],
51
+ });
52
+ try {
53
+ let result = String(yield compiler.process(opts.content));
54
+ result = result.replace('function MDXContent(props = {}) {', `
55
+ import { useEffect } from 'react';
56
+
57
+ function MDXContent(props = {}) {
58
+
59
+ useEffect(() => {
60
+ if (window.location.hash.length !== 0) {
61
+ const hash = window.location.hash;
62
+ document.getElementById(hash.slice(1))?.scrollIntoView();
63
+ } else {
64
+ window.scrollTo(0, 0);
65
+ }
66
+ document.getElementById('active-nav-item')?.scrollIntoView({
67
+ behavior: 'smooth',
68
+ block: 'center'
69
+ });
70
+ }, []);
71
+
72
+ `);
73
+ return { result };
74
+ }
75
+ catch (e) {
76
+ plugin_utils_1.logger.error(e.reason);
77
+ plugin_utils_1.logger.error(`Above error occurred in ${opts.fileName} at line ${e.line}`);
78
+ plugin_utils_1.logger.error(opts.content
79
+ .split('\n')
80
+ .filter((_, i) => i == e.line - 1)
81
+ .join('\n'));
82
+ plugin_utils_1.logger.error(' '.repeat(e.column - 1) + '^');
83
+ return { result: '' };
84
+ }
85
+ });
86
+ }
87
+ exports.compile = compile;
@@ -0,0 +1,3 @@
1
+ import { IApi } from 'umi';
2
+ declare const _default: (api: IApi) => void;
3
+ export default _default;
package/dist/index.js ADDED
@@ -0,0 +1,148 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ const bundler_utils_1 = require("@umijs/bundler-utils");
27
+ const utils_1 = require("@umijs/utils");
28
+ const fs_1 = __importStar(require("fs"));
29
+ const path_1 = require("path");
30
+ const markdown_1 = require("./markdown");
31
+ exports.default = (api) => {
32
+ // 把用户当前有设置在 docs/locales 下的语系放到变量 locales 中,方便后续使用
33
+ const locales = {};
34
+ const localesPath = (0, path_1.join)(api.cwd, 'docs/locales');
35
+ if ((0, fs_1.existsSync)(localesPath)) {
36
+ fs_1.default.readdirSync(localesPath).forEach((file) => {
37
+ if (file.endsWith('.json')) {
38
+ const filePath = (0, path_1.join)(localesPath, file);
39
+ const content = fs_1.default.readFileSync(filePath).toString();
40
+ const json = JSON.parse(content);
41
+ const localeName = file.replace('.json', '');
42
+ locales[localeName] = json;
43
+ }
44
+ });
45
+ }
46
+ api.modifyDefaultConfig((memo) => {
47
+ memo.conventionRoutes = Object.assign(Object.assign({}, memo.conventionRoutes), { base: (0, path_1.join)(api.cwd, 'docs') });
48
+ memo.mdx = {
49
+ loader: require.resolve('./loader'),
50
+ loaderOptions: {},
51
+ };
52
+ return memo;
53
+ });
54
+ api.addLayouts(() => {
55
+ return [
56
+ {
57
+ id: 'docs-layout',
58
+ file: withTmpPath({ api, path: 'Layout.tsx' }),
59
+ },
60
+ ];
61
+ });
62
+ api.onPatchRoute(({ route }) => {
63
+ if (route.__content) {
64
+ route.titles = (0, markdown_1.parseTitle)({
65
+ content: route.__content,
66
+ });
67
+ }
68
+ // 放在 docs/xxx.zh-CN.md 的文档,会被映射到 /zh-CN/docs/xxx 目录
69
+ if (route.file.match(/.[a-z]{2}-[A-Z]{2}.md$/)) {
70
+ route.path = route.path.replace(/(.*).([a-z]{2}-[A-Z]{2})$/, '$2/$1');
71
+ // 放在 docs/xxx/README.zh-CN.md 格式结尾的文档,会被映射到 /zh-CN/docs 目录
72
+ if (route.path.endsWith('README')) {
73
+ route.path = route.path.replace(/README$/, '');
74
+ }
75
+ }
76
+ });
77
+ // 检查路由是否存在其他语言,没有的话做 fallback 处理
78
+ api.modifyRoutes((r) => {
79
+ if (!locales)
80
+ return r;
81
+ for (const route in r) {
82
+ if (r[route].path.match(/^[a-z]{2}-[A-Z]{2}\/.*/))
83
+ continue;
84
+ const defaultLangFile = r[route].file.replace(/(.[a-z]{2}-[A-Z]{2})?.md$/, '');
85
+ Object.keys(locales).map((l) => {
86
+ if (r[defaultLangFile] && !r[defaultLangFile + '.' + l]) {
87
+ r[defaultLangFile + '.' + l] = Object.assign(Object.assign({}, r[defaultLangFile]), { path: `/${l}/${r[defaultLangFile].path}` });
88
+ }
89
+ });
90
+ }
91
+ return r;
92
+ });
93
+ api.onGenerateFiles(() => {
94
+ var _a;
95
+ // theme path
96
+ let theme = ((_a = api.config.docs) === null || _a === void 0 ? void 0 : _a.theme) || require.resolve('../client/theme-doc/index.ts');
97
+ if (theme === 'blog') {
98
+ theme = require.resolve('../client/theme-blog/index.ts');
99
+ }
100
+ theme = (0, utils_1.winPath)(theme);
101
+ const themeConfigPath = (0, utils_1.winPath)((0, path_1.join)(api.cwd, 'theme.config.ts'));
102
+ const themeExists = (0, fs_1.existsSync)(themeConfigPath);
103
+ // 将 docs/locales 目录下的 json 文件注入到 themeConfig.locales 中
104
+ let injectLocale = `themeConfig.locales = ${JSON.stringify(locales)};`;
105
+ // exports don't start with $ will be MDX Component
106
+ const [_, exports] = (0, bundler_utils_1.parseModuleSync)({
107
+ content: (0, fs_1.readFileSync)(theme, 'utf-8'),
108
+ path: theme,
109
+ });
110
+ api.writeTmpFile({
111
+ path: 'index.ts',
112
+ content: `
113
+ export { ${exports
114
+ .filter((item) => !item.startsWith('$'))
115
+ .join(', ')} } from '${(0, utils_1.winPath)(require.resolve('../client/theme-doc/index.ts'))}';
116
+ `,
117
+ });
118
+ api.writeTmpFile({
119
+ path: 'Layout.tsx',
120
+ content: `
121
+ import React from 'react';
122
+ import { useOutlet, useAppData, useLocation, Link } from 'umi';
123
+ import { $Layout as Layout } from '${(0, utils_1.winPath)(require.resolve('../client/theme-doc/index.ts'))}';
124
+ ${themeExists
125
+ ? `import themeConfig from '${themeConfigPath}'`
126
+ : `const themeConfig = {}`}
127
+
128
+ ${injectLocale}
129
+
130
+ export default () => {
131
+ const outlet = useOutlet();
132
+ const appData = useAppData();
133
+ const location = useLocation();
134
+ return (
135
+ <Layout appData={appData} components={{Link}} themeConfig={themeConfig} location={location}>
136
+ <div>{ outlet }</div>
137
+ </Layout>
138
+ );
139
+ };
140
+ `,
141
+ });
142
+ });
143
+ };
144
+ function withTmpPath(opts) {
145
+ return (0, path_1.join)(opts.api.paths.absTmpPath, opts.api.plugin.key && !opts.noPluginDir
146
+ ? `plugin-${opts.api.plugin.key}`
147
+ : '', opts.path);
148
+ }
@@ -0,0 +1 @@
1
+ export default function (content: string): Promise<any>;
package/dist/loader.js ADDED
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ const compiler_1 = require("./compiler");
13
+ function default_1(content) {
14
+ return __awaiter(this, void 0, void 0, function* () {
15
+ // @ts-ignore
16
+ const filename = this.resourcePath;
17
+ // @ts-ignore
18
+ const callback = this.async();
19
+ try {
20
+ const { result } = yield (0, compiler_1.compile)({
21
+ content,
22
+ fileName: filename,
23
+ });
24
+ return callback(null, result);
25
+ }
26
+ catch (e) {
27
+ const err = e;
28
+ e.message = `${filename}: ${e.message}`;
29
+ throw err;
30
+ }
31
+ });
32
+ }
33
+ exports.default = default_1;
@@ -0,0 +1,6 @@
1
+ export declare function parseTitle(opts: {
2
+ content: string;
3
+ }): {
4
+ level: number;
5
+ title: string;
6
+ }[];
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseTitle = void 0;
4
+ function parseTitle(opts) {
5
+ const lines = opts.content.split('\n');
6
+ let i = 0;
7
+ const ret = [];
8
+ while (i < lines.length) {
9
+ const line = lines[i].trim();
10
+ const match = line.match(/^(#+)\s+(.*)/);
11
+ if (match) {
12
+ ret.push({
13
+ level: match[1].length,
14
+ title: match[2],
15
+ });
16
+ }
17
+ i += 1;
18
+ }
19
+ return ret;
20
+ }
21
+ exports.parseTitle = parseTitle;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@umijs/plugin-docs",
3
- "version": "4.0.0-canary.20220429.3",
3
+ "version": "4.0.0-canary.20220429.4",
4
4
  "description": "@umijs/plugin-docs",
5
5
  "homepage": "https://github.com/umijs/umi-next/tree/master/packages/plugin-docs#readme",
6
6
  "bugs": "https://github.com/umijs/umi-next/issues",
@@ -39,7 +39,7 @@
39
39
  "rehype-slug": "5.0.1",
40
40
  "remark-gfm": "^3.0.1",
41
41
  "tailwindcss": "^3.0.23",
42
- "umi": "4.0.0-canary.20220429.3"
42
+ "umi": "4.0.0-canary.20220429.4"
43
43
  },
44
44
  "publishConfig": {
45
45
  "access": "public"