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