|
| 1 | +import hljs from 'highlight.js' |
| 2 | +import { JSDOM } from 'jsdom' |
| 3 | +import type { GetStaticPaths, GetStaticPathsResult, GetStaticProps, NextPage } from 'next' |
| 4 | + |
| 5 | +import { BlogDetailLayout } from '~/src/components/BlogDetailLayout' |
| 6 | +import { BlogDetailLayoutProps } from '~/src/components/BlogDetailLayout/BlogDetailLayout' |
| 7 | +import { apiClient } from '~/src/utils/apiClient' |
| 8 | +import { getContents } from '~/src/utils/getContents' |
| 9 | +import { headers } from '~/src/utils/microCMSHeaders' |
| 10 | + |
| 11 | +export const getStaticPaths: GetStaticPaths = async () => { |
| 12 | + const { contents } = await getContents() |
| 13 | + const paths: GetStaticPathsResult['paths'] = contents.map((content) => ({ |
| 14 | + params: { |
| 15 | + slug: content.id, |
| 16 | + }, |
| 17 | + })) |
| 18 | + |
| 19 | + return { |
| 20 | + paths, |
| 21 | + fallback: 'blocking', |
| 22 | + } |
| 23 | +} |
| 24 | + |
| 25 | +const processingDom = (htmlString: string) => { |
| 26 | + const dom = new JSDOM(htmlString) |
| 27 | + const toc: BlogDetailLayoutProps['toc'] = [] |
| 28 | + dom.window.document.querySelectorAll('h1, h2, h3').forEach((heading) => { |
| 29 | + toc.push({ |
| 30 | + id: heading.id, |
| 31 | + name: heading.tagName, |
| 32 | + text: heading.textContent ?? '', |
| 33 | + }) |
| 34 | + }) |
| 35 | + dom.window.document.querySelectorAll('pre code').forEach((element) => { |
| 36 | + const res = hljs.highlightAuto(element.textContent ?? '') |
| 37 | + element.innerHTML = res.value |
| 38 | + element.classList.add('hljs') |
| 39 | + }) |
| 40 | + dom.window.document.querySelectorAll('img').forEach((element) => { |
| 41 | + element.classList.add('lazyload') |
| 42 | + element.setAttribute('data-src', element.src) |
| 43 | + element.src = '' |
| 44 | + }) |
| 45 | + |
| 46 | + return { toc } |
| 47 | +} |
| 48 | + |
| 49 | +type Props = BlogDetailLayoutProps |
| 50 | + |
| 51 | +export const getStaticProps: GetStaticProps<Props> = async ({ params, preview, previewData }) => { |
| 52 | + if (params === undefined || typeof params.slug !== 'string') |
| 53 | + throw Error('pagesのディレクトリ構造かファイル名が間違っています。') |
| 54 | + |
| 55 | + const contents = await getContents() |
| 56 | + const content = await apiClient.blog._slug(params.slug).$get({ |
| 57 | + headers, |
| 58 | + query: { |
| 59 | + depth: 2, |
| 60 | + draftKey: preview ? previewData.draftKey : undefined, |
| 61 | + }, |
| 62 | + }) |
| 63 | + const { toc } = processingDom(content.body) |
| 64 | + |
| 65 | + return { |
| 66 | + props: { ...contents, content, toc, latestArticles: contents.contents }, |
| 67 | + } |
| 68 | +} |
| 69 | + |
| 70 | +const IndexPage: NextPage<Props> = (props) => { |
| 71 | + return <BlogDetailLayout {...props} /> |
| 72 | +} |
| 73 | + |
| 74 | +export default IndexPage |
0 commit comments