@@ -7,6 +7,15 @@ type options = {
7
7
@bs. val @bs. scope ("window" )
8
8
external docsearch : option <options => unit > = "docsearch"
9
9
10
+ type keyboardEventLike = {key : string }
11
+
12
+ @bs. val @bs. scope ("window" )
13
+ external addKeyboardEventListener : (string , keyboardEventLike => unit ) => unit = "addEventListener"
14
+
15
+ @bs. val @bs. scope ("window" )
16
+ external removeKeyboardEventListener : (string , keyboardEventLike => unit ) => unit =
17
+ "addEventListener"
18
+
10
19
type state =
11
20
| Active
12
21
| Inactive
@@ -17,6 +26,10 @@ type state =
17
26
18
27
@react.component
19
28
let make = () => {
29
+ // Used for the text input
30
+ let inputRef = React .useRef (Js .Nullable .null )
31
+ let (state , setState ) = React .useState (_ => Inactive )
32
+
20
33
React .useEffect1 (() => {
21
34
switch docsearch {
22
35
| Some (init ) =>
@@ -27,12 +40,21 @@ let make = () => {
27
40
})
28
41
| None => ()
29
42
}
30
- None
31
- }, [])
32
43
33
- // Used for the text input
34
- let inputRef = React .useRef (Js .Nullable .null )
35
- let (state , setState ) = React .useState (_ => Inactive )
44
+ let handleKeyDown = e => {
45
+ if e .key == "/" {
46
+ setState (_ => Active )
47
+
48
+ Js .Global .setTimeout (() => {
49
+ // execture focus in the next tick to avoid setting / inside input
50
+ inputRef .current -> Js .Nullable .toOption -> Belt .Option .forEach (focus )
51
+ }, 0 )-> ignore
52
+ }
53
+ }
54
+
55
+ addKeyboardEventListener ("keydown" , handleKeyDown )
56
+ Some (() => removeKeyboardEventListener ("keydown" , handleKeyDown ))
57
+ }, [])
36
58
37
59
let focusInput = () =>
38
60
inputRef .current -> Js .Nullable .toOption -> Belt .Option .forEach (el => el -> focus )
0 commit comments