Skip to content

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

TypeScript

feat(lint): add no-react-introspection ESLint rule (#1297)

Cindy Zhang396a67a890fd
diff --git a/eslint.config.js b/eslint.config.js
index a0babf178c..e69a8df605 100644
--- a/eslint.config.js
+++ b/eslint.config.js
@@ -60,5 +60,17 @@ export default tseslint.config(
files: ["packages/core/src/**/*.{ts,tsx}"],
ignores: ["packages/core/src/theme/**"],
...xdsConfig,
+ rules: {
+ ...xdsConfig.rules,
+ // Temporarily allow Children.* in files that need architectural fixes.
+ // Tracked: OverflowList, MetadataList, Carousel need data-driven APIs.
+ '@xds/no-react-introspection': ['error', {
+ allowFiles: [
+ 'OverflowList/XDSOverflowList',
+ 'MetadataList/XDSMetadataList',
+ 'Carousel/XDSCarousel',
+ ],
+ }],
+ },
},
);
diff --git a/internal/eslint-plugin-xds/index.js b/internal/eslint-plugin-xds/index.js
index a32e2b845e..3d1c776be7 100644
--- a/internal/eslint-plugin-xds/index.js
+++ b/internal/eslint-plugin-xds/index.js
@@ -16,6 +16,7 @@ import booleanPropNamingRule from './boolean-prop-naming.js';
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';
// =============================================================================
// Rule: no-hardcoded-styles
@@ -220,6 +221,7 @@ const plugin = {
'presentational-component': presentationalComponentRule,
'docblock-example-format': docblockExampleFormatRule,
'no-stylex-null-override': noStylexNullOverrideRule,
+ 'no-react-introspection': noReactIntrospectionRule,
},
configs: {},
};
@@ -235,6 +237,7 @@ plugin.configs.strict = {
'@xds/presentational-component': 'error',
'@xds/docblock-example-format': 'error',
'@xds/no-stylex-null-override': 'error',
+ '@xds/no-react-introspection': 'error',
},
};
@@ -249,6 +252,7 @@ plugin.configs.recommended = {
'@xds/presentational-component': 'error',
'@xds/docblock-example-format': 'warn',
'@xds/no-stylex-null-override': 'warn',
+ '@xds/no-react-introspection': 'error',
},
};
diff --git a/internal/eslint-plugin-xds/no-react-introspection.js b/internal/eslint-plugin-xds/no-react-introspection.js
new file mode 100644
index 0000000000..360877d523
--- /dev/null
+++ b/internal/eslint-plugin-xds/no-react-introspection.js
@@ -0,0 +1,181 @@
+/**
+ * @file no-react-introspection.js
+ * @description ESLint rule banning React child introspection and prop inspection.
+ *
+ * React introspection (Children.map, Children.forEach, Children.toArray,
+ * Children.count, cloneElement, child.type, child.props)
+ * creates fragile coupling between parent and child components:
+ *
+ * - Breaks when children are wrapped in HOCs, forwardRef, or memo
+ * - Prevents React from optimizing rendering
+ * - Creates implicit contracts that types can't enforce
+ * - Makes composition unpredictable (fragments, portals, etc.)
+ *
+ * Alternatives:
+ * - Compound components with context
+ * - Render props or slot props
+ * - Data-driven APIs (array of config objects)
+ * - CSS-based solutions (grid, flexbox, :nth-child, etc.)
+ *
+ * @see https://github.com/facebookexperimental/xds/wiki/API-Conventions
+ */
+
+// React.Children methods that introspect the children tree
+const CHILDREN_METHODS = new Set([
+ 'map',
+ 'forEach',
+ 'toArray',
+ 'count',
+ 'only',
+]);
+
+const noReactIntrospectionRule = {
+ meta: {
+ type: 'problem',
+ docs: {
+ description:
+ 'Ban React child introspection (Children.map, cloneElement, child.props, child.type)',
+ category: 'XDS Architecture',
+ recommended: true,
+ url: 'https://github.com/facebookexperimental/xds/wiki/API-Conventions',
+ },
+ messages: {
+ childrenMethod:
+ 'React.Children.{{method}}() introspects the children tree. ' +
+ 'Use a data-driven API (array prop), compound components with context, or CSS layout instead.',
+ cloneElement:
+ 'cloneElement() injects props into children. ' +
+ 'Use context, a wrapper component, or a render-prop API instead.',
+ propAccess:
+ 'Accessing .props on a React element inspects child internals. ' +
+ 'Use context or a data-driven API to pass information between components.',
+ typeAccess:
+ 'Accessing .type on a React element inspects child identity. ' +
+ 'Use a data-driven API (discriminated union) or compound components with context.',
+ },
+ schema: [
+ {
+ type: 'object',
+ properties: {
+ // Specific files that are allowed to use introspection
+ // (escape hatch for legitimate cases like DevTools, test utils)
+ allowFiles: {
+ type: 'array',
+ items: {type: 'string'},
+ },
+ },
+ additionalProperties: false,
+ },
+ ],
+ },
+ create(context) {
+ const options = context.options[0] || {};
+ const allowFiles = options.allowFiles || [];
+
+ // Check if this file is explicitly allowed
+ const filename = context.getFilename();
+ if (allowFiles.some(pattern => filename.includes(pattern))) {
+ return {};
+ }
+
+ return {
+ // Catch: React.Children.map(), Children.forEach(), etc.
+ // Also catches: React.isValidElement(), React.cloneElement()
+ CallExpression(node) {
+ const callee = node.callee;
+
+ // React.Children.method() or Children.method()
+ if (callee.type === 'MemberExpression') {
+ const obj = callee.object;
+ const prop = callee.property;
+
+ // Children.map(), Children.forEach(), etc.
+ if (
+ obj.type === 'Identifier' &&
+ obj.name === 'Children' &&
+ prop.type === 'Identifier' &&
+ CHILDREN_METHODS.has(prop.name)
+ ) {
+ context.report({
+ node,
+ messageId: 'childrenMethod',
+ data: {method: prop.name},
+ });
+ return;
+ }
+
+ // React.Children.method()
+ if (
+ obj.type === 'MemberExpression' &&
+ obj.object?.type === 'Identifier' &&
+ obj.object.name === 'React' &&
+ obj.property?.type === 'Identifier' &&
+ obj.property.name === 'Children' &&
+ prop.type === 'Identifier' &&
+ CHILDREN_METHODS.has(prop.name)
+ ) {
+ context.report({
+ node,
+ messageId: 'childrenMethod',
+ data: {method: prop.name},
+ });
+ return;
+ }
+
+ // React.cloneElement()
+ if (
+ obj.type === 'Identifier' &&
+ obj.name === 'React' &&
+ prop.type === 'Identifier' &&
+ prop.name === 'cloneElement'
+ ) {
+ context.report({node, messageId: 'cloneElement'});
+ return;
+ }
+ }
+
+ // Direct call: cloneElement()
+ if (callee.type === 'Identifier') {
+ if (callee.name === 'cloneElement') {
+ context.report({node, messageId: 'cloneElement'});
+ return;
+ }
+ }
+ },
+
+ // Catch: child.props.X, child.type
+ MemberExpression(node) {
+ // Only flag on identifiers (not computed access like obj[key])
+ if (node.computed) return;
+
+ const prop = node.property;
+ if (prop.type !== 'Identifier') return;
+
+ // child.props or child.type — but only on variables that came from
+ // Children iteration or isValidElement checks.
+ // Heuristic: flag .props and .type access on variables named
+ // 'child', 'item', 'element', or 'el' — common iteration variable names.
+ // This avoids false positives on data objects.
+ if (prop.name === 'props' || prop.name === 'type') {
+ const obj = node.object;
+ if (obj.type === 'Identifier') {
+ const name = obj.name.toLowerCase();
+ // Common child-iteration variable names
+ if (
+ name === 'child' ||
+ name === 'element' ||
+ name === 'el' ||
+ name === 'item'
+ ) {
+ const messageId =
+ prop.name === 'props' ? 'propAccess' : 'typeAccess';
+ context.report({node, messageId});
+ }
+ }
+ }
+ },
+ };
+ },
+};
+
+export default noReactIntrospectionRule;
diff --git a/internal/eslint-plugin-xds/no-react-introspection.test.mjs b/internal/eslint-plugin-xds/no-react-introspection.test.mjs
new file mode 100644
index 0000000000..9656ccc5bd
--- /dev/null
+++ b/internal/eslint-plugin-xds/no-react-introspection.test.mjs
@@ -0,0 +1,90 @@
+import {RuleTester} from 'eslint';
+import noReactIntrospectionRule from './no-react-introspection.js';
+
+const tester = new RuleTester({
+ languageOptions: {
+ ecmaVersion: 2022,
+ sourceType: 'module',
+ parserOptions: {ecmaFeatures: {jsx: true}},
+ },
+});
+
+tester.run('no-react-introspection', noReactIntrospectionRule, {
+ valid: [
+ // Data-driven API
+ {code: `function Tabs({ items }) { return items.map(item => item); }`},
+ // Pass-through children
+ {code: `function TabList({ children }) { return children; }`},
+ // Normal .type access on data objects
+ {code: `const x = option.type === 'divider';`},
+ // Normal .props on data objects
+ {code: `const x = config.props.label;`},
+ // isValidElement is allowed — it's a type guard, not introspection
+ {code: `import { isValidElement } from 'react'; if (isValidElement(x)) {}`},
+ {code: `if (React.isValidElement(x)) {}`},
+ // allowFiles escape hatch
+ {
+ code: `import { Children } from 'react'; Children.map(children, c => c);`,
+ options: [{allowFiles: ['test-utils']}],
+ filename: '/packages/test-utils/src/helpers.tsx',
+ },
+ ],
+ invalid: [
+ // Children.toArray
+ {
+ code: `import { Children } from 'react'; const items = Children.toArray(children);`,
+ errors: [{messageId: 'childrenMethod'}],
+ },
+ // Children.map
+ {
+ code: `import { Children } from 'react'; Children.map(children, c => c);`,
+ errors: [{messageId: 'childrenMethod'}],
+ },
+ // Children.forEach
+ {
+ code: `import { Children } from 'react'; Children.forEach(children, c => c);`,
+ errors: [{messageId: 'childrenMethod'}],
+ },
+ // Children.count
+ {
+ code: `import { Children } from 'react'; const n = Children.count(children);`,
+ errors: [{messageId: 'childrenMethod'}],
+ },
+ // React.Children.map
+ {
+ code: `React.Children.map(children, c => c);`,
+ errors: [{messageId: 'childrenMethod'}],
+ },
+ // React.Children.forEach
+ {
+ code: `React.Children.forEach(children, c => c);`,
+ errors: [{messageId: 'childrenMethod'}],
+ },
+ // cloneElement
+ {
+ code: `import { cloneElement } from 'react'; cloneElement(x, { a: 1 });`,
+ errors: [{messageId: 'cloneElement'}],
+ },
+ {
+ code: `React.cloneElement(x, { a: 1 });`,
+ errors: [{messageId: 'cloneElement'}],
+ },
+ // child.props access
+ {
+ code: `const val = child.props.isCurrent;`,
+ errors: [{messageId: 'propAccess'}],
+ },
+ // child.type access
+ {
+ code: `if (child.type === Foo) {}`,
+ errors: [{messageId: 'typeAccess'}],
+ },
+ // element.props access
+ {
+ code: `const val = element.props.name;`,
+ errors: [{messageId: 'propAccess'}],
+ },
+ ],
+});
+
+console.log('All tests passed!');
diff --git a/packages/core/src/Breadcrumbs/XDSBreadcrumbItem.tsx b/packages/core/src/Breadcrumbs/XDSBreadcrumbItem.tsx
index d638a0e756..88b2573564 100644
--- a/packages/core/src/Breadcrumbs/XDSBreadcrumbItem.tsx
+++ b/packages/core/src/Breadcrumbs/XDSBreadcrumbItem.tsx
@@ -2,7 +2,7 @@
/**
* @file XDSBreadcrumbItem.tsx
- * @input Uses React useContext, stylex, theme tokens, BreadcrumbContext
+ * @input Uses React useContext/useRef/useEffect, stylex, theme tokens, BreadcrumbContext
* @output Exports XDSBreadcrumbItem component and XDSBreadcrumbItemProps
* @position Individual breadcrumb item; used inside XDSBreadcrumbs
*
@@ -13,7 +13,13 @@
* - /apps/storybook/stories/Breadcrumbs.stories.tsx
*/
-import {useContext, type ReactNode, type MouseEvent} from 'react';
+import {
+ useContext,
+ useRef,
+ useEffect,
+ type ReactNode,
+ type MouseEvent,
+} from 'react';
import * as stylex from '@stylexjs/stylex';
import {colorVars, spacingVars, typeScaleVars} from '../theme/tokens.stylex';
import {BreadcrumbCtx} from './XDSBreadcrumbs';
@@ -70,6 +76,10 @@ const itemStyles = stylex.create({
alignItems: 'center',
gap: spacingVars['--spacing-1'],
margin: 0,
+ '--separator-display': {
+ default: 'flex',
+ ':first-child': 'none',
+ },
},
defaultSize: {
fontSize: typeScaleVars['--text-body-size'],
@@ -117,6 +127,13 @@ const itemStyles = stylex.create({
alignItems: 'center',
flexShrink: 0,
},
+ separator: {
+ display: 'var(--separator-display)',
+ alignItems: 'center',
+ color: colorVars['--color-text-secondary'],
+ paddingBlock: spacingVars['--spacing-1'],
+ userSelect: 'none',
+ },
});
// =============================================================================
@@ -127,6 +144,10 @@ const itemStyles = stylex.create({
* An individual breadcrumb item. Renders as a link (`<a>`) or a span
* depending on whether it represents the current page.
*
+ * Each item renders its own leading separator, hidden on :first-child via
+ * CSS. Auto-current detection uses a post-render effect that checks the
+ * DOM — no React child introspection.
+ *
* @example
* ```
* <XDSBreadcrumbItem href="/projects">Projects</XDSBreadcrumbItem>
@@ -143,9 +164,37 @@ export function XDSBreadcrumbItem({
'data-testid': testId,
}: XDSBreadcrumbItemProps) {
const ctx = useContext(BreadcrumbCtx);
- const isCurrent = isCurrentProp ?? ctx.isAutoLast;
const LinkComponent = useXDSLinkComponent(as);
const isSupporting = ctx.variant === 'supporting';
+ const liRef = useRef<HTMLLIElement>(null);
+
+ const isCurrent = isCurrentProp === true;
+ const isAutoCandidate = isCurrentProp == null;
+
+ // Auto-detect: if no sibling has aria-current="page" and this is the last
+ // non-separator item, set aria-current on our content element.
+ // Runs as useEffect (not layout) — only sets an aria attribute, no visual change.
+ useEffect(() => {
+ if (!isAutoCandidate) return;
+
+ const li = liRef.current;
+ if (!li) return;
+ const ol = li.parentElement;
+ if (!ol) return;
+
+ // All breadcrumb items (li without aria-hidden are items, with aria-hidden are separators — but we no longer have separator lis)
+ const items = Array.from(ol.children) as HTMLElement[];
+ const isLast = items.length > 0 && items[items.length - 1] === li;
+ const hasExplicit = ol.querySelector('[aria-current="page"]');
+
+ if (isLast && !hasExplicit) {
+ li.setAttribute('aria-current', 'page');
+ }
+
+ return () => {
+ li.removeAttribute('aria-current');
+ };
+ });
const content = (
<>
@@ -157,6 +206,7 @@ export function XDSBreadcrumbItem({
if (isCurrent) {
return (
<li
+ ref={liRef}
{...mergeProps(
xdsClassName('breadcrumb-item'),
stylex.props(
@@ -165,6 +215,9 @@ export function XDSBreadcrumbItem({
),
)}
data-testid={testId}>
+ <span aria-hidden="true" {...stylex.props(itemStyles.separator)}>
+ {ctx.separator}
+ </span>
<span
{...stylex.props(
itemStyles.contentWrapper,
@@ -180,8 +233,11 @@ export function XDSBreadcrumbItem({
);
}
+ // Items without isCurrent set render as links (if href) or plain spans.
+ // The effect handles adding aria-current for auto-last detection.
return (
<li
+ ref={liRef}
{...mergeProps(
xdsClassName('breadcrumb-item'),
stylex.props(
@@ -190,15 +246,31 @@ export function XDSBreadcrumbItem({
),
)}
data-testid={testId}>
- <LinkComponent
- href={href}
- onClick={onClick}
- {...stylex.props(
- itemStyles.link,
- isSupporting ? itemStyles.supportingLink : itemStyles.defaultLink,
- )}>
- {content}
- </LinkComponent>
+ <span aria-hidden="true" {...stylex.props(itemStyles.separator)}>
+ {ctx.separator}
+ </span>
+ {href != null ? (
+ <LinkComponent
+ href={href}
+ onClick={onClick}
+ {...stylex.props(
+ itemStyles.link,
+ isSupporting ? itemStyles.supportingLink : itemStyles.defaultLink,
+ )}>
+ {content}
+ </LinkComponent>
+ ) : (
+ <span
+ {...stylex.props(
+ itemStyles.contentWrapper,
+ itemStyles.current,
+ isSupporting
+ ? itemStyles.supportingCurrent
+ : itemStyles.defaultCurrent,
+ )}>
+ {content}
+ </span>
+ )}
</li>
);
}
diff --git a/packages/core/src/Breadcrumbs/XDSBreadcrumbs.test.tsx b/packages/core/src/Breadcrumbs/XDSBreadcrumbs.test.tsx
index d3b8caa55d..ba159b56d4 100644
--- a/packages/core/src/Breadcrumbs/XDSBreadcrumbs.test.tsx
+++ b/packages/core/src/Breadcrumbs/XDSBreadcrumbs.test.tsx
@@ -1,5 +1,5 @@
import {describe, it, expect, vi} from 'vitest';
-import {render, screen} from '@testing-library/react';
+import {render, screen, waitFor} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {forwardRef, type ComponentPropsWithoutRef} from 'react';
import {XDSBreadcrumbs} from './XDSBreadcrumbs';
@@ -57,8 +57,9 @@ describe('XDSBreadcrumbs', () => {
<XDSBreadcrumbItem isCurrent>Detail</XDSBreadcrumbItem>
</XDSBreadcrumbs>,
);
- const separators = container.querySelectorAll('li[aria-hidden="true"]');
- expect(separators).toHaveLength(2);
+ // Each item renders its own separator span; first is hidden via CSS
+ const separators = container.querySelectorAll('span[aria-hidden="true"]');
+ expect(separators).toHaveLength(3);
expect(separators[0].textContent).toBe('/');
});
@@ -69,19 +70,22 @@ describe('XDSBreadcrumbs', () => {
<XDSBreadcrumbItem isCurrent>Page</XDSBreadcrumbItem>
</XDSBreadcrumbs>,
);
- const separators = container.querySelectorAll('li[aria-hidden="true"]');
- expect(separators[0].textContent).toBe('›');
+ const separators = container.querySelectorAll('span[aria-hidden="true"]');
+ // Custom separator content is nested inside the aria-hidden span
+ // First item's separator is hidden via CSS, but still in the DOM
+ expect(separators[1].textContent).toBe('›');
});
- it('separators have role="presentation"', () => {
+ it('separators are aria-hidden', () => {
const {container} = render(
<XDSBreadcrumbs>
<XDSBreadcrumbItem href="/">Home</XDSBreadcrumbItem>
<XDSBreadcrumbItem isCurrent>Page</XDSBreadcrumbItem>
</XDSBreadcrumbs>,
);
- const separators = container.querySelectorAll('li[aria-hidden="true"]');
- expect(separators[0]).toHaveAttribute('role', 'presentation');
+ const separators = container.querySelectorAll('span[aria-hidden="true"]');
+ expect(separators.length).toBeGreaterThan(0);
+ expect(separators[0]).toHaveAttribute('aria-hidden', 'true');
});
it('forwards ref to the nav element', () => {
@@ -164,7 +168,7 @@ describe('XDSBreadcrumbItem', () => {
expect(current).toHaveAttribute('aria-current', 'page');
});
- it('auto-detects last child as current when no isCurrent is set', () => {
+ it('auto-detects last child as current when no isCurrent is set', async () => {
render(
<XDSBreadcrumbs>
<XDSBreadcrumbItem href="/">Home</XDSBreadcrumbItem>
@@ -172,12 +176,15 @@ describe('XDSBreadcrumbItem', () => {
<XDSBreadcrumbItem>Last Item</XDSBreadcrumbItem>
</XDSBreadcrumbs>,
);
- const lastItem = screen.getByText('Last Item');
- expect(lastItem).toHaveAttribute('aria-current', 'page');
- expect(lastItem.tagName).toBe('SPAN');
+ // aria-current is set via useEffect, so we need to wait for it
+ const lastLi = screen.getByText('Last Item').closest('li')!;
+ await waitFor(() => {
+ expect(lastLi).toHaveAttribute('aria-current', 'page');
+ });
+ expect(screen.getByText('Last Item').tagName).toBe('SPAN');
});
- it('does not auto-detect when isCurrent is explicitly set', () => {
+ it('does not auto-detect when isCurrent is explicitly set', async () => {
render(
<XDSBreadcrumbs>
<XDSBreadcrumbItem isCurrent>First</XDSBreadcrumbItem>
@@ -186,9 +193,12 @@ describe('XDSBreadcrumbItem', () => {
</XDSBreadcrumbs>,
);
expect(screen.getByText('First')).toHaveAttribute('aria-current', 'page');
- const third = screen.getByText('Third');
- expect(third).not.toHaveAttribute('aria-current');
- expect(third.tagName).toBe('A');
+ // Wait for effects to settle, then confirm third has no aria-current
+ const thirdLi = screen.getByText('Third').closest('li')!;
+ await waitFor(() => {
+ expect(thirdLi).not.toHaveAttribute('aria-current');
+ });
+ expect(screen.getByText('Third').tagName).toBe('A');
});
it('handles onClick', async () => {
@@ -235,27 +245,31 @@ describe('XDSBreadcrumbItem', () => {
expect(screen.getByTestId('crumb-current')).toBeInTheDocument();
});
- it('renders single item as current by auto-detection', () => {
+ it('renders single item as current by auto-detection', async () => {
render(
<XDSBreadcrumbs>
<XDSBreadcrumbItem>Only Item</XDSBreadcrumbItem>
</XDSBreadcrumbs>,
);
- const item = screen.getByText('Only Item');
- expect(item).toHaveAttribute('aria-current', 'page');
- expect(item.tagName).toBe('SPAN');
+ const li = screen.getByText('Only Item').closest('li')!;
+ await waitFor(() => {
+ expect(li).toHaveAttribute('aria-current', 'page');
+ });
+ expect(screen.getByText('Only Item').tagName).toBe('SPAN');
});
- it('auto-detects last child as current with supporting variant', () => {
+ it('auto-detects last child as current with supporting variant', async () => {
render(
<XDSBreadcrumbs variant="supporting">
<XDSBreadcrumbItem href="/">Home</XDSBreadcrumbItem>
<XDSBreadcrumbItem>Last</XDSBreadcrumbItem>
</XDSBreadcrumbs>,
);
- const last = screen.getByText('Last');
- expect(last).toHaveAttribute('aria-current', 'page');
- expect(last.tagName).toBe('SPAN');
+ const li = screen.getByText('Last').closest('li')!;
+ await waitFor(() => {
+ expect(li).toHaveAttribute('aria-current', 'page');
+ });
+ expect(screen.getByText('Last').tagName).toBe('SPAN');
});
it('renders custom component for non-current items when as is provided', () => {
diff --git a/packages/core/src/Breadcrumbs/XDSBreadcrumbs.tsx b/packages/core/src/Breadcrumbs/XDSBreadcrumbs.tsx
index 52a8459578..2783fab0ac 100644
--- a/packages/core/src/Breadcrumbs/XDSBreadcrumbs.tsx
+++ b/packages/core/src/Breadcrumbs/XDSBreadcrumbs.tsx
@@ -2,7 +2,7 @@
/**
* @file XDSBreadcrumbs.tsx
- * @input Uses React, Children, createContext, stylex, theme tokens
+ * @input Uses React, createContext, stylex, theme tokens
* @output Exports XDSBreadcrumbs component, XDSBreadcrumbsProps, BreadcrumbCtx
* @position Core container component; consumed by index.ts
*
@@ -13,11 +13,10 @@
* - /apps/storybook/stories/Breadcrumbs.stories.tsx
*/
-import {Children, isValidElement, createContext, type ReactNode} from 'react';
+import {createContext, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {StyleXStyles} from '@stylexjs/stylex';
-import {colorVars, spacingVars, typeScaleVars} from '../theme/tokens.stylex';
-import type {XDSBreadcrumbItemProps} from './XDSBreadcrumbItem';
+import {spacingVars} from '../theme/tokens.stylex';
import {xdsClassName, mergeProps} from '../utils';
// =============================================================================
@@ -55,15 +54,15 @@ export type XDSBreadcrumbsVariant = keyof XDSBreadcrumbsVariantMap;
// Context shared with XDSBreadcrumbItem
// =============================================================================
-/** @internal Context for passing state from XDSBreadcrumbs to XDSBreadcrumbItem. */
+/** @internal Context for passing variant and separator from XDSBreadcrumbs to XDSBreadcrumbItem. */
export interface BreadcrumbContextValue {
- isAutoLast: boolean;
variant: XDSBreadcrumbsVariant;
+ separator: ReactNode;
}
export const BreadcrumbCtx = createContext<BreadcrumbContextValue>({
- isAutoLast: false,
variant: 'default',
+ separator: '/',
});
// =============================================================================
@@ -143,24 +142,6 @@ const listStyles = stylex.create({
},
});
-const separatorStyles = stylex.create({
- root: {
- display: 'flex',
- alignItems: 'center',
- color: colorVars['--color-text-secondary'],
- paddingBlock: spacingVars['--spacing-1'],
- userSelect: 'none',
- },
- defaultSize: {
- fontSize: typeScaleVars['--text-body-size'],
- lineHeight: typeScaleVars['--text-body-leading'],
- },
- supportingSize: {
- fontSize: typeScaleVars['--text-supporting-size'],
- lineHeight: typeScaleVars['--text-supporting-leading'],
- },
-});
-
// =============================================================================
// Component
// =============================================================================
@@ -170,7 +151,8 @@ const separatorStyles = stylex.create({
* semantic `<nav>` + `<ol>` markup with separators between items.
*
* Auto-detects the last child as the current page if no item has
- * `isCurrent` explicitly set.
+ * `isCurrent` explicitly set — handled by each item via DOM inspection,
+ * no React child introspection needed.
*
* @example
* ```
@@ -192,64 +174,23 @@ export function XDSBreadcrumbs({
'data-testid': testId,
ref,
}: XDSBreadcrumbsProps) {
- const items = Children.toArray(children);
- const isSupporting = variant === 'supporting';
-
- // Check if any child has isCurrent explicitly set
- const hasExplicitCurrent = items.some(
- child =>
- isValidElement<XDSBreadcrumbItemProps>(child) &&
- child.props.isCurrent === true,
- );
-
- const rendered: ReactNode[] = [];
-
- items.forEach((child, index) => {
- const isLast = index === items.length - 1;
-
- const ctxValue: BreadcrumbContextValue = {
- isAutoLast: !hasExplicitCurrent && isLast,
- variant,
- };
-
- rendered.push(
- <BreadcrumbCtx.Provider key={`item-${index}`} value={ctxValue}>
- {child}
- </BreadcrumbCtx.Provider>,
- );
-
- // Add separator between items (not after the last one)
- if (!isLast) {
- rendered.push(
- <li
- key={`sep-${index}`}
- role="presentation"
- aria-hidden="true"
- {...stylex.props(
- separatorStyles.root,
- isSupporting
- ? separatorStyles.supportingSize
- : separatorStyles.defaultSize,
- )}>
- {separator}
- </li>,
- );
- }
- });
+ const ctxValue: BreadcrumbContextValue = {variant, separator};
return (
- <nav
- ref={ref}
- aria-label={label}
- data-testid={testId}
- {...mergeProps(
- xdsClassName('breadcrumbs', {variant}),
- stylex.props(navStyles.root, xstyle),
- className,
- style,
- )}>
- <ol {...stylex.props(listStyles.root)}>{rendered}</ol>
- </nav>
+ <BreadcrumbCtx.Provider value={ctxValue}>
+ <nav
+ ref={ref}
+ aria-label={label}
+ data-testid={testId}
+ {...mergeProps(
+ xdsClassName('breadcrumbs', {variant}),
+ stylex.props(navStyles.root, xstyle),
+ className,
+ style,
+ )}>
+ <ol {...stylex.props(listStyles.root)}>{children}</ol>
+ </nav>
+ </BreadcrumbCtx.Provider>
);
}
diff --git a/packages/core/src/HoverCard/XDSHoverCard.tsx b/packages/core/src/HoverCard/XDSHoverCard.tsx
index b59c075d5b..1ffab93e01 100644
--- a/packages/core/src/HoverCard/XDSHoverCard.tsx
+++ b/packages/core/src/HoverCard/XDSHoverCard.tsx
@@ -115,13 +115,7 @@ export interface XDSHoverCardProps {
* Check if children are text-only (no React elements)
*/
function isTextOnly(children: ReactNode): boolean {
- let hasElement = false;
- React.Children.forEach(children, child => {
- if (React.isValidElement(child)) {
- hasElement = true;
- }
- });
- return !hasElement;
+ return typeof children === 'string' || typeof children === 'number';
}
/**
diff --git a/packages/core/src/Tooltip/XDSTooltip.tsx b/packages/core/src/Tooltip/XDSTooltip.tsx
index 717f9e5ffd..0e9543df15 100644
--- a/packages/core/src/Tooltip/XDSTooltip.tsx
+++ b/packages/core/src/Tooltip/XDSTooltip.tsx
@@ -11,7 +11,6 @@
* - /apps/storybook/stories/Tooltip.stories.tsx
*/
-
import React, {
useCallback,
useLayoutEffect,
@@ -126,13 +125,7 @@ export interface XDSTooltipProps {
* Check if children are text-only (no React elements)
*/
function isTextOnly(children: ReactNode): boolean {
- let hasElement = false;
- React.Children.forEach(children, child => {
- if (React.isValidElement(child)) {
- hasElement = true;
- }
- });
- return !hasElement;
+ return typeof children === 'string' || typeof children === 'number';
}
/**