-
Notifications
You must be signed in to change notification settings - Fork 454
/
Copy pathuseTrapFocus.ts
156 lines (138 loc) · 4.99 KB
/
useTrapFocus.ts
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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
import { unrefElement } from '@vueuse/core';
import { CheckOptions, FocusableElement, tabbable, TabbableOptions } from 'tabbable';
import { type Ref, ref, watch } from 'vue';
import { focusNext, focusPrev, isTab, isTabAndShift } from '@storefront-ui/shared';
import { waitForNextRender } from '@storefront-ui/vue';
export enum InitialFocusType {
autofocus = 'autofocus',
container = 'container',
}
type UseTrapFocusOptions = TabbableOptions &
CheckOptions & {
trapTabs?: boolean;
arrowFocusGroupSelector?: string;
activeState?: Ref<boolean>;
initialFocus?: number | `${InitialFocusType}` | false;
initialFocusContainerFallback?: boolean;
arrowKeysLeftRight?: boolean;
arrowKeysUpDown?: boolean;
};
type UseTrapFocusReturn = {
current: Ref<HTMLElement | undefined>;
focusables: Ref<FocusableElement[]>;
focusNext: typeof focusNext;
focusPrev: typeof focusPrev;
updateFocusableElements: () => void;
};
const defaultOptions = {
trapTabs: true,
activeState: ref(true),
initialFocus: 0,
initialFocusContainerFallback: false,
arrowKeysLeftRight: false,
arrowKeysUpDown: false,
};
export const useTrapFocus = (
containerElementRef: Ref<HTMLElement | undefined>,
options?: UseTrapFocusOptions,
): UseTrapFocusReturn => {
const {
trapTabs,
arrowFocusGroupSelector,
includeContainer,
activeState,
initialFocus,
arrowKeysLeftRight,
arrowKeysUpDown,
initialFocusContainerFallback,
} = {
...defaultOptions,
...options,
};
const currentlyFocused = ref<HTMLElement | undefined>();
const focusableElements = ref<FocusableElement[]>([]);
let containerHTMLElement: HTMLElement | undefined;
const onFocusListener = () => {
currentlyFocused.value = document.activeElement as HTMLElement;
};
const focusPreviousItem = ({
event,
additionalData,
}: {
event?: KeyboardEvent;
additionalData?: Record<string, unknown>;
}) =>
focusPrev({
current: currentlyFocused.value,
focusables: focusableElements.value,
event,
...additionalData,
});
const focusNextItem = ({
event,
additionalData,
}: {
event?: KeyboardEvent;
additionalData?: Record<string, unknown>;
}) =>
focusNext({
current: currentlyFocused.value,
focusables: focusableElements.value,
event,
...additionalData,
});
const onKeyDownListener = (event: KeyboardEvent) => {
const isAnyGroupElement = arrowFocusGroupSelector && containerHTMLElement?.querySelector(arrowFocusGroupSelector);
const additionalData = isAnyGroupElement ? { arrowFocusGroupSelector } : {};
if (arrowKeysLeftRight && event.key === 'ArrowLeft') focusPreviousItem({ additionalData });
if (arrowKeysLeftRight && event.key === 'ArrowRight') focusNextItem({ additionalData });
if (arrowKeysUpDown && event.key === 'ArrowUp') focusPreviousItem({ additionalData });
if (arrowKeysUpDown && event.key === 'ArrowDown') focusNextItem({ additionalData });
if (trapTabs && isTab(event)) focusNextItem({ event });
if (trapTabs && isTabAndShift(event)) focusPreviousItem({ event });
};
const removeEventListeners = () => {
containerHTMLElement?.removeEventListener('keydown', onKeyDownListener);
containerHTMLElement?.removeEventListener('focus', onFocusListener, true);
};
watch(
[containerElementRef, activeState],
async ([containerElement, activeState]) => {
if (containerElement && activeState) {
let focusFallbackNeeded = false;
await waitForNextRender();
containerHTMLElement = unrefElement(containerElement);
containerHTMLElement?.addEventListener('focus', onFocusListener, true);
containerHTMLElement?.addEventListener('keydown', onKeyDownListener);
focusableElements.value = tabbable(containerHTMLElement as HTMLElement, { includeContainer });
if (typeof initialFocus === 'number') {
if (!focusableElements.value[initialFocus]) {
console.error(`There is no element with given index ${initialFocus}`);
focusFallbackNeeded = true;
} else focusableElements.value[initialFocus].focus();
} else if (initialFocus === InitialFocusType.autofocus) {
const autofocusElement = focusableElements.value.find((focusable) => focusable.hasAttribute('autofocus'));
if (autofocusElement) autofocusElement.focus();
else focusFallbackNeeded = true;
}
if ((initialFocusContainerFallback && focusFallbackNeeded) || initialFocus === InitialFocusType.container)
containerHTMLElement?.focus();
} else {
focusableElements.value = [];
currentlyFocused.value = undefined;
removeEventListeners();
}
},
{ immediate: true },
);
const updateFocusableElements = () => {
focusableElements.value = tabbable(containerElementRef.value as HTMLElement, { includeContainer });
};
return {
current: currentlyFocused,
focusables: focusableElements,
focusNext,
focusPrev,
updateFocusableElements,
};
};