返回 slidev
loaders.ts
根目录 / packages / slidev / node / vite / loaders.ts
1 import type { ResolvedSlidevOptions, SlideInfo, SlidePatch, SlidevData, SlidevServerOptions } from '@slidev/types'
2 import type { ModuleNode, Plugin, Rolldown, ViteDevServer } from 'vite'
3 import type { VirtualModuleContext } from '../virtual/types'
4 import { notNullish, range } from '@antfu/utils'
5 import * as parser from '@slidev/parser/fs'
6 import equal from 'fast-deep-equal'
7 import MarkdownExit from 'markdown-exit'
8 import YAML from 'yaml'
9 import { createDataUtils } from '../options'
10 import MarkdownItKatex from '../syntax/katex'
11 import markdownItLink from '../syntax/link'
12 import { applyNotesAutoRuby, createMakeAbsoluteImportGlob, getBodyJson, updateFrontmatterPatch } from '../utils'
13 import { templates } from '../virtual'
14 import { templateConfigs } from '../virtual/configs'
15 import { templateMonacoRunDeps } from '../virtual/monaco-deps'
16 import { templateMonacoTypes } from '../virtual/monaco-types'
17 import { templateSlides, VIRTUAL_SLIDE_PREFIX } from '../virtual/slides'
18 import { templateTitleRendererMd } from '../virtual/titles'
19 import { regexSlideFacadeId, regexSlideReqPath, regexSlideSourceId } from './common'
20
21 export function createSlidesLoader(
22 options: ResolvedSlidevOptions,
23 serverOptions: SlidevServerOptions,
24 ): Plugin {
25 const { data, mode, utils, withoutNotes } = options
26
27 const notesMd = MarkdownExit({ html: true })
28 notesMd.use(markdownItLink)
29 if (data.features.katex)
30 notesMd.use(MarkdownItKatex, utils.katexOptions)
31
32 const hmrSlidesIndexes = new Set<number>()
33 let server: ViteDevServer | undefined
34 let skipHmr: { filePath: string, fileContent: string } | null = null
35 const makeAbsoluteImportGlob = createMakeAbsoluteImportGlob(options.userRoot)
36
37 interface ResolvedSourceIds {
38 md: string[]
39 frontmatter: string[]
40 }
41 let sourceIds = resolveSourceIds(data)
42
43 function resolveSourceIds(data: SlidevData) {
44 const ids: ResolvedSourceIds = {
45 md: [],
46 frontmatter: [],
47 }
48 for (const type of ['md', 'frontmatter'] as const) {
49 for (let i = 0; i < data.slides.length; i++) {
50 ids[type].push(`${data.slides[i].source.filepath}__slidev_${i + 1}.${type}`)
51 }
52 }
53 return ids
54 }
55
56 function updateServerWatcher() {
57 if (!server)
58 return
59 server.watcher.add(Object.keys(data.watchFiles))
60 }
61
62 function getFrontmatter(pageNo: number) {
63 return {
64 ...(data.headmatter?.defaults as object || {}),
65 ...(data.slides[pageNo]?.frontmatter || {}),
66 }
67 }
68
69 return {
70 name: 'slidev:loader',
71 enforce: 'pre',
72
73 configureServer(_server) {
74 server = _server
75 updateServerWatcher()
76
77 server.middlewares.use(async (req, res, next) => {
78 const match = req.url?.match(regexSlideReqPath)
79 if (!match)
80 return next()
81
82 const [, no] = match
83 const idx = Number.parseInt(no) - 1
84 const targetSlide = data.slides[idx]
85 if (!targetSlide) {
86 res.statusCode = 404
87 return res.end()
88 }
89
90 if (req.method === 'GET') {
91 res.write(JSON.stringify(withRenderedNote(targetSlide)))
92 return res.end()
93 }
94 else if (req.method === 'POST') {
95 const body: SlidePatch = await getBodyJson(req)
96 const slide = targetSlide
97
98 if (body.content && body.content !== slide.source.content)
99 hmrSlidesIndexes.add(idx)
100
101 if (body.content)
102 slide.content = slide.source.content = body.content
103 if (body.frontmatterRaw != null) {
104 if (body.frontmatterRaw.trim() === '') {
105 slide.source.frontmatterDoc = slide.source.frontmatterStyle = undefined
106 }
107 else {
108 const parsed = YAML.parseDocument(body.frontmatterRaw)
109 if (parsed.errors.length)
110 console.error('ERROR when saving frontmatter', parsed.errors)
111 else
112 slide.source.frontmatterDoc = parsed
113 }
114 }
115 if (body.note != null)
116 slide.note = slide.source.note = body.note
117 if (body.frontmatter) {
118 updateFrontmatterPatch(slide.source, body.frontmatter)
119 Object.assign(slide.frontmatter, body.frontmatter)
120 }
121
122 parser.prettifySlide(slide.source)
123 const fileContent = await parser.save(data.markdownFiles[slide.source.filepath])
124 if (body.skipHmr) {
125 skipHmr = {
126 filePath: slide.source.filepath,
127 fileContent,
128 }
129 server?.moduleGraph.invalidateModule(
130 server.moduleGraph.getModuleById(sourceIds.md[idx])!,
131 )
132 if (body.frontmatter) {
133 server?.moduleGraph.invalidateModule(
134 server.moduleGraph.getModuleById(sourceIds.frontmatter[idx])!,
135 )
136 }
137 }
138
139 res.statusCode = 200
140 res.write(JSON.stringify(withRenderedNote(slide)))
141 return res.end()
142 }
143
144 next()
145 })
146 },
147
148 async handleHotUpdate(ctx) {
149 const forceChangedSlides = data.watchFiles[ctx.file]
150 if (!forceChangedSlides)
151 return
152
153 for (const index of forceChangedSlides) {
154 hmrSlidesIndexes.add(index)
155 }
156
157 const newData = await serverOptions.loadData?.({
158 [ctx.file]: await ctx.read(),
159 })
160
161 if (!newData)
162 return []
163
164 if (skipHmr && newData.markdownFiles[skipHmr.filePath]?.raw === skipHmr.fileContent) {
165 skipHmr = null
166 return []
167 }
168
169 const moduleIds = new Set<string>()
170
171 const newSourceIds = resolveSourceIds(newData)
172 for (const type of ['md', 'frontmatter'] as const) {
173 const old = sourceIds[type]
174 const newIds = newSourceIds[type]
175 for (let i = 0; i < newIds.length; i++) {
176 if (old[i] !== newIds[i]) {
177 moduleIds.add(`${VIRTUAL_SLIDE_PREFIX}${i + 1}/${type}`)
178 }
179 }
180 }
181 sourceIds = newSourceIds
182
183 if (data.slides.length !== newData.slides.length) {
184 moduleIds.add(templateSlides.id)
185 }
186
187 if (!equal(data.headmatter.defaults, newData.headmatter.defaults)) {
188 moduleIds.add(templateSlides.id)
189 range(data.slides.length).map(i => hmrSlidesIndexes.add(i))
190 }
191
192 if (!equal(data.config, newData.config))
193 moduleIds.add(templateConfigs.id)
194
195 if (!equal(data.features, newData.features)) {
196 setTimeout(() => {
197 ctx.server.hot.send({ type: 'full-reload' })
198 }, 1)
199 }
200
201 const length = Math.min(data.slides.length, newData.slides.length)
202
203 // Only titles are baked into `/@slidev/title-renderer.md`. Invalidating that
204 // virtual module on every content change dead-ends HMR under Vite 8 when the
205 // module is not self-accepting (#2784). Skip it unless a title (or slide count) changed.
206 const titlesChanged = data.slides.length !== newData.slides.length
207 || range(length).some(i => data.slides[i].title?.trim() !== newData.slides[i].title?.trim())
208
209 for (let i = 0; i < length; i++) {
210 const a = data.slides[i]
211 const b = newData.slides[i]
212
213 if (
214 !hmrSlidesIndexes.has(i)
215 && a.content.trim() === b.content.trim()
216 && a.title?.trim() === b.title?.trim()
217 && equal(a.frontmatter, b.frontmatter)
218 ) {
219 if (a.note !== b.note) {
220 ctx.server.hot.send(
221 'slidev:update-note',
222 {
223 no: i + 1,
224 note: b!.note || '',
225 noteHTML: renderNote(b!.note || ''),
226 },
227 )
228 }
229 continue
230 }
231
232 ctx.server.hot.send(
233 'slidev:update-slide',
234 {
235 no: i + 1,
236 data: withRenderedNote(newData.slides[i]),
237 },
238 )
239 hmrSlidesIndexes.add(i)
240 }
241
242 // Snippet imports (`<<<` and inside magic-move) add their files to `watchFiles`
243 // when a slide is rendered, not when it is parsed, so the reloaded data does
244 // not have them. Keep them, or later edits to those files are ignored.
245 for (const [file, indexes] of Object.entries(data.watchFiles)) {
246 if (!data.markdownFiles[file] && !newData.watchFiles[file])
247 newData.watchFiles[file] = indexes
248 }
249
250 Object.assign(data, newData)
251 Object.assign(utils, createDataUtils(options))
252
253 if (titlesChanged)
254 moduleIds.add(templateTitleRendererMd.id)
255
256 for (const idx of hmrSlidesIndexes) {
257 moduleIds.add(sourceIds.frontmatter[idx])
258 }
259
260 const reloadBeforeOthers: ModuleNode[] = []
261 const vueModules: ModuleNode[] = []
262 for (const idx of hmrSlidesIndexes) {
263 const main = ctx.server.moduleGraph.getModuleById(sourceIds.md[idx])
264 if (main) {
265 const styles = [...main.clientImportedModules].filter(m => m.id?.includes(`&type=style`))
266 if (styles.length) {
267 // `pluginVue.transform(mainModule)` must be called before `pluginVue.load(styleModule)`
268 // to refresh the internal descriptor cache of `@vitejs/plugin-vue`
269 reloadBeforeOthers.push(main)
270 vueModules.push(...styles)
271 }
272 else {
273 vueModules.push(main)
274 }
275 }
276 }
277
278 hmrSlidesIndexes.clear()
279
280 await Promise.all(reloadBeforeOthers.map(m => ctx.server.reloadModule(m)))
281
282 const moduleEntries = [
283 ...ctx.modules.filter(i => i.id === templateMonacoRunDeps.id || i.id === templateMonacoTypes.id),
284 ...vueModules,
285 ...Array.from(moduleIds).map(id => ctx.server.moduleGraph.getModuleById(id)),
286 ]
287 .filter(notNullish)
288 .filter(i => !i.id?.startsWith('/@id/@vite-icons'))
289
290 updateServerWatcher()
291
292 return moduleEntries
293 },
294
295 resolveId: {
296 order: 'pre',
297 filter: { id: /^\/@slidev\/|__slidev_/ },
298 handler(id) {
299 if (id.startsWith('/@slidev/') || id.includes('__slidev_'))
300 return id
301 return null
302 },
303 },
304
305 transform: {
306 // Snippet imports register their files in `watchFiles` while the slide is
307 // rendered by the Markdown plugin, so watch them once that has happened.
308 order: 'post',
309 handler(_code, id) {
310 if (regexSlideSourceId.test(id))
311 updateServerWatcher()
312 },
313 },
314
315 async load(id): Promise<Rolldown.LoadResult> {
316 const template = templates.find(i => i.id === id)
317 if (template) {
318 const templateContext: VirtualModuleContext = {
319 resolve: this.resolve.bind(this),
320 makeAbsoluteImportGlob,
321 }
322 return {
323 code: await template.getContent.call(templateContext, options),
324 map: { mappings: '' },
325 }
326 }
327
328 const matchFacade = id.match(regexSlideFacadeId)
329 if (matchFacade) {
330 const [, no, type] = matchFacade
331 const idx = +no - 1
332 const sourceId = JSON.stringify(sourceIds[type as 'md' | 'frontmatter'][idx])
333 return [
334 `export * from ${sourceId}`,
335 `export { default } from ${sourceId}`,
336 ].join('\n')
337 }
338
339 const matchSource = id.match(regexSlideSourceId)
340 if (matchSource) {
341 const [, no, type] = matchSource
342 const idx = +no - 1
343 const slide = data.slides[idx]
344 if (!slide)
345 return
346
347 if (type === 'md') {
348 return {
349 code: slide.content,
350 map: { mappings: '' },
351 }
352 }
353 else if (type === 'frontmatter') {
354 const slideBase = {
355 ...withRenderedNote(slide),
356 frontmatter: undefined,
357 source: undefined,
358 importChain: undefined,
359 // The runtime image preloader reads `slide.images`, but `source` is
360 // stripped just above — carry the extracted image URLs onto the client
361 // slide so runtime preloading actually receives them.
362 images: slide.images ?? slide.source?.images,
363 // remove raw content in build, optimize the bundle size
364 ...(mode === 'build'
365 ? { raw: '', content: '', note: '' }
366 : {}),
367 }
368 const fontmatter = getFrontmatter(idx)
369
370 return {
371 code: [
372 '// @unocss-include',
373 'import { computed, reactive, shallowReactive } from "vue"',
374 `export const frontmatterData = ${JSON.stringify(fontmatter)}`,
375 // handle HMR, update frontmatter with update
376 'if (import.meta.hot) {',
377 ' import.meta.hot.data.frontmatter ??= reactive(frontmatterData)',
378 ' import.meta.hot.accept(({ frontmatterData: update }) => {',
379 ' const frontmatter = import.meta.hot.data.frontmatter',
380 ' Object.keys(frontmatter).forEach(key => {',
381 ' if (!(key in update)) delete frontmatter[key]',
382 ' })',
383 ' Object.assign(frontmatter, update)',
384 ' })',
385 '}',
386 'export const frontmatter = import.meta.hot ? import.meta.hot.data.frontmatter : reactive(frontmatterData)',
387 'export default frontmatter',
388 'export const meta = shallowReactive({',
389 ' get layout(){ return frontmatter.layout },',
390 ' get transition(){ return frontmatter.transition },',
391 ' get class(){ return frontmatter.class },',
392 ' get clicks(){ return frontmatter.clicks },',
393 ' get name(){ return frontmatter.name },',
394 ' get preload(){ return frontmatter.preload },',
395 // No need to be reactive, as it's only used once after reload
396 ' slide: {',
397 ` ...(${JSON.stringify(slideBase)}),`,
398 ` frontmatter,`,
399 ` filepath: ${JSON.stringify(mode === 'dev'
400 ? slide.source.filepath
401 : '')},`,
402 ` start: ${JSON.stringify(slide.source.start)},`,
403 ` sourceIndex: ${JSON.stringify(slide.source.index)},`,
404 ` id: ${idx},`,
405 ` no: ${no},`,
406 ' },',
407 ' __clicksContext: null,',
408 ' __preloaded: false,',
409 '})',
410 ].join('\n'),
411 map: { mappings: '' },
412 }
413 }
414 }
415
416 // Entry files, shouldn't be processed by MarkdownIt
417 if (data.markdownFiles[id])
418 return ''
419 },
420 }
421
422 function renderNote(text: string = '') {
423 if (withoutNotes)
424 return ''
425
426 let clickCount = 0
427 const notesAutoRuby: Record<string, string | undefined> = (data.headmatter as any).notesAutoRuby || {}
428
429 // Apply [click] marker
430 const md = text
431 // replace [click] marker with span
432 .replace(/\[click(?::(\d+))?\]/gi, (_, count = 1) => {
433 clickCount += Number(count)
434 return `<span class="slidev-note-click-mark" data-clicks="${clickCount}"></span>`
435 })
436
437 const html = notesMd.render(applyNotesAutoRuby(md, notesAutoRuby))
438 return html
439 }
440
441 function withRenderedNote(data: SlideInfo): SlideInfo {
442 return {
443 ...data,
444 ...withoutNotes && { note: '' },
445 noteHTML: renderNote(data?.note),
446 }
447 }
448 }
449
449 lines TYPESCRIPT