| 1 | import path from 'path' |
| 2 | import { getProperty } from 'dot-prop' |
| 3 | import { |
| 4 | GetStaticPaths, |
| 5 | GetStaticPropsContext, |
| 6 | InferGetStaticPropsType, |
| 7 | } from 'next' |
| 8 | import { Typography } from 'components/Typography' |
| 9 | import { Layout } from 'components/docs/Layout' |
| 10 | import { parse, renderToReact } from 'utils/markdown' |
| 11 | |
| 12 | const defaultSlug = ['introduction', 'whats-marp'] |
| 13 | const docsCtx = () => require.context('docs', true, /\.md$/) |
| 14 | |
| 15 | export const getStaticPaths: GetStaticPaths = async () => ({ |
| 16 | paths: [ |
| 17 | '/docs', |
| 18 | ...docsCtx() |
| 19 | .keys() |
| 20 | .map((id) => path.join('/docs/', id).slice(0, -3)), |
| 21 | ], |
| 22 | fallback: false, |
| 23 | }) |
| 24 | |
| 25 | export const getStaticProps = async ({ params }: GetStaticPropsContext) => { |
| 26 | // Manifest |
| 27 | const { default: manifest } = await import('docs/manifest.yaml') |
| 28 | |
| 29 | // Page data |
| 30 | const slug = ([] as string[]).concat(params?.slug ?? defaultSlug) |
| 31 | if (slug[0] === 'docs') slug.splice(0, 1) // for webpack 5 |
| 32 | |
| 33 | const { default: md } = await import(`docs/${path.join(...slug)}.md`) |
| 34 | const { data, mdast } = await parse(md) |
| 35 | |
| 36 | // Breadcrumbs |
| 37 | const breadcrumbs = slug.map((sl, i) => { |
| 38 | const slugs = slug.slice(0, i + 1) |
| 39 | const key = slugs.join('/') |
| 40 | const data = getProperty( |
| 41 | { pages: manifest }, |
| 42 | slugs.flatMap((s) => ['pages', s]).join('.'), |
| 43 | undefined as Record<string, string> | undefined |
| 44 | ) |
| 45 | const hasLink = docsCtx().keys().includes(`./${key}.md`) |
| 46 | |
| 47 | return { |
| 48 | key, |
| 49 | title: data?.title || sl, |
| 50 | ...(hasLink ? { link: `/docs/${key}` } : {}), |
| 51 | } |
| 52 | }) |
| 53 | |
| 54 | return { props: { breadcrumbs, data, manifest, mdast, slug } } |
| 55 | } |
| 56 | |
| 57 | const Docs = ({ |
| 58 | breadcrumbs, |
| 59 | manifest, |
| 60 | mdast, |
| 61 | slug, |
| 62 | }: InferGetStaticPropsType<typeof getStaticProps>) => ( |
| 63 | <Layout breadcrumbs={breadcrumbs} manifest={manifest} slug={slug}> |
| 64 | {/* key is required to fix broken Google Translator built in Chrome */} |
| 65 | <Typography key={slug.join('/')}>{renderToReact(mdast)}</Typography> |
| 66 | </Layout> |
| 67 | ) |
| 68 | |
| 69 | export default Docs |
| 70 |