Skip to content

Commit 833c3b9

Browse files
souporseriousTrySound
authored andcommitted
Use onMouseDown instead of setTimeout to manage focus (#103)
1 parent 23578a4 commit 833c3b9

File tree

1 file changed

+33
-28
lines changed

1 file changed

+33
-28
lines changed

src/components/FocusManager.js

Lines changed: 33 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -2,35 +2,40 @@ import * as React from 'react'
22
import State from './State'
33
import renderProps from '../utils/renderProps'
44

5-
const FocusManager = ({ onChange, ...props }) => (
6-
<State
7-
initial={{ isFocused: false, timeoutId: null }}
8-
onChange={({ isFocused }) => onChange && onChange({ isFocused })}
9-
>
10-
{({ state, setState }) =>
11-
renderProps(props, {
12-
isFocused: state.isFocused,
13-
blur: () => {
14-
setState({ isFocused: false })
15-
},
16-
bind: {
17-
tabIndex: -1,
18-
onBlur: () => {
19-
// the timeoutId is saved in state to not cleanup in a rerender
20-
setState({
21-
timeoutId: setTimeout(() => {
22-
setState({ isFocused: false })
23-
}),
24-
})
5+
const FocusManager = ({ onChange, ...props }) => {
6+
let canBlur = true
7+
return (
8+
<State
9+
initial={{ isFocused: false }}
10+
onChange={({ isFocused }) => onChange && onChange({ isFocused })}
11+
>
12+
{({ state, setState }) =>
13+
renderProps(props, {
14+
isFocused: state.isFocused,
15+
blur: () => {
16+
setState({ isFocused: false })
2517
},
26-
onFocus: () => {
27-
clearTimeout(state.timeoutId)
28-
setState({ isFocused: true })
18+
bind: {
19+
tabIndex: -1,
20+
onBlur: () => {
21+
if (canBlur) {
22+
setState({ isFocused: false })
23+
}
24+
},
25+
onFocus: () => {
26+
setState({ isFocused: true })
27+
},
28+
onMouseDown: () => {
29+
canBlur = false
30+
},
31+
onMouseUp: () => {
32+
canBlur = true
33+
},
2934
},
30-
},
31-
})
32-
}
33-
</State>
34-
)
35+
})
36+
}
37+
</State>
38+
)
39+
}
3540

3641
export default FocusManager

0 commit comments

Comments
 (0)