This repository was archived by the owner on Dec 15, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 402
/
Copy pathautofocus.js
75 lines (72 loc) · 1.65 KB
/
autofocus.js
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
74
75
/**
* When triggered, automatically focus the first element ref passed to this object.
*
* To unconditionally focus a single element:
*
* ```
* class SomeComponent extends React.Component {
* constructor(props) {
* super(props);
* this.autofocus = new Autofocus();
* }
*
* render() {
* return (
* <div className="github-Form">
* <input ref={this.autofocus.target} type="text" />
* <input type="text" />
* </div>
* );
* }
*
* componentDidMount() {
* this.autofocus.trigger();
* }
* }
* ```
*
* If multiple form elements are present, use `firstTarget` to create the ref instead. The rendered ref you assign the
* lowest numeric index will be focused on trigger:
*
* ```
* class SomeComponent extends React.Component {
* constructor(props) {
* super(props);
* this.autofocus = new Autofocus();
* }
*
* render() {
* return (
* <div className="github-Form">
* {this.props.someProp && <input ref={this.autofocus.firstTarget(0)} />}
* <input ref={this.autofocus.firstTarget(1)} type="text" />
* <input type="text" />
* </div>
* );
* }
*
* componentDidMount() {
* this.autofocus.trigger();
* }
* }
* ```
*
*/
export default class AutoFocus {
constructor() {
this.index = Infinity;
this.captured = null;
}
target = element => this.firstTarget(0)(element);
firstTarget = index => element => {
if (index < this.index) {
this.index = index;
this.captured = element;
}
};
trigger() {
if (this.captured !== null) {
setTimeout(() => this.captured.focus(), 0);
}
}
}