-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathindex.js
More file actions
419 lines (366 loc) · 13.2 KB
/
Copy pathindex.js
File metadata and controls
419 lines (366 loc) · 13.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
/* eslint-disable padded-blocks, no-multiple-empty-lines */
/* global axe */
import 'axe-core';
import { rulesArray, checksArray, standardRuleIdsArray, customRuleIdsArray } from './config/rules';
import { exclusionsArray } from './config/exclusions';
import imgAnimated from './rules/img-animated';
import { preScanAnimatedImages } from './checks/img-animated-check';
import { getPageDensity } from './helpers/density';
const SCAN_TIMEOUT_IN_SECONDS = 30;
// Hold the timeout for the scan so it can bail on long-running scans.
let tooLongTimeout;
// Landmark detection rules, sourced from edac_get_landmark_types() (PHP) via
// window.scanOptions when available — see admin/class-enqueue-admin.php and
// src/editorApp/checkPage.js. Hardcoded values here are only a fallback for
// contexts that don't localize scanOptions (e.g. standalone test runs).
const LANDMARK_TAGS = Array.isArray( window?.scanOptions?.landmarkTags ) ? window.scanOptions.landmarkTags : [ 'MAIN', 'HEADER', 'FOOTER', 'NAV', 'ASIDE' ];
const LANDMARK_ROLES = Array.isArray( window?.scanOptions?.landmarkRoles ) ? window.scanOptions.landmarkRoles : [
'main',
'navigation',
'banner',
'contentinfo',
'complementary',
];
// Conditional landmark tags/roles that only become landmarks when they have accessible names
const CONDITIONAL_LANDMARK_TAGS = Array.isArray( window?.scanOptions?.conditionalLandmarkTags ) ? window.scanOptions.conditionalLandmarkTags : [ 'SECTION', 'ARTICLE', 'FORM' ];
const CONDITIONAL_LANDMARK_ROLES = Array.isArray( window?.scanOptions?.conditionalLandmarkRoles ) ? window.scanOptions.conditionalLandmarkRoles : [ 'region', 'article', 'form' ];
function getLandmarkForSelector( selector ) {
const el = document.querySelector( selector );
if ( ! el ) {
return { type: null, selector: null };
}
let current = el;
while ( current && current !== document.body ) {
// Check unconditional landmark tags
if ( LANDMARK_TAGS.includes( current.tagName ) ) {
return { type: current.tagName.toLowerCase(), selector: getElementSelector( current ) };
}
// Check conditional landmark tags (require accessible name)
if (
CONDITIONAL_LANDMARK_TAGS.includes( current.tagName ) &&
( current.hasAttribute( 'aria-label' ) || current.hasAttribute( 'aria-labelledby' ) )
) {
return { type: current.tagName.toLowerCase(), selector: getElementSelector( current ) };
}
// Check roles
if ( current.hasAttribute( 'role' ) ) {
const role = current.getAttribute( 'role' ).toLowerCase();
// Check unconditional landmark roles
if ( LANDMARK_ROLES.includes( role ) ) {
return { type: role, selector: getElementSelector( current ) };
}
// Check conditional landmark roles (require accessible name)
if (
CONDITIONAL_LANDMARK_ROLES.includes( role ) &&
( current.hasAttribute( 'aria-label' ) || current.hasAttribute( 'aria-labelledby' ) )
) {
return { type: role, selector: getElementSelector( current ) };
}
}
current = current.parentElement;
}
return { type: null, selector: null };
}
// Helper to get a unique CSS selector for an element
function getElementSelector( element ) {
if ( ! element ) {
return null;
}
// Use ID if available (most reliable)
if ( element.id ) {
return `#${ element.id }`;
}
// For landmark elements, try to use semantic selectors first
const tagName = element.tagName.toLowerCase();
// For main element, use tag selector if it's unique
if ( tagName === 'main' ) {
const mainElements = document.querySelectorAll( 'main' );
if ( mainElements.length === 1 ) {
return 'main';
}
}
// For header/footer, check if they're direct children of body
if ( ( tagName === 'header' || tagName === 'footer' ) && element.parentElement === document.body ) {
return tagName;
}
// For nav elements, try role-based selector first
if ( tagName === 'nav' || element.getAttribute( 'role' ) === 'navigation' ) {
const navElements = document.querySelectorAll( 'nav, [role="navigation"]' );
if ( navElements.length === 1 ) {
return tagName === 'nav' ? 'nav' : '[role="navigation"]';
}
// If multiple, try to use aria-label or other identifying attributes
if ( element.hasAttribute( 'aria-label' ) ) {
const ariaLabel = element.getAttribute( 'aria-label' );
return `${ tagName === 'nav' ? 'nav' : '[role="navigation"]' }[aria-label="${ ariaLabel }"]`;
}
}
// For other landmark roles, use role selector if unique
const role = element.getAttribute( 'role' );
if ( role && LANDMARK_ROLES.includes( role ) ) {
const roleElements = document.querySelectorAll( `[role="${ role }"]` );
if ( roleElements.length === 1 ) {
return `[role="${ role }"]`;
}
// If multiple, try to use aria-label
if ( element.hasAttribute( 'aria-label' ) ) {
const ariaLabel = element.getAttribute( 'aria-label' );
return `[role="${ role }"][aria-label="${ ariaLabel }"]`;
}
}
// Fallback to path-based selector (simplified)
const path = [];
let current = element;
while ( current && current.nodeType === Node.ELEMENT_NODE && current !== document.body ) {
let selector = current.nodeName.toLowerCase();
// Add ID if available
if ( current.id ) {
selector = `#${ current.id }`;
path.unshift( selector );
break; // Stop here since ID is unique
}
// Add stable classes (avoid dynamic/generated classes)
if ( current.className ) {
const classes = current.className.trim().split( /\s+/ )
.map( ( cls ) => CSS.escape( cls ) )
.filter( ( cls ) => ! cls.match( /^(wp-|js-|css-|generated-|dynamic-)/ ) ) // Filter out common dynamic classes
.slice( 0, 2 ); // Limit to first 2 classes for stability
if ( classes.length > 0 ) {
selector += `.${ classes.join( '.' ) }`;
}
}
// Only add nth-child as last resort and only if element has no other identifying features
if ( ! current.id && ! current.className ) {
const siblingIndex = Array.from( current.parentNode.children ).indexOf( current ) + 1;
selector += `:nth-child(${ siblingIndex })`;
}
path.unshift( selector );
current = current.parentElement;
// Limit path depth to avoid overly complex selectors
if ( path.length >= 4 ) {
break;
}
}
return path.length ? path.join( ' > ' ) : null;
}
// Read the data passed from the parent document.
const body = document.querySelector( 'body' );
const iframeId = body.getAttribute( 'data-iframe-id' );
const eventName = body.getAttribute( 'data-iframe-event-name' );
const postId = body.getAttribute( 'data-iframe-post-id' );
/**
* Check if the current context the script is loaded in is a scanner iframe.
*
* @return {boolean} True if in iframe context, false otherwise.
*/
function isIframeContext() {
return !! ( body && body.hasAttribute( 'data-iframe-id' ) && body.hasAttribute( 'data-iframe-event-name' ) );
}
/**
* Get the iframe options from the body attributes/
*
* @return {Object} {{configOptions: {}, runOptions: {}, iframeId: string | Attribute, eventName: string | Attribute, postId: string | Attribute}}
*/
function getIframeOptions() {
return {
configOptions: {},
runOptions: {},
iframeId: body.getAttribute( 'data-iframe-id' ),
eventName: body.getAttribute( 'data-iframe-event-name' ),
postId: body.getAttribute( 'data-iframe-post-id' ),
};
}
const scan = async (
options = { configOptions: {}, runOptions: {} }
) => {
const context = { exclude: exclusionsArray };
const defaults = {
configOptions: {
reporter: 'raw',
rules: rulesArray,
checks: checksArray,
iframes: false,
},
resultTypes: [ 'violations', 'incomplete' ],
runOptions: {
runOnly: {
type: 'rule',
values: [ ...standardRuleIdsArray, ...customRuleIdsArray ],
},
},
};
const configOptions = Object.assign( defaults.configOptions, options.configOptions );
axe.configure( configOptions );
const runOptions = Object.assign( defaults.runOptions, options.runOptions );
// Axe core checks can't run async and to find animated gifs we need to use fetch. So this
// function will do that fetching and cache the results so they are available when the
// img_animated rule runs.
// NOTE: in future we should flag this and run it only if the img_animated rule is enabled.
if ( runOptions?.runOnly?.values?.includes( imgAnimated.id ) ) {
await preScanAnimatedImages();
}
return await axe.run( context, runOptions )
.then( ( rules ) => {
const violations = [];
rules.forEach( ( item ) => {
//Build an array of the dom selectors and ruleIDs for violations/failed tests
item.violations.forEach( ( violation ) => {
if ( violation.result === 'failed' ) {
violations.push( processViolation( violation, item ) );
}
} );
// Handle incomplete results for form-field-multiple-labels only.
if ( item.id === 'form-field-multiple-labels' ) { // Allow incomplete results for this rule.
item.incomplete.forEach( ( incompleteItem ) => {
violations.push( processViolation( incompleteItem, item ) );
} );
}
} );
const rulesMin = rules.map( ( r ) => {
return {
id: r.id,
description: r.description,
help: r.help,
impact: r.impact,
tags: r.tags,
};
} );
//Sort the violations by order they appear in the document
violations.sort( function( a, b ) {
a = document.querySelector( a.selector );
b = document.querySelector( b.selector );
if ( a === b ) {
return 0;
}
/* eslint-disable no-bitwise */
if ( a.compareDocumentPosition( b ) & 2 ) {
// b comes before a
return 1;
}
return -1;
} );
return { rules, rulesMin, violations };
} ).catch( ( err ) => {
throw err;
} );
};
/**
* Dispatch the done event to the parent window.
*
* @param {Array} violations The violations found during the scan.
* @param {Array} errorMsgs Any error messages that occurred during the scan.
* @param {string} error The error message if an error occurred during scan cleanup.
*/
function dispatchDoneEvent( violations, errorMsgs, error ) {
const [ elementCount, contentLength ] = getPageDensity( body );
const customEvent = new CustomEvent( eventName, {
detail: {
iframeId,
postId,
violations,
errorMsgs,
error,
densityMetrics: {
elementCount,
contentLength,
},
},
bubbles: false,
} );
top.dispatchEvent( customEvent );
}
// eslint-disable-next-line no-unused-vars
const onDone = ( violations = [], errorMsgs = [], error = false ) => {
// cleanup the timeout.
clearTimeout( tooLongTimeout );
// cleanup axe.
if ( typeof ( axe.cleanup ) !== 'undefined' ) {
axe.cleanup(
function() {
axe.teardown();
axe = null;
dispatchDoneEvent( violations, errorMsgs, '' );
},
function() {
axe.teardown();
axe = null;
errorMsgs.push( '***** axe.cleanup() failed.' );
dispatchDoneEvent( violations, errorMsgs, 'cleanup-failed' );
}
);
} else {
errorMsgs.push( '***** axe.cleanup() does not exist.' );
axe = null;
dispatchDoneEvent( violations, errorMsgs, 'cleanup-not-exists' );
}
};
/**
* Attach an axe runner to the window object to allow for running the scan from
* the active document.
*
* @param {Object} options Options for the accessibility scan.
* @return {Promise<Object>} Promise resolving to the scan result.
*/
window.runAccessibilityScan = async function( options = {} ) {
return scan( options )
.then( ( result ) => {
if ( typeof options.onComplete === 'function' ) {
options.onComplete( result );
}
return result;
} )
.catch( ( err ) => {
if ( typeof options.onComplete === 'function' ) {
options.onComplete( null, err );
}
throw err;
} );
};
// Auto-run scan and dispatch event to parent frame if in iframe context
if ( isIframeContext() ) {
const iframeOptions = getIframeOptions();
tooLongTimeout = setTimeout( () => {
dispatchDoneEvent( [], [ 'Scan timed out' ], 'timeout' );
}, SCAN_TIMEOUT_IN_SECONDS * 1000 );
scan( iframeOptions )
.then( ( result ) => onDone( result.violations, [], null ) )
.catch( ( err ) => onDone( [], [ err.message || 'Unknown error' ], err.message ) );
}
// Helper to process a violation and return the formatted object
function processViolation( violation, item ) {
// Note that this is an array, generally with one item, but can be more.
const selector = violation.node.selector;
const landmark = getLandmarkForSelector( selector );
const ancestry = violation.node.ancestry || [];
const xpath = violation.node.xpath || [];
const html = document.querySelector( selector )?.outerHTML;
const result = {
selector,
ancestry,
xpath,
html,
ruleId: item.id,
impact: item.impact,
tags: item.tags,
landmark: landmark.type,
landmarkSelector: landmark.selector,
};
// item.id matches the plugin rule ID defined in src/pageScanner/rules/color-contrast-failure.js
if ( item.id === 'color_contrast_failure' ) {
const check = violation.any?.find( ( c ) => c.id === 'color-contrast' );
if ( check?.data ) {
result.extraData = {
fgColor: check.data.fgColor,
bgColor: check.data.bgColor,
contrastRatio: check.data.contrastRatio,
expectedContrastRatio: check.data.expectedContrastRatio,
fontSize: check.data.fontSize,
fontWeight: check.data.fontWeight,
};
} else if ( check ) {
// eslint-disable-next-line no-console
console.warn( '[accessibility-checker] color-contrast check returned no data for node:', violation.node.selector );
}
}
return result;
}