Skip to content

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

TypeScript

fix: className/style clobber by stylex.props spread + lint rule (#1462)

Cindy Zhangcf08a504a3f5
diff --git a/internal/eslint-plugin-xds/index.js b/internal/eslint-plugin-xds/index.js
index 3d1c776be7..3526948ffa 100644
--- a/internal/eslint-plugin-xds/index.js
+++ b/internal/eslint-plugin-xds/index.js
@@ -17,6 +17,7 @@ import presentationalComponentRule from './presentational-component.js';
import docblockExampleFormatRule from './docblock-example-format.js';
import noStylexNullOverrideRule from './no-stylex-null-override.js';
import noReactIntrospectionRule from './no-react-introspection.js';
+import noClassnameClobberRule from './no-classname-clobber.js';
// =============================================================================
// Rule: no-hardcoded-styles
@@ -222,6 +223,7 @@ const plugin = {
'docblock-example-format': docblockExampleFormatRule,
'no-stylex-null-override': noStylexNullOverrideRule,
'no-react-introspection': noReactIntrospectionRule,
+ 'no-classname-clobber': noClassnameClobberRule,
},
configs: {},
};
@@ -238,6 +240,7 @@ plugin.configs.strict = {
'@xds/docblock-example-format': 'error',
'@xds/no-stylex-null-override': 'error',
'@xds/no-react-introspection': 'error',
+ '@xds/no-classname-clobber': 'error',
},
};
@@ -253,6 +256,7 @@ plugin.configs.recommended = {
'@xds/docblock-example-format': 'warn',
'@xds/no-stylex-null-override': 'warn',
'@xds/no-react-introspection': 'error',
+ '@xds/no-classname-clobber': 'error',
},
};
diff --git a/internal/eslint-plugin-xds/no-classname-clobber.js b/internal/eslint-plugin-xds/no-classname-clobber.js
new file mode 100644
index 0000000000..56400b1700
--- /dev/null
+++ b/internal/eslint-plugin-xds/no-classname-clobber.js
@@ -0,0 +1,85 @@
+/**
+ * @file no-classname-clobber.js
+ * @description Disallow `className` or `style` alongside `{...stylex.props()}` on JSX elements.
+ *
+ * `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.
+ *
+ * Fix: Use `mergeProps(xdsClassName(...), stylex.props(...), className, style)`
+ * which concatenates class names and merges style objects correctly.
+ *
+ * Bad:
+ * <div className={xdsClassName('foo')} {...stylex.props(styles.root)} />
+ * <div style={dynamicStyle} {...stylex.props(styles.root)} />
+ * <div {...stylex.props(styles.root)} style={dynamicStyle} />
+ *
+ * Good:
+ * <div {...mergeProps(xdsClassName('foo'), stylex.props(styles.root))} />
+ * <div {...mergeProps(xdsClassName('foo'), stylex.props(styles.root), undefined, dynamicStyle)} />
+ */
+
+const rule = {
+ meta: {
+ type: 'problem',
+ docs: {
+ description:
+ 'Disallow className/style alongside {...stylex.props()} — 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.',
+ styleClobber:
+ 'style and {...stylex.props()} clobber each other. ' +
+ 'Use mergeProps(xdsClassName(...), stylex.props(...), undefined, style) to merge them correctly.',
+ },
+ schema: [],
+ },
+ create(context) {
+ return {
+ JSXOpeningElement(node) {
+ const attrs = node.attributes;
+
+ let hasClassName = false;
+ let hasStyle = false;
+ let hasStylexSpread = false;
+
+ for (const attr of attrs) {
+ if (attr.type === 'JSXAttribute') {
+ if (attr.name?.name === 'className') {
+ hasClassName = true;
+ }
+ if (attr.name?.name === 'style') {
+ hasStyle = true;
+ }
+ }
+
+ // 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 (hasStylexSpread) {
+ if (hasClassName) {
+ context.report({ node, messageId: 'classNameClobber' });
+ }
+ if (hasStyle) {
+ context.report({ node, messageId: 'styleClobber' });
+ }
+ }
+ },
+ };
+ },
+};
+
+export default rule;
diff --git a/packages/core/src/Chat/XDSChatComposerInput.tsx b/packages/core/src/Chat/XDSChatComposerInput.tsx
index 0fd4c998f4..de242b5c5c 100644
--- a/packages/core/src/Chat/XDSChatComposerInput.tsx
+++ b/packages/core/src/Chat/XDSChatComposerInput.tsx
@@ -566,8 +566,7 @@ export function XDSChatComposerInput(props: XDSChatComposerInputProps) {
onKeyDown={handleKeyDown}
onPaste={handlePaste}
{...triggerMenu.ariaProps}
- {...stylex.props(styles.editable)}
- style={{maxHeight: `${maxHeight}px`}}
+ {...mergeProps(stylex.props(styles.editable), {style: {maxHeight: `${maxHeight}px`}})}
/>
{triggerMenu.renderMenu()}
{tokens.tokenPortals
diff --git a/packages/core/src/Chat/XDSChatDictationButton.tsx b/packages/core/src/Chat/XDSChatDictationButton.tsx
index 14fbed32a0..3db2d1630c 100644
--- a/packages/core/src/Chat/XDSChatDictationButton.tsx
+++ b/packages/core/src/Chat/XDSChatDictationButton.tsx
@@ -21,6 +21,7 @@ import type {StyleXStyles} from '@stylexjs/stylex';
import {colorVars, radiusVars} from '../theme/tokens.stylex';
import {XDSButton} from '../Button';
import {XDSIcon} from '../Icon';
+import {mergeProps} from '../utils';
// =============================================================================
// Types
@@ -116,20 +117,18 @@ export function XDSChatDictationButton({
{isListening && (
<span
aria-hidden
- {...stylex.props(styles.barsContainer)}
- style={{gap: barGap, height: barMaxHeight}}>
+ {...mergeProps(stylex.props(styles.barsContainer), {style: {gap: barGap, height: barMaxHeight}})}>
{boostedBands.slice(0, BAR_COUNT).map((level, i) => {
const scale = BAR_MIN_SCALE + level * (1 - BAR_MIN_SCALE);
return (
<span
key={i}
- {...stylex.props(styles.bar)}
- style={{
+ {...mergeProps(stylex.props(styles.bar), {style: {
width: barWidth,
height: '100%',
backgroundColor: barColor,
transform: `scaleY(${scale})`,
- }}
+ }})}
/>
);
})}
diff --git a/packages/core/src/Chat/XDSChatMessageMetadata.tsx b/packages/core/src/Chat/XDSChatMessageMetadata.tsx
index bd71dec67b..4d73160352 100644
--- a/packages/core/src/Chat/XDSChatMessageMetadata.tsx
+++ b/packages/core/src/Chat/XDSChatMessageMetadata.tsx
@@ -21,7 +21,7 @@ import {
import {useXDSChatMessageContext} from './XDSChatContext';
import {XDSIcon} from '../Icon';
import type {XDSIconName} from '../Icon/globalIconRegistry';
-import {xdsClassName} from '../utils';
+import {mergeProps, xdsClassName} from '../utils';
export type XDSChatMessageStatus =
| 'sending'
@@ -121,10 +121,12 @@ export function XDSChatMessageMetadata({
return (
<div
- className={xdsClassName('chat-message-metadata')}
- {...stylex.props(
- styles.meta,
- sender === 'user' ? styles.metaUser : styles.metaAssistant,
+ {...mergeProps(
+ xdsClassName('chat-message-metadata'),
+ stylex.props(
+ styles.meta,
+ sender === 'user' ? styles.metaUser : styles.metaAssistant,
+ ),
)}>
{timestamp != null && <span>{timestamp}</span>}
{timestamp != null && (footer != null || statusConfig != null) && (
diff --git a/packages/core/src/Chat/XDSChatTokenizedText.tsx b/packages/core/src/Chat/XDSChatTokenizedText.tsx
index 8810318bff..5417696a34 100644
--- a/packages/core/src/Chat/XDSChatTokenizedText.tsx
+++ b/packages/core/src/Chat/XDSChatTokenizedText.tsx
@@ -18,7 +18,7 @@ import type {ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import {XDSBadge} from '../Badge';
import type {XDSChatComposerToken} from './XDSChatComposerInput';
-import {xdsClassName} from '../utils';
+import {mergeProps, xdsClassName} from '../utils';
// =============================================================================
// Styles
@@ -86,11 +86,27 @@ export function XDSChatTokenizedText({
tokens,
}: XDSChatTokenizedTextProps) {
if (!children || !tokens || tokens.length === 0) {
- return <span className={xdsClassName('chat-tokenized-text')} {...stylex.props(styles.root)}>{children ?? ''}</span>;
+ return (
+ <span
+ {...mergeProps(
+ xdsClassName('chat-tokenized-text'),
+ stylex.props(styles.root),
+ )}>
+ {children ?? ''}
+ </span>
+ );
}
const parts = renderTokens(children, tokens);
- return <span className={xdsClassName('chat-tokenized-text')} {...stylex.props(styles.root)}>{parts}</span>;
+ return (
+ <span
+ {...mergeProps(
+ xdsClassName('chat-tokenized-text'),
+ stylex.props(styles.root),
+ )}>
+ {parts}
+ </span>
+ );
}
XDSChatTokenizedText.displayName = 'XDSChatTokenizedText';
diff --git a/packages/core/src/CodeBlock/XDSCodeBlock.tsx b/packages/core/src/CodeBlock/XDSCodeBlock.tsx
index 84ea00d799..ea3eaf4d41 100644
--- a/packages/core/src/CodeBlock/XDSCodeBlock.tsx
+++ b/packages/core/src/CodeBlock/XDSCodeBlock.tsx
@@ -280,8 +280,7 @@ function renderLines(
chunks.push(
<div
key={start}
- {...stylex.props(styles.lineChunk)}
- style={{containIntrinsicBlockSize: `auto ${estimatedHeight}`}}>
+ {...mergeProps(stylex.props(styles.lineChunk), {style: {containIntrinsicBlockSize: `auto ${estimatedHeight}`}})}>
<CodeChunk
lines={chunkLines}
startIndex={start}
@@ -646,8 +645,7 @@ export function XDSCodeBlock({
const codeBody = (
<div
ref={scrollContainerRef}
- {...stylex.props(styles.scrollContainer)}
- style={scrollStyle}>
+ {...mergeProps(stylex.props(styles.scrollContainer), {style: scrollStyle})}>
<div
{...stylex.props(
styles.codeWrapper,
diff --git a/packages/core/src/MetadataList/XDSMetadataList.tsx b/packages/core/src/MetadataList/XDSMetadataList.tsx
index 008cd2dda4..76069d6060 100644
--- a/packages/core/src/MetadataList/XDSMetadataList.tsx
+++ b/packages/core/src/MetadataList/XDSMetadataList.tsx
@@ -266,8 +266,7 @@ export function XDSMetadataList({
{titleContent}
<dl
id={contentId}
- style={dynamicGridStyle}
- {...stylex.props(styles.dl, getGridStyle())}>
+ {...mergeProps(stylex.props(styles.dl, getGridStyle()), {style: dynamicGridStyle})}>
{visibleChildren}
</dl>
{isExceedMax && (
diff --git a/packages/core/src/SideNav/XDSSideNav.tsx b/packages/core/src/SideNav/XDSSideNav.tsx
index 643ae8b988..25b1dccc8e 100644
--- a/packages/core/src/SideNav/XDSSideNav.tsx
+++ b/packages/core/src/SideNav/XDSSideNav.tsx
@@ -502,8 +502,7 @@ export function XDSSideNav({
const content = showResizeHandle ? (
<div
ref={containerRef}
- {...stylex.props(styles.resizableContainer)}
- style={{width}}>
+ {...mergeProps(stylex.props(styles.resizableContainer), {style: {width}})}>
{navElement}
<div
data-testid="xds-sidenav-resize-handle"
diff --git a/packages/core/src/SideNav/XDSSideNavSection.tsx b/packages/core/src/SideNav/XDSSideNavSection.tsx
index e3ed271099..9d280c46f4 100644
--- a/packages/core/src/SideNav/XDSSideNavSection.tsx
+++ b/packages/core/src/SideNav/XDSSideNavSection.tsx
@@ -184,8 +184,7 @@ export function XDSSideNavSection({
stylex.props(styles.root),
)}>
<div
- style={shouldHideHeader ? visuallyHiddenStyle : undefined}
- {...stylex.props(styles.header)}>
+ {...mergeProps(stylex.props(styles.header), {style: shouldHideHeader ? visuallyHiddenStyle : undefined})}>
{headerContent}
</div>
<div {...stylex.props(styles.items)}>{children}</div>
diff --git a/packages/core/src/Slider/XDSSlider.tsx b/packages/core/src/Slider/XDSSlider.tsx
index da43f20455..fc024d3094 100644
--- a/packages/core/src/Slider/XDSSlider.tsx
+++ b/packages/core/src/Slider/XDSSlider.tsx
@@ -771,13 +771,15 @@ export function XDSSlider({ref, ...props}: XDSSliderProps) {
{/* Filled track */}
<div
aria-hidden="true"
- {...stylex.props(
- styles.filledTrack,
- isHorizontal
- ? styles.filledTrackHorizontal
- : styles.filledTrackVertical,
+ {...mergeProps(
+ stylex.props(
+ styles.filledTrack,
+ isHorizontal
+ ? styles.filledTrackHorizontal
+ : styles.filledTrackVertical,
+ ),
+ {style: filledStyle},
)}
- style={filledStyle}
/>
{/* Marks */}
@@ -800,25 +802,29 @@ export function XDSSlider({ref, ...props}: XDSSliderProps) {
<div
data-testid="slider-mark"
data-mark-value={mark.value}
- {...stylex.props(
- styles.mark,
- isHorizontal
- ? styles.markHorizontal
- : styles.markVertical,
+ {...mergeProps(
+ stylex.props(
+ styles.mark,
+ isHorizontal
+ ? styles.markHorizontal
+ : styles.markVertical,
+ ),
+ {style: markPos},
)}
- style={markPos}
/>
{mark.label && (
<span
data-testid="slider-mark-label"
data-mark-value={mark.value}
- {...stylex.props(
- styles.markLabel,
- isHorizontal
- ? styles.markLabelHorizontal
- : styles.markLabelVertical,
- )}
- style={markPos}>
+ {...mergeProps(
+ stylex.props(
+ styles.markLabel,
+ isHorizontal
+ ? styles.markLabelHorizontal
+ : styles.markLabelVertical,
+ ),
+ {style: markPos},
+ )}>
{mark.label}
</span>
)}
diff --git a/packages/core/src/Toast/XDSToastViewport.tsx b/packages/core/src/Toast/XDSToastViewport.tsx
index 426992752c..7689ceab25 100644
--- a/packages/core/src/Toast/XDSToastViewport.tsx
+++ b/packages/core/src/Toast/XDSToastViewport.tsx
@@ -3,6 +3,7 @@
import {useCallback, useEffect, useMemo, useRef, useState} from 'react';
import * as stylex from '@stylexjs/stylex';
import {spacingVars, durationVars, easeVars} from '../theme/tokens.stylex';
+import {mergeProps} from '../utils';
import {XDSToast} from './XDSToast';
import {XDSToastContext, type XDSToastContextValue} from './XDSToastContext';
import type {
@@ -187,8 +188,7 @@ export function XDSToastViewport({
// popover="manual" promotes to the top layer (above dialogs).
// Omitted inside dialogs where the viewport is already in a top layer.
popover={isTopLayer ? 'manual' : undefined}
- {...stylex.props(styles.viewport, posStyle)}
- style={Object.keys(insetStyle).length > 0 ? insetStyle : undefined}>
+ {...mergeProps(stylex.props(styles.viewport, posStyle), {style: Object.keys(insetStyle).length > 0 ? insetStyle : undefined})}>
{visibleToasts.map(entry => {
const o = entry.options;
const type = o.type ?? 'info';
diff --git a/packages/core/src/TreeList/XDSTreeListBranches.tsx b/packages/core/src/TreeList/XDSTreeListBranches.tsx
index a6de333c3c..1e916d6d72 100644
--- a/packages/core/src/TreeList/XDSTreeListBranches.tsx
+++ b/packages/core/src/TreeList/XDSTreeListBranches.tsx
@@ -12,6 +12,7 @@
import * as stylex from '@stylexjs/stylex';
import {colorVars, spacingVars} from '../theme/tokens.stylex';
+import {mergeProps} from '../utils';
const LINE_WIDTH = 1;
@@ -80,10 +81,9 @@ export function XDSTreeListBranches({
level !== nestedLevel - 1 && (
<div
key={level}
- {...stylex.props(styles.container)}
- style={{
+ {...mergeProps(stylex.props(styles.container), {style: {
left: `calc(${BRANCH_MARGIN} + ${level} * ${LEVEL_INDENT})`,
- }}>
+ }})}>
<div
{...stylex.props(styles.verticalLine, styles.verticalFull)}
/>
@@ -92,10 +92,9 @@ export function XDSTreeListBranches({
)}
{nestedLevel > 0 && (
<div
- {...stylex.props(styles.container)}
- style={{
+ {...mergeProps(stylex.props(styles.container), {style: {
left: `calc(${BRANCH_MARGIN} + ${nestedLevel - 1} * ${LEVEL_INDENT})`,
- }}>
+ }})}>
<div
{...stylex.props(
styles.verticalLine,
diff --git a/packages/core/src/utils/mergeProps.ts b/packages/core/src/utils/mergeProps.ts
index 0622747c7f..ce7d7aa355 100644
--- a/packages/core/src/utils/mergeProps.ts
+++ b/packages/core/src/utils/mergeProps.ts
@@ -10,31 +10,71 @@
*
* @example
* ```tsx
+ * // Root element with xdsClassName
* <div {...mergeProps(
* xdsClassName('button', { variant }),
* stylex.props(styles.base, variants[variant]),
* className,
* style,
* )} />
+ *
+ * // Internal element — stylex + dynamic style only
+ * <div {...mergeProps(
+ * stylex.props(styles.track),
+ * { style: { width: dynamicWidth } },
+ * )} />
* ```
*/
export function mergeProps(
- xdsClass: string,
- stylexResult: {className?: string; style?: object},
- className?: string,
+ xdsClassOrStylexResult: string | {className?: string; style?: object},
+ stylexResultOrClassName?:
+ | {className?: string; style?: object}
+ | string
+ | undefined,
+ classNameOrStyle?: string | React.CSSProperties,
style?: React.CSSProperties,
): {className: string; style?: object} {
- let cls = stylexResult.className
- ? `${xdsClass} ${stylexResult.className}`
- : xdsClass;
- if (className) {
- cls = `${cls} ${className}`;
+ // Disambiguate: first arg is string → (xdsClass, stylexResult, className?, style?)
+ // first arg is object → (stylexResult, overrides?, ...)
+ if (typeof xdsClassOrStylexResult === 'string') {
+ const xdsClass = xdsClassOrStylexResult;
+ const stylexResult = (stylexResultOrClassName as {
+ className?: string;
+ style?: object;
+ }) ?? {className: ''};
+ const className = classNameOrStyle as string | undefined;
+
+ let cls = stylexResult.className
+ ? `${xdsClass} ${stylexResult.className}`
+ : xdsClass;
+ if (className) {
+ cls = `${cls} ${className}`;
+ }
+
+ const mergedStyle =
+ style && stylexResult.style
+ ? {...stylexResult.style, ...style}
+ : style || stylexResult.style;
+
+ return {className: cls, style: mergedStyle};
+ }
+
+ // Object form: mergeProps(stylex.props(...), { style, className })
+ const base = xdsClassOrStylexResult;
+ const overrides = (stylexResultOrClassName as {
+ className?: string;
+ style?: object;
+ }) ?? {};
+
+ let cls = base.className ?? '';
+ if (overrides.className) {
+ cls = cls ? `${cls} ${overrides.className}` : overrides.className;
}
const mergedStyle =
- style && stylexResult.style
- ? {...stylexResult.style, ...style}
- : style || stylexResult.style;
+ overrides.style && base.style
+ ? {...base.style, ...overrides.style}
+ : overrides.style || base.style;
return {className: cls, style: mergedStyle};
}