📦 EqualifyEverything / benchmarks-ai-alt

📄 main.js · 366 lines
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// Accessibility Image Validator

(function () {
    'use strict';

    const GITHUB_ISSUE_BASE =
        'https://github.com/EqualifyEverything/benchmarks-ai-alt/issues/new';

    // State
    let sessionId = null;
    let sessionActive = false;
    let currentIndex = 0;
    let results = [];
    let corpus = [];
    let pendingDecision = null; // 'accepted' or 'rejected'

    // DOM refs
    const els = {};

    function init() {
        // Cache elements
        els.startBtn = document.getElementById('start-session');
        els.endBtn = document.getElementById('end-session');
        els.sessionStatus = document.getElementById('session-status');
        els.sessionId = document.getElementById('session-id-display');
        els.progressCount = document.getElementById('progress-count');
        els.totalCount = document.getElementById('total-count');
        els.progressBar = document.getElementById('progress-bar');
        els.progressFill = document.getElementById('progress-fill');
        els.card = document.getElementById('validation-card');
        els.image = document.getElementById('current-image');
        els.placeholder = document.getElementById('image-placeholder');
        els.altText = document.getElementById('current-alt');
        els.altSource = document.getElementById('current-alt-source');
        els.acceptBtn = document.getElementById('accept-btn');
        els.rejectBtn = document.getElementById('reject-btn');
        els.reasonGroup = document.getElementById('reason-group');
        els.reasonInput = document.getElementById('reason-input');
        els.reasonLabel = document.getElementById('reason-label');
        els.reasonHint = document.getElementById('reason-hint');
        els.submitBtn = document.getElementById('submit-btn');
        els.cancelBtn = document.getElementById('cancel-btn');
        els.results = document.getElementById('results');
        els.resultsSummary = document.getElementById('results-summary');
        els.downloadBtn = document.getElementById('download-results');
        els.issueLink = document.getElementById('github-issue-link');
        els.contextPage = document.getElementById('context-page');
        els.contextRole = document.getElementById('context-role');
        els.contextAlt = document.getElementById('context-alt');
        els.contextSurrounding = document.getElementById('context-surrounding');

        // Events
        els.startBtn.addEventListener('click', startSession);
        els.endBtn.addEventListener('click', endSession);
        els.acceptBtn.addEventListener('click', function () { choose('accepted'); });
        els.rejectBtn.addEventListener('click', function () { choose('rejected'); });
        els.submitBtn.addEventListener('click', submitReason);
        els.cancelBtn.addEventListener('click', cancelReason);
        els.downloadBtn.addEventListener('click', downloadResults);

        // Keyboard: Enter in textarea submits
        els.reasonInput.addEventListener('keydown', function (e) {
            if (e.key === 'Enter' && e.ctrlKey) {
                submitReason();
            }
        });

        loadCorpus();
    }

    // Data loading
    async function loadCorpus() {
        try {
            let response = await fetch('./functional-images.jsonl');
            if (!response.ok) {
                response = await fetch(
                    '../projects/corpus-construction/corpus/functional-images.jsonl'
                );
            }
            const text = await response.text();
            corpus = text.trim().split('\n').map(function (line) {
                try { return JSON.parse(line); }
                catch (e) { return null; }
            }).filter(Boolean);
        } catch (err) {
            console.error('Failed to load corpus:', err);
        }
    }

    // Session management
    function startSession() {
        if (corpus.length === 0) {
            alert('No corpus data loaded. Check the data file.');
            return;
        }

        sessionId = 'v-' + Date.now().toString(36) + '-' +
            Math.random().toString(36).substr(2, 5);
        sessionActive = true;
        currentIndex = 0;
        results = [];
        pendingDecision = null;

        els.sessionId.textContent = sessionId;
        els.totalCount.textContent = corpus.length;
        updateProgress();

        show(els.sessionStatus);
        show(els.card);
        hide(els.results);

        els.startBtn.disabled = true;
        els.startBtn.setAttribute('aria-disabled', 'true');
        els.endBtn.disabled = false;
        els.endBtn.removeAttribute('aria-disabled');

        loadItem();
    }

    function endSession() {
        sessionActive = false;
        pendingDecision = null;

        hide(els.card);
        hide(els.sessionStatus);
        hide(els.reasonGroup);
        show(els.results);

        els.startBtn.disabled = false;
        els.startBtn.removeAttribute('aria-disabled');
        els.endBtn.disabled = true;
        els.endBtn.setAttribute('aria-disabled', 'true');

        // Summary
        var accepted = results.filter(function (r) { return r.status === 'accepted'; }).length;
        var rejected = results.filter(function (r) { return r.status === 'rejected'; }).length;
        var total = corpus.length;
        var reviewed = results.length;

        els.resultsSummary.textContent =
            'You reviewed ' + reviewed + ' of ' + total + ' items. ' +
            accepted + ' accepted, ' + rejected + ' rejected.';

        // Update issue link
        var params = new URLSearchParams({
            template: 'validation-report.md',
            labels: 'validation report',
            title: '[Validation Report] ' + sessionId
        });
        els.issueLink.href = GITHUB_ISSUE_BASE + '?' + params.toString();
    }

    // The text under review, in the order a browser resolves it.
    function announcedName(item) {
        if (typeof item.accessible_name === 'string'
            && item.accessible_name !== '') {
            return item.accessible_name;
        }
        return item.observed_alt || '';
    }

    var SOURCE_LABELS = {
        'alt': "the image's alt attribute",
        'aria-label': 'an aria-label',
        'aria-labelledby': 'an aria-labelledby reference',
        'title': 'a title attribute',
        'svg-title': 'a title inside the SVG',
        'control-text': "the link or button's own text"
    };

    function sourceLabel(item) {
        return SOURCE_LABELS[item.accessible_name_source]
            || 'text in the markup';
    }

    // Whether the image itself carries alt text, separately from whatever the
    // surrounding control contributes.
    function altAttributeLabel(item) {
        if (item.observed_alt === null || item.observed_alt === undefined) {
            return '(no alt attribute on the image)';
        }
        if (item.observed_alt === '') {
            return '(alt="", deliberately empty)';
        }
        return item.observed_alt;
    }

    // Validation flow
    function loadItem() {
        if (currentIndex >= corpus.length) {
            endSession();
            return;
        }

        var item = corpus[currentIndex];

        // Image
        var imageSrc = null;
        if (item.image_file) {
            // Prefer local downloaded image
            imageSrc = '../corpus-construction/' + item.image_file;
        } else if (item.image_url) {
            imageSrc = item.image_url;
        }

        // What a screen reader actually announces. For many items the text
        // lives on the link or button rather than on the image itself, so
        // observed_alt alone would show nothing to judge.
        var announced = announcedName(item);

        if (imageSrc) {
            els.image.src = imageSrc;
            els.image.alt = announced;
            els.image.style.display = '';
            hide(els.placeholder);
            // Remove any previously rendered inline SVG
            var oldSvg = document.querySelector('.card-image .inline-svg');
            if (oldSvg) oldSvg.remove();
        } else if (item.element_html && item.element_html.indexOf('<svg') !== -1) {
            // Render the inline SVG from element_html
            els.image.style.display = 'none';
            hide(els.placeholder);
            var oldSvg = document.querySelector('.card-image .inline-svg');
            if (oldSvg) oldSvg.remove();
            var svgMatch = item.element_html.match(/<svg[\s\S]*<\/svg>/);
            if (svgMatch) {
                var wrapper = document.createElement('div');
                wrapper.className = 'inline-svg';
                wrapper.setAttribute('role', 'img');
                wrapper.setAttribute('aria-label', announced);
                wrapper.innerHTML = svgMatch[0];
                document.querySelector('.card-image').appendChild(wrapper);
            }
        } else {
            els.image.src = '';
            els.image.alt = '';
            els.image.style.display = 'none';
            hide(els.placeholder);
            var oldSvg = document.querySelector('.card-image .inline-svg');
            if (oldSvg) oldSvg.remove();
            show(els.placeholder);
        }

        // Alt text display
        els.altText.textContent = announced || '(no text at all)';
        if (els.altSource) {
            els.altSource.textContent = announced
                ? 'Written in the page as ' + sourceLabel(item) + '.'
                : '';
        }

        // Context
        els.contextPage.textContent = item.page_url || 'Unknown';
        els.contextRole.textContent = item.element_role || 'Unknown';
        if (els.contextAlt) {
            els.contextAlt.textContent = altAttributeLabel(item);
        }
        els.contextSurrounding.textContent =
            item.surrounding_text || '(none)';

        // Reset decision UI
        resetDecisionUI();
        updateProgress();
    }

    function choose(decision) {
        pendingDecision = decision;

        // Update label based on decision
        if (decision === 'accepted') {
            els.reasonLabel.textContent = 'Reason for accepting';
        } else {
            els.reasonLabel.textContent = 'Reason for rejecting';
        }
        els.reasonHint.textContent = 'Optional.';

        // Show reason group
        show(els.reasonGroup);

        // Disable decision buttons while entering reason
        els.acceptBtn.disabled = true;
        els.rejectBtn.disabled = true;

        // Focus the textarea
        els.reasonInput.focus();
    }

    function submitReason() {
        var reason = els.reasonInput.value.trim();

        results.push({
            id: corpus[currentIndex].id,
            status: pendingDecision,
            reason: reason || null,
            timestamp: new Date().toISOString()
        });

        // Advance
        pendingDecision = null;
        els.reasonInput.value = '';
        currentIndex++;
        loadItem();
    }

    function cancelReason() {
        pendingDecision = null;
        els.reasonInput.value = '';
        els.reasonInput.removeAttribute('aria-invalid');
        resetDecisionUI();
        els.acceptBtn.focus();
    }

    function resetDecisionUI() {
        hide(els.reasonGroup);
        els.acceptBtn.disabled = false;
        els.rejectBtn.disabled = false;
    }

    // Progress
    function updateProgress() {
        var reviewed = Math.min(currentIndex, corpus.length);
        els.progressCount.textContent = reviewed;
        var pct = corpus.length > 0
            ? Math.round((reviewed / corpus.length) * 100)
            : 0;
        els.progressFill.style.width = pct + '%';
        els.progressBar.setAttribute('aria-valuenow', pct);
    }

    // Results export
    function downloadResults() {
        var data = {
            session_id: sessionId,
            timestamp: new Date().toISOString(),
            corpus_size: corpus.length,
            reviewed: results.length,
            accepted: results.filter(function (r) { return r.status === 'accepted'; }).length,
            rejected: results.filter(function (r) { return r.status === 'rejected'; }).length,
            results: results
        };

        var json = JSON.stringify(data, null, 2);
        var blob = new Blob([json], { type: 'application/json' });
        var url = URL.createObjectURL(blob);

        var a = document.createElement('a');
        a.href = url;
        a.download = 'validation-' + sessionId + '.json';
        a.click();
        URL.revokeObjectURL(url);
    }

    // Helpers
    function show(el) {
        if (typeof el === 'string') el = document.getElementById(el);
        el.classList.remove('hidden');
    }

    function hide(el) {
        if (typeof el === 'string') el = document.getElementById(el);
        el.classList.add('hidden');
    }

    // Boot
    document.addEventListener('DOMContentLoaded', init);
})();