Skip to content

Commit

Permalink
refactor(mdx-loader): use vfile.path to access Markdown file path (#6443
Browse files Browse the repository at this point in the history
)
  • Loading branch information
Josh-Cena authored Jan 22, 2022
1 parent e40cafc commit 3d7ba33
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 22 deletions.
2 changes: 0 additions & 2 deletions packages/docusaurus-mdx-loader/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,15 +128,13 @@ export default async function mdxLoader(
transformImage,
{
staticDirs: reqOptions.staticDirs,
filePath,
siteDir: reqOptions.siteDir,
},
],
[
transformLinks,
{
staticDirs: reqOptions.staticDirs,
filePath,
siteDir: reqOptions.siteDir,
},
],
Expand Down
25 changes: 15 additions & 10 deletions packages/docusaurus-mdx-loader/src/remark/transformImage/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,14 @@ const {
loaders: {inlineMarkdownImageFileLoader},
} = getFileLoaderUtils();

interface PluginOptions {
filePath: string;
type PluginOptions = {
staticDirs: string[];
siteDir: string;
}
};

type Context = PluginOptions & {
filePath: string;
};

async function toImageRequireNode(
node: Image,
Expand Down Expand Up @@ -89,7 +92,7 @@ async function ensureImageFileExist(imagePath: string, sourceFilePath: string) {

async function getImageAbsolutePath(
imagePath: string,
{siteDir, filePath, staticDirs}: PluginOptions,
{siteDir, filePath, staticDirs}: Context,
) {
if (imagePath.startsWith('@site/')) {
const imageFilePath = path.join(siteDir, imagePath.replace('@site/', ''));
Expand Down Expand Up @@ -123,11 +126,11 @@ async function getImageAbsolutePath(
}
}

async function processImageNode(node: Image, options: PluginOptions) {
async function processImageNode(node: Image, context: Context) {
if (!node.url) {
throw new Error(
`Markdown image URL is mandatory in "${toMessageRelativeFilePath(
options.filePath,
context.filePath,
)}" file`,
);
}
Expand All @@ -144,15 +147,17 @@ async function processImageNode(node: Image, options: PluginOptions) {
return;
}

const imagePath = await getImageAbsolutePath(parsedUrl.pathname, options);
await toImageRequireNode(node, imagePath, options.filePath);
const imagePath = await getImageAbsolutePath(parsedUrl.pathname, context);
await toImageRequireNode(node, imagePath, context.filePath);
}

const plugin: Plugin<[PluginOptions]> = (options) => {
const transformer: Transformer = async (root) => {
const transformer: Transformer = async (root, vfile) => {
const promises: Promise<void>[] = [];
visit(root, 'image', (node: Image) => {
promises.push(processImageNode(node, options));
promises.push(
processImageNode(node, {...options, filePath: vfile.path!}),
);
});
await Promise.all(promises);
};
Expand Down
23 changes: 13 additions & 10 deletions packages/docusaurus-mdx-loader/src/remark/transformLinks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,14 @@ const {
loaders: {inlineMarkdownLinkFileLoader},
} = getFileLoaderUtils();

interface PluginOptions {
filePath: string;
type PluginOptions = {
staticDirs: string[];
siteDir: string;
}
};

type Context = PluginOptions & {
filePath: string;
};

// transform the link node to a jsx link with a require() call
function toAssetRequireNode(node: Link, assetPath: string, filePath: string) {
Expand Down Expand Up @@ -71,7 +74,7 @@ async function ensureAssetFileExist(assetPath: string, sourceFilePath: string) {

async function getAssetAbsolutePath(
assetPath: string,
{siteDir, filePath, staticDirs}: PluginOptions,
{siteDir, filePath, staticDirs}: Context,
) {
if (assetPath.startsWith('@site/')) {
const assetFilePath = path.join(siteDir, assetPath.replace('@site/', ''));
Expand All @@ -96,15 +99,15 @@ async function getAssetAbsolutePath(
return null;
}

async function processLinkNode(node: Link, options: PluginOptions) {
async function processLinkNode(node: Link, context: Context) {
if (!node.url) {
// try to improve error feedback
// see https://github.com/facebook/docusaurus/issues/3309#issuecomment-690371675
const title = node.title || (node.children[0] as Literal)?.value || '?';
const line = node?.position?.start?.line || '?';
throw new Error(
`Markdown link URL is mandatory in "${toMessageRelativeFilePath(
options.filePath,
context.filePath,
)}" file (title: ${title}, line: ${line}).`,
);
}
Expand All @@ -122,17 +125,17 @@ async function processLinkNode(node: Link, options: PluginOptions) {
return;
}

const assetPath = await getAssetAbsolutePath(parsedUrl.pathname, options);
const assetPath = await getAssetAbsolutePath(parsedUrl.pathname, context);
if (assetPath) {
toAssetRequireNode(node, assetPath, options.filePath);
toAssetRequireNode(node, assetPath, context.filePath);
}
}

const plugin: Plugin<[PluginOptions]> = (options) => {
const transformer: Transformer = async (root) => {
const transformer: Transformer = async (root, vfile) => {
const promises: Promise<void>[] = [];
visit(root, 'link', (node: Link) => {
promises.push(processLinkNode(node, options));
promises.push(processLinkNode(node, {...options, filePath: vfile.path!}));
});
await Promise.all(promises);
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,26 @@ module.exports = {
};
```

:::tip

The `transformer` has a second parameter [`vfile`](https://github.com/vfile/vfile) which is useful if you need to access the current Markdown file's path.

```js
const plugin = (options) => {
const transformer = async (ast, vfile) => {
ast.children.unshift({
type: 'text',
value: `The current file path is ${vfile.path}`,
});
};
return transformer;
};
```

Our `transformImage` plugin uses this parameter, for example, to transform relative image references to `require()` calls.

:::

:::note

The default plugins of Docusaurus would operate before the custom remark plugins, and that means the images or links have been converted to JSX with `require()` calls already. For example, in the example above, the table of contents generated is still the same even when all `h2` headings are now prefixed by `Section X.`, because the TOC-generating plugin is called before our custom plugin. If you need to process the MDAST before the default plugins do, use the `beforeDefaultRemarkPlugins` and `beforeDefaultRehypePlugins`.
Expand Down

0 comments on commit 3d7ba33

Please sign in to comment.