@docusaurus/mdx-loader 2.0.0-beta.ff31de0ff → 2.0.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/lib/index.d.ts +32 -0
- package/lib/index.d.ts.map +1 -0
- package/lib/index.js +11 -0
- package/lib/index.js.map +1 -0
- package/lib/loader.d.ts +41 -0
- package/lib/loader.d.ts.map +1 -0
- package/lib/loader.js +210 -0
- package/lib/loader.js.map +1 -0
- package/lib/remark/admonitions/index.d.ts +15 -0
- package/lib/remark/admonitions/index.d.ts.map +1 -0
- package/lib/remark/admonitions/index.js +132 -0
- package/lib/remark/admonitions/index.js.map +1 -0
- package/lib/remark/headings/index.d.ts +9 -0
- package/lib/remark/headings/index.d.ts.map +1 -0
- package/lib/remark/headings/index.js +58 -0
- package/lib/remark/headings/index.js.map +1 -0
- package/lib/remark/toc/index.d.ts +9 -0
- package/lib/remark/toc/index.d.ts.map +1 -0
- package/lib/remark/toc/index.js +81 -0
- package/lib/remark/toc/index.js.map +1 -0
- package/lib/remark/transformImage/index.d.ts +13 -0
- package/lib/remark/transformImage/index.d.ts.map +1 -0
- package/lib/remark/transformImage/index.js +114 -0
- package/lib/remark/transformImage/index.js.map +1 -0
- package/lib/remark/transformLinks/index.d.ts +13 -0
- package/lib/remark/transformLinks/index.d.ts.map +1 -0
- package/lib/remark/transformLinks/index.js +106 -0
- package/lib/remark/transformLinks/index.js.map +1 -0
- package/lib/remark/unwrapMdxCodeBlocks/index.d.ts +9 -0
- package/lib/remark/unwrapMdxCodeBlocks/index.d.ts.map +1 -0
- package/lib/remark/unwrapMdxCodeBlocks/index.js +29 -0
- package/lib/remark/unwrapMdxCodeBlocks/index.js.map +1 -0
- package/lib/remark/utils/index.d.ts +11 -0
- package/lib/remark/utils/index.d.ts.map +1 -0
- package/lib/remark/utils/index.js +38 -0
- package/lib/remark/utils/index.js.map +1 -0
- package/package.json +26 -20
- package/src/deps.d.ts +31 -0
- package/src/index.ts +35 -0
- package/src/loader.ts +282 -0
- package/src/remark/admonitions/LICENSE +45 -0
- package/src/remark/admonitions/README.md +3 -0
- package/src/remark/admonitions/index.ts +186 -0
- package/src/remark/headings/{index.js → index.ts} +23 -27
- package/src/remark/toc/index.ts +98 -0
- package/src/remark/transformImage/index.ts +173 -0
- package/src/remark/transformLinks/index.ts +164 -0
- package/src/remark/unwrapMdxCodeBlocks/{index.js → index.ts} +14 -15
- package/src/remark/utils/index.ts +36 -0
- package/src/index.d.ts +0 -19
- package/src/index.js +0 -104
- package/src/remark/headings/__tests__/index.test.js +0 -315
- package/src/remark/toc/__tests__/__snapshots__/index.test.js.snap +0 -85
- package/src/remark/toc/__tests__/fixtures/empty-headings.md +0 -5
- package/src/remark/toc/__tests__/fixtures/inline-code.md +0 -9
- package/src/remark/toc/__tests__/fixtures/insert-below-imports.md +0 -11
- package/src/remark/toc/__tests__/fixtures/just-content.md +0 -15
- package/src/remark/toc/__tests__/fixtures/name-exist.md +0 -7
- package/src/remark/toc/__tests__/fixtures/non-text-content.md +0 -9
- package/src/remark/toc/__tests__/index.test.js +0 -212
- package/src/remark/toc/index.js +0 -79
- package/src/remark/toc/search.js +0 -73
- package/src/remark/transformImage/__tests__/__snapshots__/index.test.js.snap +0 -31
- package/src/remark/transformImage/__tests__/fixtures/fail.md +0 -1
- package/src/remark/transformImage/__tests__/fixtures/img.md +0 -17
- package/src/remark/transformImage/__tests__/fixtures/img.png +0 -0
- package/src/remark/transformImage/__tests__/fixtures/noUrl.md +0 -1
- package/src/remark/transformImage/__tests__/fixtures/pathname.md +0 -1
- package/src/remark/transformImage/__tests__/index.test.js +0 -59
- package/src/remark/transformImage/index.js +0 -106
- package/src/remark/transformLinks/__tests__/__snapshots__/index.test.js.snap +0 -41
- package/src/remark/transformLinks/__tests__/fixtures/asset.md +0 -29
- package/src/remark/transformLinks/__tests__/fixtures/asset.pdf +0 -0
- package/src/remark/transformLinks/__tests__/fixtures/noUrl.md +0 -1
- package/src/remark/transformLinks/__tests__/fixtures/pathname.md +0 -1
- package/src/remark/transformLinks/__tests__/fixtures/static/staticAsset.pdf +0 -0
- package/src/remark/transformLinks/__tests__/fixtures/static/staticAssetImage.png +0 -0
- package/src/remark/transformLinks/__tests__/index.test.js +0 -44
- package/src/remark/transformLinks/index.js +0 -143
- package/src/remark/unwrapMdxCodeBlocks/__tests__/__snapshots__/index.test.js.snap +0 -819
- package/src/remark/unwrapMdxCodeBlocks/__tests__/fixtures/has-mdx-code-blocks.mdx +0 -95
- package/src/remark/unwrapMdxCodeBlocks/__tests__/index.test.js +0 -38
- package/src/remark/utils/index.js +0 -39
- package/tsconfig.json +0 -9
package/src/loader.ts
ADDED
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright (c) Facebook, Inc. and its affiliates.
|
|
3
|
+
*
|
|
4
|
+
* This source code is licensed under the MIT license found in the
|
|
5
|
+
* LICENSE file in the root directory of this source tree.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import fs from 'fs-extra';
|
|
9
|
+
import logger from '@docusaurus/logger';
|
|
10
|
+
import {
|
|
11
|
+
parseFrontMatter,
|
|
12
|
+
parseMarkdownContentTitle,
|
|
13
|
+
escapePath,
|
|
14
|
+
getFileLoaderUtils,
|
|
15
|
+
} from '@docusaurus/utils';
|
|
16
|
+
import {createCompiler} from '@mdx-js/mdx';
|
|
17
|
+
import emoji from 'remark-emoji';
|
|
18
|
+
import stringifyObject from 'stringify-object';
|
|
19
|
+
|
|
20
|
+
import headings from './remark/headings';
|
|
21
|
+
import toc from './remark/toc';
|
|
22
|
+
import unwrapMdxCodeBlocks from './remark/unwrapMdxCodeBlocks';
|
|
23
|
+
import transformImage from './remark/transformImage';
|
|
24
|
+
import transformLinks from './remark/transformLinks';
|
|
25
|
+
|
|
26
|
+
import transformAdmonitions from './remark/admonitions';
|
|
27
|
+
import type {LoaderContext} from 'webpack';
|
|
28
|
+
import type {Processor, Plugin} from 'unified';
|
|
29
|
+
import type {AdmonitionOptions} from './remark/admonitions';
|
|
30
|
+
|
|
31
|
+
const {
|
|
32
|
+
loaders: {inlineMarkdownImageFileLoader},
|
|
33
|
+
} = getFileLoaderUtils();
|
|
34
|
+
|
|
35
|
+
const pragma = `
|
|
36
|
+
/* @jsxRuntime classic */
|
|
37
|
+
/* @jsx mdx */
|
|
38
|
+
/* @jsxFrag React.Fragment */
|
|
39
|
+
`;
|
|
40
|
+
|
|
41
|
+
const DEFAULT_OPTIONS: MDXOptions = {
|
|
42
|
+
admonitions: true,
|
|
43
|
+
rehypePlugins: [],
|
|
44
|
+
remarkPlugins: [unwrapMdxCodeBlocks, emoji, headings, toc],
|
|
45
|
+
beforeDefaultRemarkPlugins: [],
|
|
46
|
+
beforeDefaultRehypePlugins: [],
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
const compilerCache = new Map<string | Options, [Processor, Options]>();
|
|
50
|
+
|
|
51
|
+
export type MDXPlugin =
|
|
52
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
53
|
+
[Plugin<any[]>, any] | Plugin<any[]>;
|
|
54
|
+
|
|
55
|
+
export type MDXOptions = {
|
|
56
|
+
admonitions: boolean | AdmonitionOptions;
|
|
57
|
+
remarkPlugins: MDXPlugin[];
|
|
58
|
+
rehypePlugins: MDXPlugin[];
|
|
59
|
+
beforeDefaultRemarkPlugins: MDXPlugin[];
|
|
60
|
+
beforeDefaultRehypePlugins: MDXPlugin[];
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
export type Options = Partial<MDXOptions> & {
|
|
64
|
+
staticDirs: string[];
|
|
65
|
+
siteDir: string;
|
|
66
|
+
isMDXPartial?: (filePath: string) => boolean;
|
|
67
|
+
isMDXPartialFrontMatterWarningDisabled?: boolean;
|
|
68
|
+
removeContentTitle?: boolean;
|
|
69
|
+
metadataPath?: string | ((filePath: string) => string);
|
|
70
|
+
createAssets?: (metadata: {
|
|
71
|
+
frontMatter: {[key: string]: unknown};
|
|
72
|
+
metadata: {[key: string]: unknown};
|
|
73
|
+
}) => {[key: string]: unknown};
|
|
74
|
+
filepath: string;
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* When this throws, it generally means that there's no metadata file associated
|
|
79
|
+
* with this MDX document. It can happen when using MDX partials (usually
|
|
80
|
+
* starting with _). That's why it's important to provide the `isMDXPartial`
|
|
81
|
+
* function in config
|
|
82
|
+
*/
|
|
83
|
+
async function readMetadataPath(metadataPath: string) {
|
|
84
|
+
try {
|
|
85
|
+
return await fs.readFile(metadataPath, 'utf8');
|
|
86
|
+
} catch (err) {
|
|
87
|
+
logger.error`MDX loader can't read MDX metadata file path=${metadataPath}. Maybe the isMDXPartial option function was not provided?`;
|
|
88
|
+
throw err;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Converts assets an object with Webpack require calls code.
|
|
94
|
+
* This is useful for mdx files to reference co-located assets using relative
|
|
95
|
+
* paths. Those assets should enter the Webpack assets pipeline and be hashed.
|
|
96
|
+
* For now, we only handle that for images and paths starting with `./`:
|
|
97
|
+
*
|
|
98
|
+
* `{image: "./myImage.png"}` => `{image: require("./myImage.png")}`
|
|
99
|
+
*/
|
|
100
|
+
function createAssetsExportCode(assets: unknown) {
|
|
101
|
+
if (
|
|
102
|
+
typeof assets !== 'object' ||
|
|
103
|
+
!assets ||
|
|
104
|
+
Object.keys(assets).length === 0
|
|
105
|
+
) {
|
|
106
|
+
return 'undefined';
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// TODO implementation can be completed/enhanced
|
|
110
|
+
function createAssetValueCode(assetValue: unknown): string | undefined {
|
|
111
|
+
if (Array.isArray(assetValue)) {
|
|
112
|
+
const arrayItemCodes = assetValue.map(
|
|
113
|
+
(item: unknown) => createAssetValueCode(item) ?? 'undefined',
|
|
114
|
+
);
|
|
115
|
+
return `[${arrayItemCodes.join(', ')}]`;
|
|
116
|
+
}
|
|
117
|
+
// Only process string values starting with ./
|
|
118
|
+
// We could enhance this logic and check if file exists on disc?
|
|
119
|
+
if (typeof assetValue === 'string' && assetValue.startsWith('./')) {
|
|
120
|
+
// TODO do we have other use-cases than image assets?
|
|
121
|
+
// Probably not worth adding more support, as we want to move to Webpack 5 new asset system (https://github.com/facebook/docusaurus/pull/4708)
|
|
122
|
+
const inlineLoader = inlineMarkdownImageFileLoader;
|
|
123
|
+
return `require("${inlineLoader}${escapePath(assetValue)}").default`;
|
|
124
|
+
}
|
|
125
|
+
return undefined;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const assetEntries = Object.entries(assets);
|
|
129
|
+
|
|
130
|
+
const codeLines = assetEntries
|
|
131
|
+
.map(([key, value]: [string, unknown]) => {
|
|
132
|
+
const assetRequireCode = createAssetValueCode(value);
|
|
133
|
+
return assetRequireCode ? `"${key}": ${assetRequireCode},` : undefined;
|
|
134
|
+
})
|
|
135
|
+
.filter(Boolean);
|
|
136
|
+
|
|
137
|
+
return `{\n${codeLines.join('\n')}\n}`;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function getAdmonitionsPlugins(
|
|
141
|
+
admonitionsOption: MDXOptions['admonitions'],
|
|
142
|
+
): MDXPlugin[] {
|
|
143
|
+
if (admonitionsOption) {
|
|
144
|
+
const plugin: MDXPlugin =
|
|
145
|
+
admonitionsOption === true
|
|
146
|
+
? transformAdmonitions
|
|
147
|
+
: [transformAdmonitions, admonitionsOption];
|
|
148
|
+
return [plugin];
|
|
149
|
+
}
|
|
150
|
+
return [];
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export async function mdxLoader(
|
|
154
|
+
this: LoaderContext<Options>,
|
|
155
|
+
fileString: string,
|
|
156
|
+
): Promise<void> {
|
|
157
|
+
const callback = this.async();
|
|
158
|
+
const filePath = this.resourcePath;
|
|
159
|
+
const reqOptions = this.getOptions();
|
|
160
|
+
|
|
161
|
+
const {frontMatter, content: contentWithTitle} = parseFrontMatter(fileString);
|
|
162
|
+
|
|
163
|
+
const {content, contentTitle} = parseMarkdownContentTitle(contentWithTitle, {
|
|
164
|
+
removeContentTitle: reqOptions.removeContentTitle,
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
const hasFrontMatter = Object.keys(frontMatter).length > 0;
|
|
168
|
+
|
|
169
|
+
if (!compilerCache.has(this.query)) {
|
|
170
|
+
const remarkPlugins: MDXPlugin[] = [
|
|
171
|
+
...(reqOptions.beforeDefaultRemarkPlugins ?? []),
|
|
172
|
+
...getAdmonitionsPlugins(reqOptions.admonitions ?? false),
|
|
173
|
+
...DEFAULT_OPTIONS.remarkPlugins,
|
|
174
|
+
[
|
|
175
|
+
transformImage,
|
|
176
|
+
{
|
|
177
|
+
staticDirs: reqOptions.staticDirs,
|
|
178
|
+
siteDir: reqOptions.siteDir,
|
|
179
|
+
},
|
|
180
|
+
],
|
|
181
|
+
[
|
|
182
|
+
transformLinks,
|
|
183
|
+
{
|
|
184
|
+
staticDirs: reqOptions.staticDirs,
|
|
185
|
+
siteDir: reqOptions.siteDir,
|
|
186
|
+
},
|
|
187
|
+
],
|
|
188
|
+
...(reqOptions.remarkPlugins ?? []),
|
|
189
|
+
];
|
|
190
|
+
|
|
191
|
+
const rehypePlugins: MDXPlugin[] = [
|
|
192
|
+
...(reqOptions.beforeDefaultRehypePlugins ?? []),
|
|
193
|
+
...DEFAULT_OPTIONS.rehypePlugins,
|
|
194
|
+
...(reqOptions.rehypePlugins ?? []),
|
|
195
|
+
];
|
|
196
|
+
|
|
197
|
+
const options: Options = {
|
|
198
|
+
...reqOptions,
|
|
199
|
+
remarkPlugins,
|
|
200
|
+
rehypePlugins,
|
|
201
|
+
};
|
|
202
|
+
compilerCache.set(this.query, [createCompiler(options), options]);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const [compiler, options] = compilerCache.get(this.query)!;
|
|
206
|
+
|
|
207
|
+
let result: string;
|
|
208
|
+
try {
|
|
209
|
+
result = await compiler
|
|
210
|
+
.process({
|
|
211
|
+
contents: content,
|
|
212
|
+
path: this.resourcePath,
|
|
213
|
+
})
|
|
214
|
+
.then((res) => res.toString());
|
|
215
|
+
} catch (err) {
|
|
216
|
+
return callback(err as Error);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// MDX partials are MDX files starting with _ or in a folder starting with _
|
|
220
|
+
// Partial are not expected to have associated metadata files or front matter
|
|
221
|
+
const isMDXPartial = options.isMDXPartial?.(filePath);
|
|
222
|
+
if (isMDXPartial && hasFrontMatter) {
|
|
223
|
+
const errorMessage = `Docusaurus MDX partial files should not contain front matter.
|
|
224
|
+
Those partial files use the _ prefix as a convention by default, but this is configurable.
|
|
225
|
+
File at ${filePath} contains front matter that will be ignored:
|
|
226
|
+
${JSON.stringify(frontMatter, null, 2)}`;
|
|
227
|
+
|
|
228
|
+
if (!options.isMDXPartialFrontMatterWarningDisabled) {
|
|
229
|
+
const shouldError = process.env.NODE_ENV === 'test' || process.env.CI;
|
|
230
|
+
if (shouldError) {
|
|
231
|
+
return callback(new Error(errorMessage));
|
|
232
|
+
}
|
|
233
|
+
logger.warn(errorMessage);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function getMetadataPath(): string | undefined {
|
|
238
|
+
if (!isMDXPartial) {
|
|
239
|
+
// Read metadata for this MDX and export it.
|
|
240
|
+
if (options.metadataPath && typeof options.metadataPath === 'function') {
|
|
241
|
+
return options.metadataPath(filePath);
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
return undefined;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
const metadataPath = getMetadataPath();
|
|
248
|
+
if (metadataPath) {
|
|
249
|
+
this.addDependency(metadataPath);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
const metadataJsonString = metadataPath
|
|
253
|
+
? await readMetadataPath(metadataPath)
|
|
254
|
+
: undefined;
|
|
255
|
+
|
|
256
|
+
const metadata = metadataJsonString
|
|
257
|
+
? (JSON.parse(metadataJsonString) as {[key: string]: unknown})
|
|
258
|
+
: undefined;
|
|
259
|
+
|
|
260
|
+
const assets =
|
|
261
|
+
reqOptions.createAssets && metadata
|
|
262
|
+
? reqOptions.createAssets({frontMatter, metadata})
|
|
263
|
+
: undefined;
|
|
264
|
+
|
|
265
|
+
const exportsCode = `
|
|
266
|
+
export const frontMatter = ${stringifyObject(frontMatter)};
|
|
267
|
+
export const contentTitle = ${stringifyObject(contentTitle)};
|
|
268
|
+
${metadataJsonString ? `export const metadata = ${metadataJsonString};` : ''}
|
|
269
|
+
${assets ? `export const assets = ${createAssetsExportCode(assets)};` : ''}
|
|
270
|
+
`;
|
|
271
|
+
|
|
272
|
+
const code = `
|
|
273
|
+
${pragma}
|
|
274
|
+
import React from 'react';
|
|
275
|
+
import { mdx } from '@mdx-js/react';
|
|
276
|
+
|
|
277
|
+
${exportsCode}
|
|
278
|
+
${result}
|
|
279
|
+
`;
|
|
280
|
+
|
|
281
|
+
return callback(null, code);
|
|
282
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2020 Elvis Wolcott
|
|
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.
|
|
22
|
+
|
|
23
|
+
---
|
|
24
|
+
|
|
25
|
+
MIT License
|
|
26
|
+
|
|
27
|
+
Copyright (c) Facebook, Inc. and its affiliates.
|
|
28
|
+
|
|
29
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
30
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
31
|
+
in the Software without restriction, including without limitation the rights
|
|
32
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
33
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
34
|
+
furnished to do so, subject to the following conditions:
|
|
35
|
+
|
|
36
|
+
The above copyright notice and this permission notice shall be included in all
|
|
37
|
+
copies or substantial portions of the Software.
|
|
38
|
+
|
|
39
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
40
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
41
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
42
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
43
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
44
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
45
|
+
SOFTWARE.
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright (c) Facebook, Inc. and its affiliates.
|
|
3
|
+
*
|
|
4
|
+
* This source code is licensed under the MIT license found in the
|
|
5
|
+
* LICENSE file in the root directory of this source tree.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import visit from 'unist-util-visit';
|
|
9
|
+
import type {Transformer, Processor, Plugin} from 'unified';
|
|
10
|
+
import type {Literal} from 'mdast';
|
|
11
|
+
|
|
12
|
+
const NEWLINE = '\n';
|
|
13
|
+
|
|
14
|
+
export type AdmonitionOptions = {
|
|
15
|
+
tag: string;
|
|
16
|
+
keywords: string[];
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
export const DefaultAdmonitionOptions: AdmonitionOptions = {
|
|
20
|
+
tag: ':::',
|
|
21
|
+
keywords: [
|
|
22
|
+
'secondary',
|
|
23
|
+
'info',
|
|
24
|
+
'success',
|
|
25
|
+
'danger',
|
|
26
|
+
'note',
|
|
27
|
+
'tip',
|
|
28
|
+
'warning',
|
|
29
|
+
'important',
|
|
30
|
+
'caution',
|
|
31
|
+
],
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
function escapeRegExp(s: string): string {
|
|
35
|
+
return s.replace(/[-[\]{}()*+?.\\^$|/]/g, '\\$&');
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function normalizeOptions(
|
|
39
|
+
options: Partial<AdmonitionOptions>,
|
|
40
|
+
): AdmonitionOptions {
|
|
41
|
+
return {...DefaultAdmonitionOptions, ...options};
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// This string value does not matter much
|
|
45
|
+
// It is ignored because nodes are using hName/hProperties coming from HAST
|
|
46
|
+
const admonitionNodeType = 'admonitionHTML';
|
|
47
|
+
|
|
48
|
+
const plugin: Plugin = function plugin(
|
|
49
|
+
this: Processor,
|
|
50
|
+
optionsInput: Partial<AdmonitionOptions> = {},
|
|
51
|
+
): Transformer {
|
|
52
|
+
const options = normalizeOptions(optionsInput);
|
|
53
|
+
|
|
54
|
+
const keywords = Object.values(options.keywords).map(escapeRegExp).join('|');
|
|
55
|
+
const tag = escapeRegExp(options.tag);
|
|
56
|
+
const regex = new RegExp(`${tag}(${keywords})(?: *(.*))?\n`);
|
|
57
|
+
const escapeTag = new RegExp(escapeRegExp(`\\${options.tag}`), 'g');
|
|
58
|
+
|
|
59
|
+
// The tokenizer is called on blocks to determine if there is an admonition
|
|
60
|
+
// present and create tags for it
|
|
61
|
+
function blockTokenizer(this: any, eat: any, value: string, silent: boolean) {
|
|
62
|
+
// Stop if no match or match does not start at beginning of line
|
|
63
|
+
const match = regex.exec(value);
|
|
64
|
+
if (!match || match.index !== 0) {
|
|
65
|
+
return false;
|
|
66
|
+
}
|
|
67
|
+
// If silent return the match
|
|
68
|
+
if (silent) {
|
|
69
|
+
return true;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const now = eat.now();
|
|
73
|
+
const [opening, keyword, title] = match as string[] as [
|
|
74
|
+
string,
|
|
75
|
+
string,
|
|
76
|
+
string,
|
|
77
|
+
];
|
|
78
|
+
const food = [];
|
|
79
|
+
const content = [];
|
|
80
|
+
|
|
81
|
+
let newValue = value;
|
|
82
|
+
// consume lines until a closing tag
|
|
83
|
+
let idx = newValue.indexOf(NEWLINE);
|
|
84
|
+
while (idx !== -1) {
|
|
85
|
+
// grab this line and eat it
|
|
86
|
+
const next = newValue.indexOf(NEWLINE, idx + 1);
|
|
87
|
+
const line =
|
|
88
|
+
next !== -1 ? newValue.slice(idx + 1, next) : newValue.slice(idx + 1);
|
|
89
|
+
food.push(line);
|
|
90
|
+
newValue = newValue.slice(idx + 1);
|
|
91
|
+
// the closing tag is NOT part of the content
|
|
92
|
+
if (line.startsWith(options.tag)) {
|
|
93
|
+
break;
|
|
94
|
+
}
|
|
95
|
+
content.push(line);
|
|
96
|
+
idx = newValue.indexOf(NEWLINE);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// consume the processed tag and replace escape sequences
|
|
100
|
+
const contentString = content.join(NEWLINE).replace(escapeTag, options.tag);
|
|
101
|
+
const add = eat(opening + food.join(NEWLINE));
|
|
102
|
+
|
|
103
|
+
// parse the content in block mode
|
|
104
|
+
const exit = this.enterBlock();
|
|
105
|
+
const contentNodes = this.tokenizeBlock(contentString, now);
|
|
106
|
+
exit();
|
|
107
|
+
|
|
108
|
+
const titleNodes = this.tokenizeInline(title, now);
|
|
109
|
+
|
|
110
|
+
const isSimpleTextTitle =
|
|
111
|
+
titleNodes.length === 1 && titleNodes[0].type === 'text';
|
|
112
|
+
|
|
113
|
+
const element = {
|
|
114
|
+
type: admonitionNodeType,
|
|
115
|
+
data: {
|
|
116
|
+
// hName/hProperties come from HAST
|
|
117
|
+
// See https://github.com/syntax-tree/mdast-util-to-hast#fields-on-nodes
|
|
118
|
+
hName: 'admonition',
|
|
119
|
+
hProperties: {
|
|
120
|
+
...(title && isSimpleTextTitle && {title}),
|
|
121
|
+
type: keyword,
|
|
122
|
+
},
|
|
123
|
+
},
|
|
124
|
+
children: [
|
|
125
|
+
// For titles containing MDX syntax: create a custom element. The theme
|
|
126
|
+
// component will extract it and render it nicely.
|
|
127
|
+
//
|
|
128
|
+
// Temporary workaround, because it's complex in MDX v1 to emit
|
|
129
|
+
// interpolated JSX prop syntax (title={<>my <code>title</code></>}).
|
|
130
|
+
// For this reason, we use children instead of the title prop.
|
|
131
|
+
title &&
|
|
132
|
+
!isSimpleTextTitle && {
|
|
133
|
+
type: admonitionNodeType,
|
|
134
|
+
data: {
|
|
135
|
+
hName: 'mdxAdmonitionTitle',
|
|
136
|
+
hProperties: {},
|
|
137
|
+
},
|
|
138
|
+
children: titleNodes,
|
|
139
|
+
},
|
|
140
|
+
...contentNodes,
|
|
141
|
+
].filter(Boolean),
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
return add(element);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// add tokenizer to parser after fenced code blocks
|
|
148
|
+
const Parser = this.Parser.prototype;
|
|
149
|
+
Parser.blockTokenizers.admonition = blockTokenizer;
|
|
150
|
+
Parser.blockMethods.splice(
|
|
151
|
+
Parser.blockMethods.indexOf('fencedCode') + 1,
|
|
152
|
+
0,
|
|
153
|
+
'admonition',
|
|
154
|
+
);
|
|
155
|
+
Parser.interruptParagraph.splice(
|
|
156
|
+
Parser.interruptParagraph.indexOf('fencedCode') + 1,
|
|
157
|
+
0,
|
|
158
|
+
['admonition'],
|
|
159
|
+
);
|
|
160
|
+
Parser.interruptList.splice(
|
|
161
|
+
Parser.interruptList.indexOf('fencedCode') + 1,
|
|
162
|
+
0,
|
|
163
|
+
['admonition'],
|
|
164
|
+
);
|
|
165
|
+
Parser.interruptBlockquote.splice(
|
|
166
|
+
Parser.interruptBlockquote.indexOf('fencedCode') + 1,
|
|
167
|
+
0,
|
|
168
|
+
['admonition'],
|
|
169
|
+
);
|
|
170
|
+
|
|
171
|
+
return (root) => {
|
|
172
|
+
// escape everything except admonitionHTML nodes
|
|
173
|
+
visit(
|
|
174
|
+
root,
|
|
175
|
+
(node: unknown): node is Literal =>
|
|
176
|
+
(node as Literal | undefined)?.type !== admonitionNodeType,
|
|
177
|
+
(node: Literal) => {
|
|
178
|
+
if (node.value) {
|
|
179
|
+
node.value = node.value.replace(escapeTag, options.tag);
|
|
180
|
+
}
|
|
181
|
+
},
|
|
182
|
+
);
|
|
183
|
+
};
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
export default plugin;
|
|
@@ -7,43 +7,45 @@
|
|
|
7
7
|
|
|
8
8
|
/* Based on remark-slug (https://github.com/remarkjs/remark-slug) and gatsby-remark-autolink-headers (https://github.com/gatsbyjs/gatsby/blob/master/packages/gatsby-remark-autolink-headers) */
|
|
9
9
|
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
10
|
+
import {parseMarkdownHeadingId, createSlugger} from '@docusaurus/utils';
|
|
11
|
+
import visit from 'unist-util-visit';
|
|
12
|
+
import mdastToString from 'mdast-util-to-string';
|
|
13
|
+
import type {Transformer} from 'unified';
|
|
14
|
+
import type {Heading, Text} from 'mdast';
|
|
14
15
|
|
|
15
|
-
function
|
|
16
|
-
|
|
17
|
-
slugs
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
const
|
|
21
|
-
|
|
16
|
+
export default function plugin(): Transformer {
|
|
17
|
+
return (root) => {
|
|
18
|
+
const slugs = createSlugger();
|
|
19
|
+
visit(root, 'heading', (headingNode: Heading) => {
|
|
20
|
+
const data = headingNode.data ?? (headingNode.data = {});
|
|
21
|
+
const properties = (data.hProperties || (data.hProperties = {})) as {
|
|
22
|
+
id: string;
|
|
23
|
+
};
|
|
22
24
|
let {id} = properties;
|
|
23
25
|
|
|
24
26
|
if (id) {
|
|
25
|
-
id = slugs.slug(id, true);
|
|
27
|
+
id = slugs.slug(id, {maintainCase: true});
|
|
26
28
|
} else {
|
|
27
29
|
const headingTextNodes = headingNode.children.filter(
|
|
28
30
|
({type}) => !['html', 'jsx'].includes(type),
|
|
29
31
|
);
|
|
30
|
-
const heading =
|
|
31
|
-
headingTextNodes.length > 0
|
|
32
|
-
? {children: headingTextNodes}
|
|
33
|
-
: headingNode,
|
|
32
|
+
const heading = mdastToString(
|
|
33
|
+
headingTextNodes.length > 0 ? headingTextNodes : headingNode,
|
|
34
34
|
);
|
|
35
35
|
|
|
36
36
|
// Support explicit heading IDs
|
|
37
37
|
const parsedHeading = parseMarkdownHeadingId(heading);
|
|
38
38
|
|
|
39
|
-
id = parsedHeading.id
|
|
39
|
+
id = parsedHeading.id ?? slugs.slug(heading);
|
|
40
40
|
|
|
41
41
|
if (parsedHeading.id) {
|
|
42
42
|
// When there's an id, it is always in the last child node
|
|
43
|
-
// Sometimes heading is in multiple "parts" (** syntax creates a child
|
|
43
|
+
// Sometimes heading is in multiple "parts" (** syntax creates a child
|
|
44
|
+
// node):
|
|
44
45
|
// ## part1 *part2* part3 {#id}
|
|
45
|
-
const lastNode =
|
|
46
|
-
headingNode.children
|
|
46
|
+
const lastNode = headingNode.children[
|
|
47
|
+
headingNode.children.length - 1
|
|
48
|
+
] as Text;
|
|
47
49
|
|
|
48
50
|
if (headingNode.children.length > 1) {
|
|
49
51
|
const lastNodeText = parseMarkdownHeadingId(lastNode.value).text;
|
|
@@ -63,12 +65,6 @@ function headings() {
|
|
|
63
65
|
|
|
64
66
|
data.id = id;
|
|
65
67
|
properties.id = id;
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
visit(ast, 'heading', visitor);
|
|
68
|
+
});
|
|
69
69
|
};
|
|
70
|
-
|
|
71
|
-
return transformer;
|
|
72
70
|
}
|
|
73
|
-
|
|
74
|
-
module.exports = headings;
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright (c) Facebook, Inc. and its affiliates.
|
|
3
|
+
*
|
|
4
|
+
* This source code is licensed under the MIT license found in the
|
|
5
|
+
* LICENSE file in the root directory of this source tree.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import {parse, type ParserOptions} from '@babel/parser';
|
|
9
|
+
import traverse from '@babel/traverse';
|
|
10
|
+
import stringifyObject from 'stringify-object';
|
|
11
|
+
import toString from 'mdast-util-to-string';
|
|
12
|
+
import visit from 'unist-util-visit';
|
|
13
|
+
import {toValue} from '../utils';
|
|
14
|
+
|
|
15
|
+
import type {Identifier} from '@babel/types';
|
|
16
|
+
import type {TOCItem} from '../..';
|
|
17
|
+
import type {Node, Parent} from 'unist';
|
|
18
|
+
import type {Heading, Literal} from 'mdast';
|
|
19
|
+
import type {Transformer} from 'unified';
|
|
20
|
+
|
|
21
|
+
const parseOptions: ParserOptions = {
|
|
22
|
+
plugins: ['jsx'],
|
|
23
|
+
sourceType: 'module',
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
const name = 'toc';
|
|
27
|
+
|
|
28
|
+
const isImport = (child: Node): child is Literal => child.type === 'import';
|
|
29
|
+
const hasImports = (index: number) => index > -1;
|
|
30
|
+
const isExport = (child: Node): child is Literal => child.type === 'export';
|
|
31
|
+
|
|
32
|
+
const isTarget = (child: Literal) => {
|
|
33
|
+
let found = false;
|
|
34
|
+
const ast = parse(child.value, parseOptions);
|
|
35
|
+
traverse(ast, {
|
|
36
|
+
VariableDeclarator: (path) => {
|
|
37
|
+
if ((path.node.id as Identifier).name === name) {
|
|
38
|
+
found = true;
|
|
39
|
+
}
|
|
40
|
+
},
|
|
41
|
+
});
|
|
42
|
+
return found;
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
const getOrCreateExistingTargetIndex = (children: Node[]) => {
|
|
46
|
+
let importsIndex = -1;
|
|
47
|
+
let targetIndex = -1;
|
|
48
|
+
|
|
49
|
+
children.forEach((child, index) => {
|
|
50
|
+
if (isImport(child)) {
|
|
51
|
+
importsIndex = index;
|
|
52
|
+
} else if (isExport(child) && isTarget(child)) {
|
|
53
|
+
targetIndex = index;
|
|
54
|
+
}
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
if (targetIndex === -1) {
|
|
58
|
+
const target = {
|
|
59
|
+
default: false,
|
|
60
|
+
type: 'export',
|
|
61
|
+
value: `export const ${name} = [];`,
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
targetIndex = hasImports(importsIndex) ? importsIndex + 1 : 0;
|
|
65
|
+
children.splice(targetIndex, 0, target);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
return targetIndex;
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
export default function plugin(): Transformer {
|
|
72
|
+
return (root) => {
|
|
73
|
+
const headings: TOCItem[] = [];
|
|
74
|
+
|
|
75
|
+
visit(root, 'heading', (child: Heading, index, parent) => {
|
|
76
|
+
const value = toString(child);
|
|
77
|
+
|
|
78
|
+
// depth: 1 headings are titles and not included in the TOC
|
|
79
|
+
if (parent !== root || !value || child.depth < 2) {
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
headings.push({
|
|
84
|
+
value: toValue(child),
|
|
85
|
+
id: child.data!.id as string,
|
|
86
|
+
level: child.depth,
|
|
87
|
+
});
|
|
88
|
+
});
|
|
89
|
+
const {children} = root as Parent<Literal>;
|
|
90
|
+
const targetIndex = getOrCreateExistingTargetIndex(children);
|
|
91
|
+
|
|
92
|
+
if (headings.length) {
|
|
93
|
+
children[targetIndex]!.value = `export const ${name} = ${stringifyObject(
|
|
94
|
+
headings,
|
|
95
|
+
)};`;
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
}
|