Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat(eslint): catch a theme target rendered on nothing (spread-vs-spread className clobber) (#5334)

Cindy Zhang0dfce0282589
diff --git a/internal/eslint-plugin-astryx/README.md b/internal/eslint-plugin-astryx/README.md
index f0cf8f1203..01b7bac388 100644
--- a/internal/eslint-plugin-astryx/README.md
+++ b/internal/eslint-plugin-astryx/README.md
@@ -512,6 +512,41 @@ Autofixable, and mirrored at runtime by `.github/scripts/disabled-hover-audit.js
Ships as an **error in both tiers**: core and lab are clean, and this keeps them that way.
+### `@astryx/no-classname-clobber`
+
+Flags two things on one JSX element that each set `className`. React applies attributes left to right and does not merge them, so the later writer wins outright and everything the earlier one carried is gone.
+
+There are two ways to write it twice. The first is a literal `className=` or `style=` attribute beside a `{...stylex.props()}` spread. The second is **two spreads that each carry a className** — and that one hides, because every helper here returns a `{className, style}` object: `stylex.props()`, `themeProps()`, `focusOutlineProps.*()`, and `mergeProps()` when it merges any of those.
+
+Breadcrumbs shipped the second shape. Both halves read as correct in review, and `mergeProps` on the first line reads as if the merging is handled:
+
+**Bad:**
+
+```tsx
+<button
+ {...mergeProps(themeProps('breadcrumb-item-menu-trigger'), {...popover.triggerProps})}
+ {...stylex.props(itemStyles.link, itemStyles.buttonReset)}
+/>
+```
+
+**Good:**
+
+```tsx
+<button
+ {...popover.triggerProps}
+ {...mergeProps(
+ themeProps('breadcrumb-item-menu-trigger'),
+ stylex.props(itemStyles.link, itemStyles.buttonReset),
+ )}
+/>
+```
+
+The second spread replaced the className the first built, so `astryx-breadcrumb-item-menu-trigger` — documented, registered, part of the public theming surface — rendered on no element at all, and a theme targeting it silently did nothing. Nothing else caught it: `themingTargets.test.ts` asserts documented targets are a **subset** of what source registers, so a target that renders on zero elements passes.
+
+**Scope:** two or more spreads on one opening element whose expressions are statically recognizable className producers. A spread of anything else — `{...rest}`, `{...popover.triggerProps}`, an unknown call — is not a producer and does not count, so one producer beside any number of those is fine. `mergeProps()` is the sanctioned merge and concatenates class names, so anything already inside a single `mergeProps()` call is correct however many producers it takes; it only becomes a problem beside a **second** spread that produces a className of its own. A producer reached through a conditional (`{...(cond ? stylex.props(a) : {})}`) is out of scope: no call site writes one, and reading through the branches invites guesses the rule cannot verify.
+
+Ships as a **warning in both tiers** for now. The spread check has exactly one violation in the repo, in `BreadcrumbItem.tsx`, whose fix is open in [#5332](https://github.com/facebook/astryx/pull/5332); both tiers go back to `error` when that lands.
+
### `@astryx/disabled-cursor`
Flags a `cursor` inside `stylex.create()` that does not give way to `default` on a disabled element. The cursor is the only affordance a pointer user gets **before** they commit to a click: `cursor: pointer` on a disabled control promises a click it will not honour, and `disabled`/`[aria-disabled]` do not change what the element's own declaration paints.
diff --git a/internal/eslint-plugin-astryx/index.js b/internal/eslint-plugin-astryx/index.js
index 8b6151f18e..3443c094f1 100644
--- a/internal/eslint-plugin-astryx/index.js
+++ b/internal/eslint-plugin-astryx/index.js
@@ -13,6 +13,7 @@
* - no-nullish-jsx-guard: Flags `!= null` JSX render guards for rendered values (use isRenderable so false/''/true slots don't leak an empty element)
* - no-raw-intl-locale: Forbids raw Intl formatting/comparison outside the approved i18n infrastructure boundary, and navigator.language(s) as a locale source
* - no-unguarded-ime-keydown: Flags an onKeyDown on an editable surface that branches on command keys without an IME composition guard (isImeKeyEvent/isComposing)
+ * - no-classname-clobber: Flags two className sources on one JSX element — a literal className/style beside {...stylex.props()}, or two spreads that each carry a className (the later one silently wins)
* - no-hover-on-disabled: Flags a :hover condition that can still match a disabled element (browsers suppress a disabled control's events, not its hover styling)
* - disabled-cursor: Flags a cursor that promises an interaction without giving way to not-allowed on a disabled element
*
@@ -296,7 +297,12 @@ plugin.configs.strict = {
'@astryx/no-style-only-wrapper': 'warn',
'@astryx/no-wrapper-transform': 'error',
'@astryx/no-react-introspection': 'error',
- '@astryx/no-classname-clobber': 'error',
+ // Widened to catch two spreads that each carry a className, which is how
+ // astryx-breadcrumb-item-menu-trigger came to render on no element at
+ // all. That one violation is the only one in the repo and its fix is
+ // open in PR #5332 — warn until that lands, then flip both tiers back
+ // to 'error'.
+ '@astryx/no-classname-clobber': 'warn',
'@astryx/no-hardcoded-anchor': 'error',
'@astryx/no-raw-paragraph': 'error',
// Rolled out as a warning even in strict mode: core still has ~36 existing
@@ -351,7 +357,12 @@ plugin.configs.recommended = {
'@astryx/no-style-only-wrapper': 'warn',
'@astryx/no-wrapper-transform': 'error',
'@astryx/no-react-introspection': 'error',
- '@astryx/no-classname-clobber': 'error',
+ // Widened to catch two spreads that each carry a className, which is how
+ // astryx-breadcrumb-item-menu-trigger came to render on no element at
+ // all. That one violation is the only one in the repo and its fix is
+ // open in PR #5332 — warn until that lands, then flip both tiers back
+ // to 'error'.
+ '@astryx/no-classname-clobber': 'warn',
'@astryx/no-hardcoded-anchor': 'warn',
'@astryx/no-raw-paragraph': 'warn',
'@astryx/no-nullish-jsx-guard': 'warn',
diff --git a/internal/eslint-plugin-astryx/no-classname-clobber.js b/internal/eslint-plugin-astryx/no-classname-clobber.js
index ed7c1191d6..53c275c1a7 100644
--- a/internal/eslint-plugin-astryx/no-classname-clobber.js
+++ b/internal/eslint-plugin-astryx/no-classname-clobber.js
@@ -2,86 +2,189 @@
/**
* @file no-classname-clobber.js
- * @description Disallow `className` or `style` alongside `{...stylex.props()}` on JSX elements.
+ * @description Disallow two things on one JSX element that each set
+ * `className`, since the later one silently replaces the earlier.
*
- * `stylex.props()` returns `{ className, style }`. When a JSX element has an
- * explicit `className` or `style` attribute alongside a spread, one silently
- * clobbers the other — whichever appears last in source wins.
+ * React applies attributes left to right, so a `className` written twice on an
+ * element is not merged — the last writer wins and everything the first one
+ * carried is gone. There are two ways to write it twice:
*
- * Fix: Use `mergeProps(xdsClassName(...), stylex.props(...), className, style)`
- * which concatenates class names and merges style objects correctly.
+ * 1. A literal `className=` (or `style=`) attribute beside a
+ * `{...stylex.props()}` spread.
+ * 2. TWO SPREADS that each carry a `className`. Every one of these returns a
+ * `{className, style}` object: `stylex.props()`, `themeProps()`,
+ * `focusOutlineProps.*()`, and `mergeProps()` when it merges one of those.
+ *
+ * The second shape is the one that hides. Breadcrumbs shipped it:
+ *
+ * <button
+ * {...mergeProps(themeProps('breadcrumb-item-menu-trigger'), {...trigger})}
+ * {...stylex.props(itemStyles.link)}
+ * />
+ *
+ * Both halves read as correct, and `mergeProps` on the first line reads as if
+ * the merging is handled. It is not: the second spread replaces the className
+ * the first built, so `astryx-breadcrumb-item-menu-trigger` — documented,
+ * registered, part of the public theming surface — rendered on no element at
+ * all, and a theme targeting it did nothing.
+ *
+ * Nothing else caught it. `themingTargets.test.ts` asserts documented targets
+ * are a SUBSET of what source registers, so a target that renders on zero
+ * elements passes.
+ *
+ * `mergeProps` is the sanctioned merge and concatenates class names, so
+ * anything already inside a single `mergeProps()` call is correct. The rule
+ * fires only when two SEPARATE spreads each independently carry one.
*
* Bad:
- * <div className={xdsClassName('foo')} {...stylex.props(styles.root)} />
+ * <div className={themeProps('foo').className} {...stylex.props(styles.root)} />
* <div style={dynamicStyle} {...stylex.props(styles.root)} />
- * <div {...stylex.props(styles.root)} style={dynamicStyle} />
+ * <div {...themeProps('foo')} {...stylex.props(styles.root)} />
+ * <div {...mergeProps(themeProps('foo'), rest)} {...stylex.props(styles.root)} />
*
* Good:
- * <div {...mergeProps(xdsClassName('foo'), stylex.props(styles.root))} />
- * <div {...mergeProps(xdsClassName('foo'), stylex.props(styles.root), undefined, dynamicStyle)} />
+ * <div {...mergeProps(themeProps('foo'), stylex.props(styles.root))} />
+ * <div {...mergeProps(themeProps('foo'), stylex.props(styles.root), className, style)} />
+ * <div {...rest} {...stylex.props(styles.root)} />
+ */
+
+/**
+ * Bare-identifier calls that return a `{className}` object.
+ *
+ * `xdsClassName`/`xdsThemeProps` are the pre-rename spellings of
+ * `themeProps`. No call site uses them today; they stay listed so a
+ * re-introduction is caught rather than waved through.
+ */
+const THEME_PROP_CALLS = new Set([
+ 'themeProps',
+ 'xdsThemeProps',
+ 'xdsClassName',
+]);
+
+/** The object whose every method returns `stylex.props(...)`. */
+const CLASSNAME_NAMESPACES = new Set(['focusOutlineProps']);
+
+/** Strip TS-only wrappers so `stylex.props(x) as never` still reads as a call. */
+function unwrap(node) {
+ let current = node;
+ while (
+ current &&
+ (current.type === 'TSAsExpression' ||
+ current.type === 'TSSatisfiesExpression' ||
+ current.type === 'TSNonNullExpression')
+ ) {
+ current = current.expression;
+ }
+ return current;
+}
+
+/**
+ * Name this expression if it produces a className, else null.
+ *
+ * The returned string is the short form used in the report, not source text:
+ * a spread's real source runs to several lines and reads badly in a message.
*/
+function classNameProducer(node) {
+ const expr = unwrap(node);
+ if (!expr || expr.type !== 'CallExpression') return null;
+
+ const callee = expr.callee;
+
+ if (callee.type === 'Identifier') {
+ if (THEME_PROP_CALLS.has(callee.name)) return `${callee.name}()`;
+ // mergeProps only carries a className if something it merges has one.
+ if (callee.name === 'mergeProps') {
+ return expr.arguments.some(arg => classNameProducer(arg) !== null)
+ ? 'mergeProps()'
+ : null;
+ }
+ return null;
+ }
+
+ if (callee.type === 'MemberExpression' && !callee.computed) {
+ const object = callee.object?.name;
+ const property = callee.property?.name;
+ if (object === 'stylex' && property === 'props') return 'stylex.props()';
+ if (CLASSNAME_NAMESPACES.has(object)) return `${object}.${property}()`;
+ }
+
+ return null;
+}
const rule = {
meta: {
type: 'problem',
docs: {
description:
- 'Disallow className/style alongside {...stylex.props()} — use mergeProps() instead',
+ 'Disallow two className sources on one JSX element — use mergeProps() instead',
category: 'Possible Errors',
recommended: true,
},
messages: {
classNameClobber:
'className is clobbered by {...stylex.props()}. ' +
- 'Use mergeProps(xdsClassName(...), stylex.props(...)) to merge them correctly.',
+ 'Use mergeProps(themeProps(...), stylex.props(...)) to merge them correctly.',
styleClobber:
'style and {...stylex.props()} clobber each other. ' +
- 'Use mergeProps(xdsClassName(...), stylex.props(...), undefined, style) to merge them correctly.',
+ 'Use mergeProps(themeProps(...), stylex.props(...), undefined, style) to merge them correctly.',
+ spreadClassNameClobber:
+ '{{later}} and {{earlier}} are separate spreads that each set className, so {{later}} replaces the one {{earlier}} built and its classes never reach the DOM. ' +
+ 'Pass both through a single mergeProps() call.',
},
schema: [],
},
create(context) {
return {
JSXOpeningElement(node) {
- const attrs = node.attributes;
-
let hasClassName = false;
let hasStyle = false;
- let hasStylexSpread = false;
+ /** Every spread on this element that independently sets className. */
+ const producers = [];
- for (const attr of attrs) {
+ for (const attr of node.attributes) {
if (attr.type === 'JSXAttribute') {
- if (attr.name?.name === 'className') {
- hasClassName = true;
- }
- if (attr.name?.name === 'style') {
- hasStyle = true;
- }
+ if (attr.name?.name === 'className') hasClassName = true;
+ if (attr.name?.name === 'style') hasStyle = true;
+ continue;
}
- // Check for {...stylex.props(...)}
- if (
- attr.type === 'JSXSpreadAttribute' &&
- attr.argument?.type === 'CallExpression' &&
- attr.argument.callee?.type === 'MemberExpression' &&
- attr.argument.callee.object?.name === 'stylex' &&
- attr.argument.callee.property?.name === 'props'
- ) {
- hasStylexSpread = true;
+ if (attr.type === 'JSXSpreadAttribute') {
+ const producer = classNameProducer(attr.argument);
+ if (producer) producers.push({attr, producer});
}
}
- if (hasStylexSpread) {
+ // Original shape: a literal attribute beside a stylex.props() spread.
+ // Reported against stylex.props() only — it is the one whose class
+ // names a literal className displaces, and widening this half would
+ // re-report every element the spread-versus-spread check already
+ // covers.
+ const stylexSpread = producers.find(
+ ({producer}) => producer === 'stylex.props()',
+ );
+ if (stylexSpread) {
if (hasClassName) {
- context.report({ node, messageId: 'classNameClobber' });
+ context.report({node, messageId: 'classNameClobber'});
}
if (hasStyle) {
- context.report({ node, messageId: 'styleClobber' });
+ context.report({node, messageId: 'styleClobber'});
}
}
+
+ // One report per element rather than one per extra spread: the fix is
+ // a single rewrite of the whole attribute list either way.
+ if (producers.length > 1) {
+ const [earlier, later] = producers;
+ context.report({
+ node: later.attr,
+ messageId: 'spreadClassNameClobber',
+ data: {earlier: earlier.producer, later: later.producer},
+ });
+ }
},
};
},
};
export default rule;
+export {classNameProducer};
diff --git a/internal/eslint-plugin-astryx/no-classname-clobber.test.mjs b/internal/eslint-plugin-astryx/no-classname-clobber.test.mjs
new file mode 100644
index 0000000000..21dcef08b6
--- /dev/null
+++ b/internal/eslint-plugin-astryx/no-classname-clobber.test.mjs
@@ -0,0 +1,175 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file no-classname-clobber.test.mjs
+ * @description Tests for the no-classname-clobber ESLint rule.
+ */
+
+import {RuleTester} from 'eslint';
+import tseslint from 'typescript-eslint';
+import rule from './no-classname-clobber.js';
+
+const ruleTester = new RuleTester({
+ languageOptions: {
+ parser: tseslint.parser,
+ parserOptions: {
+ ecmaFeatures: {jsx: true},
+ sourceType: 'module',
+ },
+ },
+});
+
+ruleTester.run('no-classname-clobber', rule, {
+ valid: [
+ // One className producer on its own.
+ {code: `<div {...stylex.props(styles.root)} />`},
+ {code: `<div {...themeProps('card')} />`},
+ {code: `<div {...focusOutlineProps.focusVisible(styles.root)} />`},
+
+ // The sanctioned merge: both producers inside ONE mergeProps call.
+ {
+ code: `<div {...mergeProps(themeProps('card'), stylex.props(styles.root))} />`,
+ },
+ {
+ code: `<div {...mergeProps(themeProps('card'), stylex.props(styles.root), className, style)} />`,
+ },
+ // Nested mergeProps is still one spread.
+ {
+ code: `<div {...mergeProps(mergeProps(themeProps('card'), stylex.props(styles.root)), rest)} />`,
+ },
+
+ // A producer beside spreads that carry no className. `...rest` and a
+ // hook's prop bag are the two shapes this must never flag.
+ {code: `<div {...rest} {...stylex.props(styles.root)} />`},
+ {code: `<button {...popover.triggerProps} {...stylex.props(styles.root)} />`},
+ {
+ code: `<button {...rest} {...popover.triggerProps} {...stylex.props(styles.root)} />`,
+ },
+
+ // mergeProps merging a producer with a plain object is one producer, so
+ // it is fine beside a spread that produces nothing.
+ {
+ code: `<button {...mergeProps(themeProps('x'), {'aria-haspopup': 'menu'})} {...popover.triggerProps} />`,
+ },
+ // mergeProps merging nothing that carries a className is not a producer.
+ {
+ code: `<div {...mergeProps(rest, {role: 'group'})} {...stylex.props(styles.root)} />`,
+ },
+
+ // No spread at all, so nothing to clobber.
+ {code: `<div className={cls} style={inline} />`},
+ // A literal className beside a NON-stylex spread is out of scope: the
+ // rule speaks about stylex.props(), which is not here.
+ {code: `<div className={cls} {...rest} />`},
+
+ // Unknown calls are not producers, however many there are.
+ {code: `<div {...getAriaProps()} {...useSomething()} />`},
+ ],
+
+ invalid: [
+ // The Breadcrumbs regression, literally. `mergeProps` on the first spread
+ // reads as if merging is handled; the second spread still wins, and
+ // astryx-breadcrumb-item-menu-trigger reached no element.
+ {
+ code: `
+ <button
+ {...mergeProps(themeProps('breadcrumb-item-menu-trigger'), {
+ ...popover.triggerProps,
+ 'aria-haspopup': 'menu',
+ })}
+ {...stylex.props(
+ itemStyles.link,
+ itemStyles.buttonReset,
+ isSupporting ? itemStyles.supportingLink : itemStyles.defaultLink,
+ )}
+ />
+ `,
+ errors: [
+ {
+ messageId: 'spreadClassNameClobber',
+ data: {earlier: 'mergeProps()', later: 'stylex.props()'},
+ },
+ ],
+ },
+
+ // The bare two-spread shape.
+ {
+ code: `<div {...themeProps('card')} {...stylex.props(styles.root)} />`,
+ errors: [{messageId: 'spreadClassNameClobber'}],
+ },
+ // ...and in the other order, which loses the StyleX classes instead.
+ {
+ code: `<div {...stylex.props(styles.root)} {...themeProps('card')} />`,
+ errors: [
+ {
+ messageId: 'spreadClassNameClobber',
+ data: {earlier: 'stylex.props()', later: 'themeProps()'},
+ },
+ ],
+ },
+
+ // Two stylex.props spreads: the second replaces the first outright.
+ {
+ code: `<div {...stylex.props(styles.a)} {...stylex.props(styles.b)} />`,
+ errors: [{messageId: 'spreadClassNameClobber'}],
+ },
+
+ // focusOutlineProps.* returns stylex.props(), so the focus ring is what
+ // gets thrown away here.
+ {
+ code: `<a {...themeProps('link')} {...focusOutlineProps.focusVisible(styles.root)} />`,
+ errors: [
+ {
+ messageId: 'spreadClassNameClobber',
+ data: {earlier: 'themeProps()', later: 'focusOutlineProps.focusVisible()'},
+ },
+ ],
+ },
+
+ // Two mergeProps calls, each carrying a className of its own.
+ {
+ code: `<div {...mergeProps(themeProps('x'), rest)} {...mergeProps(stylex.props(styles.a), other)} />`,
+ errors: [{messageId: 'spreadClassNameClobber'}],
+ },
+
+ // A TS cast around the call does not hide it.
+ {
+ code: `<div {...themeProps('card')} {...(stylex.props(styles.root) as never)} />`,
+ errors: [{messageId: 'spreadClassNameClobber'}],
+ },
+
+ // Unknown spreads in between change nothing.
+ {
+ code: `<div {...themeProps('card')} {...rest} {...stylex.props(styles.root)} />`,
+ errors: [{messageId: 'spreadClassNameClobber'}],
+ },
+
+ // Three producers, one report: the fix rewrites the whole attribute list.
+ {
+ code: `<div {...themeProps('card')} {...stylex.props(styles.a)} {...focusOutlineProps.focusVisible(styles.b)} />`,
+ errors: [{messageId: 'spreadClassNameClobber'}],
+ },
+
+ // The original shape, unchanged: a literal attribute beside the spread.
+ {
+ code: `<div className={cls} {...stylex.props(styles.root)} />`,
+ errors: [{messageId: 'classNameClobber'}],
+ },
+ {
+ code: `<div {...stylex.props(styles.root)} style={inline} />`,
+ errors: [{messageId: 'styleClobber'}],
+ },
+ {
+ code: `<div className={cls} style={inline} {...stylex.props(styles.root)} />`,
+ errors: [{messageId: 'classNameClobber'}, {messageId: 'styleClobber'}],
+ },
+ // Both halves of the rule on one element, reported once each.
+ {
+ code: `<div className={cls} {...themeProps('card')} {...stylex.props(styles.root)} />`,
+ errors: [
+ {messageId: 'classNameClobber'},
+ {messageId: 'spreadClassNameClobber'},
+ ],
+ },
+ ],
+});