diff options
author | 2022-11-09 21:32:13 +0800 | |
---|---|---|
committer | 2022-11-09 08:32:13 -0500 | |
commit | dca762cf734a657d8f126fd6958892b6163a4f67 (patch) | |
tree | 25598ee01bdf771106d05186a05432a2b0f8b43d /packages/integrations/mdx/src | |
parent | dc00ca464865feccd3760b54e0ccc58dbc1e804d (diff) | |
download | astro-dca762cf734a657d8f126fd6958892b6163a4f67.tar.gz astro-dca762cf734a657d8f126fd6958892b6163a4f67.tar.zst astro-dca762cf734a657d8f126fd6958892b6163a4f67.zip |
Preserve code element node meta for rehype syntax highlighters (#5335)
Diffstat (limited to 'packages/integrations/mdx/src')
-rw-r--r-- | packages/integrations/mdx/src/plugins.ts | 3 | ||||
-rw-r--r-- | packages/integrations/mdx/src/rehype-meta-string.ts | 17 |
2 files changed, 20 insertions, 0 deletions
diff --git a/packages/integrations/mdx/src/plugins.ts b/packages/integrations/mdx/src/plugins.ts index eb53fa629..70c5b1545 100644 --- a/packages/integrations/mdx/src/plugins.ts +++ b/packages/integrations/mdx/src/plugins.ts @@ -11,6 +11,7 @@ import remarkSmartypants from 'remark-smartypants'; import type { Data, VFile } from 'vfile'; import { MdxOptions } from './index.js'; import rehypeCollectHeadings from './rehype-collect-headings.js'; +import rehypeMetaString from './rehype-meta-string.js'; import remarkPrism from './remark-prism.js'; import remarkShiki from './remark-shiki.js'; import { jsToTreeNode } from './utils.js'; @@ -150,6 +151,8 @@ export function getRehypePlugins( let rehypePlugins: PluggableList = [ // getHeadings() is guaranteed by TS, so we can't allow user to override rehypeCollectHeadings, + // ensure `data.meta` is preserved in `properties.metastring` for rehype syntax highlighters + rehypeMetaString, // rehypeRaw allows custom syntax highlighters to work without added config [rehypeRaw, { passThrough: nodeTypes }] as any, ]; diff --git a/packages/integrations/mdx/src/rehype-meta-string.ts b/packages/integrations/mdx/src/rehype-meta-string.ts new file mode 100644 index 000000000..c3f2dbd2f --- /dev/null +++ b/packages/integrations/mdx/src/rehype-meta-string.ts @@ -0,0 +1,17 @@ +import { visit } from 'unist-util-visit'; + +/** + * Moves `data.meta` to `properties.metastring` for the `code` element node + * as `rehype-raw` strips `data` from all nodes, which may contain useful information. + * e.g. ```js {1:3} => metastring: "{1:3}" + */ +export default function rehypeMetaString() { + return function (tree: any) { + visit(tree, (node) => { + if (node.type === 'element' && node.tagName === 'code' && node.data?.meta) { + node.properties ??= {}; + node.properties.metastring = node.data.meta; + } + }); + }; +} |