|
| 1 | +import { SerializeOptions } from "next-mdx-remote/dist/types"; |
| 2 | +import { serialize } from "next-mdx-remote/serialize"; |
| 3 | +import { GetStaticPropsResult } from "next/types"; |
| 4 | +import remarkGfm from "remark-gfm"; |
| 5 | +import { OutlineItem } from "../../../components/Layout/components/Outline/types"; |
| 6 | +import { getMatter } from "../frontmatter/getMatter"; |
| 7 | +import { FrontmatterProps } from "../frontmatter/types"; |
| 8 | +import { validateMatter } from "../frontmatter/validateMatter"; |
| 9 | +import { rehypeSlug } from "../plugins/rehypeSlug"; |
| 10 | +import { remarkHeadings } from "../plugins/remarkHeadings"; |
| 11 | +import { StaticProps } from "./types"; |
| 12 | + |
| 13 | +export async function buildStaticProps<F extends object, P extends object>( |
| 14 | + fileName: string | undefined, |
| 15 | + slug: string[] | undefined, |
| 16 | + frontmatterFn = ( |
| 17 | + frontmatter: FrontmatterProps<F> | undefined |
| 18 | + ): FrontmatterProps<F> | undefined => frontmatter, |
| 19 | + serializeOptions: SerializeOptions = {}, |
| 20 | + otherProps: P = {} as P |
| 21 | +): Promise< |
| 22 | + GetStaticPropsResult<StaticProps<FrontmatterProps<F>, P>> | undefined |
| 23 | +> { |
| 24 | + if (!slug) return; |
| 25 | + if (!fileName) return; |
| 26 | + |
| 27 | + // Extract frontmatter and content from the MDX file. |
| 28 | + const { content, data } = getMatter(fileName); |
| 29 | + const frontmatter = frontmatterFn(validateMatter(data)); |
| 30 | + |
| 31 | + // If the frontmatter is hidden, return. |
| 32 | + if (!frontmatter || frontmatter.hidden) return; |
| 33 | + |
| 34 | + // We expect the frontmatter to have a title. |
| 35 | + if (!frontmatter.title) return; |
| 36 | + |
| 37 | + // Serialize the MDX content. |
| 38 | + const outline: OutlineItem[] = []; |
| 39 | + const mdxSource = await serialize(content, { |
| 40 | + ...serializeOptions, |
| 41 | + mdxOptions: { |
| 42 | + development: false, |
| 43 | + rehypePlugins: [rehypeSlug], |
| 44 | + remarkPlugins: [[remarkHeadings, { outline }], remarkGfm], |
| 45 | + ...serializeOptions.mdxOptions, |
| 46 | + }, |
| 47 | + scope: { ...serializeOptions.scope, frontmatter }, |
| 48 | + }); |
| 49 | + |
| 50 | + const { title: pageTitle } = frontmatter; |
| 51 | + |
| 52 | + return { |
| 53 | + props: { |
| 54 | + frontmatter, |
| 55 | + mdxSource, |
| 56 | + outline, |
| 57 | + pageTitle, |
| 58 | + slug, |
| 59 | + ...otherProps, |
| 60 | + }, |
| 61 | + }; |
| 62 | +} |
0 commit comments