-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
loaders.ts
306 lines (252 loc) · 8.35 KB
/
loaders.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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
import { basename } from 'path'
import { ModuleNode, Update, ViteDevServer, Plugin } from 'vite'
import { isTruthy, notNullish, objectMap, slash } from '@antfu/utils'
import type { Connect } from 'vite'
import fg from 'fast-glob'
import Markdown from 'markdown-it'
// @ts-expect-error
import mila from 'markdown-it-link-attributes'
import { SlideInfo, SlideInfoExtended } from '@slidev/types'
import * as parser from '@slidev/parser/fs'
import { ResolvedSlidevOptions, SlidevPluginOptions } from '../options'
import { toAtFS } from '../utils'
const regexId = /^\/\@slidev\/slide\/(\d+)\.(md|json)(?:\?import)?$/
const regexIdQuery = /(\d+?)\.(md|json)$/
export function getBodyJson(req: Connect.IncomingMessage) {
return new Promise<any>((resolve, reject) => {
let body = ''
req.on('data', chunk => body += chunk)
req.on('error', reject)
req.on('end', () => {
try {
resolve(JSON.parse(body) || {})
}
catch (e) {
reject(e)
}
})
})
}
export function sendHmrReload(server: ViteDevServer, modules: ModuleNode[]) {
const timestamp = +Date.now()
modules.forEach(m => server.moduleGraph.invalidateModule(m))
server.ws.send({
type: 'update',
updates: modules.map<Update>(m => ({
acceptedPath: m.id || m.file!,
path: m.file!,
timestamp,
type: 'js-update',
})),
})
}
const md = Markdown()
md.use(mila, {
attrs: {
target: '_blank',
rel: 'noopener',
},
})
function prepareSlideInfo(data: SlideInfo): SlideInfoExtended {
return {
...data,
notesHTML: md.render(data.note || ''),
}
}
export function createSlidesLoader({ data, entry, clientRoot, themeRoots, userRoot }: ResolvedSlidevOptions, pluginOptions: SlidevPluginOptions): Plugin[] {
const slidePrefix = '/@slidev/slides/'
const hmrNextModuleIds: string[] = []
const entryId = slash(entry)
return [
{
name: 'slidev:loader',
configureServer(server) {
server.watcher.add(entry)
server.middlewares.use(async(req, res, next) => {
const match = req.url?.match(regexId)
if (!match)
return next()
const [, no, type] = match
const idx = parseInt(no)
if (type === 'json' && req.method === 'GET') {
res.write(JSON.stringify(prepareSlideInfo(data.slides[idx])))
return res.end()
}
if (type === 'json' && req.method === 'POST') {
const body = await getBodyJson(req)
Object.assign(data.slides[idx], body)
hmrNextModuleIds.push(`${slidePrefix}${idx}.md`)
if (body.content != null)
hmrNextModuleIds.push(`${slidePrefix}${idx}.md`)
server.ws.send({
type: 'custom',
event: 'slidev-update',
data: {
id: idx,
data: prepareSlideInfo(data.slides[idx]),
},
})
await parser.save(data, entry)
res.statusCode = 200
return res.end()
}
next()
})
},
async handleHotUpdate(ctx) {
if (ctx.file !== entryId)
return
const newData = await parser.load(entry)
const moduleIds: (string | false)[] = [
...hmrNextModuleIds,
]
hmrNextModuleIds.length = 0
if (data.slides.length !== newData.slides.length)
moduleIds.push('/@slidev/routes')
if (JSON.stringify(data.config) !== JSON.stringify(newData.config))
moduleIds.push('/@slidev/configs')
const length = Math.max(data.slides.length, newData.slides.length)
for (let i = 0; i < length; i++) {
const a = data.slides[i]
const b = newData.slides[i]
if (a?.content.trim() === b?.content.trim() && JSON.stringify(a.frontmatter) === JSON.stringify(b.frontmatter))
continue
moduleIds.push(
`${slidePrefix}${i + 1}.md`,
`${slidePrefix}${i + 1}.json`,
)
}
const moduleEntries = moduleIds
.filter(isTruthy)
.map(id => ctx.server.moduleGraph.getModuleById(id as string))
.filter(notNullish)
pluginOptions.onDataReload?.(newData, data)
data = newData
moduleEntries.map(m => ctx.server.moduleGraph.invalidateModule(m))
return moduleEntries
},
resolveId(id) {
if (id.startsWith(slidePrefix) || id.startsWith('/@slidev/'))
return id
return null
},
load(id) {
// routes
if (id === '/@slidev/routes')
return generateRoutes()
// layouts
if (id === '/@slidev/layouts')
return generateLayouts()
// configs
if (id === '/@slidev/configs')
return `export default ${JSON.stringify(data.config)}`
// pages
if (id.startsWith(slidePrefix)) {
const remaning = id.slice(slidePrefix.length)
const match = remaning.match(regexIdQuery)
if (match) {
const [, no, type] = match
const pageNo = parseInt(no) - 1
if (type === 'md')
return data.slides[pageNo]?.raw
}
return ''
}
},
},
{
name: 'slidev:layout-transform:pre',
enforce: 'pre',
async transform(code, id) {
if (id.startsWith(slidePrefix)) {
const remaning = id.slice(slidePrefix.length)
const match = remaning.match(regexIdQuery)
if (!match)
return
const [, no, type] = match
if (type !== 'md')
return
const pageNo = parseInt(no) - 1
const layouts = await getLayouts()
const layoutName = data.slides[pageNo]?.frontmatter?.layout || (pageNo === 0 ? 'cover' : 'default')
if (!layouts[layoutName])
throw new Error(`Unknown layout "${layoutName}"`)
const imports = [
`import InjectedLayout from "${toAtFS(layouts[layoutName])}"`,
`import { next, nextSlide, prev, prevSlide } from "${toAtFS(clientRoot)}/logic/nav"`,
]
code = code.replace(/(<script setup.*>)/g, `$1${imports.join('\n')}\n`)
code = code.replace(/<template>([\s\S]*?)<\/template>/mg, '<template><InjectedLayout v-bind="frontmatter">$1</InjectedLayout></template>')
return code
}
},
},
]
async function getLayouts() {
const layouts: Record<string, string> = {}
const roots = [
userRoot,
...themeRoots,
clientRoot,
]
for (const root of roots) {
const layoutPaths = await fg('layouts/*.{vue,ts}', {
cwd: root,
absolute: true,
})
for (const layoutPath of layoutPaths) {
const layout = basename(layoutPath).replace(/\.\w+$/, '')
if (layouts[layout])
continue
layouts[layout] = layoutPath
}
}
return layouts
}
async function generateLayouts() {
const imports: string[] = []
const layouts = objectMap(
await getLayouts(),
(k, v) => {
imports.push(`import __layout_${k} from "${toAtFS(v)}"`)
return [k, `__layout_${k}`]
},
)
return [
imports.join('\n'),
`export default {\n${Object.entries(layouts).map(([k, v]) => `"${k}": ${v}`).join(',\n')}\n}`,
].join('\n\n')
}
async function generateRoutes() {
const imports: string[] = []
const layouts = await getLayouts()
imports.push(`import __layout__end from '${layouts.end}'`)
let no = 1
const routes = [
...data.slides
.map((i, idx) => {
if (i.frontmatter?.disabled)
return undefined
imports.push(`import n${no} from '${slidePrefix}${idx + 1}.md'`)
const additions = {
slide: {
start: i.start,
end: i.end,
note: i.note,
file: entry,
id: idx,
no,
},
}
const meta = Object.assign({}, i.frontmatter, additions)
const route = `{ path: '${no}', name: 'page-${no}', component: n${no}, meta: ${JSON.stringify(meta)} }`
no += 1
return route
})
.filter(notNullish),
`{ path: "${no}", component: __layout__end, meta: { layout: "end" } }`,
]
const routesStr = `export default [\n${routes.join(',\n')}\n]`
return [...imports, routesStr].join('\n')
}
}