-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathFocusLink.js
130 lines (118 loc) · 2.75 KB
/
FocusLink.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import css from './FocusLink.css';
import { getNextFocusable } from '../../util/getFocusableElements';
const propTypes = {
children: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.node),
PropTypes.node,
]),
className: PropTypes.string,
component: PropTypes.string,
sendOnFocus: PropTypes.bool,
showOnFocus: PropTypes.bool,
tabIndex: PropTypes.number,
target: PropTypes.oneOfType([PropTypes.object, PropTypes.string]),
targetNextAfter: PropTypes.oneOfType([PropTypes.element, PropTypes.func]),
};
const FocusLink = ({
children,
className,
component,
sendOnFocus,
showOnFocus,
tabIndex,
target,
targetNextAfter,
...rest
}) => {
let link = null;
const focusTarget = () => {
if (typeof target === 'string') {
let id = target;
if (target.charAt(0) === '#') {
id = target.replace('#', '');
}
const tgt = document.getElementById(id);
if (tgt) {
tgt.focus();
}
} else if (typeof target === 'object') {
target.focus();
}
};
const focusNext = () => {
let nextFocusable;
if (targetNextAfter) {
if (typeof targetNextAfter === 'function') {
nextFocusable = getNextFocusable(targetNextAfter(), false);
} else {
nextFocusable = getNextFocusable(targetNextAfter, false);
}
} else {
nextFocusable = getNextFocusable(link, false);
}
nextFocusable.focus();
};
const handleClick = (e) => {
e.preventDefault();
if (target) {
focusTarget();
} else {
focusNext();
}
};
const handleKeyDown = (e) => {
e.preventDefault();
if (e.key === 'Enter') {
if (target) {
focusTarget();
} else {
focusNext();
}
}
};
const getClass = () => {
return classNames(
css.focusLink,
{ [`${css.showOnFocus}`]: showOnFocus },
className,
);
};
if (component) {
const Component = component;
return (
<Component
data-test-focus-link
ref={(ref) => { link = ref; }}
role="button"
tabIndex={tabIndex || 0}
onClick={handleClick}
onKeyDown={handleKeyDown}
className={getClass()}
onFocus={sendOnFocus && focusTarget}
{...rest}
>
{ children }
</Component>
);
}
return (
<div
data-test-focus-link
ref={(ref) => { link = ref; }}
role="button"
tabIndex={tabIndex || 0}
onClick={handleClick}
onKeyDown={handleKeyDown}
className={getClass()}
onFocus={sendOnFocus && focusTarget}
{...rest}
>
{ children }
</div>
);
};
FocusLink.propTypes = propTypes;
export default FocusLink;