[MDX] Pass injected frontmatter to layouts (#4255)

* fix: move layout generation to remark plugin

* test: frontmatter injection in layout

* chore: changeset

* fix: remove content fallback
This commit is contained in:
Ben Holmes 2022-08-11 12:36:34 -05:00 committed by GitHub
parent 5afb5ef7af
commit 4116128082
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
7 changed files with 79 additions and 10 deletions

View file

@ -0,0 +1,5 @@
---
'@astrojs/mdx': patch
---
Pass injected frontmatter from remark and rehype plugins to layouts

View file

@ -19,6 +19,42 @@ export function rehypeApplyFrontmatterExport(pageFrontmatter: Record<string, any
const exportNodes = [ const exportNodes = [
jsToTreeNode(`export const ${EXPORT_NAME} = ${JSON.stringify(frontmatter)};`), jsToTreeNode(`export const ${EXPORT_NAME} = ${JSON.stringify(frontmatter)};`),
]; ];
if (frontmatter.layout) {
exportNodes.unshift(
jsToTreeNode(
/** @see 'vite-plugin-markdown' for layout props reference */
`import { jsx as layoutJsx } from 'astro/jsx-runtime';
import Layout from ${JSON.stringify(frontmatter.layout)};
export default function ({ children }) {
const { layout, ...content } = frontmatter;
content.astro = {};
Object.defineProperty(content.astro, 'headings', {
get() {
throw new Error('The "astro" property is no longer supported! To access "headings" from your layout, try using "Astro.props.headings."')
}
});
Object.defineProperty(content.astro, 'html', {
get() {
throw new Error('The "astro" property is no longer supported! To access "html" from your layout, try using "Astro.props.compiledContent()."')
}
});
Object.defineProperty(content.astro, 'source', {
get() {
throw new Error('The "astro" property is no longer supported! To access "source" from your layout, try using "Astro.props.rawContent()."')
}
});
return layoutJsx(Layout, {
content,
frontmatter: content,
headings: getHeadings(),
'server:root': true,
children,
});
};`
)
);
}
tree.children = exportNodes.concat(tree.children); tree.children = exportNodes.concat(tree.children);
}; };
} }

View file

@ -98,16 +98,7 @@ export default function mdx(mdxOptions: MdxOptions = {}): AstroIntegration {
async transform(code, id) { async transform(code, id) {
if (!id.endsWith('mdx')) return; if (!id.endsWith('mdx')) return;
let { data: frontmatter, content: pageContent } = parseFrontmatter(code, id); const { data: frontmatter, content: pageContent } = parseFrontmatter(code, id);
if (frontmatter.layout) {
const { layout, ...contentProp } = frontmatter;
pageContent += `\n\nexport default async function({ children }) {\nconst Layout = (await import(${JSON.stringify(
frontmatter.layout
)})).default;\nconst frontmatter=${JSON.stringify(
contentProp
)};\nreturn <Layout frontmatter={frontmatter} content={frontmatter} headings={getHeadings()}>{children}</Layout> }`;
}
const compiled = await mdxCompile(new VFile({ value: pageContent, path: id }), { const compiled = await mdxCompile(new VFile({ value: pageContent, path: id }), {
...mdxPluginOpts, ...mdxPluginOpts,
rehypePlugins: [ rehypePlugins: [

View file

@ -0,0 +1,17 @@
---
const defaults = { title: 'Frontmatter not passed to layout!' }
const { frontmatter = defaults, content = defaults } = Astro.props;
---
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{frontmatter.title}</title>
</head>
<body>
<slot />
</body>
</html>

View file

@ -1,3 +1,7 @@
---
layout: '../layouts/Base.astro'
---
# Page 1 # Page 1
Look at that! Look at that!

View file

@ -1,3 +1,7 @@
---
layout: '../layouts/Base.astro'
---
# Page 2 # Page 2
## Table of contents ## Table of contents

View file

@ -1,4 +1,5 @@
import { expect } from 'chai'; import { expect } from 'chai';
import { parseHTML } from 'linkedom';
import { loadFixture } from '../../../astro/test/test-utils.js'; import { loadFixture } from '../../../astro/test/test-utils.js';
const FIXTURE_ROOT = new URL('./fixtures/mdx-frontmatter-injection/', import.meta.url); const FIXTURE_ROOT = new URL('./fixtures/mdx-frontmatter-injection/', import.meta.url);
@ -41,4 +42,15 @@ describe('MDX frontmatter injection', () => {
expect(titles).to.contain('Overridden title'); expect(titles).to.contain('Overridden title');
expect(readingTimes).to.contain('1000 min read'); expect(readingTimes).to.contain('1000 min read');
}); });
it('passes injected frontmatter to layouts', async () => {
const html1 = await fixture.readFile('/page-1/index.html');
const html2 = await fixture.readFile('/page-2/index.html');
const title1 = parseHTML(html1).document.querySelector('title');
const title2 = parseHTML(html2).document.querySelector('title');
expect(title1.innerHTML).to.equal('Page 1');
expect(title2.innerHTML).to.equal('Page 2');
});
}); });