返回 slidev
vClickMount.ts
根目录 / packages / slidev / node / vite / vClickMount.ts
1 import type { CompilerOptions } from 'vue/compiler-sfc'
2
3 type NodeTransform = NonNullable<CompilerOptions['nodeTransforms']>[number]
4
5 // Values of the `NodeTypes`, `ElementTypes` and `ConstantTypes` enums of `@vue/compiler-core`,
6 // inlined so we don't need a direct dependency on the compiler packages.
7 const NODE_ROOT = 0
8 const NODE_ELEMENT = 1
9 const NODE_TEXT = 2
10 const NODE_SIMPLE_EXPRESSION = 4
11 const NODE_ATTRIBUTE = 6
12 const NODE_DIRECTIVE = 7
13 const NODE_IF_BRANCH = 10
14 const NODE_FOR = 11
15 const ELEMENT_TYPE_COMPONENT = 1
16 const CONSTANT_CAN_STRINGIFY = 3
17
18 interface Loc {
19 start: { offset: number, line: number, column: number }
20 end: { offset: number, line: number, column: number }
21 source: string
22 }
23
24 interface AstNode {
25 type: number
26 loc: Loc
27 [key: string]: any
28 }
29
30 /**
31 * Directives that accept the `.mount` modifier, mapped to the `at` value they imply.
32 */
33 const MOUNT_DIRECTIVES: Record<string, { at?: string, hide?: boolean }> = {
34 'click': {},
35 'after': { at: '+0' },
36 'click-hide': { hide: true },
37 }
38
39 /**
40 * Directives that have to stay on the outermost node, so they are moved to the wrapper.
41 */
42 const STRUCTURAL_DIRECTIVES = ['if', 'else-if', 'else', 'for']
43
44 function getModifiers(dir: AstNode): string[] {
45 return (dir.modifiers ?? []).map((m: string | AstNode) => typeof m === 'string'
46 ? m
47 : m.content)
48 }
49
50 function isMountDirective(prop: AstNode) {
51 return prop.type === NODE_DIRECTIVE
52 && prop.name in MOUNT_DIRECTIVES
53 && getModifiers(prop).includes('mount')
54 }
55
56 function isKeyProp(prop: AstNode) {
57 if (prop.type === NODE_ATTRIBUTE)
58 return prop.name === 'key'
59 return prop.type === NODE_DIRECTIVE
60 && prop.name === 'bind'
61 && prop.arg?.type === NODE_SIMPLE_EXPRESSION
62 && prop.arg.isStatic
63 && prop.arg.content === 'key'
64 }
65
66 function createAttribute(name: string, value: string | undefined, loc: Loc): AstNode {
67 return {
68 type: NODE_ATTRIBUTE,
69 name,
70 nameLoc: loc,
71 value: value == null
72 ? undefined
73 : { type: NODE_TEXT, content: value, loc },
74 loc,
75 }
76 }
77
78 function createBind(name: string, exp: AstNode, loc: Loc): AstNode {
79 return {
80 type: NODE_DIRECTIVE,
81 name: 'bind',
82 rawName: `:${name}`,
83 arg: {
84 type: NODE_SIMPLE_EXPRESSION,
85 content: name,
86 isStatic: true,
87 constType: CONSTANT_CAN_STRINGIFY,
88 loc,
89 },
90 exp,
91 modifiers: [],
92 loc,
93 }
94 }
95
96 /**
97 * Modifiers of the directive that are not animation presets.
98 */
99 const NON_ANIMATION_MODIFIERS = ['mount', 'hide']
100
101 function wrapElement(el: AstNode): AstNode | undefined {
102 if (el.type !== NODE_ELEMENT)
103 return
104
105 const dirIndex = el.props.findIndex(isMountDirective)
106 if (dirIndex === -1)
107 return
108
109 // `<template v-slot>` is a slot outlet, not content, so it's left untouched
110 const isTemplate = el.tag === 'template'
111 if (isTemplate && el.props.some((prop: AstNode) => prop.type === NODE_DIRECTIVE && prop.name === 'slot'))
112 return
113
114 const dir = el.props[dirIndex]
115 const preset = MOUNT_DIRECTIVES[dir.name]
116 const loc = dir.loc as Loc
117
118 const props: AstNode[] = [
119 createAttribute('mount', undefined, loc),
120 ]
121 if (preset.hide || getModifiers(dir).includes('hide'))
122 props.push(createAttribute('hide', undefined, loc))
123 if (preset.at != null)
124 props.push(createAttribute('at', preset.at, loc))
125 else if (dir.exp)
126 props.push(createBind('at', dir.exp, loc))
127 // e.g. `v-click.mount.fade.up` -> `animation="fade up"`
128 const animations = getModifiers(dir).filter(m => !NON_ANIMATION_MODIFIERS.includes(m))
129 if (animations.length)
130 props.push(createAttribute('animation', animations.join(' '), loc))
131
132 // Move `v-if` / `v-for` / `key` to the wrapper, so every rendered element still
133 // gets its own click, just like with the plain `v-click` directive.
134 const kept: AstNode[] = []
135 el.props.forEach((prop: AstNode, idx: number) => {
136 if (idx === dirIndex)
137 return
138 if ((prop.type === NODE_DIRECTIVE && STRUCTURAL_DIRECTIVES.includes(prop.name)) || isKeyProp(prop))
139 props.push(prop)
140 else
141 kept.push(prop)
142 })
143 el.props = kept
144
145 return {
146 type: NODE_ELEMENT,
147 ns: el.ns,
148 tag: 'v-click',
149 tagType: ELEMENT_TYPE_COMPONENT,
150 props,
151 // `<template>` isn't rendered, so its children are moved into the wrapper
152 children: isTemplate
153 ? el.children
154 : [el],
155 isSelfClosing: false,
156 codegenNode: undefined,
157 loc: el.loc,
158 }
159 }
160
161 /**
162 * Vue template transform for the `.mount` modifier of `v-click`, `v-after` and `v-click-hide`.
163 *
164 * A directive can't stop its own element from being mounted, so
165 * `<div v-click.mount="3" />` is rewritten into `<v-click mount :at="3"><div /></v-click>`.
166 * Animation modifiers are passed as the `animation` prop, and the children of
167 * `<template v-click.mount>` are wrapped directly.
168 *
169 * The rewrite is done on the parent node, before its children are traversed,
170 * so the moved element is only transformed once.
171 */
172 export const transformVClickMount: NodeTransform = (node) => {
173 const parent = node as unknown as AstNode
174 if (![
175 NODE_ROOT,
176 NODE_ELEMENT,
177 NODE_IF_BRANCH,
178 NODE_FOR,
179 ].includes(parent.type) || !Array.isArray(parent.children)) {
180 return
181 }
182
183 parent.children.forEach((child: AstNode, idx: number) => {
184 const wrapped = wrapElement(child)
185 if (wrapped)
186 parent.children[idx] = wrapped
187 })
188 }
189
189 lines TYPESCRIPT