forked from algolia/docsearch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
useDocSearchKeyboardEvents.ts
73 lines (65 loc) · 1.93 KB
/
useDocSearchKeyboardEvents.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import React from 'react';
export interface UseDocSearchKeyboardEventsProps {
isOpen: boolean;
onOpen: () => void;
onClose: () => void;
onInput?: (event: KeyboardEvent) => void;
searchButtonRef?: React.RefObject<HTMLButtonElement>;
}
function isEditingContent(event: KeyboardEvent): boolean {
const element = event.target as HTMLElement;
const tagName = element.tagName;
return (
element.isContentEditable ||
tagName === 'INPUT' ||
tagName === 'SELECT' ||
tagName === 'TEXTAREA'
);
}
export function useDocSearchKeyboardEvents({
isOpen,
onOpen,
onClose,
onInput,
searchButtonRef,
}: UseDocSearchKeyboardEventsProps) {
React.useEffect(() => {
function onKeyDown(event: KeyboardEvent) {
function open() {
// We check that no other DocSearch modal is showing before opening
// another one.
if (!document.body.classList.contains('DocSearch--active')) {
onOpen();
}
}
if (
(event.keyCode === 27 && isOpen) ||
// The `Cmd+K` shortcut both opens and closes the modal.
(event.key.toLowerCase() === 'k' && (event.metaKey || event.ctrlKey)) ||
// The `/` shortcut opens but doesn't close the modal because it's
// a character.
(!isEditingContent(event) && event.key === '/' && !isOpen)
) {
event.preventDefault();
if (isOpen) {
onClose();
} else if (!document.body.classList.contains('DocSearch--active')) {
open();
}
}
if (
searchButtonRef &&
searchButtonRef.current === document.activeElement &&
onInput
) {
if (/[a-zA-Z0-9]/.test(String.fromCharCode(event.keyCode))) {
onInput(event);
}
}
}
window.addEventListener('keydown', onKeyDown);
return () => {
window.removeEventListener('keydown', onKeyDown);
};
}, [isOpen, onOpen, onClose, onInput, searchButtonRef]);
}