-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathfocus.ts
More file actions
48 lines (42 loc) · 1.41 KB
/
focus.ts
File metadata and controls
48 lines (42 loc) · 1.41 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
import { Attachment } from 'svelte/attachments';
import { delay } from '@layerstack/utils';
export function focusMove(
options: { restoreFocus?: boolean; delay?: number; disabled?: boolean } = {
restoreFocus: false,
delay: 0,
disabled: false,
}
): Attachment<HTMLElement | SVGElement> {
return (node: HTMLElement | SVGElement) => {
let previousActiveElement: Element | null = null;
if (!options.disabled) {
previousActiveElement = document.activeElement;
// Set `tabIndex` to `-1` which makes any element (ex. div) focusable programmaitcally (and mouse), but not via keyboard navigation - https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex
node.tabIndex = -1;
// Appear to need to wait for tabIndex to update before applying focus
delay(options.delay ?? 0).then(() => {
node.focus();
});
}
return () => {
// Restore previous active element
if (
!options.disabled &&
options.restoreFocus &&
previousActiveElement instanceof HTMLElement
) {
previousActiveElement.focus();
}
};
};
}
// TODO: Add `focusTrap`
// https://css-tricks.com/a-css-approach-to-trap-focus-inside-of-an-element/
// export function focusTrap(): Attachment<HTMLElement> {
// return (node: HTMLElement) => {
// // TODO: Implementation
// return () => {
// // cleanup
// };
// };
// }