-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.tsx
78 lines (61 loc) · 1.85 KB
/
index.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import { observer } from 'mobx-react';
import { GetStaticProps, InferGetStaticPropsType } from 'next';
import { FC } from 'react';
import { MDXLayout } from '../../components/MDXLayout';
import { i18n } from '../../models/Translation';
interface ArticleMeta {
name: string;
path?: string;
subs: ArticleMeta[];
}
const MDX_pattern = /\.mdx?$/;
export const getStaticProps: GetStaticProps<{
list: ArticleMeta[];
}> = async () => {
const { readdirSync } = await import('fs');
const pageListOf = (path: string, prefix = 'pages'): ArticleMeta[] =>
readdirSync(prefix + path, { withFileTypes: true })
.map(node => {
let { name, path } = node;
if (name.startsWith('.')) return;
const isMDX = MDX_pattern.test(name);
name = name.replace(MDX_pattern, '');
path = `${path}/${name}`.replace(new RegExp(`^${prefix}`), '');
if (node.isFile()) return isMDX && { name, path };
if (!node.isDirectory()) return;
const subs = pageListOf(path, prefix);
return subs[0] && { name, subs };
})
.filter(Boolean) as ArticleMeta[];
try {
const list = pageListOf('/article');
return { props: { list } };
} catch {
return { props: { list: [] } };
}
};
const renderTree = (list: ArticleMeta[]) => (
<ol>
{list.map(({ name, path, subs }) => (
<li key={name}>
{path ? (
<a className="h4" href={path}>
{name}
</a>
) : (
<details>
<summary className="h4">{name}</summary>
{renderTree(subs)}
</details>
)}
</li>
))}
</ol>
);
const ArticleIndexPage: FC<InferGetStaticPropsType<typeof getStaticProps>> =
observer(({ list }) => (
<MDXLayout className="" title={i18n.t('article')}>
{renderTree(list)}
</MDXLayout>
));
export default ArticleIndexPage;