Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-8813 chore(eslint): fail lint on icon-size Buttons without an accessible name (#10168)

Jiayuan Zhang5f53158b811a
diff --git a/packages/eslint-config/icon-button-name.js b/packages/eslint-config/icon-button-name.js
new file mode 100644
index 0000000000..b2ad733d4f
--- /dev/null
+++ b/packages/eslint-config/icon-button-name.js
@@ -0,0 +1,126 @@
+// An icon-size Button shows a glyph and nothing else, so without a name a
+// screen reader announces a bare "button" and tests can't find it by role.
+// A tooltip doesn't count: it is a separate popup, not the button's name.
+//
+// A Button counts as named when it has `aria-label` or `aria-labelledby`, a
+// props spread (the caller may pass the name), or content that may render
+// text: a text node, an `sr-only` element, or any expression that isn't plain
+// JSX. When the Button is the `render` element of a trigger, the trigger's own
+// props and children reach the button too, so they count as well.
+//
+// Registered by the shared React config, so every package that extends it
+// gets the rule without repeating it.
+
+const NAME_ATTRIBUTES = new Set(["aria-label", "aria-labelledby"]);
+const SR_ONLY = /(^|\s)sr-only(\s|$)/;
+
+function attributeName(attr) {
+ return attr.type === "JSXAttribute" && attr.name.type === "JSXIdentifier"
+ ? attr.name.name
+ : null;
+}
+
+function stringsIn(node) {
+ if (!node) return [];
+ switch (node.type) {
+ case "Literal":
+ return typeof node.value === "string" ? [node.value] : [];
+ case "TemplateLiteral":
+ return node.quasis.map((q) => q.value.raw);
+ case "JSXExpressionContainer":
+ return stringsIn(node.expression);
+ case "ConditionalExpression":
+ return [...stringsIn(node.consequent), ...stringsIn(node.alternate)];
+ case "LogicalExpression":
+ return [...stringsIn(node.left), ...stringsIn(node.right)];
+ default:
+ return [];
+ }
+}
+
+function isIconSize(opening) {
+ const size = opening.attributes.find((a) => attributeName(a) === "size");
+ return !!size && stringsIn(size.value).some((s) => s.startsWith("icon"));
+}
+
+function namesItself(opening) {
+ return opening.attributes.some(
+ (a) => a.type === "JSXSpreadAttribute" || NAME_ATTRIBUTES.has(attributeName(a)),
+ );
+}
+
+function isSrOnly(opening) {
+ const className = opening.attributes.find((a) => attributeName(a) === "className");
+ return !!className && stringsIn(className.value).some((s) => SR_ONLY.test(s));
+}
+
+function mayRenderText(node) {
+ switch (node.type) {
+ case "JSXText":
+ return /\S/.test(node.value);
+ case "JSXElement":
+ return isSrOnly(node.openingElement) || node.children.some(mayRenderText);
+ case "JSXFragment":
+ return node.children.some(mayRenderText);
+ case "JSXExpressionContainer":
+ return mayRenderText(node.expression);
+ case "JSXEmptyExpression":
+ return false;
+ case "ConditionalExpression":
+ return mayRenderText(node.consequent) || mayRenderText(node.alternate);
+ case "LogicalExpression":
+ return (node.operator !== "&&" && mayRenderText(node.left)) || mayRenderText(node.right);
+ case "Literal":
+ return node.value !== null && typeof node.value !== "boolean" && String(node.value).trim() !== "";
+ case "Identifier":
+ return node.name !== "undefined";
+ default:
+ return true;
+ }
+}
+
+// The element whose `render` prop is this Button, e.g. a TooltipTrigger.
+function renderHost(element) {
+ let node = element;
+ while (node.parent.type === "ConditionalExpression" || node.parent.type === "LogicalExpression") {
+ node = node.parent;
+ }
+ const container = node.parent;
+ if (container.type !== "JSXExpressionContainer") return null;
+ const attr = container.parent;
+ if (attr.type !== "JSXAttribute" || attributeName(attr) !== "render") return null;
+ return attr.parent.parent;
+}
+
+function isNamed(element) {
+ if (namesItself(element.openingElement) || element.children.some(mayRenderText)) return true;
+ const host = renderHost(element);
+ return !!host && (namesItself(host.openingElement) || host.children.some(mayRenderText));
+}
+
+const iconButtonName = {
+ meta: {
+ type: "problem",
+ docs: { description: "Require an accessible name on icon-size Buttons." },
+ schema: [],
+ messages: {
+ unnamed:
+ "Icon-only Button has no accessible name: screen readers announce a bare \"button\" and tests can't find it by role. Use IconButton from @multica/ui/components/common/icon-button — its `label` sets the name and the tooltip. In a row that repeats, keep the Button, add `aria-label`, and show the tooltip with DeferredTooltip.",
+ },
+ },
+ create(context) {
+ return {
+ JSXElement(node) {
+ const opening = node.openingElement;
+ if (opening.name.type !== "JSXIdentifier" || opening.name.name !== "Button") return;
+ if (!isIconSize(opening) || isNamed(node)) return;
+ context.report({ node: opening, messageId: "unnamed" });
+ },
+ };
+ },
+};
+
+export default {
+ meta: { name: "@multica/eslint-config/a11y" },
+ rules: { "icon-button-name": iconButtonName },
+};
diff --git a/packages/eslint-config/icon-button-name.test.js b/packages/eslint-config/icon-button-name.test.js
new file mode 100644
index 0000000000..6dd2396471
--- /dev/null
+++ b/packages/eslint-config/icon-button-name.test.js
@@ -0,0 +1,75 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import { fileURLToPath } from "node:url";
+import { ESLint, Linter } from "eslint";
+import tseslint from "typescript-eslint";
+import a11yPlugin from "./icon-button-name.js";
+
+const linter = new Linter();
+
+function flagged(code) {
+ const messages = linter.verify(
+ code,
+ [
+ {
+ files: ["**/*.tsx"],
+ languageOptions: {
+ parser: tseslint.parser,
+ parserOptions: { ecmaFeatures: { jsx: true } },
+ },
+ plugins: { "multica-a11y": a11yPlugin },
+ rules: { "multica-a11y/icon-button-name": "error" },
+ },
+ ],
+ "fixture.tsx",
+ );
+ const fatal = messages.find((m) => m.fatal);
+ if (fatal) throw new Error(`fixture failed to parse: ${fatal.message}`);
+ return messages.length > 0;
+}
+
+const FLAGGED = [
+ ["unnamed icon button", '<Button size="icon-sm"><X /></Button>'],
+ ["self-closing icon button", '<Button size="icon" />'],
+ ["icon size from a conditional", '<Button size={compact ? "icon-xs" : "icon-sm"}><X /></Button>'],
+ ["icon chosen by a conditional child", "<Button size=\"icon\">{open ? <ChevronUp /> : <ChevronDown />}</Button>"],
+ ["icon behind &&", "<Button size=\"icon\">{busy && <Spinner />}</Button>"],
+ ["unnamed render-prop trigger", '<TooltipTrigger render={<Button size="icon-sm" />}><X /></TooltipTrigger>'],
+ [
+ "render-prop trigger with content inside the Button",
+ '<TooltipTrigger render={<Button size="icon-sm"><X /></Button>} />',
+ ],
+ ["label only in a tooltip", '<Tooltip><TooltipTrigger render={<Button size="icon" />}><X /></TooltipTrigger><TooltipContent>Close</TooltipContent></Tooltip>'],
+];
+
+const ALLOWED = [
+ ["aria-label", '<Button size="icon-sm" aria-label="Close"><X /></Button>'],
+ ["translated aria-label", '<Button size="icon-sm" aria-label={t(($) => $.close)}><X /></Button>'],
+ ["aria-labelledby", '<Button size="icon" aria-labelledby="title-id"><X /></Button>'],
+ ["props spread", '<Button size="icon-sm" {...props}><X /></Button>'],
+ ["text child", '<Button size="icon">Go</Button>'],
+ ["expression child", '<Button size="icon-xs">{count}</Button>'],
+ ["sr-only child", '<Button size="icon"><X /><span className="sr-only">{t(($) => $.close)}</span></Button>'],
+ ["named render-prop trigger", '<TooltipTrigger render={<Button size="icon-sm" aria-label="More" />}><X /></TooltipTrigger>'],
+ ["render-prop trigger carrying the name", '<DropdownMenuTrigger aria-label="More" render={<Button size="icon-sm" />}><X /></DropdownMenuTrigger>'],
+ ["render-prop trigger with an sr-only child", '<TooltipTrigger render={<Button size="icon" />}><X /><span className="sr-only">Close</span></TooltipTrigger>'],
+ ["non-icon size", '<Button size="sm"><X /></Button>'],
+ ["no size", "<Button><X /></Button>"],
+ ["IconButton", '<IconButton label="Close"><X /></IconButton>'],
+];
+
+for (const [name, code] of FLAGGED) {
+ test(`flags ${name}`, () => assert.equal(flagged(code), true));
+}
+
+for (const [name, code] of ALLOWED) {
+ test(`allows ${name}`, () => assert.equal(flagged(code), false));
+}
+
+test("the shared React config turns the rule on", async () => {
+ const eslint = new ESLint({ cwd: fileURLToPath(new URL("../views", import.meta.url)) });
+ const [result] = await eslint.lintText('export const A = () => <Button size="icon" />;\n', {
+ filePath: "fixture.tsx",
+ });
+ assert.equal(result.messages.filter((m) => m.ruleId === "multica-a11y/icon-button-name").length, 1);
+});
diff --git a/packages/eslint-config/react.js b/packages/eslint-config/react.js
index 78d58189ca..7b26e69481 100644
--- a/packages/eslint-config/react.js
+++ b/packages/eslint-config/react.js
@@ -1,6 +1,7 @@
import baseConfig from "./base.js";
import reactPlugin from "eslint-plugin-react";
import reactHooksPlugin from "eslint-plugin-react-hooks";
+import a11yPlugin from "./icon-button-name.js";
/** @type {import("eslint").Linter.Config[]} */
export default [
@@ -8,12 +9,13 @@ export default [
// React rules (JSX only)
{
files: ["**/*.{jsx,tsx}"],
- plugins: { react: reactPlugin },
+ plugins: { react: reactPlugin, "multica-a11y": a11yPlugin },
rules: {
...reactPlugin.configs.recommended.rules,
...reactPlugin.configs["jsx-runtime"].rules,
"react/prop-types": "off",
"react/no-unknown-property": "off",
+ "multica-a11y/icon-button-name": "error",
},
settings: {
react: { version: "detect" },