forked from ember-cli/eslint-plugin-ember
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtemplate-require-input-label.js
More file actions
233 lines (199 loc) · 6.45 KB
/
template-require-input-label.js
File metadata and controls
233 lines (199 loc) · 6.45 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
function hasAttr(node, name) {
return node.attributes?.some((a) => a.name === name);
}
function isString(value) {
return typeof value === 'string';
}
function isRegExp(value) {
return value instanceof RegExp;
}
function allowedFormat(value) {
return isString(value) || isRegExp(value);
}
function parseConfig(config) {
if (config === false) {
return false;
}
if (config === true || config === undefined) {
return { labelTags: ['label'] };
}
if (config && typeof config === 'object' && Array.isArray(config.labelTags)) {
return {
labelTags: ['label', ...config.labelTags.filter(allowedFormat)],
};
}
return { labelTags: ['label'] };
}
function matchesLabelTag(tag, configuredTag) {
return isRegExp(configuredTag) ? configuredTag.test(tag) : configuredTag === tag;
}
/** @type {import('eslint').Rule.RuleModule} */
module.exports = {
meta: {
type: 'suggestion',
docs: {
description: 'require label for form input elements',
category: 'Accessibility',
url: 'https://github.com/ember-cli/eslint-plugin-ember/tree/master/docs/rules/template-require-input-label.md',
templateMode: 'both',
},
schema: [
{
anyOf: [
{ type: 'boolean' },
{
type: 'object',
properties: {
labelTags: {
type: 'array',
},
},
additionalProperties: false,
},
],
},
],
messages: {
requireLabel: 'form elements require a valid associated label.',
multipleLabels: 'form elements should not have multiple labels.',
},
originallyFrom: {
name: 'ember-template-lint',
rule: 'lib/rules/require-input-label.js',
docs: 'docs/rule/require-input-label.md',
tests: 'test/unit/rules/require-input-label-test.js',
},
},
create(context) {
const config = parseConfig(context.options[0]);
if (config === false) {
return {};
}
const filename = context.filename;
const isStrictMode = filename.endsWith('.gjs') || filename.endsWith('.gts');
const elementStack = [];
// local name → original name ('Input' | 'Textarea')
// Only populated in GJS/GTS files via ImportDeclaration
const importedFormComponents = new Map();
function hasValidLabelParent() {
for (let i = elementStack.length - 1; i >= 0; i--) {
const entry = elementStack[i];
const hasMatchingLabelTag = config.labelTags.some((configuredTag) =>
matchesLabelTag(entry.tag, configuredTag)
);
if (hasMatchingLabelTag) {
if (entry.tag !== 'label') {
return true;
}
const children = entry.node.children || [];
return children.length > 1;
}
}
return false;
}
return {
ImportDeclaration(node) {
if (!isStrictMode) {
return;
}
if (node.source.value === '@ember/component') {
for (const specifier of node.specifiers) {
if (specifier.type === 'ImportSpecifier') {
const original = specifier.imported.name;
if (original === 'Input' || original === 'Textarea') {
importedFormComponents.set(specifier.local.name, original);
}
}
}
}
},
GlimmerElementNode(node) {
elementStack.push({ tag: node.tag, node });
const tag = node.tag;
// Is this tag one we should check?
// - Native <input>/<textarea>/<select> always.
// - <Input>/<Textarea> built-ins:
// - In strict mode (.gjs/.gts): only if the tag resolves to a tracked
// import from '@ember/component' (supports renames).
// - In HBS: match by bare tag name.
const isNativeFormElement = tag === 'input' || tag === 'textarea' || tag === 'select';
const isBuiltinFormComponent = isStrictMode
? importedFormComponents.has(tag)
: tag === 'Input' || tag === 'Textarea';
if (!isNativeFormElement && !isBuiltinFormComponent) {
return;
}
// Skip if input has type="hidden"
const typeAttr = node.attributes?.find((a) => a.name === 'type');
if (typeAttr?.value?.type === 'GlimmerTextNode' && typeAttr.value.chars === 'hidden') {
return;
}
// Skip if has ...attributes (can't determine labelling)
if (hasAttr(node, '...attributes')) {
return;
}
let labelCount = 0;
const validLabel = hasValidLabelParent();
if (validLabel) {
labelCount++;
}
if (hasAttr(node, 'aria-label')) {
labelCount++;
}
if (hasAttr(node, 'aria-labelledby')) {
labelCount++;
}
if (labelCount === 1) {
return;
}
// An `id` may pair with a sibling `<label for>` we can't see in this
// template. Treat id-only as valid to avoid false positives, but don't
// count it toward labelCount — otherwise id + aria-label is wrongly
// flagged as multiple labels.
if (labelCount === 0 && hasAttr(node, 'id')) {
return;
}
context.report({
node,
messageId: labelCount === 0 ? 'requireLabel' : 'multipleLabels',
});
},
'GlimmerElementNode:exit'() {
elementStack.pop();
},
GlimmerMustacheStatement(node) {
// Classic {{input}}/{{textarea}} curly helpers only exist in HBS.
// In GJS/GTS, these identifiers are user-imported JS bindings with
// no relation to the classic helpers, so skip.
if (isStrictMode) {
return;
}
const name = node.path?.original;
if (name !== 'input' && name !== 'textarea') {
return;
}
const pairs = node.hash?.pairs || [];
function hasPair(key) {
return pairs.some((p) => p.key === key);
}
// Skip if type="hidden" (literal string only)
const typePair = pairs.find((p) => p.key === 'type');
if (typePair?.value?.type === 'GlimmerStringLiteral' && typePair.value.value === 'hidden') {
return;
}
// If in a valid label, it's valid
if (hasValidLabelParent()) {
return;
}
// If has id, it's valid
if (hasPair('id')) {
return;
}
context.report({
node,
messageId: 'requireLabel',
});
},
};
},
};