-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfocus.ts
More file actions
59 lines (54 loc) · 1.64 KB
/
focus.ts
File metadata and controls
59 lines (54 loc) · 1.64 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
const FOCUSABLE_SELETORS = [
'a[href]',
'area[href]',
'input:not([disabled]):not([type="hidden"]):not([aria-hidden])',
'select:not([disabled]):not([aria-hidden])',
'textarea:not([disabled]):not([aria-hidden])',
'button:not([disabled]):not([aria-hidden])',
'iframe',
'object',
'embed',
'[contenteditable]',
'[tabindex]:not([tabindex^="-"])',
] as const;
export const getFocusableNodes = (element: HTMLElement) => {
return Object.values(
element.querySelectorAll<HTMLElement>(
(FOCUSABLE_SELETORS as unknown) as string
)
);
};
export const focusFirstNode = (element: HTMLElement) => {
const focusableNodes = getFocusableNodes(element);
let focusedElement: HTMLElement | undefined;
if (focusableNodes.length) {
[focusedElement] = focusableNodes;
focusedElement.focus();
}
return focusedElement;
};
export const handleTabPress = (element: HTMLElement, event: KeyboardEvent) => {
const focusableNodes = getFocusableNodes(element);
if (!focusableNodes.length) {
return undefined;
}
const focusedElement = focusableNodes[0];
if (!element.contains(document.activeElement)) {
focusedElement.focus();
event.preventDefault();
} else {
const focusedItemIndex = focusableNodes.indexOf(
document.activeElement as HTMLElement
);
if (event.shiftKey && focusedItemIndex === 0) {
focusableNodes[focusableNodes.length - 1].focus();
event.preventDefault();
}
if (!event.shiftKey && focusedItemIndex === focusableNodes.length - 1) {
focusedElement.focus();
event.preventDefault();
}
return focusableNodes[focusedItemIndex];
}
return focusedElement;
};