Skip to content

Commit

Permalink
refactor: handle all admonitions via JSX component (#7152)
Browse files Browse the repository at this point in the history
Co-authored-by: Joshua Chen <sidachen2003@gmail.com>
Co-authored-by: sebastienlorber <lorber.sebastien@gmail.com>
  • Loading branch information
3 people authored Jun 3, 2022
1 parent 17fe43e commit 5746c58
Show file tree
Hide file tree
Showing 39 changed files with 708 additions and 249 deletions.
4 changes: 4 additions & 0 deletions jest/deps.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ declare module 'remark-mdx' {
export = mdx;
}

declare module 'remark-rehype';

declare module 'rehype-stringify';

declare module '@testing-utils/git' {
const createTempRepo: typeof import('./utils/git').createTempRepo;
export {createTempRepo};
Expand Down
2 changes: 2 additions & 0 deletions packages/docusaurus-mdx-loader/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@
"@types/unist": "^2.0.6",
"remark": "^12.0.1",
"remark-mdx": "^1.6.21",
"rehype-stringify": "^8.0.0",
"remark-rehype": "^8.1.0",
"to-vfile": "^6.1.0",
"unist-builder": "^2.0.3",
"unist-util-remove-position": "^3.0.0"
Expand Down
71 changes: 47 additions & 24 deletions packages/docusaurus-mdx-loader/src/loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,10 @@ import unwrapMdxCodeBlocks from './remark/unwrapMdxCodeBlocks';
import transformImage from './remark/transformImage';
import transformLinks from './remark/transformLinks';

import transformAdmonitions from './remark/admonitions';
import type {LoaderContext} from 'webpack';
import type {Processor, Plugin} from 'unified';
import type {AdmonitionOptions} from './remark/admonitions';

const {
loaders: {inlineMarkdownImageFileLoader},
Expand All @@ -37,6 +39,7 @@ const pragma = `
`;

const DEFAULT_OPTIONS: MDXOptions = {
admonitions: true,
rehypePlugins: [],
remarkPlugins: [unwrapMdxCodeBlocks, emoji, headings, toc],
beforeDefaultRemarkPlugins: [],
Expand All @@ -48,7 +51,9 @@ const compilerCache = new Map<string | Options, [Processor, Options]>();
export type MDXPlugin =
// eslint-disable-next-line @typescript-eslint/no-explicit-any
[Plugin<any[]>, any] | Plugin<any[]>;

export type MDXOptions = {
admonitions: boolean | AdmonitionOptions;
remarkPlugins: MDXPlugin[];
rehypePlugins: MDXPlugin[];
beforeDefaultRemarkPlugins: MDXPlugin[];
Expand Down Expand Up @@ -132,6 +137,19 @@ function createAssetsExportCode(assets: unknown) {
return `{\n${codeLines.join('\n')}\n}`;
}

function getAdmonitionsPlugins(
admonitionsOption: MDXOptions['admonitions'],
): MDXPlugin[] {
if (admonitionsOption) {
const plugin: MDXPlugin =
admonitionsOption === true
? transformAdmonitions
: [transformAdmonitions, admonitionsOption];
return [plugin];
}
return [];
}

export async function mdxLoader(
this: LoaderContext<Options>,
fileString: string,
Expand All @@ -149,32 +167,37 @@ export async function mdxLoader(
const hasFrontMatter = Object.keys(frontMatter).length > 0;

if (!compilerCache.has(this.query)) {
const options: Options = {
...reqOptions,
remarkPlugins: [
...(reqOptions.beforeDefaultRemarkPlugins ?? []),
...DEFAULT_OPTIONS.remarkPlugins,
[
transformImage,
{
staticDirs: reqOptions.staticDirs,
siteDir: reqOptions.siteDir,
},
],
[
transformLinks,
{
staticDirs: reqOptions.staticDirs,
siteDir: reqOptions.siteDir,
},
],
...(reqOptions.remarkPlugins ?? []),
const remarkPlugins: MDXPlugin[] = [
...(reqOptions.beforeDefaultRemarkPlugins ?? []),
...getAdmonitionsPlugins(reqOptions.admonitions ?? false),
...DEFAULT_OPTIONS.remarkPlugins,
[
transformImage,
{
staticDirs: reqOptions.staticDirs,
siteDir: reqOptions.siteDir,
},
],
rehypePlugins: [
...(reqOptions.beforeDefaultRehypePlugins ?? []),
...DEFAULT_OPTIONS.rehypePlugins,
...(reqOptions.rehypePlugins ?? []),
[
transformLinks,
{
staticDirs: reqOptions.staticDirs,
siteDir: reqOptions.siteDir,
},
],
...(reqOptions.remarkPlugins ?? []),
];

const rehypePlugins: MDXPlugin[] = [
...(reqOptions.beforeDefaultRehypePlugins ?? []),
...DEFAULT_OPTIONS.rehypePlugins,
...(reqOptions.rehypePlugins ?? []),
];

const options: Options = {
...reqOptions,
remarkPlugins,
rehypePlugins,
};
compilerCache.set(this.query, [createCompiler(options), options]);
}
Expand Down
45 changes: 45 additions & 0 deletions packages/docusaurus-mdx-loader/src/remark/admonitions/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
MIT License

Copyright (c) 2020 Elvis Wolcott

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

---

MIT License

Copyright (c) Facebook, Inc. and its affiliates.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Docusaurus admonitions

Code from [remark-admonitions](https://github.com/remarkjs/remark-directive) (MIT license) has been copied to this folder, and highly customized for Docusaurus needs.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`admonitions remark plugin base 1`] = `
"<p>The blog feature enables you to deploy in no time a full-featured blog.</p>
<admonition title="Sample Title" type="info"><p>Check the <a href="./api/plugins/plugin-content-blog.md">Blog Plugin API Reference documentation</a> for an exhaustive list of options.</p></admonition>
<h2>Initial setup {#initial-setup}</h2>
<p>To set up your site's blog, start by creating a <code>blog</code> directory.</p>
<admonition type="tip"><p>Use the <strong><a href="introduction.md#fast-track">Fast Track</a></strong> to understand Docusaurus in <strong>5 minutes ⏱</strong>!</p><p>Use <strong><a href="https://docusaurus.new">docusaurus.new</a></strong> to test Docusaurus immediately in your browser!</p></admonition>
<p>++++tip</p>
<p>Admonition with different syntax</p>
<p>++++</p>"
`;

exports[`admonitions remark plugin custom keywords 1`] = `
"<p>The blog feature enables you to deploy in no time a full-featured blog.</p>
<p>:::info Sample Title</p>
<p>Check the <a href="./api/plugins/plugin-content-blog.md">Blog Plugin API Reference documentation</a> for an exhaustive list of options.</p>
<p>:::</p>
<h2>Initial setup {#initial-setup}</h2>
<p>To set up your site's blog, start by creating a <code>blog</code> directory.</p>
<admonition type="tip"><p>Use the <strong><a href="introduction.md#fast-track">Fast Track</a></strong> to understand Docusaurus in <strong>5 minutes ⏱</strong>!</p><p>Use <strong><a href="https://docusaurus.new">docusaurus.new</a></strong> to test Docusaurus immediately in your browser!</p></admonition>
<p>++++tip</p>
<p>Admonition with different syntax</p>
<p>++++</p>"
`;

exports[`admonitions remark plugin custom tag 1`] = `
"<p>The blog feature enables you to deploy in no time a full-featured blog.</p>
<p>:::info Sample Title</p>
<p>Check the <a href="./api/plugins/plugin-content-blog.md">Blog Plugin API Reference documentation</a> for an exhaustive list of options.</p>
<p>:::</p>
<h2>Initial setup {#initial-setup}</h2>
<p>To set up your site's blog, start by creating a <code>blog</code> directory.</p>
<p>:::tip</p>
<p>Use the <strong><a href="introduction.md#fast-track">Fast Track</a></strong> to understand Docusaurus in <strong>5 minutes ⏱</strong>!</p>
<p>Use <strong><a href="https://docusaurus.new">docusaurus.new</a></strong> to test Docusaurus immediately in your browser!</p>
<p>:::</p>
<admonition type="tip"><p>Admonition with different syntax</p></admonition>"
`;

exports[`admonitions remark plugin interpolation 1`] = `
"<p>Test admonition with interpolated title/body</p>
<admonition type="tip"><mdxAdmonitionTitle>My <code>interpolated</code> <strong>title</strong> &#x3C;button style={{color: "red"}} onClick={() => alert("click")}>test</mdxAdmonitionTitle><p><code>body</code> <strong>interpolated</strong> content</p></admonition>"
`;
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

import path from 'path';
import remark from 'remark';
import remark2rehype from 'remark-rehype';
import stringify from 'rehype-stringify';

import vfile from 'to-vfile';
import plugin from '../index';
import type {AdmonitionOptions} from '../index';

const processFixture = async (
name: string,
options?: Partial<AdmonitionOptions>,
) => {
const filePath = path.join(__dirname, '__fixtures__', `${name}.md`);
const file = await vfile.read(filePath);

const result = await remark()
.use(plugin, options)
.use(remark2rehype)
.use(stringify)
.process(file);

return result.toString();
};

describe('admonitions remark plugin', () => {
it('base', async () => {
const result = await processFixture('base');
expect(result).toMatchSnapshot();
});

it('custom keywords', async () => {
const result = await processFixture('base', {keywords: ['tip']});
expect(result).toMatchSnapshot();
});

it('custom tag', async () => {
const result = await processFixture('base', {tag: '++++'});
expect(result).toMatchSnapshot();
});

it('interpolation', async () => {
const result = await processFixture('interpolation');
expect(result).toMatchSnapshot();
});
});
Loading

0 comments on commit 5746c58

Please sign in to comment.