Skip to content

Commit 24b8e21

Browse files
committed
feat: Implement / event listener to focus search
1 parent 59ee704 commit 24b8e21

File tree

2 files changed

+52
-11
lines changed

2 files changed

+52
-11
lines changed

src/components/DocSearch.js

Lines changed: 25 additions & 6 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/components/DocSearch.res

Lines changed: 27 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,15 @@ type options = {
77
@bs.val @bs.scope("window")
88
external docsearch: option<options => unit> = "docsearch"
99

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+
1019
type state =
1120
| Active
1221
| Inactive
@@ -17,6 +26,10 @@ type state =
1726

1827
@react.component
1928
let make = () => {
29+
// Used for the text input
30+
let inputRef = React.useRef(Js.Nullable.null)
31+
let (state, setState) = React.useState(_ => Inactive)
32+
2033
React.useEffect1(() => {
2134
switch docsearch {
2235
| Some(init) =>
@@ -27,12 +40,21 @@ let make = () => {
2740
})
2841
| None => ()
2942
}
30-
None
31-
}, [])
3243

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+
}, [])
3658

3759
let focusInput = () =>
3860
inputRef.current->Js.Nullable.toOption->Belt.Option.forEach(el => el->focus)

0 commit comments

Comments
 (0)