Skip to content

Commit

Permalink
feat: listen shortcut keys on root element
Browse files Browse the repository at this point in the history
  • Loading branch information
ambar committed Jan 29, 2022
1 parent d7a6924 commit 63f554a
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 7 deletions.
10 changes: 7 additions & 3 deletions packages/griffith/src/components/Player.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ import useBoolean from '../hooks/useBoolean'
import useMount from '../hooks/useMount'
import useHandler from '../hooks/useHandler'
import usePlayerShortcuts from './usePlayerShortcuts'

const CONTROLLER_HIDE_DELAY = 3000

// 被 Provider 包装后的属性
Expand Down Expand Up @@ -138,7 +139,7 @@ const InnerPlayer: React.FC<InnerPlayerProps> = ({
}) => {
const {emitEvent, subscribeAction} = useContext(InternalMessageContext)
const {currentSrc} = useContext(VideoSourceContext)
const rootRef = useRef<HTMLDivElement>(null)
const [root, setRoot] = useState<HTMLDivElement | null>(null)
const videoRef = useRef<{
root: HTMLVideoElement
seek(currentTime: number): void
Expand Down Expand Up @@ -368,7 +369,7 @@ const InnerPlayer: React.FC<InnerPlayerProps> = ({
const onExit = () => {
return emitEvent(EVENTS.EXIT_FULLSCREEN)
}
BigScreen?.toggle(rootRef.current!, onEnter, onExit)
BigScreen?.toggle(root!, onEnter, onExit)
}
})

Expand Down Expand Up @@ -463,6 +464,7 @@ const InnerPlayer: React.FC<InnerPlayerProps> = ({
})

usePlayerShortcuts({
root,
prevVolumeRef,
isPlaying,
volume,
Expand Down Expand Up @@ -603,7 +605,9 @@ const InnerPlayer: React.FC<InnerPlayerProps> = ({
onMouseDown={handleMouseDown}
onMouseUp={handleMouseUp}
onMouseMove={handleShowController}
ref={rootRef}
ref={setRoot}
tabIndex={-1}
aria-label={title}
>
<div className={css(styles.video)}>
<Video
Expand Down
11 changes: 7 additions & 4 deletions packages/griffith/src/components/usePlayerShortcuts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {useActionToastDispatch} from './ActionToast'
import VideoSourceContext from '../contexts/VideoSourceContext'

type Options = {
root: HTMLDivElement | null
prevVolumeRef: React.MutableRefObject<number>
isPlaying: boolean
isPageFullScreen: boolean
Expand All @@ -22,6 +23,7 @@ type Options = {
}

const usePlayerShortcuts = ({
root,
prevVolumeRef,
isPlaying,
isPageFullScreen,
Expand Down Expand Up @@ -156,13 +158,14 @@ const usePlayerShortcuts = ({
})

useEffect(() => {
if (standalone) {
document.addEventListener('keydown', handleKeyDown)
const el = standalone ? document.body : root
if (el) {
el.addEventListener('keydown', handleKeyDown)
return () => {
document.removeEventListener('keydown', handleKeyDown)
el.removeEventListener('keydown', handleKeyDown)
}
}
}, [handleKeyDown, standalone])
}, [handleKeyDown, root, standalone])
}

export default usePlayerShortcuts

0 comments on commit 63f554a

Please sign in to comment.