返回 slidev
slot-sugar.ts
根目录 / packages / slidev / node / syntax / slot-sugar.ts
1 import type { MarkdownExit } from 'markdown-exit'
2
3 const RE_SLOT_MARKER = /^::\s*([\w.\-:]+)\s*::\s*$/
4
5 export default function MarkdownItSlotSugar(md: MarkdownExit) {
6 md.block.ruler.before('fence', 'slot_marker', (state, startLine, _endLine, silent) => {
7 if (state.sCount[startLine] - state.blkIndent > 0)
8 return false
9
10 const pos = state.bMarks[startLine] + state.tShift[startLine]
11 const max = state.eMarks[startLine]
12 const lineText = state.src.slice(pos, max)
13
14 const match = lineText.match(RE_SLOT_MARKER)
15 if (!match)
16 return false
17
18 if (silent)
19 return true
20
21 const token = state.push('slot_marker', '', 0)
22 token.meta = { slotName: match[1] }
23 token.map = [startLine, startLine + 1]
24
25 state.line = startLine + 1
26 state.env.hasSlotMarker = true
27
28 return true
29 }, {
30 alt: [
31 'paragraph',
32 'reference',
33 'blockquote',
34 'list',
35 ],
36 })
37
38 md.core.ruler.push('slot_sugar_compiler', (state) => {
39 if (!state.env.hasSlotMarker)
40 return
41
42 const tokens = state.tokens
43 const newTokens = []
44 let hasOpenSlot = false
45
46 for (let i = 0; i < tokens.length; i++) {
47 const token = tokens[i]
48
49 if (token.type === 'slot_marker') {
50 if (hasOpenSlot) {
51 const closeHtml = new state.Token('html_block', '', 0)
52 closeHtml.content = '\n</template>\n'
53 newTokens.push(closeHtml)
54 }
55
56 const openHtml = new state.Token('html_block', '', 0)
57 openHtml.content = `\n<template v-slot:${token.meta.slotName}="slotProps">\n`
58 newTokens.push(openHtml)
59
60 hasOpenSlot = true
61 }
62 else {
63 newTokens.push(token)
64 }
65 }
66
67 if (hasOpenSlot) {
68 const closeHtml = new state.Token('html_block', '', 0)
69 closeHtml.content = '\n</template>\n'
70 newTokens.push(closeHtml)
71 }
72
73 state.tokens = newTokens
74 })
75 }
76
76 lines TYPESCRIPT