返回 slidev
useEmbeddedCtrl.ts
根目录 / packages / client / composables / useEmbeddedCtrl.ts
1 import { throttledWatch } from '@vueuse/core'
2 import { useNav } from '../composables/useNav'
3 import { isDark } from '../logic/dark'
4
5 export function useEmbeddedControl() {
6 const nav = useNav()
7 const clientId = `${Date.now()}`
8
9 window.addEventListener('message', ({ data }) => {
10 if (data && data.target === 'slidev') {
11 if (data.type === 'navigate') {
12 if (data.no || data.clicks) {
13 nav.go(+data.no, +data.clicks || 0)
14 }
15 else if (typeof data.operation === 'string') {
16 const fn = nav[data.operation as keyof typeof nav]
17 if (typeof fn === 'function')
18 (fn as any)(...(data.args ?? []))
19 }
20 }
21 else if (data.type === 'css-vars') {
22 const root = document.documentElement
23 for (const [key, value] of Object.entries(data.vars || {}))
24 root.style.setProperty(key, value as any)
25 }
26 else if (data.type === 'color-schema') {
27 isDark.value = data.color === 'dark'
28 }
29 }
30 })
31
32 if (nav.isEmbedded.value) {
33 throttledWatch(
34 [
35 nav.currentSlideNo,
36 nav.clicks,
37 nav.hasNext,
38 nav.hasPrev,
39 nav.hasPrimarySlide,
40 ],
41 ([no, clicks, hasNext, hasPrev, hasPrimarySlide]) => {
42 if (!hasPrimarySlide)
43 return
44 window.parent.postMessage(
45 {
46 target: 'slidev',
47 clientId,
48 navState: {
49 no,
50 clicks,
51 hasNext,
52 hasPrev,
53 },
54 },
55 '*',
56 )
57 },
58 {
59 throttle: 50,
60 immediate: true,
61 },
62 )
63 }
64 }
65
65 lines TYPESCRIPT