ShtukbaseStandard
包文件→ .shtukbase/packages/design-a11y/checks/names.ts

checks/names.ts

34 行, 2.0 KB.

文件按包中的原样显示:代码及其注释不做翻译。

  1. // A11Y-R04. Every button and link has a name: text inside (visible or sr-only), aria-label, aria-labelledby or title.
  2. // An icon alone is not a name. Looked at: <button>, <a>, and the components Button and Link.
  3. // Skipped: elements with {...props} (the name may come from outside) and inner text built by an expression ({…}).
  4. import { attr, elements, innerText } from '../../design-base/lib/markup.ts';
  5. import { lineAt, report } from '../../design-base/lib/files.ts';
  6. import { markupFiles } from './a11ylib.ts';
  7. export const RULE = { id: 'a11y-r04', title: 'A button and a link have a name' };
  8. export function check(root = process.cwd()): string[] {
  9. const out: string[] = [];
  10. for (const f of markupFiles(root)) {
  11. for (const el of elements(f.text, /button|a|Button|Link/)) {
  12. if (el.spread || el.inAttr) continue;
  13. if (['aria-label', 'aria-labelledby', 'title'].some((a) => { const v = attr(el, a); return v !== null && v.trim() !== ''; })) continue;
  14. if (el.name === 'a' && attr(el, 'href') === null && attr(el, 'role') === null) continue; // an anchor, not a link
  15. // A component that returns only an empty <Link />/<Button /> is a template for a render prop.
  16. if (el.selfClosing && /(=>|\breturn)\s*\(?\s*$/.test(f.text.slice(Math.max(0, el.start - 40), el.start))) continue;
  17. if (el.selfClosing) {
  18. out.push(`${f.rel}:${lineAt(f.text, el.start)}: <${el.name} /> without text and aria-label`);
  19. continue;
  20. }
  21. if (el.inner === null) continue;
  22. const text = innerText(el.inner);
  23. if (text === null || text) continue;
  24. if (/\balt\s*=\s*["'][^"']+["']|\baria-label\s*=\s*["'{]/.test(el.inner)) continue; // image with alt, labelled child
  25. const tag = el.name === 'a' || el.name === 'Link' ? 'link' : 'button';
  26. out.push(`${f.rel}:${lineAt(f.text, el.start)}: ${tag} <${el.name}> without a name (only an icon?) — add text, <span className="sr-only">…</span> or aria-label`);
  27. }
  28. }
  29. return out;
  30. }
  31. if (import.meta.main) report(check());