返回 slidev
layoutWrapper.ts
根目录 / packages / slidev / node / vite / layoutWrapper.ts
1 import type { ResolvedSlidevOptions } from '@slidev/types'
2 import type { Plugin } from 'vite'
3 import { bold, gray, red, yellow } from 'ansis'
4 import { toAtFS } from '../resolver'
5 import { regexSlideSourceId, templateImportContextUtils, templateInitContext, templateInjectionMarker } from './common'
6
7 const RE_SCRIPT_SETUP_TAG = /^<script setup.*>/m
8
9 export function createLayoutWrapperPlugin(
10 { data, utils }: ResolvedSlidevOptions,
11 ): Plugin {
12 return {
13 name: 'slidev:layout-wrapper',
14 transform: {
15 filter: {
16 id: {
17 include: regexSlideSourceId,
18 },
19 },
20 async handler(code, id) {
21 const match = id.match(regexSlideSourceId)
22 if (!match)
23 return
24 const [, no, type] = match
25 if (type !== 'md')
26 return
27 const index = +no - 1
28 const layouts = await utils.getLayouts()
29 const rawLayoutName = data.slides[index]?.frontmatter?.layout ?? data.slides[0]?.frontmatter?.defaults?.layout
30 let layoutName = rawLayoutName || (index === 0
31 ? 'cover'
32 : 'default')
33 if (!layouts[layoutName]) {
34 console.error(red(`\nUnknown layout "${bold(layoutName)}".${yellow(' Available layouts are:')}`)
35 + Object.keys(layouts).map((i, idx) => (idx % 3 === 0
36 ? '\n '
37 : '') + gray(i.padEnd(15, ' '))).join(' '))
38 console.error()
39 layoutName = 'default'
40 }
41
42 const setupTag = code.match(RE_SCRIPT_SETUP_TAG)
43 if (!setupTag)
44 throw new Error(`[Slidev] Internal error: <script setup> block not found in slide ${index + 1}.`)
45
46 const templatePart = code.slice(0, setupTag.index!)
47 const scriptPart = code.slice(setupTag.index!)
48
49 const bodyStart = templatePart.indexOf('<template>') + 10
50 const bodyEnd = templatePart.lastIndexOf('</template>')
51 let body = code.slice(bodyStart, bodyEnd).trim()
52 if (body.startsWith('<div>') && body.endsWith('</div>'))
53 body = body.slice(5, -6)
54
55 return [
56 templatePart.slice(0, bodyStart),
57 `<InjectedLayout v-bind="_frontmatterToProps($frontmatter,${index})">\n${body}\n</InjectedLayout>`,
58 templatePart.slice(bodyEnd),
59 scriptPart.slice(0, setupTag[0].length),
60 `import InjectedLayout from "${toAtFS(layouts[layoutName])}"`,
61 templateImportContextUtils,
62 templateInitContext,
63 '$clicksContext.setup()',
64 templateInjectionMarker,
65 scriptPart.slice(setupTag[0].length),
66 ].join('\n')
67 },
68 },
69 }
70 }
71
71 lines TYPESCRIPT