-
-
Notifications
You must be signed in to change notification settings - Fork 212
Expand file tree
/
Copy pathtemplate-require-input-label.js
More file actions
300 lines (261 loc) · 8.59 KB
/
template-require-input-label.js
File metadata and controls
300 lines (261 loc) · 8.59 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
function hasAttr(node, name) {
return node.attributes?.some((a) => a.name === name);
}
function getStaticAttrStr(node, name) {
const attr = node.attributes?.find((a) => a.name === name);
if (!attr || !attr.value) {
return null;
}
if (attr.value.type === 'GlimmerTextNode') {
return attr.value.chars.trim();
}
if (
attr.value.type === 'GlimmerMustacheStatement' &&
attr.value.path?.type === 'GlimmerStringLiteral'
) {
return attr.value.path.value.trim();
}
return null; // dynamic — can't determine statically
}
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'], checkLabelFor: false };
}
if (config && typeof config === 'object') {
const labelTags = Array.isArray(config.labelTags)
? ['label', ...config.labelTags.filter(allowedFormat)]
: ['label'];
return {
labelTags,
checkLabelFor: config.checkLabelFor === true,
};
}
return { labelTags: ['label'], checkLabelFor: false };
}
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',
},
checkLabelFor: {
type: 'boolean',
},
},
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();
// checkLabelFor: collect static <label for="X"> values into a Set and
// defer id-only controls until Program:exit so forward-declared labels
// are captured too. Single visitor pass + O(1) Set lookup keeps the
// cross-reference O(n + m) total (n = label nodes, m = id-only controls).
const labelForValues = new Set();
const pendingIdNodes = []; // { node } — reported if no matching for= found
function collectLabelFor(node) {
if (!config.checkLabelFor || node.tag !== 'label') {
return;
}
const forValue = getStaticAttrStr(node, 'for');
if (forValue) {
labelForValues.add(forValue);
}
}
function deferIdOnlyCheck(node) {
if (!config.checkLabelFor) {
return;
}
const idValue = getStaticAttrStr(node, 'id');
if (idValue) {
pendingIdNodes.push({ node, id: idValue });
}
// Dynamic id — can't match statically, fall back to skip.
}
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 });
collectLabelFor(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. With checkLabelFor enabled, the deferred
// helper does collect the id and verifies it against `<label for>`
// values gathered from the same template at Program:exit.
if (labelCount === 0 && hasAttr(node, 'id')) {
deferIdOnlyCheck(node);
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',
});
},
'Program:exit'() {
if (!config.checkLabelFor) {
return;
}
for (const { node, id } of pendingIdNodes) {
if (!labelForValues.has(id)) {
context.report({ node, messageId: 'requireLabel' });
}
}
},
};
},
};