Skip to content

Commit c9ae7b1

Browse files
authoredSep 12, 2024··
Handle MDX optimize for root hast node (#11975)
1 parent 86ad1fd commit c9ae7b1

File tree

5 files changed

+58
-10
lines changed

5 files changed

+58
-10
lines changed
 

‎.changeset/lovely-dolphins-draw.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@astrojs/mdx': patch
3+
---
4+
5+
Handles nested root hast node when optimizing MDX

‎packages/integrations/mdx/src/rehype-optimize-static.ts

+8-2
Original file line numberDiff line numberDiff line change
@@ -64,8 +64,14 @@ export const rehypeOptimizeStatic: RehypePlugin<[OptimizeOptions?]> = (options)
6464
* A non-static node causes all its parents to be non-optimizable
6565
*/
6666
const isNodeNonStatic = (node: Node) => {
67-
// @ts-expect-error Access `.tagName` naively for perf
68-
return node.type.startsWith('mdx') || ignoreElementNames.has(node.tagName);
67+
return (
68+
node.type.startsWith('mdx') ||
69+
// @ts-expect-error `node` should never have `type: 'root'`, but in some cases plugins may inject it as children,
70+
// which MDX will render as a fragment instead (an MDX fragment is a `mdxJsxFlowElement` type).
71+
node.type === 'root' ||
72+
// @ts-expect-error Access `.tagName` naively for perf
73+
ignoreElementNames.has(node.tagName)
74+
);
6975
};
7076

7177
visit(tree as any, {
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,37 @@
11
import mdx from '@astrojs/mdx';
22

33
export default {
4-
integrations: [mdx({
5-
optimize: {
6-
ignoreElementNames: ['strong']
7-
}
8-
})]
9-
}
4+
integrations: [
5+
mdx({
6+
optimize: {
7+
ignoreElementNames: ['strong'],
8+
},
9+
}),
10+
],
11+
markdown: {
12+
rehypePlugins: [
13+
() => {
14+
return (tree) => {
15+
tree.children.push({
16+
type: 'root',
17+
children: [
18+
{
19+
type: 'element',
20+
tagName: 'p',
21+
properties: {
22+
id: 'injected-root-hast',
23+
},
24+
children: [
25+
{
26+
type: 'text',
27+
value: 'Injected root hast from rehype plugin',
28+
},
29+
],
30+
},
31+
],
32+
});
33+
};
34+
},
35+
],
36+
},
37+
};

‎packages/integrations/mdx/test/mdx-optimize.test.js

+11
Original file line numberDiff line numberDiff line change
@@ -47,4 +47,15 @@ describe('MDX optimize', () => {
4747
assert.notEqual(blockquote, null);
4848
assert.equal(blockquote.textContent.includes('I like pancakes'), true);
4949
});
50+
51+
it('renders MDX with rehype plugin that incorrectly injects root hast node', async () => {
52+
const html = await fixture.readFile('/import/index.html');
53+
const { document } = parseHTML(html);
54+
55+
assert.doesNotMatch(html, /set:html=/);
56+
assert.equal(
57+
document.getElementById('injected-root-hast').textContent,
58+
'Injected root hast from rehype plugin',
59+
);
60+
});
5061
});

‎pnpm-lock.yaml

-2
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)
Please sign in to comment.