-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcomponentConnector.js
More file actions
66 lines (58 loc) · 1.81 KB
/
componentConnector.js
File metadata and controls
66 lines (58 loc) · 1.81 KB
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
/**
* Connect a controller and target pair when they are not adjacent siblings.
*
* @param {Popup|Disclosure} arg.component The component instance.
* @return {function} The cleanup function.
*/
export default function ComponentConnector({ component }) {
/**
* Move focus to the target's first interactive child in cases where the
* markup is disconnected or out-of-order.
*
* @param {Event} event The Event object.
*/
const tabtoTarget = (event) => {
const { key, shiftKey } = event;
if (
null != component.firstInteractiveChild
&& component.expanded
&& ! shiftKey
&& 'Tab' === key
) {
event.preventDefault();
component.firstInteractiveChild.focus();
}
};
/**
* Move focus back to the controller from the target's first interactive child
* in cases where the markup is disconnected or out-of-order.
*
* @param {Event} event The Event object.
*/
const tabBackToController = (event) => {
const { key, shiftKey } = event;
const { activeElement } = document;
if (
component.firstInteractiveChild === activeElement
&& shiftKey
&& 'Tab' === key
) {
event.preventDefault();
component.controller.focus();
}
};
/*
* Establish a relationship when the DOM heirarchy doesn't represent that
* a relationship exists.
*/
if (component.target !== component.controller.nextElementSibling) {
component.addAttribute(component.controller, 'aria-owns', component.target.id);
component.controller.addEventListener('keydown', tabtoTarget);
component.target.addEventListener('keydown', tabBackToController);
}
// Clean up.
return () => {
component.controller.removeEventListener('keydown', tabtoTarget);
component.target.removeEventListener('keydown', tabBackToController);
};
}