файл пакета→ .shtukbase/packages/design-a11y/checks/labels.ts
checks/labels.ts
48 строк, 2.6 КБ.
Файл как есть в пакете: код и комментарии в нём не переводятся.
- // A11Y-R03. Every form field has a label a screen reader can announce: <input>, <select>, <textarea> and the
- // shadcn fields (Input, Textarea, Checkbox, Switch, SelectTrigger, RadioGroupItem) have aria-label,
- // aria-labelledby or title, or an id that a <label for>/htmlFor in the same file points at, or sit inside a
- // <label> (or shadcn's Label/FieldLabel/FormControl). A placeholder is not a label.
- // Skipped: fields with {...props} (the label may come from outside), hidden and button-like inputs.
- import { attr, elements } from '../../design-base/lib/markup.ts';
- import { lineAt, report } from '../../design-base/lib/files.ts';
- import { markupFiles } from './a11ylib.ts';
- export const RULE = { id: 'a11y-r03', title: 'A form field has a label' };
- const FIELDS = /input|select|textarea|Input|Textarea|Checkbox|Switch|SelectTrigger|RadioGroupItem/;
- const WRAPS = /label|Label|FieldLabel|FormLabel|FormControl/;
- const NO_LABEL_TYPES = new Set(['hidden', 'submit', 'button', 'reset', 'image']);
- export function check(root = process.cwd()): string[] {
- const out: string[] = [];
- for (const f of markupFiles(root)) {
- const fields = elements(f.text, FIELDS);
- if (!fields.length) continue;
- const ranges = elements(f.text, WRAPS)
- .filter((w) => w.inner !== null)
- .map((w) => [w.openEnd, w.openEnd + (w.inner as string).length] as const);
- const fors = new Set<string>();
- let exprFor = false;
- for (const l of elements(f.text, /label|Label|FieldLabel|FormLabel/)) {
- const v = attr(l, 'htmlFor') ?? attr(l, 'for');
- if (v === '{…}') exprFor = true;
- else if (v) fors.add(v);
- }
- for (const el of fields) {
- if (el.spread || el.inAttr) continue;
- if (attr(el, 'aria-hidden') === 'true' || /(^|\s)hidden(\s|$)/.test(attr(el, 'className') ?? attr(el, 'class') ?? '') || attr(el, 'hidden') === '') continue;
- const type = (attr(el, 'type') ?? '').toLowerCase();
- if (NO_LABEL_TYPES.has(type)) continue;
- if (['aria-label', 'aria-labelledby', 'title'].some((a) => { const v = attr(el, a); return v !== null && v.trim() !== ''; })) continue;
- const id = attr(el, 'id');
- if (id === '{…}' && (exprFor || fors.size)) continue;
- if (id && fors.has(id)) continue;
- if (ranges.some(([a, b]) => el.start >= a && el.start < b)) continue;
- const hint = attr(el, 'placeholder') !== null ? ' (a placeholder is not a label)' : '';
- out.push(`${f.rel}:${lineAt(f.text, el.start)}: <${el.name}> without a label${hint} — add <label htmlFor> with its id, wrap it in <label> or use aria-label`);
- }
- }
- return out;
- }
- if (import.meta.main) report(check());