forked from CodingCatDev/codingcat.dev
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfocus.ts
More file actions
67 lines (58 loc) · 1.58 KB
/
focus.ts
File metadata and controls
67 lines (58 loc) · 1.58 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
67
export function focusable_children(node: HTMLElement) {
const nodes = Array.from(
node.querySelectorAll(
'a[href], button, input, textarea, select, details, [tabindex]:not([tabindex="-1"])'
)
);
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
const index = nodes.indexOf(document.activeElement);
const update = (d: number) => {
let i = index + d;
i += nodes.length;
i %= nodes.length;
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
nodes[i].focus();
};
return {
next: (selector: string) => {
const reordered: any[] = [...nodes.slice(index + 1), ...nodes.slice(0, index + 1)];
for (let i = 0; i < reordered.length; i += 1) {
if (!selector || reordered[i].matches(selector)) {
reordered[i].focus();
return;
}
}
},
prev: (selector: string) => {
const reordered: any[] = [...nodes.slice(index + 1), ...nodes.slice(0, index + 1)];
for (let i = reordered.length - 2; i >= 0; i -= 1) {
if (!selector || reordered[i].matches(selector)) {
reordered[i].focus();
return;
}
}
},
update
};
}
export function trap(node: HTMLDivElement) {
const handle_keydown = (e: { key: string; preventDefault: () => void; shiftKey: any; }) => {
if (e.key === 'Tab') {
e.preventDefault();
const group = focusable_children(node);
// if (e.shiftKey) {
// group.prev();
// } else {
// group.next();
// }
}
};
node.addEventListener('keydown', handle_keydown);
return {
destroy: () => {
node.removeEventListener('keydown', handle_keydown);
}
};
}