-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
contentLoader.ts
165 lines (152 loc) · 4.27 KB
/
contentLoader.ts
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
import fs from 'fs-extra'
import path from 'path'
import glob from 'fast-glob'
import type { SiteConfig } from './config'
import matter from 'gray-matter'
import { normalizePath } from 'vite'
import { createMarkdownRenderer, type MarkdownRenderer } from './markdown'
export interface ContentOptions<T = ContentData[]> {
/**
* Include src?
* @default false
*/
includeSrc?: boolean
/**
* Render src to HTML and include in data?
* @default false
*/
render?: boolean
/**
* If `boolean`, whether to parse and include excerpt? (rendered as HTML)
*
* If `function`, control how the excerpt is extracted from the content.
*
* If `string`, define a custom separator to be used for extracting the
* excerpt. Default separator is `---` if `excerpt` is `true`.
*
* @see https://github.com/jonschlinkert/gray-matter#optionsexcerpt
* @see https://github.com/jonschlinkert/gray-matter#optionsexcerpt_separator
*
* @default false
*/
excerpt?:
| boolean
| ((
file: {
data: { [key: string]: any }
content: string
excerpt?: string
},
options?: any
) => void)
| string
/**
* Transform the data. Note the data will be inlined as JSON in the client
* bundle if imported from components or markdown files.
*/
transform?: (data: ContentData[]) => T | Promise<T>
}
export interface ContentData {
url: string
src: string | undefined
html: string | undefined
frontmatter: Record<string, any>
excerpt: string | undefined
}
/**
* Create a loader object that can be directly used as the default export
* of a data loader file.
*/
export function createContentLoader<T = ContentData[]>(
/**
* files to glob / watch - relative to <project root>
*/
pattern: string | string[],
{
includeSrc,
render,
excerpt: renderExcerpt,
transform
}: ContentOptions<T> = {}
): {
watch: string | string[]
load: () => Promise<T>
} {
const config: SiteConfig = (global as any).VITEPRESS_CONFIG
if (!config) {
throw new Error(
'content loader invoked without an active vitepress process, ' +
'or before vitepress config is resolved.'
)
}
if (typeof pattern === 'string') pattern = [pattern]
pattern = pattern.map((p) => normalizePath(path.join(config.root, p)))
let md: MarkdownRenderer
const cache = new Map<
string,
{
data: any
timestamp: number
}
>()
return {
watch: pattern,
async load(files?: string[]) {
if (!files) {
// the loader is being called directly, do a fresh glob
files = (
await glob(pattern, {
ignore: ['**/node_modules/**', '**/dist/**']
})
).sort()
}
md =
md ||
(await createMarkdownRenderer(
config.srcDir,
config.markdown,
config.site.base,
config.logger
))
const raw: ContentData[] = []
for (const file of files) {
if (!file.endsWith('.md')) {
continue
}
const timestamp = fs.statSync(file).mtimeMs
const cached = cache.get(file)
if (cached && timestamp === cached.timestamp) {
raw.push(cached.data)
} else {
const src = fs.readFileSync(file, 'utf-8')
const { data: frontmatter, excerpt } = matter(
src,
// @ts-expect-error gray-matter types are wrong
typeof renderExcerpt === 'string'
? { excerpt_separator: renderExcerpt }
: { excerpt: renderExcerpt }
)
const url =
config.site.base +
normalizePath(path.relative(config.srcDir, file))
.replace(/(^|\/)index\.md$/, '$1')
.replace(/\.md$/, config.cleanUrls ? '' : '.html')
const html = render ? md.render(src) : undefined
const renderedExcerpt = renderExcerpt
? excerpt && md.render(excerpt)
: undefined
const data: ContentData = {
src: includeSrc ? src : undefined,
html,
frontmatter,
excerpt: renderedExcerpt,
url
}
cache.set(file, { data, timestamp })
raw.push(data)
}
}
return (transform ? transform(raw) : raw) as any
}
}
}