|
1 | 1 | var React = require('react'); |
2 | 2 | var assertions = require('./assertions'); |
3 | 3 |
|
4 | | -var assertAccessibility = (tagName, props, children, log) => { |
| 4 | +var assertAccessibility = (tagName, props, children) => { |
5 | 5 | var key; |
| 6 | + var failures = []; |
6 | 7 |
|
7 | | - var tagTests = assertions.tags[tagName]; |
8 | | - if (tagTests) |
9 | | - for (key in tagTests) |
10 | | - log(tagTests[key].test(tagName, props, children), tagTests[key].msg); |
| 8 | + var tagTests = assertions.tags[tagName] || []; |
| 9 | + for (key in tagTests) |
| 10 | + if (tagTests[key] && !tagTests[key].test(tagName, props, children)) |
| 11 | + failures.push(tagTests[key].msg); |
11 | 12 |
|
12 | 13 | var propTests; |
13 | 14 | for (var propName in props) { |
14 | 15 | if (props[propName] === null || props[propName] === undefined) continue; |
15 | | - propTests = assertions.props[propName]; |
16 | | - if (propTests) |
17 | | - for (key in propTests) |
18 | | - log(propTests[key].test(tagName, props, children), propTests[key].msg); |
| 16 | + propTests = assertions.props[propName] || []; |
| 17 | + for (key in propTests) |
| 18 | + if (propTests[key] && !propTests[key].test(tagName, props, children)) |
| 19 | + failures.push(propTests[key].msg); |
19 | 20 | } |
| 21 | + return failures; |
20 | 22 | }; |
21 | 23 |
|
22 | | -var error = (passed, msg) => { |
23 | | - if (!passed) |
24 | | - throw new Error(msg); |
| 24 | +var error = (id, msg) => { |
| 25 | + throw new Error('#' + id + ": " + msg); |
25 | 26 | }; |
26 | 27 |
|
27 | | -var warn = (passed, msg) => { |
28 | | - if (!passed) |
29 | | - console.warn(msg); |
| 28 | +var warn = (id, msg) => { |
| 29 | + console.warn('#' + id, msg); |
30 | 30 | }; |
31 | 31 |
|
| 32 | +var nextId = 0; |
32 | 33 | module.exports = (options) => { |
33 | 34 | var _createElement = React.createElement; |
34 | 35 | var log = options && options.throw ? error : warn; |
35 | 36 | React.createElement = function (type, _props, ...children) { |
| 37 | + var props = _props || {}; |
36 | 38 | if (typeof type === 'string') { |
37 | | - var props = _props || {}; |
38 | | - assertAccessibility(type, props, children, log); |
| 39 | + var failures = assertAccessibility(type, props, children); |
| 40 | + if (failures.length) { |
| 41 | + // Generate an id if one doesn't exist |
| 42 | + props.id = (props.id || 'a11y-' + nextId++); |
| 43 | + |
| 44 | + for (var i = 0; i < failures.length; i++) |
| 45 | + log(props.id, failures[i]); |
| 46 | + } |
39 | 47 | } |
40 | | - return _createElement.apply(this, arguments); |
| 48 | + // make sure props with the id is passed down, even if no props were passed in. |
| 49 | + return _createElement.apply(this, [type, props].concat(children)); |
41 | 50 | }; |
42 | 51 | }; |
0 commit comments