返回 slidev
shortcuts.ts
根目录 / packages / client / logic / shortcuts.ts
1 import type { ShortcutOptions } from '@slidev/types'
2 import type { Fn, KeyFilter } from '@vueuse/core'
3 import type { Ref } from 'vue'
4 import { onKeyStroke } from '@vueuse/core'
5 import { and, not } from '@vueuse/math'
6 import { watch } from 'vue'
7 import { useNav } from '../composables/useNav'
8 import setupShortcuts from '../setup/shortcuts'
9 import { fullscreen, isInputting, isOnFocus, magicKeys, shortcutsEnabled, shortcutsLocked } from '../state'
10 import { isPresentShortcut } from './utils'
11
12 export function registerShortcuts() {
13 const { isPrintMode } = useNav()
14 const enabled = and(not(isInputting), not(isOnFocus), not(isPrintMode), shortcutsEnabled, not(shortcutsLocked))
15
16 const allShortcuts = setupShortcuts()
17 const shortcuts = new Map<string | Ref<boolean>, ShortcutOptions>(
18 allShortcuts.map((options: ShortcutOptions) => [options.key, options]),
19 )
20
21 shortcuts.forEach((options) => {
22 if (options.fn)
23 shortcut(options.key, options.fn, options.autoRepeat)
24 })
25
26 strokeShortcut('f', () => fullscreen.toggle())
27 strokeShortcut(isPresentShortcut, (ev) => {
28 ev.preventDefault() // Ctrl+F5 would otherwise reload the page
29 fullscreen.toggle()
30 })
31
32 function shortcut(key: string | Ref<boolean>, fn: Fn, autoRepeat = false) {
33 if (typeof key === 'string')
34 key = magicKeys[key]
35
36 const source = and(key, enabled)
37 let count = 0
38 let timer: any
39 const trigger = () => {
40 clearTimeout(timer)
41 if (!source.value) {
42 count = 0
43 return
44 }
45 if (autoRepeat) {
46 timer = setTimeout(trigger, Math.max(1000 - count * 250, 150))
47 count++
48 }
49 fn()
50 }
51
52 return watch(source, trigger, { flush: 'sync' })
53 }
54
55 function strokeShortcut(key: KeyFilter, fn: (ev: KeyboardEvent) => void) {
56 return onKeyStroke(key, (ev) => {
57 if (!enabled.value)
58 return
59 if (!ev.repeat)
60 fn(ev)
61 })
62 }
63 }
64
64 lines TYPESCRIPT