Skip to content

Commit

Permalink
Handle MDX optimize for root hast node (#11975)
Browse files Browse the repository at this point in the history
  • Loading branch information
bluwy authored Sep 12, 2024
1 parent 86ad1fd commit c9ae7b1
Show file tree
Hide file tree
Showing 5 changed files with 58 additions and 10 deletions.
5 changes: 5 additions & 0 deletions .changeset/lovely-dolphins-draw.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@astrojs/mdx': patch
---

Handles nested root hast node when optimizing MDX
10 changes: 8 additions & 2 deletions packages/integrations/mdx/src/rehype-optimize-static.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,14 @@ export const rehypeOptimizeStatic: RehypePlugin<[OptimizeOptions?]> = (options)
* A non-static node causes all its parents to be non-optimizable
*/
const isNodeNonStatic = (node: Node) => {
// @ts-expect-error Access `.tagName` naively for perf
return node.type.startsWith('mdx') || ignoreElementNames.has(node.tagName);
return (
node.type.startsWith('mdx') ||
// @ts-expect-error `node` should never have `type: 'root'`, but in some cases plugins may inject it as children,
// which MDX will render as a fragment instead (an MDX fragment is a `mdxJsxFlowElement` type).
node.type === 'root' ||
// @ts-expect-error Access `.tagName` naively for perf
ignoreElementNames.has(node.tagName)
);
};

visit(tree as any, {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,37 @@
import mdx from '@astrojs/mdx';

export default {
integrations: [mdx({
optimize: {
ignoreElementNames: ['strong']
}
})]
}
integrations: [
mdx({
optimize: {
ignoreElementNames: ['strong'],
},
}),
],
markdown: {
rehypePlugins: [
() => {
return (tree) => {
tree.children.push({
type: 'root',
children: [
{
type: 'element',
tagName: 'p',
properties: {
id: 'injected-root-hast',
},
children: [
{
type: 'text',
value: 'Injected root hast from rehype plugin',
},
],
},
],
});
};
},
],
},
};
11 changes: 11 additions & 0 deletions packages/integrations/mdx/test/mdx-optimize.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,15 @@ describe('MDX optimize', () => {
assert.notEqual(blockquote, null);
assert.equal(blockquote.textContent.includes('I like pancakes'), true);
});

it('renders MDX with rehype plugin that incorrectly injects root hast node', async () => {
const html = await fixture.readFile('/import/index.html');
const { document } = parseHTML(html);

assert.doesNotMatch(html, /set:html=/);
assert.equal(
document.getElementById('injected-root-hast').textContent,
'Injected root hast from rehype plugin',
);
});
});
2 changes: 0 additions & 2 deletions pnpm-lock.yaml

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

0 comments on commit c9ae7b1

Please sign in to comment.