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

Add new markdown.frontmatterPlugins config option #3411

Closed
wants to merge 2 commits into from
Closed
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
18 changes: 18 additions & 0 deletions packages/astro/src/@types/astro.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import type {
ShikiConfig,
RemarkPlugins,
RehypePlugins,
FrontmatterPlugins,
MarkdownHeader,
MarkdownMetadata,
MarkdownRenderingResult,
Expand Down Expand Up @@ -592,6 +593,23 @@ export interface AstroUserConfig {
* ```
*/
rehypePlugins?: RehypePlugins;
/**
* @docs
* @name markdown.frontmatterPlugins
* @type {FrontmatterPlugins}
* @description
* Pass a custom Frontmatter plugin to customize Markdown frontmatter.
*
* ```js
* {
* markdown: {
* // Example: The default set of frontmatter plugins used by Astro
* frontmatterPlugins: [],
* },
* };
* ```
*/
frontmatterPlugins?: FrontmatterPlugins;
};

/**
Expand Down
11 changes: 10 additions & 1 deletion packages/astro/src/core/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { AstroConfig, AstroUserConfig, CLIFlags, ViteUserConfig } from '../
import type { Arguments as Flags } from 'yargs-parser';
import type * as Postcss from 'postcss';
import type { ILanguageRegistration, IThemeRegistration, Theme } from 'shiki';
import type { RemarkPlugin, RehypePlugin } from '@astrojs/markdown-remark';
import type { RemarkPlugin, RehypePlugin, FrontmatterPlugin } from '@astrojs/markdown-remark';

import * as colors from 'kleur/colors';
import path from 'path';
Expand Down Expand Up @@ -180,6 +180,15 @@ export const AstroConfigSchema = z.object({
])
.array()
.default([]),
frontmatterPlugins: z
.union([
z.string(),
z.tuple([z.string(), z.any()]),
z.custom<FrontmatterPlugin>((data) => typeof data === 'function'),
z.tuple([z.custom<FrontmatterPlugin>((data) => typeof data === 'function'), z.any()]),
])
.array()
.default([]),
})
.default({}),
vite: z
Expand Down
15 changes: 13 additions & 2 deletions packages/astro/src/vite-plugin-markdown/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { renderMarkdown } from '@astrojs/markdown-remark';
import { renderMarkdown, loadPlugins } from '@astrojs/markdown-remark';
import { transform } from '@astrojs/compiler';
import ancestor from 'common-ancestor-path';
import esbuild from 'esbuild';
Expand Down Expand Up @@ -118,7 +118,17 @@ export default function markdown({ config }: AstroPluginOptions): Plugin {
const hasInjectedScript = isPage && config._ctx.scripts.some((s) => s.stage === 'page-ssr');

// Extract special frontmatter keys
const { data: frontmatter, content: markdownContent } = matter(source);
let { data: frontmatter, content: markdownContent } = matter(source);

if (renderOpts.frontmatterPlugins.length > 0) {
const loadedFrontmatterPlugins = await Promise.all(
loadPlugins(renderOpts.frontmatterPlugins)
);
loadedFrontmatterPlugins.forEach(([plugin, opts]) => {
frontmatter = plugin(frontmatter, getFileInfo(id, config), opts);
});
}

let renderResult = await renderMarkdown(markdownContent, renderOpts);
let { code: astroResult, metadata } = renderResult;
const { layout = '', components = '', setup = '', ...content } = frontmatter;
Expand Down Expand Up @@ -162,6 +172,7 @@ ${tsResult}`;
sourcemap: false,
sourcefile: id,
});

return {
code,
map: null,
Expand Down
15 changes: 13 additions & 2 deletions packages/astro/test/astro-markdown-plugins.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { expect } from 'chai';
import * as cheerio from 'cheerio';
import { loadFixture } from './test-utils.js';
import addClasses from './fixtures/astro-markdown-plugins/add-classes.mjs';
import updateFrontmatter from './fixtures/astro-markdown-plugins/update-frontmatter.mjs';

describe('Astro Markdown plugins', () => {
let fixture;
Expand All @@ -19,6 +20,7 @@ describe('Astro Markdown plugins', () => {
['rehype-toc', { headings: ['h2', 'h3'] }],
[addClasses, { 'h1,h2,h3': 'title' }],
],
frontmatterPlugins: [updateFrontmatter],
},
});
await fixture.build();
Expand All @@ -32,7 +34,7 @@ describe('Astro Markdown plugins', () => {
expect($('.toc')).to.have.lengthOf(1);

// teste 2: Added .title to h1
expect($('#hello-world').hasClass('title')).to.equal(true);
expect($('#hello-world-from-page').hasClass('title')).to.equal(true);
});

it('Can render Astro <Markdown> with plugins', async () => {
Expand All @@ -43,6 +45,15 @@ describe('Astro Markdown plugins', () => {
expect($('.toc')).to.have.lengthOf(1);

// teste 2: Added .title to h1
expect($('#hello-world').hasClass('title')).to.equal(true);
expect($('#hello-world-from-component').hasClass('title')).to.equal(true);
});

it('Can update Markdown frontmatter from config', async () => {
const html = await fixture.readFile('/index.html');
const $ = cheerio.load(html);

// test 1: Switched layout
expect($('.container-alt')).to.have.lengthOf(1);
expect($('.container')).to.have.lengthOf(0);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<html>
<head>
<!-- Head Stuff -->
</head>
<body>
<div class="container-alt">
<slot></slot>
</div>
</body>
</html>
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@ import Layout from '../layouts/content.astro';

<Layout>
<Markdown>
# Hello world
# Hello world from component
</Markdown>
</Layout>
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
layout: ../layouts/content.astro
---

# Hello world
# Hello world from page
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export default (frontmatter, {fileId, fileUrl}) => {
let newFrontmatter = Object.assign({}, frontmatter)
newFrontmatter.layout = "../layouts/content-alt.astro";
return newFrontmatter;
};
2 changes: 2 additions & 0 deletions packages/markdown/remark/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ import rehypeRaw from 'rehype-raw';

export * from './types.js';

export { loadPlugins };

export const DEFAULT_REMARK_PLUGINS = ['remark-gfm', 'remark-smartypants'];
export const DEFAULT_REHYPE_PLUGINS = [];

Expand Down
13 changes: 13 additions & 0 deletions packages/markdown/remark/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,18 @@ export type RehypePlugin<PluginParameters extends any[] = any[]> = unified.Plugi

export type RehypePlugins = (string | [string, any] | RehypePlugin | [RehypePlugin, any])[];

export type FrontmatterPlugin<PluginParameters extends any[] = any[]> = unified.Plugin<
PluginParameters,
hast.Root
>;

export type FrontmatterPlugins = (
| string
| [string, any]
| FrontmatterPlugin
| [FrontmatterPlugin, any]
)[];

export interface ShikiConfig {
langs: ILanguageRegistration[];
theme: Theme | IThemeRegistration;
Expand All @@ -32,6 +44,7 @@ export interface AstroMarkdownOptions {
shikiConfig: ShikiConfig;
remarkPlugins: RemarkPlugins;
rehypePlugins: RehypePlugins;
frontmatterPlugins: FrontmatterPlugins;
}

export interface MarkdownRenderingOptions extends AstroMarkdownOptions {
Expand Down