| 40 | * Handles keyboard interactions for a focusable element. |
| 41 | */ |
| 42 | export function useKeyboard(props: KeyboardProps): KeyboardResult { |
| 43 | let {shortcuts, allowRepeats = false, allowComposing = false} = props; |
| 44 | let onKeyDown; |
| 45 | let onKeyUp; |
| 46 | if (shortcuts) { |
| 47 | let shortcutHandler = createKeyboardShortcutHandler(shortcuts); |
| 48 | let shortcutOnKeyDown = createEventHandler<ReactKeyboardEvent<any>>(e => { |
| 49 | // If keyboard event didn't originate from a child of the current target, |
| 50 | // then it's a React event coming through a portal. We should ignore it. |
| 51 | if (!nodeContains(e.currentTarget, getEventTarget(e))) { |
| 52 | e.continuePropagation(); |
| 53 | return; |
| 54 | } |
| 55 | if ( |
| 56 | (e.nativeEvent?.repeat && !allowRepeats) || |
| 57 | (e.nativeEvent?.isComposing && !allowComposing) |
| 58 | ) { |
| 59 | e.continuePropagation(); |
| 60 | return; |
| 61 | } |
| 62 | |
| 63 | shortcutHandler(e); |
| 64 | }); |
| 65 | let shortcutOnKeyUp = createEventHandler<ReactKeyboardEvent<any>>(e => { |
| 66 | // If keyboard event didn't originate from a child of the current target, |
| 67 | // then it's a React event coming through a portal. We should ignore it. |
| 68 | if (!nodeContains(e.currentTarget, getEventTarget(e))) { |
| 69 | e.continuePropagation(); |
| 70 | return; |
| 71 | } |
| 72 | if ( |
| 73 | (e.nativeEvent?.repeat && !allowRepeats) || |
| 74 | (e.nativeEvent?.isComposing && !allowComposing) |
| 75 | ) { |
| 76 | e.continuePropagation(); |
| 77 | return; |
| 78 | } |
| 79 | // implement shortcut handler on keyup, what should the map be called? or should it be another syntax on shortcuts? |
| 80 | e.continuePropagation(); |
| 81 | }); |
| 82 | onKeyDown = props.onKeyDown ? chain(props.onKeyDown, shortcutOnKeyDown) : shortcutOnKeyDown; |
| 83 | onKeyUp = props.onKeyUp ? chain(props.onKeyUp, shortcutOnKeyUp) : shortcutOnKeyUp; |
| 84 | } else { |
| 85 | onKeyDown = createEventHandler(props.onKeyDown); |
| 86 | onKeyUp = createEventHandler(props.onKeyUp); |
| 87 | } |
| 88 | return { |
| 89 | keyboardProps: props.isDisabled |
| 90 | ? {} |
| 91 | : { |
| 92 | onKeyDown, |
| 93 | onKeyUp |
| 94 | } |
| 95 | }; |
| 96 | } |