-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathaccessibility.js
More file actions
420 lines (358 loc) · 14.2 KB
/
Copy pathaccessibility.js
File metadata and controls
420 lines (358 loc) · 14.2 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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
// accessibility.js - Core utilities for quiz accessibility and keyboard navigation
// ------------------------------------------------------------
// This script provides functions to initialize ARIA roles, manage focus, and handle
// keyboard shortcuts for quiz pages. It attaches its API to the global `window` object.
(function () {
// Initialize accessibility for a quiz.
function initQuizAccessibility({ containerId = 'quiz-box', optionsContainerId = 'options', statusId = 'sr-status' } = {}) {
const container = document.getElementById(containerId);
const optionsContainer = document.getElementById(optionsContainerId);
const srStatus = document.getElementById(statusId);
// Ensure the options container has proper ARIA role (radiogroup) if not already set.
if (optionsContainer && !optionsContainer.getAttribute('role')) {
optionsContainer.setAttribute('role', 'radiogroup');
}
refreshOptionTabStops(optionsContainer);
// Attach a keydown listener for navigation shortcuts.
document.addEventListener('keydown', (e) => handleKeyNavigation(e, optionsContainer, srStatus));
if (optionsContainer) {
optionsContainer.addEventListener('click', () => refreshOptionTabStops(optionsContainer));
optionsContainer.addEventListener('focusin', (event) => {
if (event.target?.classList?.contains('option')) {
setActiveOption(event.target, optionsContainer, false);
}
});
// Automatically refresh option tab stops when options are dynamically populated/re-rendered.
const observer = new MutationObserver(() => {
refreshOptionTabStops(optionsContainer);
});
observer.observe(optionsContainer, { childList: true });
}
return { container, optionsContainer, srStatus };
}
// Keyboard navigation handler.
function handleKeyNavigation(event, optionsContainer, srStatus) {
const KEY = {
LEFT: 'ArrowLeft',
RIGHT: 'ArrowRight',
UP: 'ArrowUp',
DOWN: 'ArrowDown',
HOME: 'Home',
END: 'End',
ENTER: 'Enter',
SPACE: ' ',
CTRL_ENTER: 'Enter',
};
const activeEl = document.activeElement;
const isOption = activeEl && activeEl.classList && activeEl.classList.contains('option');
if ((event.key === KEY.LEFT || event.key === KEY.UP) && isOption) {
focusRelativeOption(activeEl, optionsContainer, -1);
event.preventDefault();
return;
}
if ((event.key === KEY.RIGHT || event.key === KEY.DOWN) && isOption) {
focusRelativeOption(activeEl, optionsContainer, 1);
event.preventDefault();
return;
}
if (event.key === KEY.HOME && isOption) {
focusOptionAt(optionsContainer, 0);
event.preventDefault();
return;
}
if (event.key === KEY.END && isOption) {
focusOptionAt(optionsContainer, getOptions(optionsContainer).length - 1);
event.preventDefault();
return;
}
if ((event.key === KEY.ENTER || event.key === KEY.SPACE) && isOption) {
activeEl.click();
event.preventDefault();
return;
}
// Ctrl+Enter to submit current answer (if submit button is visible).
if (event.key === KEY.CTRL_ENTER && event.ctrlKey) {
const submitBtn = document.getElementById('submit-btn');
if (submitBtn && !submitBtn.classList.contains('hidden')) {
submitBtn.click();
event.preventDefault();
}
return;
}
}
function getOptions(optionsContainer) {
const scope = optionsContainer || document;
return Array.from(scope.querySelectorAll('.option'));
}
function refreshOptionTabStops(optionsContainer) {
const options = getOptions(optionsContainer);
const selected = options.find((option) => option.classList.contains('selected'));
const active = selected || options[0];
options.forEach((option) => {
option.setAttribute('tabindex', option === active ? '0' : '-1');
if (!option.getAttribute('role')) {
option.setAttribute('role', 'radio');
}
if (!option.getAttribute('aria-checked')) {
option.setAttribute('aria-checked', option.classList.contains('selected') ? 'true' : 'false');
}
});
}
function setActiveOption(option, optionsContainer, shouldFocus = true) {
const options = getOptions(optionsContainer);
options.forEach((item) => {
item.setAttribute('tabindex', item === option ? '0' : '-1');
});
if (shouldFocus) option.focus();
announceOptionChange(option, options.indexOf(option), options.length);
}
function focusRelativeOption(current, optionsContainer, delta) {
const options = getOptions(optionsContainer);
const idx = options.indexOf(current);
if (idx === -1 || options.length === 0) return;
const nextIndex = (idx + delta + options.length) % options.length;
setActiveOption(options[nextIndex], optionsContainer);
}
function focusOptionAt(optionsContainer, index) {
const options = getOptions(optionsContainer);
if (!options.length || index < 0 || index >= options.length) return;
setActiveOption(options[index], optionsContainer);
}
function announceOptionChange(optionEl, index, total) {
const sr = document.getElementById('sr-status');
if (sr) {
const position = typeof index === 'number' && typeof total === 'number'
? `Option ${index + 1} of ${total}: `
: 'Option ';
sr.textContent = `${position}${optionEl.textContent.trim()}`;
}
}
function announce(message) {
const sr = document.getElementById('sr-status');
if (sr) {
sr.textContent = '';
setTimeout(() => {
sr.textContent = message;
}, 0);
}
}
// ------------------------------
// Dialog helpers (focus trap + escape + restore focus)
// ------------------------------
function getFocusableElementsWithin(root) {
if (!root) return [];
const selector = [
'a[href]:not([tabindex="-1"])',
'button:not([disabled]):not([tabindex="-1"])',
'textarea:not([disabled]):not([tabindex="-1"])',
'input:not([disabled]):not([type="hidden"]):not([tabindex="-1"])',
'select:not([disabled]):not([tabindex="-1"])',
'[tabindex]:not([tabindex="-1"])'
].join(',');
const nodes = Array.from(root.querySelectorAll(selector));
// filter out hidden elements
return nodes.filter((el) => {
const style = window.getComputedStyle(el);
return style && style.visibility !== 'hidden' && style.display !== 'none';
});
}
function trapFocusWithinDialog(event, dialogEl) {
if (!dialogEl) return;
if (event.key !== 'Tab') return;
const focusables = getFocusableElementsWithin(dialogEl);
if (!focusables.length) {
event.preventDefault();
return;
}
const first = focusables[0];
const last = focusables[focusables.length - 1];
const active = document.activeElement;
if (event.shiftKey) {
if (active === first || !dialogEl.contains(active)) {
event.preventDefault();
last.focus();
}
} else {
if (active === last || !dialogEl.contains(active)) {
event.preventDefault();
first.focus();
}
}
}
function openDialog(dialogEl, { initialFocusId = null, returnFocusToEl = null } = {}) {
if (!dialogEl) return;
// Store restore target each open so focus is predictable.
if (returnFocusToEl) {
dialogEl.dataset.restoreFocusId = returnFocusToEl.id || '';
} else if (document.activeElement) {
dialogEl.dataset.restoreFocusId = document.activeElement.id || '';
} else {
dialogEl.dataset.restoreFocusId = '';
}
dialogEl.style.display = 'block';
if (dialogEl.classList.contains('hidden')) dialogEl.classList.remove('hidden');
// Ensure only one focus trap handler is attached.
if (!dialogEl._lsTrapHandlerBound) {
const handler = (e) => trapFocusWithinDialog(e, dialogEl);
dialogEl._lsTrapHandlerBound = true;
dialogEl._lsTrapHandler = handler;
dialogEl.addEventListener('keydown', handler);
}
const focusTarget = initialFocusId ? dialogEl.querySelector(`#${CSS.escape(initialFocusId)}`) : null;
const focusables = getFocusableElementsWithin(dialogEl);
const firstFocusable = focusables[0];
// Prefer explicit focus target, else first focusable, else dialog itself.
(focusTarget || firstFocusable || dialogEl).focus?.();
dialogEl.dataset.dialogOpen = 'true';
// Escape closes dialog.
function onDocKeyDown(e) {
if (e.key !== 'Escape') return;
if (dialogEl.dataset.dialogOpen !== 'true') return;
e.preventDefault();
closeDialog(dialogEl);
}
if (dialogEl._lsOnEscape) {
document.removeEventListener('keydown', dialogEl._lsOnEscape);
}
dialogEl._lsOnEscape = onDocKeyDown;
document.addEventListener('keydown', onDocKeyDown);
}
function closeDialog(dialogEl) {
if (!dialogEl) return;
dialogEl.dataset.dialogOpen = 'false';
dialogEl.style.display = 'none';
if (!dialogEl.classList.contains('hidden')) dialogEl.classList.add('hidden');
if (dialogEl._lsTrapHandlerBound && dialogEl._lsTrapHandler) {
// keep trap handler attached; it is lightweight. No need to remove.
}
// Remove escape handler.
if (dialogEl._lsOnEscape) {
document.removeEventListener('keydown', dialogEl._lsOnEscape);
dialogEl._lsOnEscape = null;
}
// Restore focus.
const restoreId = dialogEl.dataset.restoreFocusId;
if (restoreId) {
const el = document.getElementById(restoreId);
if (el && typeof el.focus === 'function') el.focus();
return;
}
// Fallback: focus first focusable on page body.
const bodyFocusable = getFocusableElementsWithin(document.body)[0];
if (bodyFocusable && typeof bodyFocusable.focus === 'function') bodyFocusable.focus();
}
function focusResultHeading(resultEl, headingId = null) {
if (!resultEl) return;
if (headingId) {
const el = resultEl.querySelector(`#${CSS.escape(headingId)}`);
if (el) el.focus?.();
return;
}
// If it has tabindex="-1" focusable heading use first heading.
const focusable = resultEl.querySelector('[tabindex="-1"]');
(focusable || resultEl.querySelector('h1,h2,h3') || resultEl).focus?.();
}
// Detect reduced motion preference and add a class to the body.
if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
document.body.classList.add('prefers-reduced-motion');
}
// Detect high‑contrast preference (CSS Level 4 media query) and add a class.
if (window.matchMedia('(prefers-contrast: more)').matches) {
document.body.classList.add('high-contrast');
}
// ------------------------------
// User controls: Reduced motion + Larger text
// ------------------------------
const A11Y_STORAGE_KEY = 'learnsphere_a11y';
function safeParse(json) {
try {
return JSON.parse(json);
} catch (e) {
return {};
}
}
function getStoredA11yPrefs() {
const raw = localStorage.getItem(A11Y_STORAGE_KEY);
if (!raw) return {};
const parsed = safeParse(raw);
return parsed && typeof parsed === 'object' ? parsed : {};
}
function setStoredA11yPrefs(next) {
try {
localStorage.setItem(A11Y_STORAGE_KEY, JSON.stringify(next));
} catch (e) {
// ignore
}
}
function applyLargerText(sizeKey) {
// sizeKey: 'sm' | 'lg' | 'xl'
const html = document.documentElement;
html.dataset.fontScale = sizeKey || 'lg';
// Persist
const stored = getStoredA11yPrefs();
stored.fontScale = html.dataset.fontScale;
setStoredA11yPrefs(stored);
}
function applyReducedMotion(enabled) {
const html = document.documentElement;
html.dataset.reducedMotion = enabled ? 'true' : 'false';
const stored = getStoredA11yPrefs();
stored.reducedMotion = !!enabled;
setStoredA11yPrefs(stored);
}
function initA11yControls() {
const reducedToggle = document.getElementById('reducedMotionToggle');
const fontToggle = document.getElementById('fontSizeToggle');
// If controls do not exist on this page, do nothing.
if (!reducedToggle && !fontToggle) return;
const stored = getStoredA11yPrefs();
// Reduced motion: stored override, otherwise OS preference
const osPrefersReduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
const reducedEnabled = typeof stored.reducedMotion === 'boolean' ? stored.reducedMotion : osPrefersReduced;
applyReducedMotion(reducedEnabled);
// Larger text: stored override, otherwise default scale
const fontScale = stored.fontScale || 'lg';
applyLargerText(fontScale);
// Update UI states
if (reducedToggle) {
reducedToggle.setAttribute('aria-pressed', String(reducedEnabled));
reducedToggle.textContent = reducedEnabled ? 'Reduced motion: On' : 'Reduced motion: Off';
}
if (fontToggle) {
const map = { sm: 'Small text', lg: 'Larger text', xl: 'Extra large text' };
fontToggle.setAttribute('aria-pressed', 'true');
fontToggle.textContent = map[fontScale] || 'Larger text';
}
// Events
if (reducedToggle) {
reducedToggle.addEventListener('click', () => {
const current = document.documentElement.dataset.reducedMotion === 'true';
const next = !current;
applyReducedMotion(next);
reducedToggle.setAttribute('aria-pressed', String(next));
reducedToggle.textContent = next ? 'Reduced motion: On' : 'Reduced motion: Off';
});
}
if (fontToggle) {
// cycle: lg -> xl -> sm -> lg
fontToggle.addEventListener('click', () => {
const current = document.documentElement.dataset.fontScale || 'lg';
const next = current === 'lg' ? 'xl' : current === 'xl' ? 'sm' : 'lg';
applyLargerText(next);
const map = { sm: 'Small text', lg: 'Larger text', xl: 'Extra large text' };
fontToggle.textContent = map[next] || 'Larger text';
});
}
}
// Run immediately on load (works for deferred scripts too)
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initA11yControls);
} else {
initA11yControls();
}
// Expose API globally.
window.initQuizAccessibility = initQuizAccessibility;
window.srAnnounce = announce;
window.openDialog = openDialog;
window.closeDialog = closeDialog;
})();