File size: 7,430 Bytes
bc2f725
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**

 * ============================================

 * ACCESSIBILITY ENHANCEMENTS

 * Keyboard navigation, focus management, announcements

 * ============================================

 */

class AccessibilityManager {
    constructor() {
        this.init();
    }

    init() {
        this.detectInputMethod();
        this.setupKeyboardNavigation();
        this.setupAnnouncements();
        this.setupFocusManagement();
        console.log('[A11y] Accessibility manager initialized');
    }

    /**

     * Detect if user is using keyboard or mouse

     */
    detectInputMethod() {
        // Track mouse usage
        document.addEventListener('mousedown', () => {
            document.body.classList.add('using-mouse');
        });

        // Track keyboard usage
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Tab') {
                document.body.classList.remove('using-mouse');
            }
        });
    }

    /**

     * Setup keyboard navigation shortcuts

     */
    setupKeyboardNavigation() {
        document.addEventListener('keydown', (e) => {
            // Ctrl/Cmd + K: Focus search
            if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
                e.preventDefault();
                const searchInput = document.querySelector('[role="searchbox"], input[type="search"]');
                if (searchInput) searchInput.focus();
            }

            // Escape: Close modals/dropdowns
            if (e.key === 'Escape') {
                this.closeAllModals();
                this.closeAllDropdowns();
            }

            // Arrow keys for tab navigation
            if (e.target.getAttribute('role') === 'tab') {
                this.handleTabNavigation(e);
            }
        });
    }

    /**

     * Handle tab navigation with arrow keys

     */
    handleTabNavigation(e) {
        const tabs = Array.from(document.querySelectorAll('[role="tab"]'));
        const currentIndex = tabs.indexOf(e.target);

        let nextIndex;
        if (e.key === 'ArrowRight' || e.key === 'ArrowDown') {
            nextIndex = (currentIndex + 1) % tabs.length;
        } else if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') {
            nextIndex = (currentIndex - 1 + tabs.length) % tabs.length;
        }

        if (nextIndex !== undefined) {
            e.preventDefault();
            tabs[nextIndex].focus();
            tabs[nextIndex].click();
        }
    }

    /**

     * Setup screen reader announcements

     */
    setupAnnouncements() {
        // Create announcement regions if they don't exist
        if (!document.getElementById('aria-live-polite')) {
            const polite = document.createElement('div');
            polite.id = 'aria-live-polite';
            polite.setAttribute('aria-live', 'polite');
            polite.setAttribute('aria-atomic', 'true');
            polite.className = 'sr-only';
            document.body.appendChild(polite);
        }

        if (!document.getElementById('aria-live-assertive')) {
            const assertive = document.createElement('div');
            assertive.id = 'aria-live-assertive';
            assertive.setAttribute('aria-live', 'assertive');
            assertive.setAttribute('aria-atomic', 'true');
            assertive.className = 'sr-only';
            document.body.appendChild(assertive);
        }
    }

    /**

     * Announce message to screen readers

     */
    announce(message, priority = 'polite') {
        const region = document.getElementById(`aria-live-${priority}`);
        if (!region) return;

        // Clear and set new message
        region.textContent = '';
        setTimeout(() => {
            region.textContent = message;
        }, 100);
    }

    /**

     * Setup focus management

     */
    setupFocusManagement() {
        // Trap focus in modals
        document.addEventListener('focusin', (e) => {
            const modal = document.querySelector('.modal-backdrop');
            if (!modal) return;

            const focusableElements = modal.querySelectorAll(
                'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
            );

            if (focusableElements.length === 0) return;

            const firstElement = focusableElements[0];
            const lastElement = focusableElements[focusableElements.length - 1];

            if (!modal.contains(e.target)) {
                firstElement.focus();
            }
        });

        // Handle Tab key in modals
        document.addEventListener('keydown', (e) => {
            if (e.key !== 'Tab') return;

            const modal = document.querySelector('.modal-backdrop');
            if (!modal) return;

            const focusableElements = modal.querySelectorAll(
                'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
            );

            if (focusableElements.length === 0) return;

            const firstElement = focusableElements[0];
            const lastElement = focusableElements[focusableElements.length - 1];

            if (e.shiftKey) {
                if (document.activeElement === firstElement) {
                    e.preventDefault();
                    lastElement.focus();
                }
            } else {
                if (document.activeElement === lastElement) {
                    e.preventDefault();
                    firstElement.focus();
                }
            }
        });
    }

    /**

     * Close all modals

     */
    closeAllModals() {
        document.querySelectorAll('.modal-backdrop').forEach(modal => {
            modal.remove();
        });
    }

    /**

     * Close all dropdowns

     */
    closeAllDropdowns() {
        document.querySelectorAll('[aria-expanded="true"]').forEach(element => {
            element.setAttribute('aria-expanded', 'false');
        });
    }

    /**

     * Set page title (announces to screen readers)

     */
    setPageTitle(title) {
        document.title = title;
        this.announce(`Page: ${title}`);
    }

    /**

     * Add skip link

     */
    addSkipLink() {
        const skipLink = document.createElement('a');
        skipLink.href = '#main-content';
        skipLink.className = 'skip-link';
        skipLink.textContent = 'Skip to main content';
        document.body.insertBefore(skipLink, document.body.firstChild);

        // Add id to main content if it doesn't exist
        const mainContent = document.querySelector('.main-content, main');
        if (mainContent && !mainContent.id) {
            mainContent.id = 'main-content';
        }
    }

    /**

     * Mark element as loading

     */
    markAsLoading(element, label = 'Loading') {
        element.setAttribute('aria-busy', 'true');
        element.setAttribute('aria-label', label);
    }

    /**

     * Unmark element as loading

     */
    unmarkAsLoading(element) {
        element.setAttribute('aria-busy', 'false');
        element.removeAttribute('aria-label');
    }
}

// Export singleton
window.a11y = new AccessibilityManager();

// Utility functions
window.announce = (message, priority) => window.a11y.announce(message, priority);