返回 slidev
snapshot.ts
根目录 / packages / client / logic / snapshot.ts
1 import type { SlidevContextNavFull } from '../composables/useNav'
2 import type { ScreenshotSession } from './screenshot'
3 import { sleep } from '@antfu/utils'
4 import { slideHeight, slideWidth } from '../env'
5 import { captureDelay, disableTransition } from '../state'
6 import { snapshotState } from '../state/snapshot'
7 import { isDark } from './dark'
8 import { startScreenshotSession } from './screenshot'
9 import { getSlide } from './slides'
10
11 const chromeVersion = window.navigator.userAgent.match(/Chrome\/(\d+)/)?.[1]
12 export const isScreenshotSupported = chromeVersion
13 ? Number(chromeVersion) >= 94
14 : false
15
16 const initialWait = 100
17
18 export class SlideSnapshotManager {
19 private _screenshotSession: ScreenshotSession | null = null
20
21 getSnapshot(slideNo: number, isDark: boolean) {
22 const id = slideNo + (isDark ? '-dark' : '-light')
23 const data = snapshotState.state[id]
24 if (!data) {
25 return
26 }
27 const slide = getSlide(slideNo)
28 if (!slide) {
29 return
30 }
31 if (data?.revision === slide?.meta.slide.revision) {
32 return data.image
33 }
34 }
35
36 private async saveSnapshot(slideNo: number, dataUrl: string, isDark: boolean) {
37 if (!__DEV__)
38 return false
39 const slide = getSlide(slideNo)
40 if (!slide)
41 return false
42
43 const id = slideNo + (isDark ? '-dark' : '-light')
44 const revision = slide.meta.slide.revision
45 snapshotState.patch(id, {
46 revision,
47 image: dataUrl,
48 })
49 }
50
51 async startCapturing(nav: SlidevContextNavFull) {
52 if (!__DEV__)
53 return false
54
55 // TODO: show a dialog to confirm
56
57 if (this._screenshotSession) {
58 this._screenshotSession.dispose()
59 this._screenshotSession = null
60 }
61
62 try {
63 this._screenshotSession = await startScreenshotSession(
64 slideWidth.value,
65 slideHeight.value,
66 )
67
68 disableTransition.value = true
69 nav.go(1, 0, true)
70
71 await sleep(initialWait + captureDelay.value)
72 while (true) {
73 if (!this._screenshotSession) {
74 break
75 }
76 this.saveSnapshot(
77 nav.currentSlideNo.value,
78 this._screenshotSession.screenshot(document.getElementById('slide-content')!),
79 isDark.value,
80 )
81 if (nav.hasNext.value) {
82 await sleep(captureDelay.value)
83 nav.nextSlide(true)
84 await sleep(captureDelay.value)
85 }
86 else {
87 break
88 }
89 }
90
91 // TODO: show a message when done
92
93 return true
94 }
95 catch (e) {
96 console.error(e)
97 return false
98 }
99 finally {
100 disableTransition.value = false
101 if (this._screenshotSession) {
102 this._screenshotSession.dispose()
103 this._screenshotSession = null
104 }
105 }
106 }
107 }
108
109 export const snapshotManager = new SlideSnapshotManager()
110
110 lines TYPESCRIPT