Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[MDX] Pass injected frontmatter to layouts #4255

Merged
merged 4 commits into from
Aug 11, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/tasty-masks-draw.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@astrojs/mdx': patch
---

Pass injected frontmatter from remark and rehype plugins to layouts
36 changes: 36 additions & 0 deletions packages/integrations/mdx/src/astro-data-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,42 @@ export function rehypeApplyFrontmatterExport(pageFrontmatter: Record<string, any
const exportNodes = [
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, {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Now using astro/jsx-runtime manually instead of raw JSX expressions. Otherwise, acorn can't properly parse to an ES tree entry.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense!

content,
frontmatter: content,
headings: getHeadings(),
'server:root': true,
children,
});
};`
)
);
}
tree.children = exportNodes.concat(tree.children);
};
}
Expand Down
11 changes: 1 addition & 10 deletions packages/integrations/mdx/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,16 +98,7 @@ export default function mdx(mdxOptions: MdxOptions = {}): AstroIntegration {
async transform(code, id) {
if (!id.endsWith('mdx')) return;

let { 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 { data: frontmatter, content: pageContent } = parseFrontmatter(code, id);
const compiled = await mdxCompile(new VFile({ value: pageContent, path: id }), {
...mdxPluginOpts,
rehypePlugins: [
Expand Down
Original file line number Diff line number Diff line change
@@ -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>
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
---
layout: '../layouts/Base.astro'
---

# Page 1

Look at that!
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
---
layout: '../layouts/Base.astro'
---

# Page 2

## Table of contents
Expand Down
12 changes: 12 additions & 0 deletions packages/integrations/mdx/test/mdx-frontmatter-injection.test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { expect } from 'chai';
import { parseHTML } from 'linkedom';
import { loadFixture } from '../../../astro/test/test-utils.js';

const FIXTURE_ROOT = new URL('./fixtures/mdx-frontmatter-injection/', import.meta.url);
Expand Down Expand Up @@ -41,4 +42,15 @@ describe('MDX frontmatter injection', () => {
expect(titles).to.contain('Overridden title');
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');
});
});