forked from dequelabs/axe-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrule.js
635 lines (544 loc) · 16.3 KB
/
rule.js
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
/*global SupportError */
import { createExecutionContext } from './check';
import RuleResult from './rule-result';
import {
performanceTimer,
getAllChecks,
getCheckOption,
queue,
DqElement,
select,
assert
} from '../utils';
import { isVisibleToScreenReaders } from '../../commons/dom';
import constants from '../constants';
import log from '../log';
export default function Rule(spec, parentAudit) {
this._audit = parentAudit;
/**
* The code, or string ID of the rule
* @type {String}
*/
this.id = spec.id;
/**
* Selector that this rule applies to
* @type {String}
*/
this.selector = spec.selector || '*';
/**
* Impact of the rule (optional)
* @type {"minor" | "moderate" | "serious" | "critical"}
*/
if (spec.impact) {
assert(
constants.impact.includes(spec.impact),
`Impact ${spec.impact} is not a valid impact`
);
this.impact = spec.impact;
}
/**
* Whether to exclude hiddden elements form analysis. Defaults to true.
* @type {Boolean}
*/
this.excludeHidden =
typeof spec.excludeHidden === 'boolean' ? spec.excludeHidden : true;
/**
* Flag to enable or disable rule
* @type {Boolean}
*/
this.enabled = typeof spec.enabled === 'boolean' ? spec.enabled : true;
/**
* Denotes if the rule should be run if Context is not an entire page AND whether
* the Rule should be satisified regardless of Node
* @type {Boolean}
*/
this.pageLevel = typeof spec.pageLevel === 'boolean' ? spec.pageLevel : false;
/**
* Flag to force the rule to return as needs review rather than a violation if any of the checks fail.
* @type {Boolean}
*/
this.reviewOnFail =
typeof spec.reviewOnFail === 'boolean' ? spec.reviewOnFail : false;
/**
* Checks that any may return true to satisfy rule
* @type {Array}
*/
this.any = spec.any || [];
/**
* Checks that must all return true to satisfy rule
* @type {Array}
*/
this.all = spec.all || [];
/**
* Checks that none may return true to satisfy rule
* @type {Array}
*/
this.none = spec.none || [];
/**
* Tags associated to this rule
* @type {Array}
*/
this.tags = spec.tags || [];
/**
* Preload necessary for this rule
*/
this.preload = spec.preload ? true : false;
/**
* IDs of ACT rules the axe-core rule maps to
* @type {Array|undefined}
*/
this.actIds = spec.actIds;
if (spec.matches) {
/**
* Optional function to test if rule should be run against a node, overrides Rule#matches
* @type {Function}
*/
this.matches = createExecutionContext(spec.matches);
}
}
/**
* Optionally test each node against a `matches` function to determine if the rule should run against
* a given node. Defaults to `true`.
* @return {Boolean} Whether the rule should run
*/
Rule.prototype.matches = function matches() {
return true;
};
/**
* Selects `HTMLElement`s based on configured selector
* @param {Context} context The resolved Context object
* @param {Mixed} options Options specific to this rule
* @return {Array} All matching `HTMLElement`s
*/
Rule.prototype.gather = function gather(context, options = {}) {
const markStart = 'mark_gather_start_' + this.id;
const markEnd = 'mark_gather_end_' + this.id;
const markHiddenStart = 'mark_isVisibleToScreenReaders_start_' + this.id;
const markHiddenEnd = 'mark_isVisibleToScreenReaders_end_' + this.id;
if (options.performanceTimer) {
performanceTimer.mark(markStart);
}
let elements = select(this.selector, context);
if (this.excludeHidden) {
if (options.performanceTimer) {
performanceTimer.mark(markHiddenStart);
}
elements = elements.filter(element => {
return isVisibleToScreenReaders(element);
});
if (options.performanceTimer) {
performanceTimer.mark(markHiddenEnd);
performanceTimer.measure(
'rule_' + this.id + '#gather_axe.utils.isVisibleToScreenReaders',
markHiddenStart,
markHiddenEnd
);
}
}
if (options.performanceTimer) {
performanceTimer.mark(markEnd);
performanceTimer.measure('rule_' + this.id + '#gather', markStart, markEnd);
}
return elements;
};
Rule.prototype.runChecks = function runChecks(
type,
node,
options,
context,
resolve,
reject
) {
const self = this;
const checkQueue = queue();
this[type].forEach(c => {
const check = self._audit.checks[c.id || c];
const option = getCheckOption(check, self.id, options);
checkQueue.defer((res, rej) => {
check.run(node, option, context, res, rej);
});
});
checkQueue
.then(results => {
results = results.filter(check => check);
resolve({ type: type, results: results });
})
.catch(reject);
};
/**
* Run a check for a rule synchronously.
*/
Rule.prototype.runChecksSync = function runChecksSync(
type,
node,
options,
context
) {
const self = this;
let results = [];
this[type].forEach(c => {
const check = self._audit.checks[c.id || c];
const option = getCheckOption(check, self.id, options);
results.push(check.runSync(node, option, context));
});
results = results.filter(check => check);
return { type: type, results: results };
};
/**
* Runs the Rule's `evaluate` function
* @param {Context} context The resolved Context object
* @param {Mixed} options Options specific to this rule
* @param {Function} callback Function to call when evaluate is complete; receives a RuleResult instance
*/
Rule.prototype.run = function run(context, options = {}, resolve, reject) {
if (options.performanceTimer) {
this._trackPerformance();
}
const q = queue();
const ruleResult = new RuleResult(this);
let nodes;
try {
// Matches throws an error when it lacks support for document methods
nodes = this.gatherAndMatchNodes(context, options);
} catch (error) {
// Exit the rule execution if matches fails
reject(new SupportError({ cause: error, ruleId: this.id }));
return;
}
if (options.performanceTimer) {
this._logGatherPerformance(nodes);
}
nodes.forEach(node => {
q.defer((resolveNode, rejectNode) => {
const checkQueue = queue();
['any', 'all', 'none'].forEach(type => {
checkQueue.defer((res, rej) => {
this.runChecks(type, node, options, context, res, rej);
});
});
checkQueue
.then(results => {
const result = getResult(results);
if (result) {
result.node = new DqElement(node);
ruleResult.nodes.push(result);
// mark rule as incomplete rather than failure for rules with reviewOnFail
if (this.reviewOnFail) {
['any', 'all'].forEach(type => {
result[type].forEach(checkResult => {
if (checkResult.result === false) {
checkResult.result = undefined;
}
});
});
result.none.forEach(checkResult => {
if (checkResult.result === true) {
checkResult.result = undefined;
}
});
}
}
resolveNode();
})
.catch(err => rejectNode(err));
});
});
// Defer the rule's execution to prevent "unresponsive script" warnings.
// See https://github.com/dequelabs/axe-core/pull/1172 for discussion and details.
q.defer(res => setTimeout(res, 0));
if (options.performanceTimer) {
this._logRulePerformance();
}
q.then(() => resolve(ruleResult)).catch(error => reject(error));
};
/**
* Runs the Rule's `evaluate` function synchronously
* @param {Context} context The resolved Context object
* @param {Mixed} options Options specific to this rule
*/
Rule.prototype.runSync = function runSync(context, options = {}) {
if (options.performanceTimer) {
this._trackPerformance();
}
const ruleResult = new RuleResult(this);
let nodes;
try {
nodes = this.gatherAndMatchNodes(context, options);
} catch (error) {
// Exit the rule execution if matches fails
throw new SupportError({ cause: error, ruleId: this.id });
}
if (options.performanceTimer) {
this._logGatherPerformance(nodes);
}
nodes.forEach(node => {
const results = [];
['any', 'all', 'none'].forEach(type => {
results.push(this.runChecksSync(type, node, options, context));
});
const result = getResult(results);
if (result) {
result.node = node.actualNode ? new DqElement(node) : null;
ruleResult.nodes.push(result);
// mark rule as incomplete rather than failure for rules with reviewOnFail
if (this.reviewOnFail) {
['any', 'all'].forEach(type => {
result[type].forEach(checkResult => {
if (checkResult.result === false) {
checkResult.result = undefined;
}
});
});
result.none.forEach(checkResult => {
if (checkResult.result === true) {
checkResult.result = undefined;
}
});
}
}
});
if (options.performanceTimer) {
this._logRulePerformance();
}
return ruleResult;
};
/**
* Add performance tracking properties to the rule
* @private
*/
Rule.prototype._trackPerformance = function _trackPerformance() {
this._markStart = 'mark_rule_start_' + this.id;
this._markEnd = 'mark_rule_end_' + this.id;
this._markChecksStart = 'mark_runchecks_start_' + this.id;
this._markChecksEnd = 'mark_runchecks_end_' + this.id;
};
/**
* Log performance of rule.gather
* @private
* @param {Rule} rule The rule to log
* @param {Array} nodes Result of rule.gather
*/
Rule.prototype._logGatherPerformance = function _logGatherPerformance(nodes) {
log('gather (', nodes.length, '):', performanceTimer.timeElapsed() + 'ms');
performanceTimer.mark(this._markChecksStart);
};
/**
* Log performance of the rule
* @private
* @param {Rule} rule The rule to log
*/
Rule.prototype._logRulePerformance = function _logRulePerformance() {
performanceTimer.mark(this._markChecksEnd);
performanceTimer.mark(this._markEnd);
performanceTimer.measure(
'runchecks_' + this.id,
this._markChecksStart,
this._markChecksEnd
);
performanceTimer.measure('rule_' + this.id, this._markStart, this._markEnd);
};
/**
* Process the results of each check and return the result if a check
* has a result
* @private
* @param {Array} results Array of each check result
* @returns {Object|null}
*/
function getResult(results) {
if (results.length) {
let hasResults = false;
const result = {};
results.forEach(r => {
const res = r.results.filter(_result => _result);
result[r.type] = res;
if (res.length) {
hasResults = true;
}
});
if (hasResults) {
return result;
}
return null;
}
}
/**
* Selects `HTMLElement`s based on configured selector and filters them based on
* the rules matches function
* @param {Rule} rule The rule to check for after checks
* @param {Context} context The resolved Context object
* @param {Mixed} options Options specific to this rule
* @return {Array} All matching `HTMLElement`s
*/
Rule.prototype.gatherAndMatchNodes = function gatherAndMatchNodes(
context,
options
) {
const markMatchesStart = 'mark_matches_start_' + this.id;
const markMatchesEnd = 'mark_matches_end_' + this.id;
let nodes = this.gather(context, options);
if (options.performanceTimer) {
performanceTimer.mark(markMatchesStart);
}
nodes = nodes.filter(node => this.matches(node.actualNode, node, context));
if (options.performanceTimer) {
performanceTimer.mark(markMatchesEnd);
performanceTimer.measure(
'rule_' + this.id + '#matches',
markMatchesStart,
markMatchesEnd
);
}
return nodes;
};
/**
* Iterates the rule's Checks looking for ones that have an after function
* @private
* @param {Rule} rule The rule to check for after checks
* @return {Array} Checks that have an after function
*/
function findAfterChecks(rule) {
return getAllChecks(rule)
.map(c => {
const check = rule._audit.checks[c.id || c];
return check && typeof check.after === 'function' ? check : null;
})
.filter(Boolean);
}
/**
* Finds and collates all results for a given Check on a specific Rule
* @private
* @param {Array} nodes RuleResult#nodes; array of 'detail' objects
* @param {String} checkID The ID of the Check to find
* @return {Array} Matching CheckResults
*/
function findCheckResults(nodes, checkID) {
const checkResults = [];
nodes.forEach(nodeResult => {
const checks = getAllChecks(nodeResult);
checks.forEach(checkResult => {
if (checkResult.id === checkID) {
checkResult.node = nodeResult.node;
checkResults.push(checkResult);
}
});
});
return checkResults;
}
function filterChecks(checks) {
return checks.filter(check => {
return check.filtered !== true;
});
}
function sanitizeNodes(result) {
const checkTypes = ['any', 'all', 'none'];
let nodes = result.nodes.filter(detail => {
let length = 0;
checkTypes.forEach(type => {
detail[type] = filterChecks(detail[type]);
length += detail[type].length;
});
return length > 0;
});
if (result.pageLevel && nodes.length) {
nodes = [
nodes.reduce((a, b) => {
if (a) {
checkTypes.forEach(type => {
a[type].push.apply(a[type], b[type]);
});
return a;
}
})
];
}
return nodes;
}
/**
* Runs all of the Rule's Check#after methods
* @param {RuleResult} result The "pre-after" RuleResult
* @param {Mixed} options Options specific to the rule
* @return {RuleResult} The RuleResult as filtered by after functions
*/
Rule.prototype.after = function after(result, options) {
const afterChecks = findAfterChecks(this);
const ruleID = this.id;
afterChecks.forEach(check => {
const beforeResults = findCheckResults(result.nodes, check.id);
const checkOption = getCheckOption(check, ruleID, options);
const afterResults = check.after(beforeResults, checkOption.options);
if (this.reviewOnFail) {
afterResults.forEach(checkResult => {
const changeAnyAllResults =
(this.any.includes(checkResult.id) ||
this.all.includes(checkResult.id)) &&
checkResult.result === false;
const changeNoneResult =
this.none.includes(checkResult.id) && checkResult.result === true;
if (changeAnyAllResults || changeNoneResult) {
checkResult.result = undefined;
}
});
}
beforeResults.forEach(item => {
// only add the node property for the check.after so we can
// look at which iframe a check result came from, but we don't
// want it for the final results object
delete item.node;
if (afterResults.indexOf(item) === -1) {
item.filtered = true;
}
});
});
result.nodes = sanitizeNodes(result);
return result;
};
/**
* Reconfigure a rule after it has been added
* @param {Object} spec - the attributes to be reconfigured
*/
Rule.prototype.configure = function configure(spec) {
/*eslint no-eval:0 */
if (spec.hasOwnProperty('selector')) {
this.selector = spec.selector;
}
if (spec.hasOwnProperty('excludeHidden')) {
this.excludeHidden =
typeof spec.excludeHidden === 'boolean' ? spec.excludeHidden : true;
}
if (spec.hasOwnProperty('enabled')) {
this.enabled = typeof spec.enabled === 'boolean' ? spec.enabled : true;
}
if (spec.hasOwnProperty('pageLevel')) {
this.pageLevel =
typeof spec.pageLevel === 'boolean' ? spec.pageLevel : false;
}
if (spec.hasOwnProperty('reviewOnFail')) {
this.reviewOnFail =
typeof spec.reviewOnFail === 'boolean' ? spec.reviewOnFail : false;
}
if (spec.hasOwnProperty('any')) {
this.any = spec.any;
}
if (spec.hasOwnProperty('all')) {
this.all = spec.all;
}
if (spec.hasOwnProperty('none')) {
this.none = spec.none;
}
if (spec.hasOwnProperty('tags')) {
this.tags = spec.tags;
}
if (spec.hasOwnProperty('actIds')) {
this.actIds = spec.actIds;
}
if (spec.hasOwnProperty('matches')) {
this.matches = createExecutionContext(spec.matches);
}
if (spec.impact) {
assert(
constants.impact.includes(spec.impact),
`Impact ${spec.impact} is not a valid impact`
);
this.impact = spec.impact;
}
};