返回 slidev
overview.vue
根目录 / packages / client / pages / overview.vue
1 <script setup lang="ts">
2 import type { ClicksContext, SlideRoute } from '@slidev/types'
3 import { useHead } from '@unhead/vue'
4 import { computed, nextTick, onMounted, onUnmounted, reactive, ref, shallowRef } from 'vue'
5 import { useRoute, useRouter } from 'vue-router'
6 import { createFixedClicks } from '../composables/useClicks'
7 import { useNav } from '../composables/useNav'
8 import { CLICKS_MAX } from '../constants'
9 import { pathPrefix, slideAspect, slidesTitle } from '../env'
10 import ClicksSlider from '../internals/ClicksSlider.vue'
11 import DrawingPreview from '../internals/DrawingPreview.vue'
12 import IconButton from '../internals/IconButton.vue'
13 import NoteEditable from '../internals/NoteEditable.vue'
14 import SlideContainer from '../internals/SlideContainer.vue'
15 import SlideWrapper from '../internals/SlideWrapper.vue'
16 import { isColorSchemaConfigured, isDark, toggleDark } from '../logic/dark'
17 import { getSlidePath } from '../logic/slides'
18 import { windowSize } from '../state'
19
20 const cardWidth = 450
21
22 useHead({ title: `Overview - ${slidesTitle}` })
23
24 const currentRoute = useRoute()
25 const router = useRouter()
26 const { openInEditor, slides, isEmbedded } = useNav()
27 const isPreviewMode = computed(() => currentRoute.query.mode === 'preview')
28 const isEmbeddedPreviewMode = computed(() => isPreviewMode.value && isEmbedded.value)
29 const overviewCardWidth = computed(() => {
30 if (!isPreviewMode.value)
31 return cardWidth
32 if (isEmbeddedPreviewMode.value)
33 return Math.max(0, windowSize.width.value - 16)
34 return Math.min(900, Math.max(320, windowSize.width.value - 160))
35 })
36 const overviewSlideHeight = computed(() => overviewCardWidth.value / slideAspect.value)
37
38 const blocks: Map<number, HTMLElement> = reactive(new Map())
39 const slidePreviews: Map<number, HTMLElement> = reactive(new Map())
40 const activeBlocks = ref<number[]>([])
41 const scroller = ref<HTMLElement>()
42 const edittingNote = ref<number | null>(null)
43 let ignoreOverviewScrollUntil = 0
44 let pendingOverviewScrollNo: number | undefined
45 let overviewScrollTimer: ReturnType<typeof setTimeout> | undefined
46 const wordCounts = computed(() => slides.value.map(route => wordCount(route.meta?.slide?.note || '')))
47 const totalWords = computed(() => wordCounts.value.reduce((a, b) => a + b, 0))
48 const totalClicks = computed(() => slides.value.map(route => getSlideClicks(route)).reduce((a, b) => a + b, 0))
49 const slideNoDigits = computed(() => String(Math.max(1, slides.value.length)).length)
50
51 const activeSlide = shallowRef<SlideRoute>()
52 const clicksContextMap = new WeakMap<SlideRoute, ClicksContext>()
53 function getClicksContext(route: SlideRoute) {
54 // We create a local clicks context to calculate the total clicks of the slide
55 if (!clicksContextMap.has(route))
56 clicksContextMap.set(route, createFixedClicks(route, CLICKS_MAX))
57 return clicksContextMap.get(route)!
58 }
59
60 function getSlideClicks(route: SlideRoute) {
61 return route.meta?.clicks || getClicksContext(route)?.total
62 }
63
64 function toggleRoute(route: SlideRoute) {
65 if (activeSlide.value === route)
66 activeSlide.value = undefined
67 else
68 activeSlide.value = route
69 }
70
71 function wordCount(str: string) {
72 const pattern = /[\w`'\-\u0392-\u03C9\u00C0-\u00FF\u0600-\u06FF\u0400-\u04FF]+|[\u4E00-\u9FFF\u3400-\u4DBF\uF900-\uFAFF\u3040-\u309F\uAC00-\uD7AF]+/g
73 const m = str.match(pattern)
74 let count = 0
75 if (!m)
76 return 0
77 for (let i = 0; i < m.length; i++) {
78 if (m[i].charCodeAt(0) >= 0x4E00) {
79 count += m[i].length
80 }
81 else {
82 count += 1
83 }
84 }
85 return count
86 }
87
88 function checkActiveBlocks() {
89 const viewportHeight = window.innerHeight || document.documentElement.clientHeight
90 let active: { idx: number, visibleHeight: number } | undefined
91 const fullyVisible: number[] = []
92
93 for (const [idx, el] of blocks.entries()) {
94 const rect = el.getBoundingClientRect()
95 const visibleHeight = Math.max(0, Math.min(rect.bottom, viewportHeight) - Math.max(rect.top, 0))
96 if (visibleHeight === 0)
97 continue
98 if (visibleHeight >= rect.height)
99 fullyVisible.push(idx)
100 if (!active || visibleHeight > active.visibleHeight)
101 active = { idx, visibleHeight }
102 }
103
104 activeBlocks.value = fullyVisible.length
105 ? fullyVisible
106 : active
107 ? [active.idx]
108 : []
109 }
110
111 function openSlideInNewTab(path: string) {
112 const a = document.createElement('a')
113 a.target = '_blank'
114 a.href = pathPrefix + path.slice(1)
115 a.click()
116 }
117
118 function openSlideInBrowser(path: string) {
119 const url = new URL(pathPrefix + path.slice(1), location.href).href
120 if (isEmbedded.value) {
121 window.parent.postMessage({
122 target: 'slidev',
123 sender: 'slidev',
124 type: 'open-external',
125 url,
126 }, '*')
127 return
128 }
129 openSlideInNewTab(path)
130 }
131
132 function scrollToSlide(idx: number) {
133 const el = blocks.get(idx)
134 if (el)
135 el.scrollIntoView({ behavior: 'smooth', block: 'start' })
136 }
137
138 function getSlidePreviewTop(idx: number) {
139 const el = slidePreviews.get(idx) || blocks.get(idx)
140 if (!el || !scroller.value)
141 return null
142 const scrollerRect = scroller.value.getBoundingClientRect()
143 const elRect = el.getBoundingClientRect()
144 return elRect.top - scrollerRect.top + scroller.value.scrollTop
145 }
146
147 function scrollSlideNoIntoCenter(no: number) {
148 if (!scroller.value || slides.value.length === 0)
149 return
150 const clamped = Math.min(Math.max(no, 1), slides.value.length)
151 const idx = Math.floor(clamped) - 1
152 const progress = clamped - (idx + 1)
153 const start = getSlidePreviewTop(idx)
154 const end = getSlidePreviewTop(idx + 1)
155 if (start == null)
156 return
157 const top = start
158 + (end == null
159 ? 0
160 : (end - start) * progress)
161 - scroller.value.clientHeight * 0.5
162 if (Math.abs(scroller.value.scrollTop - top) < 1)
163 return
164 scroller.value.scrollTo({ top })
165 }
166
167 function getInitialSlideNo() {
168 const value = currentRoute.query.slideNo
169 const no = Number(Array.isArray(value)
170 ? value[0]
171 : value)
172 return Number.isFinite(no) && no > 0
173 ? no
174 : undefined
175 }
176
177 function updateSlideNoQuery(no: number) {
178 if (!isEmbeddedPreviewMode.value)
179 return
180 const slideNo = Number(no.toFixed(3)).toString()
181 if (currentRoute.query.slideNo === slideNo)
182 return
183 router.replace({
184 query: {
185 ...currentRoute.query,
186 slideNo,
187 },
188 })
189 }
190
191 function getCenteredSlideNo() {
192 if (!scroller.value || slides.value.length === 0)
193 return null
194 const center = scroller.value.scrollTop + scroller.value.clientHeight * 0.5
195 const tops = slides.value
196 .map((_, idx) => getSlidePreviewTop(idx))
197 .filter((top): top is number => top != null)
198 if (tops.length === 0)
199 return null
200 if (tops.length === 1 || center <= tops[0])
201 return 1
202 for (let i = 1; i < tops.length; i++) {
203 if (center <= tops[i]) {
204 const span = Math.max(1, tops[i] - tops[i - 1])
205 return i + (center - tops[i - 1]) / span
206 }
207 }
208 return slides.value.length
209 }
210
211 function postOverviewScroll(no: number) {
212 pendingOverviewScrollNo = no
213 if (overviewScrollTimer)
214 return
215 overviewScrollTimer = setTimeout(() => {
216 overviewScrollTimer = undefined
217 const no = pendingOverviewScrollNo
218 pendingOverviewScrollNo = undefined
219 if (no == null)
220 return
221 updateSlideNoQuery(no)
222 if (Date.now() < ignoreOverviewScrollUntil)
223 return
224 window.parent.postMessage({
225 target: 'slidev',
226 sender: 'slidev',
227 type: 'overview-scroll',
228 no,
229 }, '*')
230 }, 50)
231 }
232
233 function onOverviewScroll() {
234 checkActiveBlocks()
235 if (!isEmbeddedPreviewMode.value || Date.now() < ignoreOverviewScrollUntil)
236 return
237 const no = getCenteredSlideNo()
238 if (no != null)
239 postOverviewScroll(no)
240 }
241
242 function onOverviewMessage({ data }: MessageEvent) {
243 if (
244 !isEmbeddedPreviewMode.value
245 || data?.target !== 'slidev'
246 || data.sender !== 'vscode'
247 || data.type !== 'overview-scroll'
248 ) {
249 return
250 }
251 const no = Number(data.no)
252 if (no > 0) {
253 ignoreOverviewScrollUntil = Date.now() + 300
254 pendingOverviewScrollNo = undefined
255 updateSlideNoQuery(no)
256 scrollSlideNoIntoCenter(no)
257 }
258 }
259
260 function onMarkerClick(e: MouseEvent, clicks: number, route: SlideRoute) {
261 const ctx = getClicksContext(route)
262 if (ctx.current === clicks)
263 ctx.current = CLICKS_MAX
264 else
265 ctx.current = clicks
266 e.preventDefault()
267 }
268
269 function openOverviewSlideSource(e: MouseEvent, route: SlideRoute) {
270 if (e.ctrlKey || e.metaKey) {
271 e.preventDefault()
272 openSlideInBrowser(getSlidePath(route, false))
273 return
274 }
275 const slide = route.meta?.slide
276 if (!slide)
277 return
278 window.parent.postMessage({
279 target: 'slidev',
280 type: 'command',
281 command: 'goto',
282 args: [slide.filepath, slide.sourceIndex],
283 }, '*')
284 }
285
286 onMounted(() => {
287 window.addEventListener('message', onOverviewMessage)
288 const initialSlideNo = isEmbeddedPreviewMode.value
289 ? getInitialSlideNo()
290 : undefined
291 if (initialSlideNo != null) {
292 ignoreOverviewScrollUntil = Date.now() + 300
293 scrollSlideNoIntoCenter(initialSlideNo)
294 }
295 nextTick(() => {
296 if (initialSlideNo != null)
297 scrollSlideNoIntoCenter(initialSlideNo)
298 checkActiveBlocks()
299 })
300 })
301
302 onUnmounted(() => {
303 window.removeEventListener('message', onOverviewMessage)
304 if (overviewScrollTimer)
305 clearTimeout(overviewScrollTimer)
306 })
307 </script>
308
309 <template>
310 <div class="h-screen w-screen of-hidden flex">
311 <nav
312 v-if="!isEmbedded"
313 class="grid grid-rows-[auto_max-content] border-r border-main select-none max-h-full h-full"
314 >
315 <div class="relative">
316 <div class="absolute left-0 top-0 bottom-0 w-200 flex flex-col flex-auto items-end group p-6px md:p-10px gap-1 max-h-full of-x-visible of-y-auto" style="direction:rtl">
317 <div
318 v-for="(route, idx) of slides"
319 :key="route.no"
320 class="relative"
321 style="direction:ltr"
322 >
323 <button
324 class="relative transition duration-300 w-8 h-8 rounded hover:bg-active hover:op100"
325 :class="activeBlocks.includes(idx) ? 'op100 text-primary bg-gray:5' : 'op20'"
326 @click="scrollToSlide(idx)"
327 >
328 <div>{{ idx + 1 }}</div>
329 </button>
330 <div
331 v-if="route.meta?.slide?.title"
332 class="pointer-events-none select-none absolute left-110% top-50% translate-y--50% ws-nowrap z-label px2 slidev-glass-effect transition duration-400 op0 group-hover:op100"
333 :class="activeBlocks.includes(idx) ? 'text-primary' : 'text-main important-text-op-50'"
334 >
335 {{ route.meta?.slide?.title }}
336 </div>
337 </div>
338 </div>
339 </div>
340 <div p2 border="t main">
341 <IconButton
342 v-if="!isColorSchemaConfigured"
343 :title="isDark ? 'Switch to light mode theme' : 'Switch to dark mode theme'"
344 @click="toggleDark()"
345 >
346 <carbon-moon v-if="isDark" />
347 <carbon-sun v-else />
348 </IconButton>
349 <IconButton
350 v-else
351 :title="isDark ? 'Dark mode' : 'Light mode'"
352 pointer-events-none op50
353 >
354 <carbon-moon v-if="isDark" />
355 <carbon-sun v-else />
356 </IconButton>
357 </div>
358 </nav>
359 <main
360 ref="scroller"
361 class="flex-1 h-full of-auto"
362 :style="`grid-template-columns: repeat(auto-fit,minmax(${cardWidth}px,1fr))`"
363 @scroll="onOverviewScroll"
364 >
365 <div
366 v-for="(route, idx) of slides"
367 :key="route.no"
368 :ref="el => blocks.set(idx, el as any)"
369 class="overview-slide-block relative of-hidden flex gap-4 min-h-50"
370 :class="[idx === 0 && !isEmbeddedPreviewMode ? 'pt2' : '', isEmbeddedPreviewMode ? 'justify-center' : 'border-t border-main']"
371 >
372 <div
373 v-if="!isEmbeddedPreviewMode"
374 class="select-none text-right my5 flex flex-col justify-between items-end"
375 :class="isPreviewMode ? 'w-9' : 'w-13'"
376 :style="{ height: `${overviewSlideHeight}px` }"
377 >
378 <div class="self-center text-3xl op20 mb2 text-center mr--14px tabular-nums" :style="{ width: `${slideNoDigits}ch` }">
379 {{ idx + 1 }}
380 </div>
381 <div class="flex flex-col gap-1 mx-1 items-end">
382 <IconButton
383 class="overview-slide-action mr--4 op0"
384 :class="isPreviewMode ? 'text-lg' : ''"
385 title="Play in new tab"
386 @click="openSlideInNewTab(getSlidePath(route, false))"
387 >
388 <div class="i-carbon:presentation-file" />
389 </IconButton>
390 <IconButton
391 v-if="__DEV__ && route.meta?.slide"
392 class="overview-slide-action mr--4 op0"
393 :class="isPreviewMode ? 'text-lg' : ''"
394 title="Open in editor"
395 @click="openInEditor(`${route.meta.slide.filepath}:${route.meta.slide.start}`)"
396 >
397 <div class="i-carbon:edit" />
398 </IconButton>
399 </div>
400 </div>
401 <div
402 class="flex flex-col"
403 :class="isEmbeddedPreviewMode ? 'my1 gap-0' : 'my5 gap-2'"
404 :style="{ width: `${overviewCardWidth}px` }"
405 >
406 <div
407 v-if="isEmbeddedPreviewMode"
408 class="flex items-end gap-2"
409 >
410 <button
411 type="button"
412 class="select-none pl-1 text-lg leading-tight op60 tabular-nums hover:op90 hover:underline underline-offset-2"
413 @click="openOverviewSlideSource($event, route)"
414 >
415 {{ idx + 1 }}
416 </button>
417 <ClicksSlider
418 v-if="getSlideClicks(route)"
419 :active="activeSlide === route"
420 :clicks-context="getClicksContext(route)"
421 resettable
422 compact
423 attached
424 class="ml-auto w-88 min-w-[70%] max-w-[calc(100%-3rem)]"
425 @dblclick="toggleRoute(route)"
426 @activate="activeSlide = route"
427 @reset="activeSlide = undefined"
428 />
429 </div>
430 <div
431 :ref="el => slidePreviews.set(idx, el as any)"
432 class="border rounded border-main overflow-hidden bg-main h-max"
433 :class="[isEmbeddedPreviewMode && getSlideClicks(route) ? 'rounded-tr-0' : '', isEmbeddedPreviewMode ? '' : 'select-none']"
434 @dblclick="!isEmbeddedPreviewMode && openSlideInNewTab(getSlidePath(route, false))"
435 >
436 <SlideContainer
437 :key="route.no"
438 :width="overviewCardWidth"
439 :class="isEmbeddedPreviewMode ? '' : 'pointer-events-none important:[&_*]:select-none'"
440 >
441 <SlideWrapper
442 :clicks-context="getClicksContext(route)"
443 :route="route"
444 render-context="overview"
445 />
446 <DrawingPreview :page="route.no" />
447 </SlideContainer>
448 </div>
449 <ClicksSlider
450 v-if="getSlideClicks(route) && !isEmbeddedPreviewMode"
451 :active="activeSlide === route"
452 :clicks-context="getClicksContext(route)"
453 resettable
454 class="ml-1 w-[calc(100%-0.25rem)]"
455 :class="isPreviewMode ? '' : 'mt-2'"
456 @dblclick="toggleRoute(route)"
457 @activate="activeSlide = route"
458 @reset="activeSlide = undefined"
459 />
460 </div>
461 <NoteEditable
462 v-if="!isPreviewMode"
463 :no="route.no"
464 class="relative z-1 max-w-250 w-250 text-lg rounded p3"
465 :auto-height="true"
466 :highlight="activeSlide === route"
467 :editing="edittingNote === route.no"
468 :clicks-context="getClicksContext(route)"
469 @dblclick="edittingNote !== route.no ? edittingNote = route.no : null"
470 @update:editing="edittingNote = null"
471 @marker-click="(e, clicks) => onMarkerClick(e, clicks, route)"
472 />
473 <div
474 v-if="!isPreviewMode && wordCounts[idx] > 0"
475 class="select-none absolute bottom-0 right-0 bg-main rounded-tl p2 op35 text-xs"
476 >
477 {{ wordCounts[idx] }} words
478 </div>
479 </div>
480 </main>
481 <div
482 v-if="!isEmbedded"
483 class="absolute z-2 top-0 right-0 px3 py1.5 border-b border-l rounded-lb bg-main/80 backdrop-blur border-main select-none"
484 >
485 <div class="text-xs op50">
486 {{ slides.length }} slides ·
487 {{ totalClicks + slides.length - 1 }} clicks ·
488 {{ totalWords }} words
489 </div>
490 </div>
491 </div>
492 </template>
493
494 <style scoped>
495 .overview-slide-block:hover .overview-slide-action {
496 opacity: 0.6;
497 }
498
499 .overview-slide-action:hover {
500 opacity: 0.8;
501 }
502 </style>
503
503 lines Plain Text