-
Notifications
You must be signed in to change notification settings - Fork 19
/
blog-plugin.js
111 lines (96 loc) · 2.28 KB
/
blog-plugin.js
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
import { createPage } from 'vuepress/core'
const slugify = (name) =>
name
.replace(/[ _]/g, '-')
.replace(/[:?*|\\/<>]/g, '')
.toLowerCase()
const generateCategory = async (app, name) => {
const map = {}
await app.pages.map(async (page) => {
const value = page.frontmatter[name]
await (Array.isArray(value) ? value : [value]).map(async (item) => {
if (item) {
if (!map[item]) {
const itemPath = `/${name}/${slugify(item)}/`
map[item] = {
path: itemPath,
keys: [],
}
app.pages.push(
await createPage(app, {
path: itemPath,
frontmatter: {
title: `${name} > ${item}`,
key: item,
layout: name[0].toUpperCase() + name.slice(1),
sidebar: false,
},
}),
)
}
map[item].keys.push(page.key)
}
})
})
app.pages.push(
await createPage(app, {
path: `/${name}/`,
frontmatter: {
title: name,
layout: name[0].toUpperCase() + name.slice(1),
sidebar: false,
},
}),
)
await app.writeTemp(
`blog/${name}.js`,
`\
export const map = ${JSON.stringify(map)};
`,
)
}
const generateType = async (
app,
name,
{ filter = () => true, sorter = () => 0 },
) => {
app.pages.push(
await createPage(app, {
path: `/${name}/`,
frontmatter: {
title: name,
layout: name[0].toUpperCase() + name.slice(1),
sidebar: false,
},
}),
)
const keys = app.pages.filter(filter).map(({ key }) => key)
await app.writeTemp(
`blog/${name}.js`,
`\
export const keys = ${JSON.stringify(keys)};
`,
)
}
export const simpleBlogPlugin = ({
filter = () => true,
getInfo,
category = [],
type = [],
}) => ({
name: 'simple-blog-plugin',
onInitialized: async (app) => {
// inject meta information
app.pages.filter(filter).forEach((page) => {
page.routeMeta = {
...page.routeMeta,
...getInfo(page),
}
})
// generate pages and temp files
await Promise.all([
...category.map((name) => generateCategory(app, name)),
...type.map(({ key, ...options }) => generateType(app, key, options)),
])
},
})