Skip to content

Commit

Permalink
add a11y-label-has-associated-control check (sveltejs#5074)
Browse files Browse the repository at this point in the history
  • Loading branch information
skippednote authored and taylorzane committed Dec 17, 2020
1 parent df7e397 commit 9829b11
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/compiler/compile/nodes/Element.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,17 @@ const a11y_no_onchange = new Set([
'option'
]);

const a11y_labelable = new Set([
"button",
"input",
"keygen",
"meter",
"output",
"progress",
"select",
"textarea"
]);

const invisible_elements = new Set(['meta', 'html', 'script', 'style']);

const valid_modifiers = new Set([
Expand Down Expand Up @@ -507,6 +518,16 @@ export default class Element extends Node {
}
}

if (this.name === 'label') {
const has_input_child = this.children.some(i => (i instanceof Element && a11y_labelable.has(i.name) ));
if (!attribute_map.has('for') && !has_input_child) {
component.warn(this, {
code: `a11y-label-has-associated-control`,
message: `A11y: A form label must be associated with a control.`
});
}
}

if (a11y_no_onchange.has(this.name)) {
if (handlers_map.has('change') && !handlers_map.has('blur')) {
component.warn(this, {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<label>A</label>
<label for="id">B</label>

<label>C <input type="text" /></label>
<label>D <button>D</button></label>
<label>E <span></span></label>
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
[
{
"code": "a11y-label-has-associated-control",
"end": {
"character": 16,
"column": 16,
"line": 1
},
"message": "A11y: A form label must be associated with a control.",
"pos": 0,
"start": {
"character": 0,
"column": 0,
"line": 1
}
},
{
"code": "a11y-label-has-associated-control",
"end": {
"character": 149,
"column": 30,
"line": 6
},
"message": "A11y: A form label must be associated with a control.",
"pos": 119,
"start": {
"character": 119,
"column": 0,
"line": 6
}
}
]

0 comments on commit 9829b11

Please sign in to comment.