返回 slidev
useNav.ts
根目录 / packages / client / composables / useNav.ts
1 import type { ClicksContext, SlideRoute, TocItem } from '@slidev/types'
2 import type { ComputedRef, Ref, TransitionGroupProps, WritableComputedRef } from 'vue'
3 import type { RouteLocationNormalized, Router } from 'vue-router'
4 import { clamp } from '@antfu/utils'
5 import { parseRangeString } from '@slidev/parser/utils'
6 import { createSharedComposable, injectLocal } from '@vueuse/core'
7 import { computed, hasInjectionContext, ref, toRaw, watch } from 'vue'
8 import { useRoute, useRouter } from 'vue-router'
9 import { slides } from '#slidev/slides'
10 import { CLICKS_MAX, injectionSlidevContext } from '../constants'
11 import { configs } from '../env'
12 import { useRouteQuery } from '../logic/route'
13 import { getSlide, getSlidePath } from '../logic/slides'
14 import { getCurrentTransition } from '../logic/transition'
15 import { hmrSkipTransition } from '../state'
16 import { createClicksContextBase } from './useClicks'
17 import { useTocTree } from './useTocTree'
18
19 export interface SlidevContextNav {
20 slides: Ref<SlideRoute[]>
21 total: ComputedRef<number>
22
23 currentPath: ComputedRef<string>
24 currentPage: ComputedRef<number>
25 currentSlideNo: ComputedRef<number>
26 currentSlideRoute: ComputedRef<SlideRoute>
27 currentTransition: ComputedRef<TransitionGroupProps | undefined>
28 currentLayout: ComputedRef<string>
29 currentFrontmatter: ComputedRef<Record<string, any>>
30
31 nextRoute: ComputedRef<SlideRoute>
32 prevRoute: ComputedRef<SlideRoute>
33 hasNext: ComputedRef<boolean>
34 hasPrev: ComputedRef<boolean>
35
36 clicksContext: ComputedRef<ClicksContext>
37 clicks: ComputedRef<number>
38 clicksStart: ComputedRef<number>
39 clicksTotal: ComputedRef<number>
40
41 /** The table of content tree */
42 tocTree: ComputedRef<TocItem[]>
43 /** The direction of the navigation, 1 for forward, -1 for backward */
44 navDirection: Ref<number>
45 /** The direction of the clicks, 1 for forward, -1 for backward */
46 clicksDirection: Ref<number>
47 /** Utility function for open file in editor, only avaible in dev mode */
48 openInEditor: (url?: string) => Promise<boolean>
49
50 /** Go to next click */
51 next: () => Promise<void>
52 /** Go to previous click */
53 prev: () => Promise<void>
54 /** Go to next slide */
55 nextSlide: (lastClicks?: boolean) => Promise<void>
56 /** Go to previous slide */
57 prevSlide: (lastClicks?: boolean) => Promise<void>
58 /** Go to slide */
59 go: (no: number | string, clicks?: number, force?: boolean) => Promise<void>
60 /** Go to the first slide */
61 goFirst: () => Promise<void>
62 /** Go to the last slide */
63 goLast: () => Promise<void>
64
65 /** Enter presenter mode */
66 enterPresenter: () => void
67 /** Exit presenter mode */
68 exitPresenter: () => void
69 }
70
71 export interface SlidevContextNavState {
72 router: Router
73 currentRoute: ComputedRef<RouteLocationNormalized>
74 isPrintMode: ComputedRef<boolean>
75 isPrintWithClicks: Ref<boolean>
76 isEmbedded: ComputedRef<boolean>
77 isPlaying: ComputedRef<boolean>
78 isPresenter: ComputedRef<boolean>
79 isNotesViewer: ComputedRef<boolean>
80 isPresenterAvailable: ComputedRef<boolean>
81 hasPrimarySlide: ComputedRef<boolean>
82 currentSlideNo: ComputedRef<number>
83 currentSlideRoute: ComputedRef<SlideRoute>
84 clicksContext: ComputedRef<ClicksContext>
85 queryClicksRaw: Ref<string>
86 queryClicks: WritableComputedRef<number>
87 printRange: Ref<number[]>
88 getPrimaryClicks: (route: SlideRoute) => ClicksContext
89 }
90
91 export interface SlidevContextNavFull extends SlidevContextNav, SlidevContextNavState { }
92
93 export function useNavBase(
94 currentSlideRoute: ComputedRef<SlideRoute>,
95 clicksContext: ComputedRef<ClicksContext>,
96 queryClicks: Ref<number> = ref(0),
97 isPresenter: Ref<boolean>,
98 isPrint: Ref<boolean>,
99 router?: Router,
100 ): SlidevContextNav {
101 const total = computed(() => slides.value.length)
102
103 const navDirection = ref(0)
104 const clicksDirection = ref(0)
105 let lastAdvance = Number.NEGATIVE_INFINITY
106
107 function acceptAdvance() {
108 const interval = configs.advanceDebounce
109 if (isPrint.value || !Number.isFinite(interval) || interval <= 0)
110 return true
111
112 const now = performance.now()
113 if (now - lastAdvance < interval)
114 return false
115
116 lastAdvance = now
117 return true
118 }
119
120 const currentPath = computed(() => getSlidePath(currentSlideRoute.value, isPresenter.value))
121 const currentSlideNo = computed(() => currentSlideRoute.value.no)
122 const currentLayout = computed(() => currentSlideRoute.value.meta?.layout || (currentSlideNo.value === 1
123 ? 'cover'
124 : 'default'))
125 const currentFrontmatter = computed(() => currentSlideRoute.value.meta.slide.frontmatter)
126
127 const clicks = computed(() => clicksContext.value.current)
128 const clicksStart = computed(() => clicksContext.value.clicksStart)
129 const clicksTotal = computed(() => clicksContext.value.total)
130 const nextRoute = computed(() => slides.value[Math.min(slides.value.length, currentSlideNo.value + 1) - 1])
131 const prevRoute = computed(() => slides.value[Math.max(1, currentSlideNo.value - 1) - 1])
132 const hasNext = computed(() => currentSlideNo.value < slides.value.length || clicks.value < clicksTotal.value)
133 const hasPrev = computed(() => currentSlideNo.value > 1 || clicks.value > 0)
134
135 const currentTransition = computed(() => isPrint.value
136 ? undefined
137 : getCurrentTransition(navDirection.value, currentSlideRoute.value, prevRoute.value))
138
139 watch(currentSlideRoute, (next, prev) => {
140 navDirection.value = next.no - prev.no
141 })
142
143 async function openInEditor(url?: string) {
144 if (!__DEV__)
145 return false
146 if (url == null) {
147 const slide = currentSlideRoute.value?.meta?.slide
148 if (!slide)
149 return false
150 url = `${slide.filepath}:${slide.start}`
151 }
152 await fetch(`/__open-in-editor?file=${encodeURIComponent(url)}`)
153 return true
154 }
155
156 const tocTree = useTocTree(
157 slides,
158 currentSlideNo,
159 currentSlideRoute,
160 )
161
162 async function next() {
163 if (!acceptAdvance())
164 return
165 clicksDirection.value = 1
166 if (clicksTotal.value <= queryClicks.value)
167 await advanceSlide()
168 else
169 queryClicks.value += 1
170 }
171
172 async function prev() {
173 lastAdvance = Number.NEGATIVE_INFINITY
174 clicksDirection.value = -1
175 if (queryClicks.value <= clicksStart.value)
176 await prevSlide(true)
177 else
178 queryClicks.value -= 1
179 }
180
181 async function nextSlide(lastClicks = false) {
182 if (!acceptAdvance())
183 return
184 await advanceSlide(lastClicks)
185 }
186
187 // Internal navigation must not consume or reset the suppression window.
188 async function advanceSlide(lastClicks = false) {
189 clicksDirection.value = 1
190 if (currentSlideNo.value < slides.value.length) {
191 await navigate(
192 currentSlideNo.value + 1,
193 lastClicks && !isPrint.value
194 ? CLICKS_MAX
195 : undefined,
196 )
197 }
198 }
199
200 async function prevSlide(lastClicks = false) {
201 lastAdvance = Number.NEGATIVE_INFINITY
202 clicksDirection.value = -1
203 if (currentSlideNo.value > 1) {
204 await go(
205 currentSlideNo.value - 1,
206 lastClicks && !isPrint.value
207 ? CLICKS_MAX
208 : undefined,
209 )
210 }
211 }
212
213 function goFirst() {
214 return go(1)
215 }
216
217 function goLast() {
218 return go(total.value)
219 }
220
221 async function go(no: number | string, clicks: number = 0, force = false) {
222 lastAdvance = Number.NEGATIVE_INFINITY
223 await navigate(no, clicks, force)
224 }
225
226 async function navigate(no: number | string, clicks: number = 0, force = false) {
227 hmrSkipTransition.value = false
228 const pageChanged = currentSlideNo.value !== no
229 const clicksChanged = clicks !== queryClicks.value
230 const meta = getSlide(no)?.meta
231 const clicksStart = meta?.slide?.frontmatter.clicksStart ?? 0
232 clicks = clamp(clicks, clicksStart, meta?.__clicksContext?.total ?? CLICKS_MAX)
233 if (force || pageChanged || clicksChanged) {
234 await router?.push({
235 path: getSlidePath(no, isPresenter.value, router.currentRoute.value.name === 'export'),
236 query: {
237 ...router.currentRoute.value.query,
238 clicks: clicks === 0
239 ? undefined
240 : clicks.toString(),
241 embedded: location.search.includes('embedded')
242 ? 'true'
243 : undefined,
244 },
245 })
246 }
247 }
248
249 function enterPresenter() {
250 router?.push({
251 path: getSlidePath(currentSlideNo.value, true),
252 query: { ...router.currentRoute.value.query },
253 })
254 }
255 function exitPresenter() {
256 router?.push({
257 path: getSlidePath(currentSlideNo.value, false),
258 query: { ...router.currentRoute.value.query },
259 })
260 }
261
262 return {
263 slides,
264 total,
265 currentPath,
266 currentSlideNo,
267 currentPage: currentSlideNo,
268 currentSlideRoute,
269 currentLayout,
270 currentFrontmatter,
271 currentTransition,
272 clicksDirection,
273 nextRoute,
274 prevRoute,
275 clicksContext,
276 clicks,
277 clicksStart,
278 clicksTotal,
279 hasNext,
280 hasPrev,
281 tocTree,
282 navDirection,
283 openInEditor,
284 next,
285 prev,
286 go,
287 goLast,
288 goFirst,
289 nextSlide,
290 prevSlide,
291 enterPresenter,
292 exitPresenter,
293 }
294 }
295
296 export function useFixedNav(
297 currentSlideRoute: SlideRoute,
298 clicksContext: ClicksContext,
299 ): SlidevContextNav {
300 const noop = async () => { }
301 return {
302 ...useNavBase(
303 computed(() => currentSlideRoute),
304 computed(() => clicksContext),
305 ref(CLICKS_MAX),
306 ref(false),
307 ref(false),
308 ),
309 next: noop,
310 prev: noop,
311 nextSlide: noop,
312 prevSlide: noop,
313 goFirst: noop,
314 goLast: noop,
315 go: noop,
316 }
317 }
318
319 const useNavState = createSharedComposable((): SlidevContextNavState => {
320 const router = useRouter()
321 const currentRoute = useRoute()
322
323 const query = computed(() => {
324 // eslint-disable-next-line ts/no-unused-expressions
325 router?.currentRoute?.value?.query
326 return new URLSearchParams(location.search)
327 })
328 const isPrintMode = computed(() => query.value.has('print') || currentRoute.name === 'export')
329 const isPrintWithClicks = ref(query.value.get('print') === 'clicks')
330 const isEmbedded = computed(() => query.value.has('embedded'))
331 const isPlaying = computed(() => currentRoute.name === 'play')
332 const isPresenter = computed(() => currentRoute.name === 'presenter')
333 const isNotesViewer = computed(() => currentRoute.name === 'notes')
334 const isPresenterAvailable = computed(() => !isPresenter.value && (!configs.remote || query.value.get('password') === configs.remote))
335 const hasPrimarySlide = computed(() => !!currentRoute.params.no)
336 const currentSlideNo = computed(() => hasPrimarySlide.value
337 ? getSlide(currentRoute.params.no as string)?.no ?? 1
338 : 1)
339 const currentSlideRoute = computed(() => slides.value[currentSlideNo.value - 1])
340 const printRange = ref(parseRangeString(slides.value.length, currentRoute?.query?.range as string | undefined))
341
342 const queryClicksRaw = useRouteQuery<string>('clicks', '0')
343
344 const clicksContext = computed(() => getPrimaryClicks(currentSlideRoute.value))
345
346 const queryClicks = computed({
347 get() {
348 let v = +(queryClicksRaw.value || 0)
349 if (Number.isNaN(v))
350 v = 0
351 return v
352 },
353 set(v) {
354 hmrSkipTransition.value = false
355 queryClicksRaw.value = v.toString()
356 },
357 })
358
359 function getPrimaryClicks(
360 route: SlideRoute,
361 ): ClicksContext {
362 if (route?.meta?.__clicksContext)
363 return route.meta.__clicksContext
364
365 const thisNo = route.no
366 const context = createClicksContextBase(
367 computed({
368 get() {
369 if (currentSlideNo.value === thisNo)
370 return Math.max(+(queryClicksRaw.value ?? 0), context.clicksStart)
371 else if (currentSlideNo.value > thisNo)
372 return CLICKS_MAX
373 else
374 return context.clicksStart
375 },
376 set(v) {
377 if (currentSlideNo.value === thisNo)
378 queryClicksRaw.value = v.toString()
379 },
380 }),
381 route?.meta.slide?.frontmatter.clicksStart ?? 0,
382 route?.meta.clicks,
383 )
384
385 if (route?.meta)
386 route.meta.__clicksContext = context
387
388 return context
389 }
390
391 return {
392 router,
393 currentRoute: computed(() => currentRoute),
394 isPrintMode,
395 isPrintWithClicks,
396 isEmbedded,
397 isPlaying,
398 isPresenter,
399 isNotesViewer,
400 isPresenterAvailable,
401 hasPrimarySlide,
402 currentSlideNo,
403 currentSlideRoute,
404 clicksContext,
405 queryClicksRaw,
406 queryClicks,
407 printRange,
408 getPrimaryClicks,
409 }
410 })
411
412 const useSharedNav = createSharedComposable((): SlidevContextNavFull => {
413 const state = useNavState()
414 const router = useRouter()
415
416 const nav = useNavBase(
417 state.currentSlideRoute,
418 state.clicksContext,
419 state.queryClicks,
420 state.isPresenter,
421 state.isPrintMode,
422 router,
423 )
424
425 watch(
426 [nav.total, state.currentRoute],
427 async () => {
428 const no = state.currentRoute.value.params.no as string
429 if (state.hasPrimarySlide.value && !getSlide(no)) {
430 if (no && no !== 'index.html') {
431 // The current slide may has been removed. Redirect to the last slide.
432 await nav.go(nav.total.value, 0, true)
433 }
434 else {
435 // Redirect to the first slide
436 await nav.go(1, 0, true)
437 }
438 }
439 },
440 { flush: 'pre', immediate: true },
441 )
442
443 return {
444 ...nav,
445 ...state,
446 }
447 })
448
449 // HMR re-runs this module for the updated slide. Keep the nav created in `setupRoot()`.
450 const useAppNav: typeof useSharedNav = import.meta.hot
451 ? (import.meta.hot.data.useSharedNav ??= useSharedNav)
452 : useSharedNav
453
454 export function useNav(): SlidevContextNavFull {
455 const nav = useAppNav()
456 // `useNav()` is also called outside of `setup()`, most notably from the
457 // `mounted`/`created` hooks of the `v-motion` and `v-mark` directives.
458 // `injectLocal` throws there, and there is no slide-local context to read
459 // anyway, so fall back to the shared nav.
460 const context = hasInjectionContext()
461 ? injectLocal(injectionSlidevContext, undefined)
462 : undefined
463 if (!context)
464 return nav
465
466 const localNav = toRaw(context).nav as unknown as SlidevContextNav
467 return {
468 ...nav,
469 ...localNav,
470 }
471 }
472
472 lines TYPESCRIPT