返回 slidev
v-click-mount.test.ts
根目录 / test / v-click-mount.test.ts
1 import type { ClicksContext } from '@slidev/types'
2 import type { RendererElement, RendererNode } from 'vue'
3 import { compileTemplate } from '@vue/compiler-sfc'
4 import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
5 import { compile, createRenderer, defineComponent, h, nextTick, onMounted, onUnmounted, ref, shallowRef } from 'vue'
6 import VAfter from '../packages/client/builtin/VAfter'
7 import VClick from '../packages/client/builtin/VClick'
8 import { createClicksContextBase } from '../packages/client/composables/useClicks'
9 import { injectionClicksContext, injectionFrontmatter } from '../packages/client/constants'
10 import { createVClickDirectives } from '../packages/client/modules/v-click'
11 import { transformVClickMount } from '../packages/slidev/node/vite/vClickMount'
12
13 vi.stubGlobal('__DEV__', true)
14
15 // `<Transition>` of the `.mount` content reads the computed transition of the element,
16 // so this is what `.slidev-vclick-target { transition: all 0.1s }` would give in a browser.
17 let transitionDuration = '0s'
18 beforeEach(() => {
19 transitionDuration = '0s'
20 vi.useFakeTimers()
21 vi.stubGlobal('requestAnimationFrame', (cb: () => void) => setTimeout(cb, 16))
22 vi.stubGlobal('window', {
23 getComputedStyle: (el: TestNode) => ({
24 transitionDuration: el.classList.contains('slidev-vclick-target') || String(el.props.class).includes('slidev-vclick-target')
25 ? transitionDuration
26 : '0s',
27 transitionDelay: '0s',
28 transitionProperty: 'all',
29 animationDuration: '0s',
30 animationDelay: '0s',
31 }),
32 })
33 })
34 afterEach(() => {
35 vi.useRealTimers()
36 vi.unstubAllGlobals()
37 vi.stubGlobal('__DEV__', true)
38 })
39
40 vi.mock('../packages/client/env', () => ({
41 configs: {},
42 }))
43
44 // `.vue` files aren't compiled in this test. With a single `<v-click>` the gap is always 0.
45 vi.mock('../packages/client/builtin/VClickGap.vue', async () => {
46 const { defineComponent } = await import('vue')
47 return {
48 default: defineComponent({
49 render: () => null,
50 }),
51 }
52 })
53
54 function compileToCode(source: string) {
55 const { code, errors } = compileTemplate({
56 source,
57 filename: 'slides.md',
58 id: 'test',
59 compilerOptions: {
60 nodeTransforms: [transformVClickMount],
61 },
62 })
63 expect(errors).toEqual([])
64 return code
65 }
66
67 describe('v-click.mount template transform', () => {
68 it('wraps the element in <v-click mount>', () => {
69 const code = compileToCode(`<div v-click.mount="3" class="a">A</div>`)
70 expect(code).toContain('_resolveComponent("v-click")')
71 expect(code).toContain('mount: ""')
72 expect(code).toContain('at: 3')
73 expect(code).not.toContain('_resolveDirective("click")')
74 expect(code).toMatchInlineSnapshot(`
75 "import { createElementVNode as _createElementVNode, resolveComponent as _resolveComponent, withCtx as _withCtx, openBlock as _openBlock, createBlock as _createBlock } from "vue"
76
77 export function render(_ctx, _cache) {
78 const _component_v_click = _resolveComponent("v-click")
79
80 return (_openBlock(), _createBlock(_component_v_click, {
81 mount: "",
82 at: 3
83 }, {
84 default: _withCtx(() => [...(_cache[0] || (_cache[0] = [
85 _createElementVNode("div", { class: "a" }, "A", -1 /* CACHED */)
86 ]))]),
87 _: 1 /* STABLE */
88 }))
89 }"
90 `)
91 })
92
93 it('keeps the default value, arrays and relative values', () => {
94 expect(compileToCode(`<div v-click.mount>A</div>`)).not.toContain('at:')
95 expect(compileToCode(`<div v-click.mount="[3, 5]">A</div>`)).toContain('at: [3, 5]')
96 expect(compileToCode(`<div v-click.mount="'+2'">A</div>`)).toContain(`at: '+2'`)
97 })
98
99 it('supports .hide, v-after and v-click-hide', () => {
100 const hide = compileToCode(`<div v-click.mount.hide="3">A</div>`)
101 expect(hide).toContain('hide: ""')
102 expect(hide).toContain('at: 3')
103
104 const after = compileToCode(`<div v-after.mount>A</div>`)
105 expect(after).toContain('at: "+0"')
106 expect(after).not.toContain('hide:')
107
108 expect(compileToCode(`<div v-after.mount.hide>A</div>`)).toContain('hide: ""')
109 expect(compileToCode(`<div v-click-hide.mount="2">A</div>`)).toContain('hide: ""')
110 })
111
112 it('passes animation modifiers as the animation prop', () => {
113 const code = compileToCode(`<div v-click.mount.fade.up="3">A</div>`)
114 expect(code).toContain('animation: "fade up"')
115 expect(code).toContain('at: 3')
116 expect(compileToCode(`<div v-after.mount.hide.scale>A</div>`)).toMatch(/hide: "",\s+at: "\+0",\s+animation: "scale"/)
117 expect(compileToCode(`<div v-click.mount.hide>A</div>`)).not.toContain('animation:')
118 })
119
120 it('wraps the children of <template v-click.mount>', () => {
121 const code = compileToCode(`<template v-click.mount="2"><p>A</p><p>B</p></template>`)
122 expect(code).toContain('_resolveComponent("v-click")')
123 expect(code).toContain('at: 2')
124 expect(code).not.toContain('"template"')
125
126 const forCode = compileToCode(`<template v-for="i in items" :key="i" v-click.mount><p>{{ i }}</p><p>B</p></template>`)
127 expect(forCode).toMatch(/_renderList\(_ctx\.items, \(i\) => \{\s+return \(_openBlock\(\), _createBlock\(_component_v_click, \{\s+mount: "",\s+key: i\s+\}/)
128
129 // slot templates are not content, so they are left alone
130 expect(compileToCode(`<Foo><template #a v-click.mount>A</template></Foo>`)).not.toContain('_resolveComponent("v-click")')
131 })
132
133 it('leaves v-click without .mount untouched', () => {
134 const code = compileToCode(`<div v-click="3">A</div><div v-click.hide>B</div>`)
135 expect(code).toContain('_resolveDirective("click")')
136 expect(code).not.toContain('_resolveComponent("v-click")')
137 })
138
139 it('moves v-for, v-if and key to the wrapper', () => {
140 const forCode = compileToCode(`<div v-for="i in items" :key="i" v-click.mount>{{ i }}</div>`)
141 expect(forCode).toMatch(/_renderList\(_ctx\.items, \(i\) => \{\s+return \(_openBlock\(\), _createBlock\(_component_v_click, \{\s+mount: "",\s+key: i\s+\}/)
142
143 const ifCode = compileToCode(`<div v-if="ok" v-click.mount>A</div><p v-else>B</p>`)
144 expect(ifCode).toMatch(/\(_ctx\.ok\)\s+\? \(_openBlock\(\), _createBlock\(_component_v_click/)
145 })
146
147 it('keeps the other props and handlers on the element, transformed once', () => {
148 const code = compileToCode(`<div v-click.mount="step" :class="cls" @vue:mounted="onShow()">A</div>`)
149 expect(code).toContain('at: _ctx.step')
150 expect(code).toContain('class: _normalizeClass(_ctx.cls)')
151 expect(code).toContain('onVnodeMounted')
152 expect(code).not.toContain('_ctx._ctx')
153 })
154
155 it('handles nested elements and slots', () => {
156 const code = compileToCode(`<Foo><template #a><span v-click.mount="2">A</span></template></Foo><section><p v-click.mount>B</p></section>`)
157 expect(code.match(/_component_v_click,/g)).toHaveLength(2)
158 })
159 })
160
161 // A tiny in-memory renderer, so components really mount and unmount without a DOM
162 interface TestNode extends RendererNode {
163 tag: string
164 text: string
165 parent: TestNode | null
166 children: TestNode[]
167 props: Record<string, any>
168 dataset: Record<string, string>
169 ownerDocument: { body: { offsetHeight: number } }
170 addEventListener: (name: string, fn: (e: { target: TestNode }) => void) => void
171 removeEventListener: (name: string, fn: (e: { target: TestNode }) => void) => void
172 classList: {
173 add: (c: string) => void
174 remove: (c: string) => void
175 toggle: (c: string, force?: boolean) => void
176 contains: (c: string) => boolean
177 forEach: (fn: (c: string) => void) => void
178 }
179 }
180
181 function createNode(tag: string, text = ''): TestNode {
182 const classes = new Set<string>()
183 return {
184 tag,
185 text,
186 parent: null,
187 children: [],
188 props: {},
189 dataset: {},
190 ownerDocument: {
191 body: { offsetHeight: 0 },
192 },
193 addEventListener: () => {},
194 removeEventListener: () => {},
195 classList: {
196 add: c => classes.add(c),
197 remove: c => classes.delete(c),
198 toggle: (c, force = !classes.has(c)) => force
199 ? classes.add(c)
200 : classes.delete(c),
201 contains: c => classes.has(c),
202 forEach: fn => [...classes].forEach(fn),
203 },
204 }
205 }
206
207 function remove(child: TestNode) {
208 const parent = child.parent
209 if (parent) {
210 parent.children.splice(parent.children.indexOf(child), 1)
211 child.parent = null
212 }
213 }
214
215 const { createApp } = createRenderer<TestNode, TestNode & RendererElement>({
216 createElement: tag => createNode(tag),
217 createText: text => createNode('#text', text),
218 createComment: text => createNode('#comment', text),
219 setText: (node, text) => {
220 node.text = text
221 },
222 setElementText: (node, text) => {
223 node.children.forEach(c => c.parent = null)
224 node.children = text
225 ? [
226 Object.assign(createNode('#text', text), { parent: node }),
227 ]
228 : []
229 },
230 insert: (child, parent, anchor) => {
231 remove(child)
232 const idx = anchor
233 ? parent.children.indexOf(anchor)
234 : -1
235 if (idx === -1)
236 parent.children.push(child)
237 else
238 parent.children.splice(idx, 0, child)
239 child.parent = parent
240 },
241 remove,
242 parentNode: node => node.parent,
243 nextSibling: (node) => {
244 const siblings = node.parent?.children ?? []
245 return siblings[siblings.indexOf(node) + 1] ?? null
246 },
247 patchProp: (el, key, _prev, next) => {
248 el.props[key] = next
249 },
250 })
251
252 function findByText(node: TestNode, text: string): TestNode | undefined {
253 if (node.children.length === 1 && node.children[0].tag === '#text' && node.children[0].text === text)
254 return node
255 for (const child of node.children) {
256 const found = findByText(child, text)
257 if (found)
258 return found
259 }
260 }
261
262 const cleanups: (() => void)[] = []
263
264 afterEach(() => {
265 cleanups.splice(0).forEach(fn => fn())
266 })
267
268 async function mountSlide(template: string, frontmatter: Record<string, any> = {}) {
269 const current = ref(0)
270 const clicks = createClicksContextBase(current)
271 const log: string[] = []
272 const mounted = new Set<string>()
273 const warnings: string[] = []
274 // e.g. "[slidev] ClicksContext: Unexpected register after mounted"
275 const consoleWarn = vi.spyOn(console, 'warn').mockImplementation(msg => warnings.push(String(msg)))
276
277 const Probe = defineComponent({
278 props: {
279 name: { type: String, required: true },
280 },
281 setup(props) {
282 onMounted(() => {
283 log.push(`mount ${props.name}`)
284 mounted.add(props.name)
285 })
286 onUnmounted(() => {
287 log.push(`unmount ${props.name}`)
288 mounted.delete(props.name)
289 })
290 return () => h('span', props.name)
291 },
292 })
293
294 const Slide = defineComponent({
295 render: compile(template, {
296 prefixIdentifiers: true,
297 nodeTransforms: [transformVClickMount],
298 }),
299 })
300
301 const Root = defineComponent({
302 setup() {
303 clicks.setup()
304 return () => h(Slide)
305 },
306 })
307
308 const app = createApp(Root)
309 app.provide(injectionClicksContext, shallowRef<ClicksContext>(clicks))
310 app.provide(injectionFrontmatter, frontmatter)
311 app.component('VClick', VClick)
312 app.component('VAfter', VAfter)
313 app.component('Probe', Probe)
314 app.config.globalProperties.$log = log
315 app.use(createVClickDirectives())
316 app.config.warnHandler = (msg) => {
317 warnings.push(msg)
318 }
319 const root = createNode('root')
320 app.mount(root)
321 cleanups.push(() => {
322 app.unmount()
323 consoleWarn.mockRestore()
324 })
325 await nextTick()
326 await vi.runAllTimersAsync()
327
328 // Changes the click without waiting for the transitions
329 async function step(n: number) {
330 clicks.current = n
331 await nextTick()
332 }
333
334 // Changes the click and lets all the transitions finish
335 async function go(n: number) {
336 await step(n)
337 await vi.runAllTimersAsync()
338 expect(warnings).toEqual([])
339 return [...mounted].sort()
340 }
341
342 return {
343 clicks,
344 log,
345 mounted,
346 go,
347 step,
348 root,
349 find: (text: string) => findByText(root, text),
350 unmount: () => cleanups.pop()?.(),
351 }
352 }
353
354 function classesOf(node: TestNode | undefined) {
355 if (!node)
356 return []
357 const classes = String(node.props.class ?? '').split(' ').filter(Boolean)
358 node.classList.forEach(c => classes.push(c))
359 return classes.sort()
360 }
361
362 describe('v-click.mount at runtime', () => {
363 it('mounts on the click, with the same positions as v-click', async () => {
364 const { clicks, log, go } = await mountSlide(`
365 <div v-click>first</div>
366 <Probe name="B" v-click.mount />
367 <Probe name="C" v-after.mount />
368 <Probe name="D" v-click.mount="[3, 5]" />
369 <Probe name="E" v-click.mount.hide="3" />
370 <Probe name="F" v-click.mount="'+1'" />
371 `)
372
373 // same click count as with the plain directives: first=1, B=2, C=2, D=3..4, E=3, F=3
374 expect(clicks.total).toBe(5)
375 expect(log).toEqual(['mount E'])
376
377 expect(await go(1)).toEqual(['E'])
378 expect(await go(2)).toEqual(['B', 'C', 'E'])
379 expect(await go(3)).toEqual(['B', 'C', 'D', 'F'])
380 expect(await go(4)).toEqual(['B', 'C', 'D', 'F'])
381 expect(await go(5)).toEqual(['B', 'C', 'F'])
382
383 // going back unmounts again
384 expect(await go(1)).toEqual(['E'])
385 expect(log.filter(l => l.endsWith(' D'))).toEqual(['mount D', 'unmount D'])
386 expect(log.filter(l => l.endsWith(' E'))).toEqual(['mount E', 'unmount E', 'mount E'])
387 })
388
389 it('fires @vue:mounted only when the click is reached', async () => {
390 const { go, log } = await mountSlide(`
391 <div v-click>first</div>
392 <div v-click.mount @vue:mounted="$log.push('vnode mounted')" @vue:unmounted="$log.push('vnode unmounted')">A</div>
393 `)
394 expect(log).toEqual([])
395 await go(1)
396 expect(log).toEqual([])
397 await go(2)
398 expect(log).toEqual(['vnode mounted'])
399 await go(1)
400 expect(log).toEqual(['vnode mounted', 'vnode unmounted'])
401 })
402
403 it('supports the component props', async () => {
404 const { clicks, go } = await mountSlide(`
405 <v-click mount><Probe name="A" /></v-click>
406 <v-after mount><Probe name="B" /></v-after>
407 <v-click mount hide :at="[2, 4]"><Probe name="C" /></v-click>
408 <v-click><span>plain</span></v-click>
409 `)
410 // A=1, B=1, C hidden at 2..3, plain=2
411 expect(clicks.total).toBe(4)
412 expect(await go(0)).toEqual(['C'])
413 expect(await go(1)).toEqual(['A', 'B', 'C'])
414 expect(await go(2)).toEqual(['A', 'B'])
415 expect(await go(3)).toEqual(['A', 'B'])
416 expect(await go(4)).toEqual(['A', 'B', 'C'])
417 })
418
419 it('passes the hide prop of <v-after> to the directive', async () => {
420 const { go, find } = await mountSlide(`
421 <div v-click>A</div>
422 <v-after hide><span>B</span></v-after>
423 `)
424 expect(find('B')!.classList.contains('slidev-vclick-hidden')).toBe(false)
425 await go(1)
426 expect(find('B')!.classList.contains('slidev-vclick-hidden')).toBe(true)
427 })
428
429 it('mounts everything when all clicks are shown, like print mode', async () => {
430 const { go } = await mountSlide(`
431 <Probe name="A" v-click.mount />
432 <Probe name="B" v-click.mount="4" />
433 <Probe name="C" v-click.mount.hide />
434 `)
435 expect(await go(999999)).toEqual(['A', 'B'])
436 })
437
438 it('mounts with opacity 0 and animates in and out like v-click', async () => {
439 transitionDuration = '0.1s'
440 const { step, go, find, log } = await mountSlide(`
441 <div v-click>first</div>
442 <Probe name="A" v-click.mount.up />
443 `)
444 expect(find('A')).toBeUndefined()
445 await go(1)
446 expect(find('A')).toBeUndefined()
447
448 // mounted on the click, still hidden (`opacity: 0` + the preset) on the first frame
449 await step(2)
450 expect(log).toEqual(['mount A'])
451 expect(classesOf(find('A'))).toEqual([
452 'slidev-vclick-anim-up',
453 'slidev-vclick-current',
454 'slidev-vclick-hidden',
455 'slidev-vclick-target',
456 ])
457
458 // then the hidden class is removed, so the CSS transition plays
459 await vi.advanceTimersByTimeAsync(40)
460 expect(classesOf(find('A'))).toEqual(['slidev-vclick-anim-up', 'slidev-vclick-current', 'slidev-vclick-target'])
461 await vi.runAllTimersAsync()
462
463 // going back unmounts it on the click, but the element is only removed
464 // after it's hidden again and the transition has ended
465 await step(1)
466 expect(log).toEqual(['mount A', 'unmount A'])
467 await vi.advanceTimersByTimeAsync(40)
468 expect(classesOf(find('A'))).toContain('slidev-vclick-hidden')
469 await vi.advanceTimersByTimeAsync(110)
470 expect(find('A')).toBeUndefined()
471 })
472
473 it('animates .hide out before unmounting', async () => {
474 transitionDuration = '0.1s'
475 const { step, find, log } = await mountSlide(`<Probe name="A" v-click.mount.hide />`)
476 // already shown when the slide is rendered, so it's not animated in
477 expect(classesOf(find('A'))).toEqual(['slidev-vclick-target'])
478
479 await step(1)
480 expect(log).toEqual(['mount A', 'unmount A'])
481 await vi.advanceTimersByTimeAsync(40)
482 expect(classesOf(find('A'))).toContain('slidev-vclick-hidden')
483 await vi.advanceTimersByTimeAsync(110)
484 expect(find('A')).toBeUndefined()
485 })
486
487 it('uses the animation prop, then the clickAnimation frontmatter', async () => {
488 const { go, find } = await mountSlide(`
489 <v-click mount><p>A</p></v-click>
490 <v-click mount animation="fade-in scale"><p>B</p></v-click>
491 <v-click mount fade><p>C</p></v-click>
492 <div v-click.mount.none>D</div>
493 `, { clickAnimation: 'up' })
494 await go(4)
495 expect(classesOf(find('A'))).toContain('slidev-vclick-anim-up')
496 expect(classesOf(find('B'))).toEqual(expect.arrayContaining(['slidev-vclick-anim-fade-in', 'slidev-vclick-anim-scale']))
497 expect(classesOf(find('B'))).not.toContain('slidev-vclick-anim-up')
498 expect(classesOf(find('C'))).toContain('slidev-vclick-anim-fade')
499 expect(classesOf(find('D'))).toContain('slidev-vclick-anim-none')
500 expect(classesOf(find('D'))).toContain('slidev-vclick-current')
501 expect(classesOf(find('A'))).toContain('slidev-vclick-prior')
502 expect(classesOf(find('A'))).not.toContain('slidev-vclick-current')
503 })
504
505 it('mounts every child of <template v-click.mount> and wraps text', async () => {
506 const { clicks, go, find } = await mountSlide(`
507 <template v-click.mount><Probe name="A" /><Probe name="B" /></template>
508 <v-click mount>text</v-click>
509 `)
510 expect(clicks.total).toBe(2)
511 expect(await go(1)).toEqual(['A', 'B'])
512 expect(classesOf(find('A'))).toContain('slidev-vclick-target')
513 expect(find('text')).toBeUndefined()
514 await go(2)
515 expect(find('text')!.tag).toBe('span')
516 expect(classesOf(find('text'))).toContain('slidev-vclick-target')
517 })
518
519 it('unregisters the click when the slide unmounts', async () => {
520 const { clicks, unmount } = await mountSlide(`<Probe name="A" v-click.mount="2" />`)
521 expect(clicks.maxMap.size).toBe(1)
522 unmount()
523 expect(clicks.maxMap.size).toBe(0)
524 })
525 })
526
526 lines TYPESCRIPT