✨(frontend) introduce long press keyboard shortcut
Needed to support push to talk using the spacebar. Introduce a utility hook. Will be called by the mic toggle in the upcoming commits. Inspired by Jitsi code.
This commit is contained in:
committed by
aleb_the_flash
parent
651cc0e5bd
commit
1faae96ccd
47
src/frontend/src/features/shortcuts/useLongPress.ts
Normal file
47
src/frontend/src/features/shortcuts/useLongPress.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import { useEffect, useRef } from 'react'
|
||||
|
||||
export type useLongPressProps = {
|
||||
keyCode?: string
|
||||
onKeyDown: () => void
|
||||
onKeyUp: () => void
|
||||
longPressThreshold?: number
|
||||
}
|
||||
|
||||
export const useLongPress = ({
|
||||
keyCode,
|
||||
onKeyDown,
|
||||
onKeyUp,
|
||||
longPressThreshold = 300,
|
||||
}: useLongPressProps) => {
|
||||
const timeoutIdRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.code != keyCode || timeoutIdRef.current) return
|
||||
timeoutIdRef.current = setTimeout(() => {
|
||||
onKeyDown()
|
||||
}, longPressThreshold)
|
||||
}
|
||||
|
||||
const handleKeyUp = (event: KeyboardEvent) => {
|
||||
if (event.code != keyCode || !timeoutIdRef.current) return
|
||||
clearTimeout(timeoutIdRef.current)
|
||||
timeoutIdRef.current = null
|
||||
onKeyUp()
|
||||
}
|
||||
|
||||
if (!keyCode) return
|
||||
|
||||
window.addEventListener('keydown', handleKeyDown)
|
||||
window.addEventListener('keyup', handleKeyUp)
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('keydown', handleKeyDown)
|
||||
window.removeEventListener('keyup', handleKeyUp)
|
||||
}
|
||||
}, [keyCode, onKeyDown, onKeyUp, longPressThreshold])
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
export default useLongPress
|
||||
Reference in New Issue
Block a user