forked from Movalabs-crew/mova-store
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaccessibility.ts
More file actions
268 lines (230 loc) · 7.11 KB
/
Copy pathaccessibility.ts
File metadata and controls
268 lines (230 loc) · 7.11 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
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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
/**
* Accessibility Utilities
*
* Helper functions and constants for improving accessibility
* throughout the Mova Store application.
*/
// =============================================================================
// Keyboard Navigation
// =============================================================================
/**
* Common keyboard keys used for navigation.
*/
export const Keys = {
ENTER: "Enter",
SPACE: " ",
ESCAPE: "Escape",
TAB: "Tab",
ARROW_UP: "ArrowUp",
ARROW_DOWN: "ArrowDown",
ARROW_LEFT: "ArrowLeft",
ARROW_RIGHT: "ArrowRight",
HOME: "Home",
END: "End",
} as const;
/**
* Checks if an element is focusable.
*/
export function isFocusable(element: Element): boolean {
if (!(element instanceof HTMLElement)) return false;
// Check if element is disabled
if ((element as HTMLButtonElement).disabled) return false;
// Check tabindex
const tabindex = element.getAttribute("tabindex");
if (tabindex && parseInt(tabindex) < 0) return false;
// Check for naturally focusable elements
const focusableTags = ["A", "BUTTON", "INPUT", "SELECT", "TEXTAREA"];
if (focusableTags.includes(element.tagName)) return true;
// Check for elements with positive tabindex
if (tabindex && parseInt(tabindex) >= 0) return true;
return false;
}
/**
* Gets all focusable elements within a container.
*/
export function getFocusableElements(container: HTMLElement): HTMLElement[] {
const elements = container.querySelectorAll(
'a[href], button, input, select, textarea, [tabindex]:not([tabindex="-1"])'
);
return Array.from(elements).filter(
(el) => isFocusable(el) && isVisible(el as HTMLElement)
) as HTMLElement[];
}
/**
* Checks if an element is visible.
*/
export function isVisible(element: HTMLElement): boolean {
return !!(
element.offsetWidth ||
element.offsetHeight ||
element.getClientRects().length
);
}
/**
* Traps focus within a container (useful for modals).
*/
export function trapFocus(container: HTMLElement): () => void {
const focusableElements = getFocusableElements(container);
const firstElement = focusableElements[0];
const lastElement = focusableElements[focusableElements.length - 1];
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key !== Keys.TAB) return;
if (event.shiftKey) {
// Shift + Tab: go backwards
if (document.activeElement === firstElement) {
event.preventDefault();
lastElement?.focus();
}
} else {
// Tab: go forwards
if (document.activeElement === lastElement) {
event.preventDefault();
firstElement?.focus();
}
}
};
container.addEventListener("keydown", handleKeyDown);
// Focus first element
firstElement?.focus();
// Return cleanup function
return () => {
container.removeEventListener("keydown", handleKeyDown);
};
}
// =============================================================================
// ARIA Helpers
// =============================================================================
/**
* Generates a unique ID for ARIA relationships.
*/
export function generateAriaId(prefix = "aria"): string {
return `${prefix}-${Math.random().toString(36).slice(2, 9)}`;
}
/**
* Creates ARIA props for a button that controls expandable content.
*/
export function ariaExpanded(isExpanded: boolean, controlsId: string) {
return {
"aria-expanded": isExpanded,
"aria-controls": controlsId,
};
}
/**
* Creates ARIA props for a live region (for screen reader announcements).
*/
export function ariaLive(priority: "polite" | "assertive" = "polite") {
return {
"aria-live": priority,
"aria-atomic": true,
};
}
/**
* Creates ARIA props for an invalid form field.
*/
export function ariaInvalid(
isInvalid: boolean,
errorId?: string
): Record<string, string | boolean> {
const props: Record<string, string | boolean> = {
"aria-invalid": isInvalid,
};
if (isInvalid && errorId) {
props["aria-describedby"] = errorId;
}
return props;
}
// =============================================================================
// Screen Reader Utilities
// =============================================================================
/**
* Announces a message to screen readers.
*/
export function announceToScreenReader(
message: string,
priority: "polite" | "assertive" = "polite"
): void {
const announcement = document.createElement("div");
announcement.setAttribute("role", "status");
announcement.setAttribute("aria-live", priority);
announcement.setAttribute("aria-atomic", "true");
announcement.className = "sr-only";
announcement.textContent = message;
document.body.appendChild(announcement);
// Remove after announcement
setTimeout(() => {
document.body.removeChild(announcement);
}, 1000);
}
/**
* CSS class for visually hidden but screen-reader accessible content.
* Include this in your global CSS or Tailwind config.
*/
export const srOnlyStyles = `
.sr-only {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border-width: 0;
}
`;
// =============================================================================
// Focus Management
// =============================================================================
/**
* Saves the currently focused element and returns a function to restore it.
*/
export function saveFocus(): () => void {
const previouslyFocused = document.activeElement as HTMLElement | null;
return () => {
previouslyFocused?.focus();
};
}
/**
* Moves focus to the first error in a form.
*/
export function focusFirstError(container: HTMLElement): void {
const errorElement = container.querySelector('[aria-invalid="true"]');
if (errorElement instanceof HTMLElement) {
errorElement.focus();
}
}
// =============================================================================
// Reduced Motion
// =============================================================================
/**
* Checks if user prefers reduced motion.
*/
export function prefersReducedMotion(): boolean {
if (typeof window === "undefined") return false;
return window.matchMedia("(prefers-reduced-motion: reduce)").matches;
}
/**
* Gets animation duration respecting reduced motion preference.
*/
export function getAnimationDuration(normalDuration: number): number {
return prefersReducedMotion() ? 0 : normalDuration;
}
// =============================================================================
// Color Contrast
// =============================================================================
/**
* Checks if a color combination meets WCAG AA contrast requirements.
* Note: This is a simplified check. For production, use a proper contrast library.
*/
export function meetsContrastRequirement(
foreground: string,
background: string,
largeText = false
): boolean {
// This is a placeholder. In production, implement proper contrast calculation.
// WCAG AA requires 4.5:1 for normal text, 3:1 for large text.
console.warn(
"meetsContrastRequirement is a placeholder. Implement proper contrast checking."
);
return true;
}