ShtukbaseStandard
файл пакета→ .shtukbase/packages/design-a11y/checks/labels.ts

checks/labels.ts

48 строк, 2.6 КБ.

Файл как есть в пакете: код и комментарии в нём не переводятся.

  1. // A11Y-R03. Every form field has a label a screen reader can announce: <input>, <select>, <textarea> and the
  2. // shadcn fields (Input, Textarea, Checkbox, Switch, SelectTrigger, RadioGroupItem) have aria-label,
  3. // aria-labelledby or title, or an id that a <label for>/htmlFor in the same file points at, or sit inside a
  4. // <label> (or shadcn's Label/FieldLabel/FormControl). A placeholder is not a label.
  5. // Skipped: fields with {...props} (the label may come from outside), hidden and button-like inputs.
  6. import { attr, elements } from '../../design-base/lib/markup.ts';
  7. import { lineAt, report } from '../../design-base/lib/files.ts';
  8. import { markupFiles } from './a11ylib.ts';
  9. export const RULE = { id: 'a11y-r03', title: 'A form field has a label' };
  10. const FIELDS = /input|select|textarea|Input|Textarea|Checkbox|Switch|SelectTrigger|RadioGroupItem/;
  11. const WRAPS = /label|Label|FieldLabel|FormLabel|FormControl/;
  12. const NO_LABEL_TYPES = new Set(['hidden', 'submit', 'button', 'reset', 'image']);
  13. export function check(root = process.cwd()): string[] {
  14. const out: string[] = [];
  15. for (const f of markupFiles(root)) {
  16. const fields = elements(f.text, FIELDS);
  17. if (!fields.length) continue;
  18. const ranges = elements(f.text, WRAPS)
  19. .filter((w) => w.inner !== null)
  20. .map((w) => [w.openEnd, w.openEnd + (w.inner as string).length] as const);
  21. const fors = new Set<string>();
  22. let exprFor = false;
  23. for (const l of elements(f.text, /label|Label|FieldLabel|FormLabel/)) {
  24. const v = attr(l, 'htmlFor') ?? attr(l, 'for');
  25. if (v === '{…}') exprFor = true;
  26. else if (v) fors.add(v);
  27. }
  28. for (const el of fields) {
  29. if (el.spread || el.inAttr) continue;
  30. if (attr(el, 'aria-hidden') === 'true' || /(^|\s)hidden(\s|$)/.test(attr(el, 'className') ?? attr(el, 'class') ?? '') || attr(el, 'hidden') === '') continue;
  31. const type = (attr(el, 'type') ?? '').toLowerCase();
  32. if (NO_LABEL_TYPES.has(type)) continue;
  33. if (['aria-label', 'aria-labelledby', 'title'].some((a) => { const v = attr(el, a); return v !== null && v.trim() !== ''; })) continue;
  34. const id = attr(el, 'id');
  35. if (id === '{…}' && (exprFor || fors.size)) continue;
  36. if (id && fors.has(id)) continue;
  37. if (ranges.some(([a, b]) => el.start >= a && el.start < b)) continue;
  38. const hint = attr(el, 'placeholder') !== null ? ' (a placeholder is not a label)' : '';
  39. 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`);
  40. }
  41. }
  42. return out;
  43. }
  44. if (import.meta.main) report(check());