Skip to content

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

TypeScript

refactor: migrate all components from forwardRef to React 19 ref prop (#535)

Cindy Zhangb940463b9c37
diff --git a/packages/core/src/AppShell/XDSAppShell.tsx b/packages/core/src/AppShell/XDSAppShell.tsx
index 326c8ed2ff..686490867e 100644
--- a/packages/core/src/AppShell/XDSAppShell.tsx
+++ b/packages/core/src/AppShell/XDSAppShell.tsx
@@ -15,14 +15,7 @@
'use client';
-import {
- forwardRef,
- useCallback,
- useEffect,
- useRef,
- useState,
- type ReactNode,
-} from 'react';
+import {useCallback, useEffect, useRef, useState, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {StyleXStyles} from '@stylexjs/stylex';
import {colorVars, fontWeightVars, textSizeVars} from '../theme/tokens.stylex';
@@ -62,6 +55,8 @@ const MAIN_CONTENT_ID = 'xds-app-shell-main';
export type XDSAppShellBreakpoint = 'sm' | 'md' | 'lg' | 'none';
export interface XDSAppShellProps {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLDivElement>;
/**
* Background color of the shell.
* - `wash`: Page-level background — subtle gray in light, near-black in dark
@@ -292,256 +287,251 @@ const styles = stylex.create({
* </XDSAppShell>
* ```
*/
-export const XDSAppShell = forwardRef<HTMLDivElement, XDSAppShellProps>(
- function XDSAppShell(
- {
- background = 'surface',
- banner,
- children,
- 'data-testid': dataTestId,
- height = 'fill',
- defaultIsSideNavCollapsed = false,
- isSideNavCollapsed: controlledCollapsed,
- mobileNav,
- onSideNavCollapsedChange,
- sideNav,
- sideNavBreakpoint = 'md',
- sideNavWidth = DEFAULT_SIDENAV_WIDTH,
- topNav,
- xstyle,
- className,
- style,
+export function XDSAppShell({
+ background = 'surface',
+ banner,
+ children,
+ 'data-testid': dataTestId,
+ height = 'fill',
+ defaultIsSideNavCollapsed = false,
+ isSideNavCollapsed: controlledCollapsed,
+ mobileNav,
+ onSideNavCollapsedChange,
+ sideNav,
+ sideNavBreakpoint = 'md',
+ sideNavWidth = DEFAULT_SIDENAV_WIDTH,
+ topNav,
+ xstyle,
+ className,
+ style,
+ ref,
+}: XDSAppShellProps) {
+ // =========================================================================
+ // SideNav collapse state (controlled + uncontrolled)
+ // =========================================================================
+ const isControlled = controlledCollapsed !== undefined;
+ const [uncontrolledCollapsed, setUncontrolledCollapsed] = useState(
+ defaultIsSideNavCollapsed,
+ );
+ const isCollapsed = isControlled
+ ? controlledCollapsed
+ : uncontrolledCollapsed;
+
+ // Track whether we're below the breakpoint
+ const [isBelowBreakpoint, setIsBelowBreakpoint] = useState(false);
+
+ const isFill = height === 'fill';
+ const isAuto = height === 'auto';
+ const hasSideNav = sideNav != null;
+ const hasMobileNav = mobileNav != null;
+ const hasTopNav = topNav != null;
+ const hasBanner = banner != null;
+
+ // =========================================================================
+ // Header height measurement for sticky sideNav offset (auto mode)
+ // =========================================================================
+ const headerRef = useRef<HTMLDivElement>(null);
+ const shellRef = useRef<HTMLDivElement>(null);
+
+ // Merge forwarded ref with internal shell ref
+ const setShellRef = useCallback(
+ (node: HTMLDivElement | null) => {
+ (shellRef as React.MutableRefObject<HTMLDivElement | null>).current =
+ node;
+ if (typeof ref === 'function') {
+ ref(node);
+ } else if (ref) {
+ (ref as React.MutableRefObject<HTMLDivElement | null>).current = node;
+ }
},
- ref,
- ) {
- // =========================================================================
- // SideNav collapse state (controlled + uncontrolled)
- // =========================================================================
- const isControlled = controlledCollapsed !== undefined;
- const [uncontrolledCollapsed, setUncontrolledCollapsed] = useState(
- defaultIsSideNavCollapsed,
- );
- const isCollapsed = isControlled
- ? controlledCollapsed
- : uncontrolledCollapsed;
-
- // Track whether we're below the breakpoint
- const [isBelowBreakpoint, setIsBelowBreakpoint] = useState(false);
-
- const isFill = height === 'fill';
- const isAuto = height === 'auto';
- const hasSideNav = sideNav != null;
- const hasMobileNav = mobileNav != null;
- const hasTopNav = topNav != null;
- const hasBanner = banner != null;
-
- // =========================================================================
- // Header height measurement for sticky sideNav offset (auto mode)
- // =========================================================================
- const headerRef = useRef<HTMLDivElement>(null);
- const shellRef = useRef<HTMLDivElement>(null);
-
- // Merge forwarded ref with internal shell ref
- const setShellRef = useCallback(
- (node: HTMLDivElement | null) => {
- (shellRef as React.MutableRefObject<HTMLDivElement | null>).current =
- node;
- if (typeof ref === 'function') {
- ref(node);
- } else if (ref) {
- (ref as React.MutableRefObject<HTMLDivElement | null>).current = node;
+ [ref],
+ );
+
+ useEffect(() => {
+ if (!isAuto || !headerRef.current || !shellRef.current) return;
+
+ const headerEl = headerRef.current;
+ const shellEl = shellRef.current;
+
+ const updateHeight = () => {
+ const height = headerEl.getBoundingClientRect().height;
+ shellEl.style.setProperty('--appshell-header-height', `${height}px`);
+ };
+
+ updateHeight();
+
+ const observer = new ResizeObserver(updateHeight);
+ observer.observe(headerEl);
+ return () => observer.disconnect();
+ }, [isAuto]);
+
+ // =========================================================================
+ // Responsive breakpoint handling
+ //
+ // Uses matchMedia which is event-driven — the listener only fires when the
+ // media query match state actually changes, not on every resize. This is
+ // efficient and does not over-trigger.
+ // =========================================================================
+ useEffect(() => {
+ if (sideNavBreakpoint === 'none' || !hasSideNav) return;
+
+ const breakpointPx = BREAKPOINT_VALUES[sideNavBreakpoint];
+ const mql = window.matchMedia(`(max-width: ${breakpointPx}px)`);
+
+ const handleChange = (e: MediaQueryListEvent | MediaQueryList) => {
+ const matches = 'matches' in e ? e.matches : false;
+ setIsBelowBreakpoint(matches);
+ if (matches) {
+ // Auto-collapse below breakpoint
+ if (!isControlled) {
+ setUncontrolledCollapsed(true);
}
- },
- [ref],
- );
-
- useEffect(() => {
- if (!isAuto || !headerRef.current || !shellRef.current) return;
-
- const headerEl = headerRef.current;
- const shellEl = shellRef.current;
-
- const updateHeight = () => {
- const height = headerEl.getBoundingClientRect().height;
- shellEl.style.setProperty('--appshell-header-height', `${height}px`);
- };
-
- updateHeight();
-
- const observer = new ResizeObserver(updateHeight);
- observer.observe(headerEl);
- return () => observer.disconnect();
- }, [isAuto]);
-
- // =========================================================================
- // Responsive breakpoint handling
- //
- // Uses matchMedia which is event-driven — the listener only fires when the
- // media query match state actually changes, not on every resize. This is
- // efficient and does not over-trigger.
- // =========================================================================
- useEffect(() => {
- if (sideNavBreakpoint === 'none' || !hasSideNav) return;
-
- const breakpointPx = BREAKPOINT_VALUES[sideNavBreakpoint];
- const mql = window.matchMedia(`(max-width: ${breakpointPx}px)`);
-
- const handleChange = (e: MediaQueryListEvent | MediaQueryList) => {
- const matches = 'matches' in e ? e.matches : false;
- setIsBelowBreakpoint(matches);
- if (matches) {
- // Auto-collapse below breakpoint
- if (!isControlled) {
- setUncontrolledCollapsed(true);
- }
- onSideNavCollapsedChange?.(true);
- }
- };
-
- // Check initial state
- handleChange(mql);
-
- mql.addEventListener('change', handleChange);
- return () => mql.removeEventListener('change', handleChange);
- }, [sideNavBreakpoint, hasSideNav, isControlled, onSideNavCollapsedChange]);
-
- // =========================================================================
- // Toggle handler — snaps open/closed (no transitions for now)
- // TODO: Add ViewTransitions support with React transition API
- // =========================================================================
- const handleToggleCollapse = useCallback(() => {
- const newValue = !isCollapsed;
- if (!isControlled) {
- setUncontrolledCollapsed(newValue);
+ onSideNavCollapsedChange?.(true);
}
- onSideNavCollapsedChange?.(newValue);
- }, [isCollapsed, isControlled, onSideNavCollapsedChange]);
-
- // =========================================================================
- // Determine if sideNav should show as overlay (mobile) or inline
- // =========================================================================
- const showSideNavInline = hasSideNav && !isCollapsed && !isBelowBreakpoint;
- // Default mobile nav: when no explicit mobileNav is provided, AppShell
- // internally renders an XDSMobileNav wrapping the sideNav content.
- // This shares the same <dialog>-based behavior as explicit mobileNav.
- const useDefaultMobileNav =
- hasSideNav && !hasMobileNav && isBelowBreakpoint;
-
- // =========================================================================
- // Build header content (topNav + banner)
- //
- // In auto mode, the header wrapper gets sticky positioning so the topNav
- // stays pinned while the page scrolls. The ref is used to measure header
- // height for the sideNav's sticky offset.
- // =========================================================================
- const headerInner =
- hasTopNav || hasBanner ? (
- <XDSLayoutHeader isFullBleed hasDivider={hasTopNav}>
- {hasBanner && <div {...stylex.props(styles.banner)}>{banner}</div>}
- {hasTopNav && topNav}
- </XDSLayoutHeader>
- ) : undefined;
-
- const headerContent =
- headerInner != null ? (
- <div ref={headerRef} {...stylex.props(isAuto && styles.headerSticky)}>
- {headerInner}
- </div>
- ) : undefined;
-
- // =========================================================================
- // Build sideNav content
- //
- // In auto mode, the sideNav panel is not internally scrollable (the page
- // scrolls as a whole), but it gets sticky positioning so it stays pinned
- // below the header while the main content scrolls. A wrapper div applies
- // the sticky behavior since XDSLayoutPanel doesn't accept style/className.
- // =========================================================================
- const sideNavPanel = showSideNavInline ? (
- <XDSLayoutPanel
- isFullBleed
- hasDivider
- width={sideNavWidth}
- role="navigation"
- label="Application navigation"
- isScrollable={isFill}>
- {sideNav}
- </XDSLayoutPanel>
+ };
+
+ // Check initial state
+ handleChange(mql);
+
+ mql.addEventListener('change', handleChange);
+ return () => mql.removeEventListener('change', handleChange);
+ }, [sideNavBreakpoint, hasSideNav, isControlled, onSideNavCollapsedChange]);
+
+ // =========================================================================
+ // Toggle handler — snaps open/closed (no transitions for now)
+ // TODO: Add ViewTransitions support with React transition API
+ // =========================================================================
+ const handleToggleCollapse = useCallback(() => {
+ const newValue = !isCollapsed;
+ if (!isControlled) {
+ setUncontrolledCollapsed(newValue);
+ }
+ onSideNavCollapsedChange?.(newValue);
+ }, [isCollapsed, isControlled, onSideNavCollapsedChange]);
+
+ // =========================================================================
+ // Determine if sideNav should show as overlay (mobile) or inline
+ // =========================================================================
+ const showSideNavInline = hasSideNav && !isCollapsed && !isBelowBreakpoint;
+ // Default mobile nav: when no explicit mobileNav is provided, AppShell
+ // internally renders an XDSMobileNav wrapping the sideNav content.
+ // This shares the same <dialog>-based behavior as explicit mobileNav.
+ const useDefaultMobileNav = hasSideNav && !hasMobileNav && isBelowBreakpoint;
+
+ // =========================================================================
+ // Build header content (topNav + banner)
+ //
+ // In auto mode, the header wrapper gets sticky positioning so the topNav
+ // stays pinned while the page scrolls. The ref is used to measure header
+ // height for the sideNav's sticky offset.
+ // =========================================================================
+ const headerInner =
+ hasTopNav || hasBanner ? (
+ <XDSLayoutHeader isFullBleed hasDivider={hasTopNav}>
+ {hasBanner && <div {...stylex.props(styles.banner)}>{banner}</div>}
+ {hasTopNav && topNav}
+ </XDSLayoutHeader>
) : undefined;
- const sideNavContent =
- sideNavPanel != null && isAuto ? (
- <div {...stylex.props(styles.sideNavAutoWrapper)}>
- <div {...stylex.props(styles.sideNavSticky)}>{sideNavPanel}</div>
- </div>
- ) : (
- sideNavPanel
- );
-
- // =========================================================================
- // Build main content
- // =========================================================================
- const mainContent = (
- <XDSLayoutContent
- isFullBleed
- role="main"
- id={MAIN_CONTENT_ID}
- isScrollable={isFill}>
- {children}
- </XDSLayoutContent>
- );
+ const headerContent =
+ headerInner != null ? (
+ <div ref={headerRef} {...stylex.props(isAuto && styles.headerSticky)}>
+ {headerInner}
+ </div>
+ ) : undefined;
- // =========================================================================
- // Render
- //
- // TODO: Include root providers (ThemeProvider, ProseProvider, LayerProvider)
- // at the app level once they're available for wrapping.
- // =========================================================================
- return (
- <div
- ref={setShellRef}
- data-testid={dataTestId}
- {...mergeProps(
- xdsClassName('app-shell', {background, height}),
- stylex.props(
- styles.root,
- background === 'wash' ? styles.rootBgWash : styles.rootBgSurface,
- isFill ? styles.rootFill : styles.rootAuto,
- xstyle,
- ),
- className,
- style,
- )}>
- {/* Skip-to-content link */}
- <a
- href={`#${MAIN_CONTENT_ID}`}
- {...stylex.props(styles.skipLink)}
- data-testid="skip-to-content">
- Skip to content
- </a>
-
- <XDSLayout
- height={height}
- isFullBleed
- header={headerContent}
- start={sideNavContent}
- content={mainContent}
- />
-
- {/* Mobile nav — either explicit mobileNav or default wrapping sideNav */}
- {mobileNav}
- {useDefaultMobileNav && (
- <XDSMobileNav
- isOpen={!isCollapsed}
- onOpenChange={() => handleToggleCollapse()}
- width={sideNavWidth}
- data-testid="sidenav-mobile">
- {sideNav}
- </XDSMobileNav>
- )}
+ // =========================================================================
+ // Build sideNav content
+ //
+ // In auto mode, the sideNav panel is not internally scrollable (the page
+ // scrolls as a whole), but it gets sticky positioning so it stays pinned
+ // below the header while the main content scrolls. A wrapper div applies
+ // the sticky behavior since XDSLayoutPanel doesn't accept style/className.
+ // =========================================================================
+ const sideNavPanel = showSideNavInline ? (
+ <XDSLayoutPanel
+ isFullBleed
+ hasDivider
+ width={sideNavWidth}
+ role="navigation"
+ label="Application navigation"
+ isScrollable={isFill}>
+ {sideNav}
+ </XDSLayoutPanel>
+ ) : undefined;
+
+ const sideNavContent =
+ sideNavPanel != null && isAuto ? (
+ <div {...stylex.props(styles.sideNavAutoWrapper)}>
+ <div {...stylex.props(styles.sideNavSticky)}>{sideNavPanel}</div>
</div>
+ ) : (
+ sideNavPanel
);
- },
-);
+
+ // =========================================================================
+ // Build main content
+ // =========================================================================
+ const mainContent = (
+ <XDSLayoutContent
+ isFullBleed
+ role="main"
+ id={MAIN_CONTENT_ID}
+ isScrollable={isFill}>
+ {children}
+ </XDSLayoutContent>
+ );
+
+ // =========================================================================
+ // Render
+ //
+ // TODO: Include root providers (ThemeProvider, ProseProvider, LayerProvider)
+ // at the app level once they're available for wrapping.
+ // =========================================================================
+ return (
+ <div
+ ref={setShellRef}
+ data-testid={dataTestId}
+ {...mergeProps(
+ xdsClassName('app-shell', {background, height}),
+ stylex.props(
+ styles.root,
+ background === 'wash' ? styles.rootBgWash : styles.rootBgSurface,
+ isFill ? styles.rootFill : styles.rootAuto,
+ xstyle,
+ ),
+ className,
+ style,
+ )}>
+ {/* Skip-to-content link */}
+ <a
+ href={`#${MAIN_CONTENT_ID}`}
+ {...stylex.props(styles.skipLink)}
+ data-testid="skip-to-content">
+ Skip to content
+ </a>
+
+ <XDSLayout
+ height={height}
+ isFullBleed
+ header={headerContent}
+ start={sideNavContent}
+ content={mainContent}
+ />
+
+ {/* Mobile nav — either explicit mobileNav or default wrapping sideNav */}
+ {mobileNav}
+ {useDefaultMobileNav && (
+ <XDSMobileNav
+ isOpen={!isCollapsed}
+ onOpenChange={() => handleToggleCollapse()}
+ width={sideNavWidth}
+ data-testid="sidenav-mobile">
+ {sideNav}
+ </XDSMobileNav>
+ )}
+ </div>
+ );
+}
XDSAppShell.displayName = 'XDSAppShell';
diff --git a/packages/core/src/AspectRatio/XDSAspectRatio.tsx b/packages/core/src/AspectRatio/XDSAspectRatio.tsx
index c2f186d4eb..4e0da80a47 100644
--- a/packages/core/src/AspectRatio/XDSAspectRatio.tsx
+++ b/packages/core/src/AspectRatio/XDSAspectRatio.tsx
@@ -1,6 +1,6 @@
/**
* @file XDSAspectRatio.tsx
- * @input Uses React forwardRef, stylex
+ * @input Uses React, stylex
* @output Exports XDSAspectRatio component and XDSAspectRatioProps
* @position AspectRatio component; maintains a specific aspect ratio for its children
*
@@ -12,13 +12,15 @@
'use client';
-import {forwardRef, type ReactNode} from 'react';
+import {type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {StyleXStyles} from '@stylexjs/stylex';
import type {XDSBaseProps} from '../XDSBaseProps';
import {xdsClassName, mergeProps} from '../utils';
export interface XDSAspectRatioProps extends XDSBaseProps<HTMLDivElement> {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLElement>;
/**
* The aspect ratio as width/height (e.g., 16/9 = 1.777..., 4/3 = 1.333..., 1 for square).
*/
@@ -81,25 +83,28 @@ const styles = stylex.create({
* </XDSAspectRatio>
* ```
*/
-export const XDSAspectRatio = forwardRef<HTMLElement, XDSAspectRatioProps>(
- function XDSAspectRatio(
- {ratio, children, xstyle, className, style, ...props},
- ref,
- ) {
- return (
- <div
- ref={ref as React.Ref<HTMLDivElement>}
- {...mergeProps(
- xdsClassName('aspect-ratio'),
- stylex.props(styles.container, xstyle),
- className,
- {...style, aspectRatio: ratio},
- )}
- {...props}>
- <div {...stylex.props(styles.child)}>{children}</div>
- </div>
- );
- },
-);
+export function XDSAspectRatio({
+ ratio,
+ children,
+ xstyle,
+ className,
+ style,
+ ref,
+ ...props
+}: XDSAspectRatioProps) {
+ return (
+ <div
+ ref={ref as React.Ref<HTMLDivElement>}
+ {...mergeProps(
+ xdsClassName('aspect-ratio'),
+ stylex.props(styles.container, xstyle),
+ className,
+ {...style, aspectRatio: ratio},
+ )}
+ {...props}>
+ <div {...stylex.props(styles.child)}>{children}</div>
+ </div>
+ );
+}
XDSAspectRatio.displayName = 'XDSAspectRatio';
diff --git a/packages/core/src/Avatar/XDSAvatar.tsx b/packages/core/src/Avatar/XDSAvatar.tsx
index 88506d2ffc..d247544b98 100644
--- a/packages/core/src/Avatar/XDSAvatar.tsx
+++ b/packages/core/src/Avatar/XDSAvatar.tsx
@@ -1,6 +1,6 @@
/**
* @file XDSAvatar.tsx
- * @input Uses React forwardRef, HTMLAttributes, ReactNode, useState
+ * @input Uses React, HTMLAttributes, ReactNode, useState
* @output Exports XDSAvatar component, XDSAvatarProps, XDSAvatarSize types
* @position Core implementation; consumed by index.ts
*
@@ -13,7 +13,7 @@
'use client';
-import {forwardRef, useState, type ReactNode} from 'react';
+import {useState, type ReactNode} from 'react';
import type {XDSBaseProps} from '../XDSBaseProps';
import * as stylex from '@stylexjs/stylex';
import {
@@ -159,6 +159,8 @@ const dynamicStyles = stylex.create({
});
export interface XDSAvatarProps extends XDSBaseProps<HTMLDivElement> {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLDivElement>;
/**
* The alt text shown on hover and made accessible to screen readers.
* Falls back to `name` if not provided.
@@ -240,94 +242,89 @@ function DefaultIcon({size}: {size: number}) {
* <XDSAvatar src="/user.jpg" status={<OnlineIndicator />} />
* ```
*/
-export const XDSAvatar = forwardRef<HTMLDivElement, XDSAvatarProps>(
- (
- {
- alt,
- 'data-testid': testId,
- fallbackSrc,
- name,
- size = 'small',
- src,
- status,
- xstyle,
- className,
- style,
- ...props
- },
- ref,
- ) => {
- const [imageError, setImageError] = useState(false);
- const [fallbackError, setFallbackError] = useState(false);
+export function XDSAvatar({
+ alt,
+ 'data-testid': testId,
+ fallbackSrc,
+ name,
+ size = 'small',
+ src,
+ status,
+ xstyle,
+ className,
+ style,
+ ref,
+ ...props
+}: XDSAvatarProps) {
+ const [imageError, setImageError] = useState(false);
+ const [fallbackError, setFallbackError] = useState(false);
- const showImage = src && !imageError;
- const showFallbackImage = !showImage && fallbackSrc && !fallbackError;
- const showInitials = !showImage && !showFallbackImage && name;
- const showIcon = !showImage && !showFallbackImage && !name;
+ const showImage = src && !imageError;
+ const showFallbackImage = !showImage && fallbackSrc && !fallbackError;
+ const showInitials = !showImage && !showFallbackImage && name;
+ const showIcon = !showImage && !showFallbackImage && !name;
- const accessibleName = alt || name || 'Avatar';
- const numericSize = resolveSize(size);
+ const accessibleName = alt || name || 'Avatar';
+ const numericSize = resolveSize(size);
- return (
- <XDSAvatarSizeContext.Provider value={numericSize}>
- <div
- ref={ref}
- role="img"
- aria-label={accessibleName}
- data-testid={testId}
- {...mergeProps(
- xdsClassName('avatar', {size}),
- stylex.props(styles.wrapper, xstyle),
- className,
- style,
+ return (
+ <XDSAvatarSizeContext.Provider value={numericSize}>
+ <div
+ ref={ref}
+ role="img"
+ aria-label={accessibleName}
+ data-testid={testId}
+ {...mergeProps(
+ xdsClassName('avatar', {size}),
+ stylex.props(styles.wrapper, xstyle),
+ className,
+ style,
+ )}
+ {...props}>
+ <div {...stylex.props(styles.content, dynamicStyles.size(numericSize))}>
+ {showImage && (
+ <img
+ src={src}
+ alt={accessibleName}
+ onError={() => setImageError(true)}
+ {...stylex.props(styles.image)}
+ />
)}
- {...props}>
- <div
- {...stylex.props(styles.content, dynamicStyles.size(numericSize))}>
- {showImage && (
- <img
- src={src}
- alt={accessibleName}
- onError={() => setImageError(true)}
- {...stylex.props(styles.image)}
- />
- )}
- {showFallbackImage && (
- <img
- src={fallbackSrc}
- alt={accessibleName}
- onError={() => setFallbackError(true)}
- {...stylex.props(styles.image)}
- />
- )}
- {showInitials && (
- <div
- {...stylex.props(
- styles.fallback,
- dynamicStyles.fontSize(numericSize),
- )}>
- {getInitials(name)}
- </div>
- )}
- {showIcon && (
- <div {...stylex.props(styles.fallback)}>
- <DefaultIcon size={numericSize} />
- </div>
- )}
- </div>
- {status && (
+ {showFallbackImage && (
+ <img
+ src={fallbackSrc}
+ alt={accessibleName}
+ onError={() => setFallbackError(true)}
+ {...stylex.props(styles.image)}
+ />
+ )}
+ {showInitials && (
<div
{...stylex.props(
- styles.status,
- dynamicStyles.statusPosition(numericSize),
+ styles.fallback,
+ dynamicStyles.fontSize(numericSize),
)}>
- {status}
+ {getInitials(name)}
+ </div>
+ )}
+ {showIcon && (
+ <div {...stylex.props(styles.fallback)}>
+ <DefaultIcon size={numericSize} />
</div>
)}
</div>
- </XDSAvatarSizeContext.Provider>
- );
- },
-);
+ {status && (
+ <div
+ {...stylex.props(
+ styles.status,
+ dynamicStyles.statusPosition(numericSize),
+ )}>
+ {status}
+ </div>
+ )}
+ </div>
+ </XDSAvatarSizeContext.Provider>
+ );
+}
XDSAvatar.displayName = 'XDSAvatar';
diff --git a/packages/core/src/Badge/XDSBadge.tsx b/packages/core/src/Badge/XDSBadge.tsx
index 739d04c3e7..2384738178 100644
--- a/packages/core/src/Badge/XDSBadge.tsx
+++ b/packages/core/src/Badge/XDSBadge.tsx
@@ -1,6 +1,6 @@
/**
* @file XDSBadge.tsx
- * @input Uses React forwardRef, HTMLAttributes
+ * @input Uses React, HTMLAttributes
* @output Exports XDSBadge component, XDSBadgeProps, XDSBadgeVariant types
* @position Core implementation; consumed by index.ts
*
@@ -13,7 +13,7 @@
'use client';
-import {forwardRef, type ReactNode} from 'react';
+import {type ReactNode} from 'react';
import type {XDSBaseProps} from '../XDSBaseProps';
import * as stylex from '@stylexjs/stylex';
import {
@@ -83,6 +83,8 @@ const variants = stylex.create({
export type XDSBadgeVariant = keyof typeof variants;
export interface XDSBadgeProps extends XDSBaseProps<HTMLSpanElement> {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLSpanElement>;
/**
* The visual style variant of the badge.
* @default 'neutral'
@@ -113,33 +115,37 @@ export interface XDSBadgeProps extends XDSBaseProps<HTMLSpanElement> {
* <XDSBadge variant="info" /> // Dot indicator
* ```
*/
-export const XDSBadge = forwardRef<HTMLSpanElement, XDSBadgeProps>(
- (
- {variant = 'neutral', children, icon, xstyle, className, style, ...props},
- ref,
- ) => {
- const isDot = children == null && icon == null;
+export function XDSBadge({
+ variant = 'neutral',
+ children,
+ icon,
+ xstyle,
+ className,
+ style,
+ ref,
+ ...props
+}: XDSBadgeProps) {
+ const isDot = children == null && icon == null;
- return (
- <span
- ref={ref}
- {...mergeProps(
- xdsClassName('badge', {variant}),
- stylex.props(
- styles.base,
- variants[variant],
- isDot && styles.dot,
- xstyle,
- ),
- className,
- style,
- )}
- {...props}>
- {icon}
- {children}
- </span>
- );
- },
-);
+ return (
+ <span
+ ref={ref}
+ {...mergeProps(
+ xdsClassName('badge', {variant}),
+ stylex.props(
+ styles.base,
+ variants[variant],
+ isDot && styles.dot,
+ xstyle,
+ ),
+ className,
+ style,
+ )}
+ {...props}>
+ {icon}
+ {children}
+ </span>
+ );
+}
XDSBadge.displayName = 'XDSBadge';
diff --git a/packages/core/src/Banner/XDSBanner.tsx b/packages/core/src/Banner/XDSBanner.tsx
index 029403365b..24206c1651 100644
--- a/packages/core/src/Banner/XDSBanner.tsx
+++ b/packages/core/src/Banner/XDSBanner.tsx
@@ -1,6 +1,6 @@
/**
* @file XDSBanner.tsx
- * @input Uses React forwardRef/useState, @heroicons/react/24/solid icons, XDSButton, XDSIcon, StyleX
+ * @input Uses ReactuseState, @heroicons/react/24/solid icons, XDSButton, XDSIcon, StyleX
* @output Exports XDSBanner component, XDSBannerProps, XDSBannerStatus, XDSBannerVariant types
* @position Core implementation; consumed by index.ts, tested by XDSBanner.test.tsx
*
@@ -19,7 +19,7 @@
'use client';
-import {forwardRef, useState, type ReactNode} from 'react';
+import {useState, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {StyleXStyles} from '@stylexjs/stylex';
import {
@@ -60,6 +60,8 @@ export type XDSBannerStatus = 'info' | 'warning' | 'error' | 'success';
export type XDSBannerVariant = 'card' | 'section';
export interface XDSBannerProps {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLDivElement>;
/**
* Status type controlling the icon and color scheme.
*/
@@ -332,135 +334,131 @@ const statusStyles = stylex.create({
* </XDSBanner>
* ```
*/
-export const XDSBanner = forwardRef<HTMLDivElement, XDSBannerProps>(
- (
- {
- status,
- title,
- description,
- icon,
- isDismissable = false,
- onDismiss,
- endContent,
- variant = 'card',
- defaultIsExpanded = false,
- children,
- xstyle,
- className,
- style,
- 'data-testid': testId,
- },
- ref,
- ) => {
- const [isDismissed, setIsDismissed] = useState(false);
- const [isExpanded, setIsExpanded] = useState(defaultIsExpanded);
- const DefaultIcon = defaultIcons[status];
- const role = statusRole[status];
- const iconColor = statusIconColor[status];
- const hasChildren = children != null;
+export function XDSBanner({
+ status,
+ title,
+ description,
+ icon,
+ isDismissable = false,
+ onDismiss,
+ endContent,
+ variant = 'card',
+ defaultIsExpanded = false,
+ children,
+ xstyle,
+ className,
+ style,
+ 'data-testid': testId,
+ ref,
+}: XDSBannerProps) {
+ const [isDismissed, setIsDismissed] = useState(false);
+ const [isExpanded, setIsExpanded] = useState(defaultIsExpanded);
+ const DefaultIcon = defaultIcons[status];
+ const role = statusRole[status];
+ const iconColor = statusIconColor[status];
+ const hasChildren = children != null;
- if (isDismissed) {
- return null;
- }
+ if (isDismissed) {
+ return null;
+ }
- const handleDismiss = () => {
- setIsDismissed(true);
- onDismiss?.();
- };
+ const handleDismiss = () => {
+ setIsDismissed(true);
+ onDismiss?.();
+ };
- const handleToggleExpand = () => {
- setIsExpanded(prev => !prev);
- };
+ const handleToggleExpand = () => {
+ setIsExpanded(prev => !prev);
+ };
- // Show the end area if there are actions, dismiss, or a collapsible toggle
- const showEndArea = endContent != null || isDismissable || hasChildren;
- // Center items vertically when there's only a title (no description)
- // and the banner has action buttons
- const hasActions = endContent != null || isDismissable;
- const isSingleLine = description == null && hasActions;
+ // Show the end area if there are actions, dismiss, or a collapsible toggle
+ const showEndArea = endContent != null || isDismissable || hasChildren;
+ // Center items vertically when there's only a title (no description)
+ // and the banner has action buttons
+ const hasActions = endContent != null || isDismissable;
+ const isSingleLine = description == null && hasActions;
- return (
+ return (
+ <div
+ ref={ref}
+ role={role}
+ data-testid={testId}
+ {...mergeProps(
+ xdsClassName('banner', {variant}),
+ stylex.props(
+ styles.root,
+ variant === 'card' && styles.card,
+ variant === 'section' && styles.section,
+ xstyle,
+ ),
+ className,
+ style,
+ )}>
+ {/* Header: colored status background */}
<div
- ref={ref}
- role={role}
- data-testid={testId}
- {...mergeProps(
- xdsClassName('banner', {variant}),
- stylex.props(
- styles.root,
- variant === 'card' && styles.card,
- variant === 'section' && styles.section,
- xstyle,
- ),
- className,
- style,
+ {...stylex.props(
+ styles.header,
+ isSingleLine && styles.headerCentered,
+ statusStyles[status],
)}>
- {/* Header: colored status background */}
- <div
- {...stylex.props(
- styles.header,
- isSingleLine && styles.headerCentered,
- statusStyles[status],
- )}>
- <div {...stylex.props(styles.iconWrapper)} aria-hidden="true">
- {icon != null ? (
- icon
- ) : (
- <XDSIcon icon={DefaultIcon} size="md" color={iconColor} />
- )}
- </div>
- <div {...stylex.props(styles.headerContent)}>
- <p {...stylex.props(styles.title)}>{title}</p>
- {description != null && (
- <p {...stylex.props(styles.description)}>{description}</p>
- )}
- </div>
- {showEndArea && (
- <div {...stylex.props(styles.endArea, edgeSignals.end)}>
- {endContent}
- {hasChildren && (
- <XDSButton
- variant="ghost"
- size="sm"
- label={isExpanded ? 'Collapse' : 'Expand'}
- tooltip={isExpanded ? 'Collapse' : 'Expand'}
- icon={
- <XDSIcon
- icon={isExpanded ? ChevronUpIcon : ChevronDownIcon}
- size="sm"
- color="inherit"
- />
- }
- onClick={handleToggleExpand}
- aria-expanded={isExpanded}
- />
- )}
- {isDismissable && (
- <XDSButton
- variant="ghost"
- size="sm"
- label="Dismiss"
- tooltip="Dismiss"
- icon={<XDSIcon icon="close" size="sm" color="inherit" />}
- onClick={handleDismiss}
- />
- )}
- </div>
+ <div {...stylex.props(styles.iconWrapper)} aria-hidden="true">
+ {icon != null ? (
+ icon
+ ) : (
+ <XDSIcon icon={DefaultIcon} size="md" color={iconColor} />
+ )}
+ </div>
+ <div {...stylex.props(styles.headerContent)}>
+ <p {...stylex.props(styles.title)}>{title}</p>
+ {description != null && (
+ <p {...stylex.props(styles.description)}>{description}</p>
)}
</div>
- {/* Content area: collapsible card background for additional content */}
- {hasChildren && isExpanded && (
- <div
- {...stylex.props(
- styles.contentArea,
- variant === 'card' && styles.contentAreaCard,
- )}>
- {children}
+ {showEndArea && (
+ <div {...stylex.props(styles.endArea, edgeSignals.end)}>
+ {endContent}
+ {hasChildren && (
+ <XDSButton
+ variant="ghost"
+ size="sm"
+ label={isExpanded ? 'Collapse' : 'Expand'}
+ tooltip={isExpanded ? 'Collapse' : 'Expand'}
+ icon={
+ <XDSIcon
+ icon={isExpanded ? ChevronUpIcon : ChevronDownIcon}
+ size="sm"
+ color="inherit"
+ />
+ }
+ onClick={handleToggleExpand}
+ aria-expanded={isExpanded}
+ />
+ )}
+ {isDismissable && (
+ <XDSButton
+ variant="ghost"
+ size="sm"
+ label="Dismiss"
+ tooltip="Dismiss"
+ icon={<XDSIcon icon="close" size="sm" color="inherit" />}
+ onClick={handleDismiss}
+ />
+ )}
</div>
)}
</div>
- );
- },
-);
+ {/* Content area: collapsible card background for additional content */}
+ {hasChildren && isExpanded && (
+ <div
+ {...stylex.props(
+ styles.contentArea,
+ variant === 'card' && styles.contentAreaCard,
+ )}>
+ {children}
+ </div>
+ )}
+ </div>
+ );
+}
XDSBanner.displayName = 'XDSBanner';
diff --git a/packages/core/src/Breadcrumbs/XDSBreadcrumbs.tsx b/packages/core/src/Breadcrumbs/XDSBreadcrumbs.tsx
index b81675256e..c4e6345a59 100644
--- a/packages/core/src/Breadcrumbs/XDSBreadcrumbs.tsx
+++ b/packages/core/src/Breadcrumbs/XDSBreadcrumbs.tsx
@@ -1,6 +1,6 @@
/**
* @file XDSBreadcrumbs.tsx
- * @input Uses React forwardRef, Children, createContext, stylex, theme tokens
+ * @input Uses React, Children, createContext, stylex, theme tokens
* @output Exports XDSBreadcrumbs component, XDSBreadcrumbsProps, BreadcrumbCtx
* @position Core container component; consumed by index.ts
*
@@ -13,13 +13,7 @@
'use client';
-import {
- forwardRef,
- Children,
- isValidElement,
- createContext,
- type ReactNode,
-} from 'react';
+import {Children, isValidElement, createContext, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {StyleXStyles} from '@stylexjs/stylex';
import {
@@ -62,6 +56,8 @@ export const BreadcrumbCtx = createContext<BreadcrumbContextValue>({
// =============================================================================
export interface XDSBreadcrumbsProps {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLElement>;
/**
* XDSBreadcrumbItem elements to render as breadcrumb trail.
*/
@@ -169,80 +165,76 @@ const separatorStyles = stylex.create({
* </XDSBreadcrumbs>
* ```
*/
-export const XDSBreadcrumbs = forwardRef<HTMLElement, XDSBreadcrumbsProps>(
- function XDSBreadcrumbs(
- {
- children,
- separator = '/',
- variant = 'default',
- xstyle,
- className,
- style,
- label = 'Breadcrumb',
- 'data-testid': testId,
- },
- ref,
- ) {
- 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,
+export function XDSBreadcrumbs({
+ children,
+ separator = '/',
+ variant = 'default',
+ xstyle,
+ className,
+ style,
+ label = 'Breadcrumb',
+ '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>,
);
- const rendered: ReactNode[] = [];
-
- items.forEach((child, index) => {
- const isLast = index === items.length - 1;
-
- const ctxValue: BreadcrumbContextValue = {
- isAutoLast: !hasExplicitCurrent && isLast,
- variant,
- };
-
+ // Add separator between items (not after the last one)
+ if (!isLast) {
rendered.push(
- <BreadcrumbCtx.Provider key={`item-${index}`} value={ctxValue}>
- {child}
- </BreadcrumbCtx.Provider>,
+ <li
+ key={`sep-${index}`}
+ role="presentation"
+ aria-hidden="true"
+ {...stylex.props(
+ separatorStyles.root,
+ isSupporting
+ ? separatorStyles.supportingSize
+ : separatorStyles.defaultSize,
+ )}>
+ {separator}
+ </li>,
);
-
- // 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>,
- );
- }
- });
-
- 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>
- );
- },
-);
+ }
+ });
+
+ 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>
+ );
+}
XDSBreadcrumbs.displayName = 'XDSBreadcrumbs';
diff --git a/packages/core/src/Button/XDSButton.tsx b/packages/core/src/Button/XDSButton.tsx
index bf2c6d54e1..4a4722ca63 100644
--- a/packages/core/src/Button/XDSButton.tsx
+++ b/packages/core/src/Button/XDSButton.tsx
@@ -1,6 +1,6 @@
/**
* @file XDSButton.tsx
- * @input Uses React, forwardRef, ButtonHTMLAttributes, ReactNode
+ * @input Uses React, ButtonHTMLAttributes, ReactNode
* @output Exports XDSButton component, XDSButtonProps, XDSButtonVariant types
* @position Core implementation; consumed by index.ts, tested by XDSButton.test.tsx
*
@@ -15,12 +15,7 @@
'use client';
-import {
- forwardRef,
- useTransition,
- type ReactElement,
- type ReactNode,
-} from 'react';
+import {useTransition, type ReactElement, type ReactNode} from 'react';
import type {XDSBaseProps} from '../XDSBaseProps';
import * as stylex from '@stylexjs/stylex';
import {
@@ -196,6 +191,8 @@ export type XDSButtonVariant = keyof typeof variants;
export type XDSButtonSize = keyof typeof sizeStyles;
export interface XDSButtonProps extends XDSBaseProps<HTMLButtonElement> {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLButtonElement>;
/** HTML button type attribute. @default 'button' */
type?: 'button' | 'submit' | 'reset';
/** HTML name attribute for form submission. */
@@ -311,114 +308,110 @@ const edgeCompStyles = stylex.create({
* <XDSButton label="Edit" icon={<PencilIcon />} endSlot={<XDSBadge>New</XDSBadge>}>Edit</XDSButton>
* ```
*/
-export const XDSButton = forwardRef<HTMLButtonElement, XDSButtonProps>(
- (
- {
- label,
- variant = 'secondary',
- size = 'md',
- isDisabled = false,
- isLoading = false,
- onClickAction,
- icon,
- children,
- endSlot,
- tooltip,
- xstyle,
- className,
- style,
- ...props
- },
- ref,
- ): ReactElement => {
- const [isPending, startTransition] = useTransition();
- const isLoadingState = isLoading || isPending;
- const buttonDisabled = isDisabled || isLoadingState;
- const useLightSpinner = variant === 'primary' || variant === 'destructive';
- const isIconOnly = icon != null && children == null;
+export function XDSButton({
+ label,
+ variant = 'secondary',
+ size = 'md',
+ isDisabled = false,
+ isLoading = false,
+ onClickAction,
+ icon,
+ children,
+ endSlot,
+ tooltip,
+ xstyle,
+ className,
+ style,
+ ref,
+ ...props
+}: XDSButtonProps): ReactElement {
+ const [isPending, startTransition] = useTransition();
+ const isLoadingState = isLoading || isPending;
+ const buttonDisabled = isDisabled || isLoadingState;
+ const useLightSpinner = variant === 'primary' || variant === 'destructive';
+ const isIconOnly = icon != null && children == null;
- const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => {
- if (onClickAction) {
- e.preventDefault();
- startTransition(async () => {
- await onClickAction(e);
- });
- }
- props.onClick?.(e);
- };
+ const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => {
+ if (onClickAction) {
+ e.preventDefault();
+ startTransition(async () => {
+ await onClickAction(e);
+ });
+ }
+ props.onClick?.(e);
+ };
- // Ghost buttons opt into edge compensation — they self-adjust margins
- // when placed at container edges (e.g., TopNav endContent).
- // The component publishes its own inline padding via --component-padding-inline
- // so the compensation formula stays theme-safe.
- const isFlat = variant === 'ghost';
- const edgeCompStyle = isFlat ? edgeCompensation.self : null;
- const edgePaddingSignal = isFlat
- ? isIconOnly
- ? edgeCompStyles.paddingInline2
- : edgeCompStyles.paddingInline3
- : null;
+ // Ghost buttons opt into edge compensation — they self-adjust margins
+ // when placed at container edges (e.g., TopNav endContent).
+ // The component publishes its own inline padding via --component-padding-inline
+ // so the compensation formula stays theme-safe.
+ const isFlat = variant === 'ghost';
+ const edgeCompStyle = isFlat ? edgeCompensation.self : null;
+ const edgePaddingSignal = isFlat
+ ? isIconOnly
+ ? edgeCompStyles.paddingInline2
+ : edgeCompStyles.paddingInline3
+ : null;
- const button = (
- <button
- ref={ref}
- disabled={buttonDisabled}
- aria-label={isIconOnly ? label : undefined}
- aria-busy={isLoadingState || undefined}
- {...mergeProps(
- xdsClassName('button', {variant, size}),
- stylex.props(
- styles.base,
- sizeStyles[size],
- variants[variant],
- isIconOnly && styles.iconOnly,
- buttonDisabled && styles.disabled,
- isLoadingState && loadingStyles.loading,
- edgePaddingSignal,
- edgeCompStyle,
- xstyle,
- ),
- className,
- style,
- )}
- {...props}
- onClick={handleClick}>
- {isLoadingState && (
- <span
- style={{
- position: 'absolute',
- top: 0,
- left: 0,
- right: 0,
- bottom: 0,
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- }}>
- <XDSSpinner
- size="sm"
- shade={useLightSpinner ? 'onMedia' : 'default'}
- />
- </span>
- )}
- {icon}
- {children ?? (isIconOnly ? null : label)}
- {!isIconOnly && endSlot && (
- <span {...stylex.props(styles.endSlotWrapper)}>{endSlot}</span>
- )}
- </button>
- );
+ const button = (
+ <button
+ ref={ref}
+ disabled={buttonDisabled}
+ aria-label={isIconOnly ? label : undefined}
+ aria-busy={isLoadingState || undefined}
+ {...mergeProps(
+ xdsClassName('button', {variant, size}),
+ stylex.props(
+ styles.base,
+ sizeStyles[size],
+ variants[variant],
+ isIconOnly && styles.iconOnly,
+ buttonDisabled && styles.disabled,
+ isLoadingState && loadingStyles.loading,
+ edgePaddingSignal,
+ edgeCompStyle,
+ xstyle,
+ ),
+ className,
+ style,
+ )}
+ {...props}
+ onClick={handleClick}>
+ {isLoadingState && (
+ <span
+ style={{
+ position: 'absolute',
+ top: 0,
+ left: 0,
+ right: 0,
+ bottom: 0,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ }}>
+ <XDSSpinner
+ size="sm"
+ shade={useLightSpinner ? 'onMedia' : 'default'}
+ />
+ </span>
+ )}
+ {icon}
+ {children ?? (isIconOnly ? null : label)}
+ {!isIconOnly && endSlot && (
+ <span {...stylex.props(styles.endSlotWrapper)}>{endSlot}</span>
+ )}
+ </button>
+ );
- if (tooltip) {
- return (
- <XDSTooltip content={tooltip} placement="above">
- {button}
- </XDSTooltip>
- );
- }
+ if (tooltip) {
+ return (
+ <XDSTooltip content={tooltip} placement="above">
+ {button}
+ </XDSTooltip>
+ );
+ }
- return button;
- },
-);
+ return button;
+}
XDSButton.displayName = 'XDSButton';
diff --git a/packages/core/src/Calendar/XDSCalendar.tsx b/packages/core/src/Calendar/XDSCalendar.tsx
index ae1772ca5b..9370ddce18 100644
--- a/packages/core/src/Calendar/XDSCalendar.tsx
+++ b/packages/core/src/Calendar/XDSCalendar.tsx
@@ -1,6 +1,6 @@
/**
* @file XDSCalendar.tsx
- * @input Uses React useState, useMemo, useCallback, forwardRef, hooks
+ * @input Uses React useState, useMemo, useCallback, hooks
* @output Exports XDSCalendar component and related types
* @position Core implementation; consumed by index.ts, tested by XDSCalendar.test.tsx
*
@@ -14,7 +14,6 @@
'use client';
import {
- forwardRef,
useState,
useMemo,
useCallback,
@@ -84,6 +83,8 @@ interface XDSCalendarBaseProps extends Omit<
XDSBaseProps<HTMLDivElement>,
'onChange' | 'defaultValue'
> {
+ /** Ref forwarded to the calendar (imperative handle) */
+ ref?: React.Ref<XDSCalendarHandle>;
/** Number of months to display (default: 1) */
numberOfMonths?: 1 | 2;
@@ -177,242 +178,238 @@ export type XDSCalendarProps = XDSCalendarSingleProps | XDSCalendarRangeProps;
* <XDSCalendar value={selectedDate} onChange={setSelectedDate} />
* ```
*/
-export const XDSCalendar = forwardRef<XDSCalendarHandle, XDSCalendarProps>(
- (props, ref) => {
- const {
- mode = 'single',
- value,
- defaultValue,
- onChange,
- numberOfMonths = 1,
- min,
- max,
- dateConstraints,
- focusDate: focusDateProp,
- onFocusDateChange,
- hasOutsideDays = true,
- hasWeekNumbers = false,
- hasVariableRowCount = false,
- weekStartsOn = 0,
- xstyle,
- className,
- style,
- ...rest
- } = props;
-
- // Today's date (memoized)
- const today = useMemo(() => new Date(), []);
-
- // Internal state for uncontrolled mode
- const [internalValue, setInternalValue] = useState<
- ISODateString | DateRange | undefined
- >(defaultValue);
-
- // Range selection in progress (first click made, waiting for second)
- const [rangeSelectionStart, setRangeSelectionStart] =
- useState<ISODateString | null>(null);
-
- // Hovered date for range preview
- const [hoveredDate, setHoveredDate] = useState<ISODateString | null>(null);
-
- // Pending focus target after month navigation
- const [pendingFocus, setPendingFocus] = useState<ISODateString | null>(
- null,
- );
-
- // Determine effective value
- const effectiveValue = value !== undefined ? value : internalValue;
+export function XDSCalendar({ref, ...props}: XDSCalendarProps) {
+ const {
+ mode = 'single',
+ value,
+ defaultValue,
+ onChange,
+ numberOfMonths = 1,
+ min,
+ max,
+ dateConstraints,
+ focusDate: focusDateProp,
+ onFocusDateChange,
+ hasOutsideDays = true,
+ hasWeekNumbers = false,
+ hasVariableRowCount = false,
+ weekStartsOn = 0,
+ xstyle,
+ className,
+ style,
+ ...rest
+ } = props;
+
+ // Today's date (memoized)
+ const today = useMemo(() => new Date(), []);
+
+ // Internal state for uncontrolled mode
+ const [internalValue, setInternalValue] = useState<
+ ISODateString | DateRange | undefined
+ >(defaultValue);
+
+ // Range selection in progress (first click made, waiting for second)
+ const [rangeSelectionStart, setRangeSelectionStart] =
+ useState<ISODateString | null>(null);
+
+ // Hovered date for range preview
+ const [hoveredDate, setHoveredDate] = useState<ISODateString | null>(null);
+
+ // Pending focus target after month navigation
+ const [pendingFocus, setPendingFocus] = useState<ISODateString | null>(null);
+
+ // Determine effective value
+ const effectiveValue = value !== undefined ? value : internalValue;
+
+ // Focus date state (which month is visible)
+ const [internalFocusDate, setInternalFocusDate] = useState<Date>(() => {
+ if (focusDateProp) return parseISO(focusDateProp);
+ if (effectiveValue) {
+ if (typeof effectiveValue === 'string') {
+ return parseISO(effectiveValue);
+ } else {
+ return parseISO(effectiveValue.start);
+ }
+ }
+ return new Date();
+ });
- // Focus date state (which month is visible)
- const [internalFocusDate, setInternalFocusDate] = useState<Date>(() => {
- if (focusDateProp) return parseISO(focusDateProp);
- if (effectiveValue) {
- if (typeof effectiveValue === 'string') {
- return parseISO(effectiveValue);
+ // Use controlled focusDate if callback is provided, otherwise use internal state
+ const isControlledFocus =
+ focusDateProp !== undefined && onFocusDateChange !== undefined;
+ const focusDate = isControlledFocus
+ ? parseISO(focusDateProp)
+ : internalFocusDate;
+
+ // Expose imperative handle for external navigation
+ useImperativeHandle(
+ ref,
+ () => ({
+ navigateTo: (date: ISODateString) => {
+ if (isControlledFocus) {
+ onFocusDateChange?.(date);
} else {
- return parseISO(effectiveValue.start);
+ setInternalFocusDate(parseISO(date));
}
- }
- return new Date();
+ },
+ }),
+ [isControlledFocus, onFocusDateChange],
+ );
+
+ // Base month (first day of focus month)
+ const baseMonth = useMemo(() => {
+ const d = new Date(focusDate);
+ d.setDate(1);
+ return d;
+ }, [focusDate]);
+
+ // Generate visible months
+ const visibleMonths = useMemo(() => {
+ return Array.from({length: numberOfMonths}, (_, i) => {
+ const m = new Date(baseMonth);
+ m.setMonth(baseMonth.getMonth() + i);
+ return m;
});
+ }, [baseMonth, numberOfMonths]);
- // Use controlled focusDate if callback is provided, otherwise use internal state
- const isControlledFocus =
- focusDateProp !== undefined && onFocusDateChange !== undefined;
- const focusDate = isControlledFocus
- ? parseISO(focusDateProp)
- : internalFocusDate;
-
- // Expose imperative handle for external navigation
- useImperativeHandle(
- ref,
- () => ({
- navigateTo: (date: ISODateString) => {
- if (isControlledFocus) {
- onFocusDateChange?.(date);
- } else {
- setInternalFocusDate(parseISO(date));
- }
- },
- }),
- [isControlledFocus, onFocusDateChange],
- );
+ // Format month header
+ const monthYearLabel = useMemo(() => {
+ const formatter = new Intl.DateTimeFormat(undefined, {
+ year: 'numeric',
+ month: 'long',
+ });
+ if (numberOfMonths === 1) {
+ return formatter.format(visibleMonths[0]);
+ }
+ return visibleMonths.map(m => formatter.format(m)).join(' – ');
+ }, [visibleMonths, numberOfMonths]);
+
+ // Navigation handlers
+ const navigateMonth = useCallback(
+ (delta: number, focusedDate?: ISODateString, offset?: number) => {
+ const newDate = new Date(baseMonth);
+ newDate.setMonth(baseMonth.getMonth() + delta);
+ const newISO = dateToISO(newDate);
- // Base month (first day of focus month)
- const baseMonth = useMemo(() => {
- const d = new Date(focusDate);
- d.setDate(1);
- return d;
- }, [focusDate]);
-
- // Generate visible months
- const visibleMonths = useMemo(() => {
- return Array.from({length: numberOfMonths}, (_, i) => {
- const m = new Date(baseMonth);
- m.setMonth(baseMonth.getMonth() + i);
- return m;
- });
- }, [baseMonth, numberOfMonths]);
-
- // Format month header
- const monthYearLabel = useMemo(() => {
- const formatter = new Intl.DateTimeFormat(undefined, {
- year: 'numeric',
- month: 'long',
- });
- if (numberOfMonths === 1) {
- return formatter.format(visibleMonths[0]);
+ // Calculate target focus date if a focused date was provided
+ if (focusedDate) {
+ const currentDate = parseISO(focusedDate);
+ const daysToMove = offset ?? 7;
+ currentDate.setDate(currentDate.getDate() + delta * daysToMove);
+ setPendingFocus(dateToISO(currentDate));
}
- return visibleMonths.map(m => formatter.format(m)).join(' – ');
- }, [visibleMonths, numberOfMonths]);
-
- // Navigation handlers
- const navigateMonth = useCallback(
- (delta: number, focusedDate?: ISODateString, offset?: number) => {
- const newDate = new Date(baseMonth);
- newDate.setMonth(baseMonth.getMonth() + delta);
- const newISO = dateToISO(newDate);
-
- // Calculate target focus date if a focused date was provided
- if (focusedDate) {
- const currentDate = parseISO(focusedDate);
- const daysToMove = offset ?? 7;
- currentDate.setDate(currentDate.getDate() + delta * daysToMove);
- setPendingFocus(dateToISO(currentDate));
- }
- if (onFocusDateChange) {
- onFocusDateChange(newISO);
- } else {
- setInternalFocusDate(newDate);
- }
- },
- [baseMonth, onFocusDateChange],
- );
+ if (onFocusDateChange) {
+ onFocusDateChange(newISO);
+ } else {
+ setInternalFocusDate(newDate);
+ }
+ },
+ [baseMonth, onFocusDateChange],
+ );
- // Day click handler
- const handleDayClick = useCallback(
- (date: Date) => {
- const iso = dateToISO(date);
+ // Day click handler
+ const handleDayClick = useCallback(
+ (date: Date) => {
+ const iso = dateToISO(date);
- if (mode === 'single') {
- setInternalValue(iso);
- (onChange as XDSCalendarSingleProps['onChange'])?.(iso, date);
+ if (mode === 'single') {
+ setInternalValue(iso);
+ (onChange as XDSCalendarSingleProps['onChange'])?.(iso, date);
+ } else {
+ // Range mode
+ if (rangeSelectionStart === null) {
+ // First click - start the range
+ setRangeSelectionStart(iso);
} else {
- // Range mode
- if (rangeSelectionStart === null) {
- // First click - start the range
- setRangeSelectionStart(iso);
+ // Second click - complete the range
+ const startDate = parseISO(rangeSelectionStart);
+ let start: ISODateString;
+ let end: ISODateString;
+
+ // Ensure start <= end
+ if (date < startDate) {
+ start = iso;
+ end = rangeSelectionStart;
} else {
- // Second click - complete the range
- const startDate = parseISO(rangeSelectionStart);
- let start: ISODateString;
- let end: ISODateString;
-
- // Ensure start <= end
- if (date < startDate) {
- start = iso;
- end = rangeSelectionStart;
- } else {
- start = rangeSelectionStart;
- end = iso;
- }
-
- const range: DateRange = {start, end};
- setInternalValue(range);
- setRangeSelectionStart(null);
- (onChange as XDSCalendarRangeProps['onChange'])?.(range);
+ start = rangeSelectionStart;
+ end = iso;
}
+
+ const range: DateRange = {start, end};
+ setInternalValue(range);
+ setRangeSelectionStart(null);
+ (onChange as XDSCalendarRangeProps['onChange'])?.(range);
}
- },
- [mode, onChange, rangeSelectionStart],
- );
+ }
+ },
+ [mode, onChange, rangeSelectionStart],
+ );
- return (
- <div
- {...mergeProps(
- xdsClassName('calendar', {mode}),
- stylex.props(calendarStyles.calendar, xstyle),
- className,
- style,
- )}
- {...rest}>
- {/* Header with navigation */}
- <div {...stylex.props(calendarStyles.header)}>
- <XDSButton
- label="Previous month"
- variant="ghost"
- icon={<XDSIcon icon="chevronLeft" size="sm" color="inherit" />}
- onClick={() => navigateMonth(-1)}
- />
+ return (
+ <div
+ {...mergeProps(
+ xdsClassName('calendar', {mode}),
+ stylex.props(calendarStyles.calendar, xstyle),
+ className,
+ style,
+ )}
+ {...rest}>
+ {/* Header with navigation */}
+ <div {...stylex.props(calendarStyles.header)}>
+ <XDSButton
+ label="Previous month"
+ variant="ghost"
+ icon={<XDSIcon icon="chevronLeft" size="sm" color="inherit" />}
+ onClick={() => navigateMonth(-1)}
+ />
- <span {...stylex.props(calendarStyles.monthYearLabel)}>
- {monthYearLabel}
- </span>
+ <span {...stylex.props(calendarStyles.monthYearLabel)}>
+ {monthYearLabel}
+ </span>
+
+ <XDSButton
+ label="Next month"
+ variant="ghost"
+ icon={<XDSIcon icon="chevronRight" size="sm" color="inherit" />}
+ onClick={() => navigateMonth(1)}
+ />
+ </div>
- <XDSButton
- label="Next month"
- variant="ghost"
- icon={<XDSIcon icon="chevronRight" size="sm" color="inherit" />}
- onClick={() => navigateMonth(1)}
+ {/* Month grids */}
+ <div {...stylex.props(calendarStyles.monthsContainer)}>
+ {visibleMonths.map(month => (
+ <MonthGrid
+ key={`${month.getFullYear()}-${month.getMonth()}`}
+ month={month}
+ value={effectiveValue}
+ mode={mode}
+ rangeSelectionStart={rangeSelectionStart}
+ hoveredDate={hoveredDate}
+ min={min}
+ max={max}
+ dateConstraints={dateConstraints}
+ hasOutsideDays={hasOutsideDays}
+ hasWeekNumbers={hasWeekNumbers}
+ hasVariableRowCount={hasVariableRowCount}
+ weekStartsOn={weekStartsOn}
+ onDayClick={handleDayClick}
+ onDayHover={date => setHoveredDate(date ? dateToISO(date) : null)}
+ today={today}
+ onNavigatePrevious={(focusedDate, offset) =>
+ navigateMonth(-1, focusedDate, offset)
+ }
+ onNavigateNext={(focusedDate, offset) =>
+ navigateMonth(1, focusedDate, offset)
+ }
+ pendingFocus={pendingFocus}
+ onPendingFocusHandled={() => setPendingFocus(null)}
/>
- </div>
-
- {/* Month grids */}
- <div {...stylex.props(calendarStyles.monthsContainer)}>
- {visibleMonths.map(month => (
- <MonthGrid
- key={`${month.getFullYear()}-${month.getMonth()}`}
- month={month}
- value={effectiveValue}
- mode={mode}
- rangeSelectionStart={rangeSelectionStart}
- hoveredDate={hoveredDate}
- min={min}
- max={max}
- dateConstraints={dateConstraints}
- hasOutsideDays={hasOutsideDays}
- hasWeekNumbers={hasWeekNumbers}
- hasVariableRowCount={hasVariableRowCount}
- weekStartsOn={weekStartsOn}
- onDayClick={handleDayClick}
- onDayHover={date => setHoveredDate(date ? dateToISO(date) : null)}
- today={today}
- onNavigatePrevious={(focusedDate, offset) =>
- navigateMonth(-1, focusedDate, offset)
- }
- onNavigateNext={(focusedDate, offset) =>
- navigateMonth(1, focusedDate, offset)
- }
- pendingFocus={pendingFocus}
- onPendingFocusHandled={() => setPendingFocus(null)}
- />
- ))}
- </div>
+ ))}
</div>
- );
- },
-);
+ </div>
+ );
+}
XDSCalendar.displayName = 'XDSCalendar';
diff --git a/packages/core/src/Card/XDSCard.tsx b/packages/core/src/Card/XDSCard.tsx
index 1894d7851f..e3cd247943 100644
--- a/packages/core/src/Card/XDSCard.tsx
+++ b/packages/core/src/Card/XDSCard.tsx
@@ -12,7 +12,7 @@
'use client';
-import {forwardRef, type ReactNode} from 'react';
+import {type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import {colorVars, radiusVars, elevationVars} from '../theme/tokens.stylex';
import {container} from '../Layout/container.stylex';
@@ -67,6 +67,8 @@ const dynamicStyles = stylex.create({
export type {SizeValue} from '../utils/types';
export interface XDSCardProps extends XDSBaseProps {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLDivElement>;
/**
* CSS class name(s) appended to the root element.
*/
@@ -132,61 +134,57 @@ export interface XDSCardProps extends XDSBaseProps {
* </XDSCard>
* ```
*/
-export const XDSCard = forwardRef<HTMLDivElement, XDSCardProps>(
- function XDSCard(
- {
- width,
- height,
- maxWidth,
- minHeight,
- children,
- isFullBleed = false,
- xstyle,
- className,
- style,
- ...props
- },
- ref,
- ) {
- // Only enable scrolling when card has a fixed height (not null/undefined and not "auto")
- const hasFixedHeight = height != null && height !== 'auto';
+export function XDSCard({
+ width,
+ height,
+ maxWidth,
+ minHeight,
+ children,
+ isFullBleed = false,
+ xstyle,
+ className,
+ style,
+ ref,
+ ...props
+}: XDSCardProps) {
+ // Only enable scrolling when card has a fixed height (not null/undefined and not "auto")
+ const hasFixedHeight = height != null && height !== 'auto';
- return (
- <div
- ref={ref}
- {...mergeProps(
- xdsClassName('card'),
- stylex.props(
- styles.cardOuter,
- dynamicStyles.sizing(
- width ?? null,
- height ?? null,
- maxWidth ?? null,
- minHeight ?? null,
- ),
- xstyle,
+ return (
+ <div
+ ref={ref}
+ {...mergeProps(
+ xdsClassName('card'),
+ stylex.props(
+ styles.cardOuter,
+ dynamicStyles.sizing(
+ width ?? null,
+ height ?? null,
+ maxWidth ?? null,
+ minHeight ?? null,
),
- className,
- style,
- )}
- {...props}>
- <div
- {...stylex.props(
- styles.cardInner,
- hasFixedHeight && styles.scrollable,
- ...container({
- paddingInnerX: 'spacing4',
- paddingInnerY: 'spacing4',
- paddingOuterX: 'spacing4',
- paddingOuterY: 'spacing4',
- }),
- isFullBleed && styles.fullBleed,
- )}>
- {children}
- </div>
+ xstyle,
+ ),
+ className,
+ style,
+ )}
+ {...props}>
+ <div
+ {...stylex.props(
+ styles.cardInner,
+ hasFixedHeight && styles.scrollable,
+ ...container({
+ paddingInnerX: 'spacing4',
+ paddingInnerY: 'spacing4',
+ paddingOuterX: 'spacing4',
+ paddingOuterY: 'spacing4',
+ }),
+ isFullBleed && styles.fullBleed,
+ )}>
+ {children}
</div>
- );
- },
-);
+ </div>
+ );
+}
XDSCard.displayName = 'XDSCard';
diff --git a/packages/core/src/Center/XDSCenter.tsx b/packages/core/src/Center/XDSCenter.tsx
index b9f4d7a07d..ba34914875 100644
--- a/packages/core/src/Center/XDSCenter.tsx
+++ b/packages/core/src/Center/XDSCenter.tsx
@@ -1,6 +1,6 @@
/**
* @file XDSCenter.tsx
- * @input Uses React forwardRef, StyleX for centering styles
+ * @input Uses React, StyleX for centering styles
* @output Exports XDSCenter component and XDSCenterProps
* @position Center component for centering children horizontally/vertically
*
@@ -12,7 +12,7 @@
'use client';
-import {forwardRef, type ReactNode} from 'react';
+import {type ReactNode} from 'react';
import type {XDSBaseProps} from '../XDSBaseProps';
import * as stylex from '@stylexjs/stylex';
import type {StyleXStyles} from '@stylexjs/stylex';
@@ -45,6 +45,8 @@ const dynamicStyles = stylex.create({
export type CenterAxis = 'both' | 'horizontal' | 'vertical';
export interface XDSCenterProps extends XDSBaseProps<HTMLDivElement> {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLDivElement>;
/**
* Center axis - which direction(s) to center.
* - `both`: Center both horizontally and vertically (default)
@@ -113,41 +115,36 @@ export interface XDSCenterProps extends XDSBaseProps<HTMLDivElement> {
* </XDSCenter>
* ```
*/
-export const XDSCenter = forwardRef<HTMLDivElement, XDSCenterProps>(
- function XDSCenter(
- {
- axis = 'both',
- width,
- height,
- isInline = false,
- children,
+export function XDSCenter({
+ axis = 'both',
+ width,
+ height,
+ isInline = false,
+ children,
+ xstyle,
+ className,
+ style,
+ ref,
+ ...props
+}: XDSCenterProps) {
+ const stylexProps = mergeProps(
+ xdsClassName('center', {axis}),
+ stylex.props(
+ isInline ? styles.inline : styles.base,
+ (axis === 'both' || axis === 'vertical') && styles.alignItemsCenter,
+ (axis === 'both' || axis === 'horizontal') && styles.justifyContentCenter,
+ dynamicStyles.sizing(width ?? null, height ?? null),
xstyle,
- className,
- style,
- ...props
- },
- ref,
- ) {
- const stylexProps = mergeProps(
- xdsClassName('center', {axis}),
- stylex.props(
- isInline ? styles.inline : styles.base,
- (axis === 'both' || axis === 'vertical') && styles.alignItemsCenter,
- (axis === 'both' || axis === 'horizontal') &&
- styles.justifyContentCenter,
- dynamicStyles.sizing(width ?? null, height ?? null),
- xstyle,
- ),
- className,
- style,
- );
+ ),
+ className,
+ style,
+ );
- return (
- <div ref={ref} {...stylexProps} {...props}>
- {children}
- </div>
- );
- },
-);
+ return (
+ <div ref={ref} {...stylexProps} {...props}>
+ {children}
+ </div>
+ );
+}
XDSCenter.displayName = 'XDSCenter';
diff --git a/packages/core/src/CheckboxInput/XDSCheckboxInput.tsx b/packages/core/src/CheckboxInput/XDSCheckboxInput.tsx
index 5f60f4b5e5..08de0a5ada 100644
--- a/packages/core/src/CheckboxInput/XDSCheckboxInput.tsx
+++ b/packages/core/src/CheckboxInput/XDSCheckboxInput.tsx
@@ -1,6 +1,6 @@
/**
* @file XDSCheckboxInput.tsx
- * @input Uses React forwardRef, useId, ChangeEvent, XDSFieldLabel, XDSFieldStatus, XDSIconType, XDSInputStatus
+ * @input Uses React, useId, ChangeEvent, XDSFieldLabel, XDSFieldStatus, XDSIconType, XDSInputStatus
* @output Exports XDSCheckboxInput component, XDSCheckboxInputProps
* @position Core implementation; consumed by index.ts, tested by XDSCheckboxInput.test.tsx
*
@@ -14,7 +14,6 @@
'use client';
import {
- forwardRef,
useId,
useOptimistic,
useTransition,
@@ -197,6 +196,8 @@ const labelWrapperSizeStyles = stylex.create({
export type XDSCheckboxInputSize = keyof typeof wrapperSizeStyles;
export interface XDSCheckboxInputProps {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLInputElement>;
/**
* Label text for the checkbox (always rendered for accessibility).
*/
@@ -289,166 +290,155 @@ export interface XDSCheckboxInputProps {
* />
* ```
*/
-export const XDSCheckboxInput = forwardRef<
- HTMLInputElement,
- XDSCheckboxInputProps
->(
- (
- {
- label,
- isLabelHidden = false,
- description,
- onChange,
- onChangeAction,
- isLoading = false,
- value,
- isDisabled = false,
- isOptional = false,
- isRequired = false,
- size = 'md',
- onFocus,
- onBlur,
- labelIcon,
- status,
- },
- ref,
- ) => {
- const id = useId();
- const descriptionID = useId();
- const statusMessageID = useId();
+export function XDSCheckboxInput({
+ label,
+ isLabelHidden = false,
+ description,
+ onChange,
+ onChangeAction,
+ isLoading = false,
+ value,
+ isDisabled = false,
+ isOptional = false,
+ isRequired = false,
+ size = 'md',
+ onFocus,
+ onBlur,
+ labelIcon,
+ status,
+ ref,
+}: XDSCheckboxInputProps) {
+ const id = useId();
+ const descriptionID = useId();
+ const statusMessageID = useId();
- const [, startTransition] = useTransition();
- const [optimisticValue, setOptimisticValue] = useOptimistic(value);
- const isBusy = isLoading || optimisticValue !== value;
+ const [, startTransition] = useTransition();
+ const [optimisticValue, setOptimisticValue] = useOptimistic(value);
+ const isBusy = isLoading || optimisticValue !== value;
- const isIndeterminate = optimisticValue === 'indeterminate';
- const isChecked = optimisticValue === true;
- const isCheckedOrIndeterminate = isChecked || isIndeterminate;
+ const isIndeterminate = optimisticValue === 'indeterminate';
+ const isChecked = optimisticValue === true;
+ const isCheckedOrIndeterminate = isChecked || isIndeterminate;
- // Build aria-describedby from description and status message
- const describedByParts: string[] = [];
- if (description) describedByParts.push(descriptionID);
- if (status?.message) describedByParts.push(statusMessageID);
- const ariaDescribedBy =
- describedByParts.length > 0 ? describedByParts.join(' ') : undefined;
+ // Build aria-describedby from description and status message
+ const describedByParts: string[] = [];
+ if (description) describedByParts.push(descriptionID);
+ if (status?.message) describedByParts.push(statusMessageID);
+ const ariaDescribedBy =
+ describedByParts.length > 0 ? describedByParts.join(' ') : undefined;
- return (
- <div className={xdsClassName('checkbox-input', {size})}>
- <div
- {...stylex.props(
- styles.container,
- isLabelHidden && styles.containerLabelHidden,
- !isDisabled && stylex.defaultMarker(),
- )}>
- <div
- {...stylex.props(styles.checkboxWrapper, wrapperSizeStyles[size])}>
- <input
- ref={ref}
- id={id}
- type="checkbox"
- checked={isChecked}
- disabled={isDisabled}
- required={isRequired}
- onChange={e => {
- const checked = e.target.checked;
- onChange?.(checked, e);
- if (onChangeAction && !e.defaultPrevented) {
- startTransition(async () => {
- setOptimisticValue(checked);
- await onChangeAction(checked, e);
- });
- }
- }}
- onFocus={onFocus}
- onBlur={onBlur}
- aria-describedby={ariaDescribedBy}
- aria-invalid={status?.type === 'error' ? true : undefined}
- aria-busy={isBusy || undefined}
- {...stylex.props(
- styles.input,
- wrapperSizeStyles[size],
- isDisabled && styles.inputDisabled,
- )}
- />
- <div
- aria-hidden="true"
- {...stylex.props(
- styles.checkbox,
- checkboxSizeStyles[size],
- isCheckedOrIndeterminate
- ? styles.checkboxChecked
- : styles.checkboxUnchecked,
- isDisabled && styles.checkboxDisabled,
- isDisabled &&
- !isCheckedOrIndeterminate &&
- styles.checkboxDisabledUnchecked,
- )}>
- {isBusy ? (
- <XDSSpinner
- size="sm"
- shade={isCheckedOrIndeterminate ? 'onMedia' : 'default'}
- />
- ) : (
- <>
- <svg
- viewBox="0 0 10 10"
- {...stylex.props(
- styles.checkmark,
- checkmarkSizeStyles[size],
- isChecked && styles.checkmarkVisible,
- )}>
- <path
- d="M8.5 2.5L4 7.5L1.5 5"
- stroke="currentColor"
- strokeWidth="1.5"
- fill="none"
- strokeLinecap="round"
- strokeLinejoin="round"
- />
- </svg>
- <div
- {...stylex.props(
- styles.indeterminateMark,
- indeterminateSizeStyles[size],
- isIndeterminate && styles.indeterminateMarkVisible,
- )}
- />
- </>
- )}
- </div>
- </div>
+ return (
+ <div className={xdsClassName('checkbox-input', {size})}>
+ <div
+ {...stylex.props(
+ styles.container,
+ isLabelHidden && styles.containerLabelHidden,
+ !isDisabled && stylex.defaultMarker(),
+ )}>
+ <div {...stylex.props(styles.checkboxWrapper, wrapperSizeStyles[size])}>
+ <input
+ ref={ref}
+ id={id}
+ type="checkbox"
+ checked={isChecked}
+ disabled={isDisabled}
+ required={isRequired}
+ onChange={e => {
+ const checked = e.target.checked;
+ onChange?.(checked, e);
+ if (onChangeAction && !e.defaultPrevented) {
+ startTransition(async () => {
+ setOptimisticValue(checked);
+ await onChangeAction(checked, e);
+ });
+ }
+ }}
+ onFocus={onFocus}
+ onBlur={onBlur}
+ aria-describedby={ariaDescribedBy}
+ aria-invalid={status?.type === 'error' ? true : undefined}
+ aria-busy={isBusy || undefined}
+ {...stylex.props(
+ styles.input,
+ wrapperSizeStyles[size],
+ isDisabled && styles.inputDisabled,
+ )}
+ />
<div
+ aria-hidden="true"
{...stylex.props(
- styles.labelWrapper,
- labelWrapperSizeStyles[size],
+ styles.checkbox,
+ checkboxSizeStyles[size],
+ isCheckedOrIndeterminate
+ ? styles.checkboxChecked
+ : styles.checkboxUnchecked,
+ isDisabled && styles.checkboxDisabled,
+ isDisabled &&
+ !isCheckedOrIndeterminate &&
+ styles.checkboxDisabledUnchecked,
)}>
- <XDSFieldLabel
- label={label}
- inputID={id}
- isLabelHidden={isLabelHidden}
- isDisabled={isDisabled}
- isOptional={isOptional}
- isRequired={isRequired}
- labelIcon={labelIcon}
- />
- {description && !isLabelHidden && (
- <span id={descriptionID} {...stylex.props(styles.description)}>
- {description}
- </span>
+ {isBusy ? (
+ <XDSSpinner
+ size="sm"
+ shade={isCheckedOrIndeterminate ? 'onMedia' : 'default'}
+ />
+ ) : (
+ <>
+ <svg
+ viewBox="0 0 10 10"
+ {...stylex.props(
+ styles.checkmark,
+ checkmarkSizeStyles[size],
+ isChecked && styles.checkmarkVisible,
+ )}>
+ <path
+ d="M8.5 2.5L4 7.5L1.5 5"
+ stroke="currentColor"
+ strokeWidth="1.5"
+ fill="none"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ </svg>
+ <div
+ {...stylex.props(
+ styles.indeterminateMark,
+ indeterminateSizeStyles[size],
+ isIndeterminate && styles.indeterminateMarkVisible,
+ )}
+ />
+ </>
)}
</div>
</div>
- {status?.message && (
- <XDSFieldStatus
- type={status.type}
- message={status.message}
- id={statusMessageID}
- variant="detached"
+ <div
+ {...stylex.props(styles.labelWrapper, labelWrapperSizeStyles[size])}>
+ <XDSFieldLabel
+ label={label}
+ inputID={id}
+ isLabelHidden={isLabelHidden}
+ isDisabled={isDisabled}
+ isOptional={isOptional}
+ isRequired={isRequired}
+ labelIcon={labelIcon}
/>
- )}
+ {description && !isLabelHidden && (
+ <span id={descriptionID} {...stylex.props(styles.description)}>
+ {description}
+ </span>
+ )}
+ </div>
</div>
- );
- },
-);
+ {status?.message && (
+ <XDSFieldStatus
+ type={status.type}
+ message={status.message}
+ id={statusMessageID}
+ variant="detached"
+ />
+ )}
+ </div>
+ );
+}
XDSCheckboxInput.displayName = 'XDSCheckboxInput';
diff --git a/packages/core/src/Collapsible/XDSCollapsible.tsx b/packages/core/src/Collapsible/XDSCollapsible.tsx
index 8249bafd03..556b4a29b5 100644
--- a/packages/core/src/Collapsible/XDSCollapsible.tsx
+++ b/packages/core/src/Collapsible/XDSCollapsible.tsx
@@ -18,7 +18,7 @@
'use client';
-import {forwardRef, type ReactNode} from 'react';
+import {type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import {
colorVars,
@@ -72,6 +72,8 @@ const styles = stylex.create({
});
export interface XDSCollapsibleProps {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLDivElement>;
/**
* Content shown in the trigger area (always visible).
* Rendered inside a button with aria-expanded and a chevron indicator.
@@ -148,57 +150,53 @@ export interface XDSCollapsibleProps {
* </XDSCollapsibleGroup>
* ```
*/
-export const XDSCollapsible = forwardRef<HTMLDivElement, XDSCollapsibleProps>(
- function XDSCollapsible(
- {
- trigger,
- children,
- defaultIsOpen,
- isOpen: controlledIsOpen,
- onOpenChange,
- value,
- ...props
- },
- ref,
- ) {
- // Build the config for the hook
- const collapsibleConfig =
- controlledIsOpen !== undefined
- ? {isOpen: controlledIsOpen, onOpenChange}
- : {defaultIsOpen: defaultIsOpen ?? true, onOpenChange};
+export function XDSCollapsible({
+ trigger,
+ children,
+ defaultIsOpen,
+ isOpen: controlledIsOpen,
+ onOpenChange,
+ value,
+ ref,
+ ...props
+}: XDSCollapsibleProps) {
+ // Build the config for the hook
+ const collapsibleConfig =
+ controlledIsOpen !== undefined
+ ? {isOpen: controlledIsOpen, onOpenChange}
+ : {defaultIsOpen: defaultIsOpen ?? true, onOpenChange};
- const {isOpen, toggle} = useXDSCollapsible({
- isCollapsible: collapsibleConfig,
- value,
- });
+ const {isOpen, toggle} = useXDSCollapsible({
+ isCollapsible: collapsibleConfig,
+ value,
+ });
- const chevronIcon = getIcon('chevronDown');
+ const chevronIcon = getIcon('chevronDown');
- return (
- <div ref={ref} className={xdsClassName('collapsible')} {...props}>
- <button
- type="button"
- onClick={toggle}
- aria-expanded={isOpen}
- {...stylex.props(styles.trigger)}>
- <span>{trigger}</span>
- <span
- {...stylex.props(
- styles.chevron,
- isOpen ? styles.chevronOpen : styles.chevronClosed,
- )}>
- {chevronIcon}
- </span>
- </button>
- <div
- {...(isOpen
- ? stylex.props(styles.content)
- : stylex.props(styles.content, styles.contentHidden))}>
- {children}
- </div>
+ return (
+ <div ref={ref} className={xdsClassName('collapsible')} {...props}>
+ <button
+ type="button"
+ onClick={toggle}
+ aria-expanded={isOpen}
+ {...stylex.props(styles.trigger)}>
+ <span>{trigger}</span>
+ <span
+ {...stylex.props(
+ styles.chevron,
+ isOpen ? styles.chevronOpen : styles.chevronClosed,
+ )}>
+ {chevronIcon}
+ </span>
+ </button>
+ <div
+ {...(isOpen
+ ? stylex.props(styles.content)
+ : stylex.props(styles.content, styles.contentHidden))}>
+ {children}
</div>
- );
- },
-);
+ </div>
+ );
+}
XDSCollapsible.displayName = 'XDSCollapsible';
diff --git a/packages/core/src/DateInput/XDSDateInput.tsx b/packages/core/src/DateInput/XDSDateInput.tsx
index 3c66d9ea3d..3a3f1bb31a 100644
--- a/packages/core/src/DateInput/XDSDateInput.tsx
+++ b/packages/core/src/DateInput/XDSDateInput.tsx
@@ -1,6 +1,6 @@
/**
* @file XDSDateInput.tsx
- * @input Uses React forwardRef, useId, useState, useEffect, useCallback, useRef, XDSField, XDSIcon, XDSCalendar, useXDSPopover
+ * @input Uses React, useId, useState, useEffect, useCallback, useRef, XDSField, XDSIcon, XDSCalendar, useXDSPopover
* @output Exports XDSDateInput component, XDSDateInputProps
* @position Core implementation; consumed by index.ts, tested by XDSDateInput.test.tsx
*
@@ -14,7 +14,6 @@
'use client';
import {
- forwardRef,
useId,
useState,
useCallback,
@@ -131,6 +130,8 @@ export interface XDSDateInputProps extends Omit<
XDSBaseProps,
'onChange' | 'defaultValue'
> {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLInputElement>;
/**
* Label text for the input (required for accessibility).
*/
@@ -247,297 +248,293 @@ export interface XDSDateInputProps extends Omit<
* />
* ```
*/
-export const XDSDateInput = forwardRef<HTMLInputElement, XDSDateInputProps>(
- (
- {
- label,
- isLabelHidden = false,
- description,
- isOptional = false,
- isRequired = false,
- isDisabled = false,
- value,
- onChange,
- onChangeAction,
- isLoading = false,
- min,
- max,
- dateConstraints,
- placeholder = 'Select a date',
- size = 'md',
- status,
- labelTooltip,
- numberOfMonths = 1,
- xstyle,
- className,
- style,
+export function XDSDateInput({
+ label,
+ isLabelHidden = false,
+ description,
+ isOptional = false,
+ isRequired = false,
+ isDisabled = false,
+ value,
+ onChange,
+ onChangeAction,
+ isLoading = false,
+ min,
+ max,
+ dateConstraints,
+ placeholder = 'Select a date',
+ size = 'md',
+ status,
+ labelTooltip,
+ numberOfMonths = 1,
+ xstyle,
+ className,
+ style,
+ ref,
+}: XDSDateInputProps) {
+ const id = useId();
+ const descriptionID = useId();
+ const statusMessageID = useId();
+ const inputRef = useRef<HTMLInputElement | null>(null);
+ const calendarRef = useRef<XDSCalendarHandle | null>(null);
+
+ const [, startTransition] = useTransition();
+ const [optimisticValue, setOptimisticValue] = useOptimistic(value);
+ const isBusy = isLoading || optimisticValue !== value;
+
+ // Status icon mapping
+ const statusIconMap: Record<XDSInputStatusType, XDSIconName> = {
+ warning: 'warning',
+ error: 'xCircle',
+ success: 'checkCircle',
+ };
+
+ const statusIconColorMap: Record<
+ XDSInputStatusType,
+ 'warning' | 'negative' | 'positive'
+ > = {
+ warning: 'warning',
+ error: 'negative',
+ success: 'positive',
+ };
+
+ const ariaDescribedBy =
+ [
+ description ? descriptionID : null,
+ status?.message ? statusMessageID : null,
+ ]
+ .filter(Boolean)
+ .join(' ') || undefined;
+
+ // Pending input while user is typing (null = show formatted value)
+ const [pendingInput, setPendingInput] = useState<string | null>(null);
+
+ // Display value: pending input if typing, otherwise formatted value
+ const displayValue = useMemo(() => {
+ if (pendingInput !== null) {
+ return pendingInput;
+ }
+ return optimisticValue ? formatDisplayDate(optimisticValue) : '';
+ }, [pendingInput, optimisticValue]);
+
+ // Check if current input is valid (for styling purposes)
+ const isInputValid = useMemo(() => {
+ // Only check pending input for validity styling
+ if (pendingInput === null || !pendingInput.trim()) {
+ return true;
+ }
+ return parseDateInput(pendingInput) !== null;
+ }, [pendingInput]);
+
+ // Use XDSPopover for popover rendering, positioning, and focus trapping
+ const popover = useXDSPopover({
+ xstyle: styles.popover,
+ dialogLabel: 'Choose date',
+ closeButtonLabel: 'Close calendar',
+ onHide: () => {
+ // Return focus to input when popover closes
+ inputRef.current?.focus();
},
- ref,
- ) => {
- const id = useId();
- const descriptionID = useId();
- const statusMessageID = useId();
- const inputRef = useRef<HTMLInputElement | null>(null);
- const calendarRef = useRef<XDSCalendarHandle | null>(null);
-
- const [, startTransition] = useTransition();
- const [optimisticValue, setOptimisticValue] = useOptimistic(value);
- const isBusy = isLoading || optimisticValue !== value;
-
- // Status icon mapping
- const statusIconMap: Record<XDSInputStatusType, XDSIconName> = {
- warning: 'warning',
- error: 'xCircle',
- success: 'checkCircle',
- };
-
- const statusIconColorMap: Record<
- XDSInputStatusType,
- 'warning' | 'negative' | 'positive'
- > = {
- warning: 'warning',
- error: 'negative',
- success: 'positive',
- };
-
- const ariaDescribedBy =
- [
- description ? descriptionID : null,
- status?.message ? statusMessageID : null,
- ]
- .filter(Boolean)
- .join(' ') || undefined;
-
- // Pending input while user is typing (null = show formatted value)
- const [pendingInput, setPendingInput] = useState<string | null>(null);
-
- // Display value: pending input if typing, otherwise formatted value
- const displayValue = useMemo(() => {
- if (pendingInput !== null) {
- return pendingInput;
+ });
+
+ // Handle opening the popover from button click (focus calendar)
+ const handleOpen = useCallback(() => {
+ if (!isDisabled && !popover.isOpen) {
+ popover.show();
+ }
+ }, [isDisabled, popover]);
+
+ // Handle opening the popover from input click (keep focus in input)
+ const handleInputClick = useCallback(() => {
+ if (!isDisabled && !popover.isOpen) {
+ popover.show({skipAutoFocus: true});
+ }
+ }, [isDisabled, popover]);
+
+ // Unified change handler that fires both onChange and onChangeAction
+ const fireChange = useCallback(
+ (newValue: ISODateString | undefined) => {
+ onChange?.(newValue);
+ if (onChangeAction) {
+ startTransition(async () => {
+ setOptimisticValue(newValue);
+ await onChangeAction(newValue);
+ });
}
- return optimisticValue ? formatDisplayDate(optimisticValue) : '';
- }, [pendingInput, optimisticValue]);
-
- // Check if current input is valid (for styling purposes)
- const isInputValid = useMemo(() => {
- // Only check pending input for validity styling
- if (pendingInput === null || !pendingInput.trim()) {
- return true;
+ },
+ [onChange, onChangeAction, startTransition, setOptimisticValue],
+ );
+
+ // Handle date selection from calendar
+ const handleDateSelect = useCallback(
+ (selectedDate: ISODateString) => {
+ fireChange(selectedDate);
+ setPendingInput(null);
+ popover.hide();
+ },
+ [fireChange, popover],
+ );
+
+ // Handle input text change - update immediately if valid
+ const handleInputChange = useCallback(
+ (e: React.ChangeEvent<HTMLInputElement>) => {
+ const newValue = e.target.value;
+ setPendingInput(newValue);
+
+ // If the input is valid, update immediately (don't wait for blur)
+ const parsed = parseDateInput(newValue);
+ if (parsed && parsed !== value) {
+ fireChange(parsed);
+ // Navigate calendar to show the parsed date's month
+ calendarRef.current?.navigateTo(parsed);
}
- return parseDateInput(pendingInput) !== null;
- }, [pendingInput]);
-
- // Use XDSPopover for popover rendering, positioning, and focus trapping
- const popover = useXDSPopover({
- xstyle: styles.popover,
- dialogLabel: 'Choose date',
- closeButtonLabel: 'Close calendar',
- onHide: () => {
- // Return focus to input when popover closes
- inputRef.current?.focus();
- },
- });
-
- // Handle opening the popover from button click (focus calendar)
- const handleOpen = useCallback(() => {
- if (!isDisabled && !popover.isOpen) {
- popover.show();
+ },
+ [value, fireChange],
+ );
+
+ // Handle blur - validate and clear pending input
+ const handleBlur = useCallback(() => {
+ if (pendingInput === null) {
+ return;
+ }
+
+ if (!pendingInput.trim()) {
+ // Empty input clears the value
+ if (value !== undefined) {
+ fireChange(undefined);
}
- }, [isDisabled, popover]);
-
- // Handle opening the popover from input click (keep focus in input)
- const handleInputClick = useCallback(() => {
- if (!isDisabled && !popover.isOpen) {
- popover.show({skipAutoFocus: true});
+ setPendingInput(null);
+ return;
+ }
+
+ const parsed = parseDateInput(pendingInput);
+ if (parsed) {
+ // Valid date - update if different
+ if (parsed !== value) {
+ fireChange(parsed);
}
- }, [isDisabled, popover]);
-
- // Unified change handler that fires both onChange and onChangeAction
- const fireChange = useCallback(
- (newValue: ISODateString | undefined) => {
- onChange?.(newValue);
- if (onChangeAction) {
- startTransition(async () => {
- setOptimisticValue(newValue);
- await onChangeAction(newValue);
- });
- }
- },
- [onChange, onChangeAction, startTransition, setOptimisticValue],
- );
-
- // Handle date selection from calendar
- const handleDateSelect = useCallback(
- (selectedDate: ISODateString) => {
- fireChange(selectedDate);
- setPendingInput(null);
+ }
+ // Clear pending input - display will revert to formatted value
+ setPendingInput(null);
+ }, [pendingInput, value, fireChange]);
+
+ // Handle keyboard events on input
+ const handleInputKeyDown = useCallback(
+ (e: React.KeyboardEvent) => {
+ if (e.key === 'Escape' && popover.isOpen) {
+ e.preventDefault();
popover.hide();
- },
- [fireChange, popover],
- );
-
- // Handle input text change - update immediately if valid
- const handleInputChange = useCallback(
- (e: React.ChangeEvent<HTMLInputElement>) => {
- const newValue = e.target.value;
- setPendingInput(newValue);
-
- // If the input is valid, update immediately (don't wait for blur)
- const parsed = parseDateInput(newValue);
- if (parsed && parsed !== value) {
- fireChange(parsed);
- // Navigate calendar to show the parsed date's month
- calendarRef.current?.navigateTo(parsed);
- }
- },
- [value, fireChange],
- );
-
- // Handle blur - validate and clear pending input
- const handleBlur = useCallback(() => {
- if (pendingInput === null) {
- return;
}
-
- if (!pendingInput.trim()) {
- // Empty input clears the value
- if (value !== undefined) {
- fireChange(undefined);
- }
- setPendingInput(null);
- return;
+ },
+ [popover],
+ );
+
+ // Combine refs
+ const setRefs = useCallback(
+ (el: HTMLInputElement | null) => {
+ inputRef.current = el;
+ if (typeof ref === 'function') {
+ ref(el);
+ } else if (ref) {
+ ref.current = el;
}
-
- const parsed = parseDateInput(pendingInput);
- if (parsed) {
- // Valid date - update if different
- if (parsed !== value) {
- fireChange(parsed);
- }
+ },
+ [ref],
+ );
+
+ return (
+ <XDSField
+ label={label}
+ isLabelHidden={isLabelHidden}
+ description={description}
+ inputID={id}
+ descriptionID={description ? descriptionID : undefined}
+ isOptional={isOptional}
+ isRequired={isRequired}
+ status={
+ status
+ ? {
+ type: status.type,
+ message: status.message,
+ messageID: status.message ? statusMessageID : undefined,
+ }
+ : undefined
}
- // Clear pending input - display will revert to formatted value
- setPendingInput(null);
- }, [pendingInput, value, fireChange]);
-
- // Handle keyboard events on input
- const handleInputKeyDown = useCallback(
- (e: React.KeyboardEvent) => {
- if (e.key === 'Escape' && popover.isOpen) {
- e.preventDefault();
- popover.hide();
- }
- },
- [popover],
- );
-
- // Combine refs
- const setRefs = useCallback(
- (el: HTMLInputElement | null) => {
- inputRef.current = el;
- if (typeof ref === 'function') {
- ref(el);
- } else if (ref) {
- ref.current = el;
- }
- },
- [ref],
- );
-
- return (
- <XDSField
- label={label}
- isLabelHidden={isLabelHidden}
- description={description}
- inputID={id}
- descriptionID={description ? descriptionID : undefined}
- isOptional={isOptional}
- isRequired={isRequired}
- status={
- status
- ? {
- type: status.type,
- message: status.message,
- messageID: status.message ? statusMessageID : undefined,
- }
- : undefined
- }
- labelTooltip={labelTooltip}>
- <div
- ref={popover.triggerRef}
- {...mergeProps(
- xdsClassName('date-input', {size}),
- stylex.props(
- inputWrapperStyles.base,
- sizeStyles[size],
- isDisabled && inputWrapperStyles.disabled,
- status && inputStatusBorderStyles[status.type],
- status && inputStatusHoverShadowStyles[status.type],
- status && inputStatusFocusWithinStyles[status.type],
- xstyle,
- ),
- className,
- style,
+ labelTooltip={labelTooltip}>
+ <div
+ ref={popover.triggerRef}
+ {...mergeProps(
+ xdsClassName('date-input', {size}),
+ stylex.props(
+ inputWrapperStyles.base,
+ sizeStyles[size],
+ isDisabled && inputWrapperStyles.disabled,
+ status && inputStatusBorderStyles[status.type],
+ status && inputStatusHoverShadowStyles[status.type],
+ status && inputStatusFocusWithinStyles[status.type],
+ xstyle,
+ ),
+ className,
+ style,
+ )}>
+ <button
+ type="button"
+ onClick={handleOpen}
+ disabled={isDisabled}
+ aria-label="Open calendar"
+ {...popover.triggerProps}
+ {...stylex.props(
+ styles.iconButton,
+ isDisabled && styles.iconButtonDisabled,
)}>
- <button
- type="button"
- onClick={handleOpen}
- disabled={isDisabled}
- aria-label="Open calendar"
- {...popover.triggerProps}
- {...stylex.props(
- styles.iconButton,
- isDisabled && styles.iconButtonDisabled,
- )}>
- <XDSIcon icon="calendar" size="sm" color="secondary" />
- </button>
- <input
- ref={setRefs}
- id={id}
- type="text"
- value={displayValue}
- onChange={handleInputChange}
- onBlur={handleBlur}
- onClick={handleInputClick}
- onKeyDown={handleInputKeyDown}
- placeholder={placeholder}
- disabled={isDisabled}
- aria-describedby={ariaDescribedBy}
- aria-required={isRequired === true ? 'true' : undefined}
- aria-invalid={status?.type === 'error' ? 'true' : undefined}
- aria-busy={isBusy || undefined}
- autoComplete="off"
- {...stylex.props(
- styles.input,
- isDisabled && styles.inputDisabled,
- !isInputValid && styles.inputInvalid,
- )}
- />
- {isBusy && <XDSSpinner size="sm" />}
- {status && (
- <XDSIcon
- icon={statusIconMap[status.type]}
- size="md"
- color={statusIconColorMap[status.type]}
- />
+ <XDSIcon icon="calendar" size="sm" color="secondary" />
+ </button>
+ <input
+ ref={setRefs}
+ id={id}
+ type="text"
+ value={displayValue}
+ onChange={handleInputChange}
+ onBlur={handleBlur}
+ onClick={handleInputClick}
+ onKeyDown={handleInputKeyDown}
+ placeholder={placeholder}
+ disabled={isDisabled}
+ aria-describedby={ariaDescribedBy}
+ aria-required={isRequired === true ? 'true' : undefined}
+ aria-invalid={status?.type === 'error' ? 'true' : undefined}
+ aria-busy={isBusy || undefined}
+ autoComplete="off"
+ {...stylex.props(
+ styles.input,
+ isDisabled && styles.inputDisabled,
+ !isInputValid && styles.inputInvalid,
)}
- </div>
- {popover.render(
- <XDSCalendar
- ref={calendarRef}
- mode="single"
- value={value}
- onChange={handleDateSelect}
- min={min}
- max={max}
- dateConstraints={dateConstraints}
- numberOfMonths={numberOfMonths}
- />,
- {placement: 'below', alignment: 'start'},
+ />
+ {isBusy && <XDSSpinner size="sm" />}
+ {status && (
+ <XDSIcon
+ icon={statusIconMap[status.type]}
+ size="md"
+ color={statusIconColorMap[status.type]}
+ />
)}
- </XDSField>
- );
- },
-);
+ </div>
+ {popover.render(
+ <XDSCalendar
+ ref={calendarRef}
+ mode="single"
+ value={value}
+ onChange={handleDateSelect}
+ min={min}
+ max={max}
+ dateConstraints={dateConstraints}
+ numberOfMonths={numberOfMonths}
+ />,
+ {placement: 'below', alignment: 'start'},
+ )}
+ </XDSField>
+ );
+}
XDSDateInput.displayName = 'XDSDateInput';
diff --git a/packages/core/src/Dialog/XDSDialog.tsx b/packages/core/src/Dialog/XDSDialog.tsx
index 0c6b1d2594..cd4e15747c 100644
--- a/packages/core/src/Dialog/XDSDialog.tsx
+++ b/packages/core/src/Dialog/XDSDialog.tsx
@@ -1,6 +1,6 @@
/**
* @file XDSDialog.tsx
- * @input Uses React forwardRef, DialogHTMLAttributes, ReactNode
+ * @input Uses React, DialogHTMLAttributes, ReactNode
* @output Exports XDSDialog component, XDSDialogProps, XDSDialogVariant, XDSDialogPurpose types
* @position Core implementation; consumed by index.ts, tested by XDSDialog.test.tsx
*
@@ -13,7 +13,7 @@
'use client';
-import {forwardRef, useEffect, useRef, type ReactNode} from 'react';
+import {useEffect, useRef, type ReactNode} from 'react';
import type {XDSBaseProps} from '../XDSBaseProps';
import * as stylex from '@stylexjs/stylex';
import {
@@ -137,6 +137,8 @@ function formatPosition(value: number | string | undefined): string | null {
}
export interface XDSDialogProps extends XDSBaseProps<HTMLDialogElement> {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLDialogElement>;
/**
* Whether the dialog is open.
*/
@@ -218,134 +220,130 @@ export interface XDSDialogProps extends XDSBaseProps<HTMLDialogElement> {
* </XDSDialog>
* ```
*/
-export const XDSDialog = forwardRef<HTMLDialogElement, XDSDialogProps>(
- (
- {
- isOpen,
- onOpenChange,
- width = 400,
- maxHeight = '75vh',
- position,
- variant = 'standard',
- purpose = 'info',
- children,
- xstyle,
- className,
- style,
- ...props
- },
- ref,
- ) => {
- const dialogRef = useRef<HTMLDialogElement>(null);
+export function XDSDialog({
+ isOpen,
+ onOpenChange,
+ width = 400,
+ maxHeight = '75vh',
+ position,
+ variant = 'standard',
+ purpose = 'info',
+ children,
+ xstyle,
+ className,
+ style,
+ ref,
+ ...props
+}: XDSDialogProps) {
+ const dialogRef = useRef<HTMLDialogElement>(null);
- // Derive dismissal behavior from purpose
- const allowEscape = purpose !== 'required';
- const allowBackdropClick = purpose === 'info';
+ // Derive dismissal behavior from purpose
+ const allowEscape = purpose !== 'required';
+ const allowBackdropClick = purpose === 'info';
- // Merge refs
- const setRefs = (element: HTMLDialogElement | null) => {
- (dialogRef as React.MutableRefObject<HTMLDialogElement | null>).current =
- element;
- if (typeof ref === 'function') {
- ref(element);
- } else if (ref) {
- ref.current = element;
- }
- };
+ // Merge refs
+ const setRefs = (element: HTMLDialogElement | null) => {
+ (dialogRef as React.MutableRefObject<HTMLDialogElement | null>).current =
+ element;
+ if (typeof ref === 'function') {
+ ref(element);
+ } else if (ref) {
+ ref.current = element;
+ }
+ };
- // Handle open/close state
- useEffect(() => {
- const dialog = dialogRef.current;
- if (!dialog) return;
+ // Handle open/close state
+ useEffect(() => {
+ const dialog = dialogRef.current;
+ if (!dialog) return;
- if (isOpen) {
- if (!dialog.open) {
- dialog.showModal();
- }
- } else {
- if (dialog.open) {
- dialog.close();
- }
+ if (isOpen) {
+ if (!dialog.open) {
+ dialog.showModal();
+ }
+ } else {
+ if (dialog.open) {
+ dialog.close();
}
- }, [isOpen]);
+ }
+ }, [isOpen]);
- // Handle Escape key
- useEffect(() => {
- const dialog = dialogRef.current;
- if (!dialog || !isOpen) return;
+ // Handle Escape key
+ useEffect(() => {
+ const dialog = dialogRef.current;
+ if (!dialog || !isOpen) return;
- const handleKeyDown = (event: KeyboardEvent) => {
- if (event.key === 'Escape') {
- event.preventDefault();
- if (allowEscape) {
- onOpenChange(false);
- }
+ const handleKeyDown = (event: KeyboardEvent) => {
+ if (event.key === 'Escape') {
+ event.preventDefault();
+ if (allowEscape) {
+ onOpenChange(false);
}
- };
+ }
+ };
- dialog.addEventListener('keydown', handleKeyDown);
- return () => dialog.removeEventListener('keydown', handleKeyDown);
- }, [isOpen, allowEscape, onOpenChange]);
+ dialog.addEventListener('keydown', handleKeyDown);
+ return () => dialog.removeEventListener('keydown', handleKeyDown);
+ }, [isOpen, allowEscape, onOpenChange]);
- // Handle backdrop click
- const handleClick = (event: React.MouseEvent<HTMLDialogElement>) => {
- const dialog = dialogRef.current;
- if (!dialog) return;
+ // Handle backdrop click
+ const handleClick = (event: React.MouseEvent<HTMLDialogElement>) => {
+ const dialog = dialogRef.current;
+ if (!dialog) return;
- // Check if click was on the backdrop (dialog element itself, not content)
- const rect = dialog.getBoundingClientRect();
- const isBackdropClick =
- event.clientX < rect.left ||
- event.clientX > rect.right ||
- event.clientY < rect.top ||
- event.clientY > rect.bottom;
+ // Check if click was on the backdrop (dialog element itself, not content)
+ const rect = dialog.getBoundingClientRect();
+ const isBackdropClick =
+ event.clientX < rect.left ||
+ event.clientX > rect.right ||
+ event.clientY < rect.top ||
+ event.clientY > rect.bottom;
- if (isBackdropClick && allowBackdropClick) {
- onOpenChange(false);
- }
- };
+ if (isBackdropClick && allowBackdropClick) {
+ onOpenChange(false);
+ }
+ };
- // Handle native cancel event (browser Escape handling)
- const handleCancel = (event: React.SyntheticEvent<HTMLDialogElement>) => {
- event.preventDefault();
- if (allowEscape) {
- onOpenChange(false);
- }
- };
+ // Handle native cancel event (browser Escape handling)
+ const handleCancel = (event: React.SyntheticEvent<HTMLDialogElement>) => {
+ event.preventDefault();
+ if (allowEscape) {
+ onOpenChange(false);
+ }
+ };
- const isFullscreen = variant === 'fullscreen';
- const hasPosition = position != null && !isFullscreen;
+ const isFullscreen = variant === 'fullscreen';
+ const hasPosition = position != null && !isFullscreen;
- return (
- <dialog
- ref={setRefs}
- onClick={handleClick}
- onCancel={handleCancel}
- aria-modal="true"
- {...mergeProps(
- xdsClassName('dialog', {variant}),
- stylex.props(
- styles.dialog,
- styles.backdrop,
- !isFullscreen && dynamicStyles.sizing(width, maxHeight),
- hasPosition &&
- dynamicStyles.position(
- position?.top,
- position?.right,
- position?.bottom,
- position?.left,
- ),
- isFullscreen && styles.fullscreen,
- xstyle,
- ),
- className,
- style,
- )}
- {...props}>
- {children}
- </dialog>
- );
- },
-);
+ return (
+ <dialog
+ ref={setRefs}
+ onClick={handleClick}
+ onCancel={handleCancel}
+ aria-modal="true"
+ {...mergeProps(
+ xdsClassName('dialog', {variant}),
+ stylex.props(
+ styles.dialog,
+ styles.backdrop,
+ !isFullscreen && dynamicStyles.sizing(width, maxHeight),
+ hasPosition &&
+ dynamicStyles.position(
+ position?.top,
+ position?.right,
+ position?.bottom,
+ position?.left,
+ ),
+ isFullscreen && styles.fullscreen,
+ xstyle,
+ ),
+ className,
+ style,
+ )}
+ {...props}>
+ {children}
+ </dialog>
+ );
+}
XDSDialog.displayName = 'XDSDialog';
diff --git a/packages/core/src/Dialog/XDSDialogHeader.tsx b/packages/core/src/Dialog/XDSDialogHeader.tsx
index 03721cfe12..3f67a77267 100644
--- a/packages/core/src/Dialog/XDSDialogHeader.tsx
+++ b/packages/core/src/Dialog/XDSDialogHeader.tsx
@@ -1,6 +1,6 @@
/**
* @file XDSDialogHeader.tsx
- * @input Uses React forwardRef, useEffect, useRef, XDSLayoutHeader, XDSButton, XDSIcon, XDSHeading, XDSText
+ * @input Uses React, useEffect, useRef, XDSLayoutHeader, XDSButton, XDSIcon, XDSHeading, XDSText
* @output Exports XDSDialogHeader component and XDSDialogHeaderProps
* @position Dialog header component; used with XDSDialog and XDSLayout
*
@@ -13,7 +13,7 @@
'use client';
-import {forwardRef, useEffect, useRef, type ReactNode} from 'react';
+import {useEffect, useRef, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import {spacingVars} from '../theme/tokens.stylex';
import {XDSLayoutHeader} from '../Layout/XDSLayoutHeader';
@@ -49,6 +49,8 @@ const styles = stylex.create({
});
export interface XDSDialogHeaderProps {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLElement>;
/**
* The title of the dialog.
* This title receives focus when the dialog opens for screen reader accessibility.
@@ -105,64 +107,60 @@ export interface XDSDialogHeaderProps {
* </XDSDialog>
* ```
*/
-export const XDSDialogHeader = forwardRef<HTMLElement, XDSDialogHeaderProps>(
- function XDSDialogHeader(
- {
- title,
- subtitle,
- onOpenChange,
- startContent,
- endContent,
- hasDivider = true,
- },
- ref,
- ) {
- const titleRef = useRef<HTMLHeadingElement>(null);
+export function XDSDialogHeader({
+ title,
+ subtitle,
+ onOpenChange,
+ startContent,
+ endContent,
+ hasDivider = true,
+ ref,
+}: XDSDialogHeaderProps) {
+ const titleRef = useRef<HTMLHeadingElement>(null);
- // Auto-focus the title when mounted for screen reader accessibility
- useEffect(() => {
- if (titleRef.current) {
- titleRef.current.tabIndex = -1;
- titleRef.current.focus();
- }
- }, []);
+ // Auto-focus the title when mounted for screen reader accessibility
+ useEffect(() => {
+ if (titleRef.current) {
+ titleRef.current.tabIndex = -1;
+ titleRef.current.focus();
+ }
+ }, []);
- return (
- <XDSLayoutHeader ref={ref} hasDivider={hasDivider}>
- <div {...stylex.props(styles.container)}>
- {startContent && (
- <div {...stylex.props(styles.actions)}>{startContent}</div>
+ return (
+ <XDSLayoutHeader ref={ref} hasDivider={hasDivider}>
+ <div {...stylex.props(styles.container)}>
+ {startContent && (
+ <div {...stylex.props(styles.actions)}>{startContent}</div>
+ )}
+ <div {...stylex.props(styles.titleWrapper)}>
+ <XDSHeading ref={titleRef} level={2} xstyle={styles.titleFocusable}>
+ {title}
+ </XDSHeading>
+ {subtitle && (
+ <XDSText type="body" size="sm" color="secondary">
+ {subtitle}
+ </XDSText>
)}
- <div {...stylex.props(styles.titleWrapper)}>
- <XDSHeading ref={titleRef} level={2} xstyle={styles.titleFocusable}>
- {title}
- </XDSHeading>
- {subtitle && (
- <XDSText type="body" size="sm" color="secondary">
- {subtitle}
- </XDSText>
+ </div>
+ {(endContent || onOpenChange) && (
+ <div {...stylex.props(styles.actions)}>
+ {endContent}
+ {onOpenChange && (
+ <div {...stylex.props(styles.closeButton)}>
+ <XDSButton
+ variant="ghost"
+ label="Close"
+ tooltip="Close"
+ icon={<XDSIcon icon="close" color="inherit" />}
+ onClick={() => onOpenChange?.(false)}
+ />
+ </div>
)}
</div>
- {(endContent || onOpenChange) && (
- <div {...stylex.props(styles.actions)}>
- {endContent}
- {onOpenChange && (
- <div {...stylex.props(styles.closeButton)}>
- <XDSButton
- variant="ghost"
- label="Close"
- tooltip="Close"
- icon={<XDSIcon icon="close" color="inherit" />}
- onClick={() => onOpenChange?.(false)}
- />
- </div>
- )}
- </div>
- )}
- </div>
- </XDSLayoutHeader>
- );
- },
-);
+ )}
+ </div>
+ </XDSLayoutHeader>
+ );
+}
XDSDialogHeader.displayName = 'XDSDialogHeader';
diff --git a/packages/core/src/Divider/XDSDivider.tsx b/packages/core/src/Divider/XDSDivider.tsx
index 3e4c7beaca..fef65d3b80 100644
--- a/packages/core/src/Divider/XDSDivider.tsx
+++ b/packages/core/src/Divider/XDSDivider.tsx
@@ -1,6 +1,6 @@
/**
* @file XDSDivider.tsx
- * @input Uses React forwardRef, stylex, spacing and color tokens
+ * @input Uses React, stylex, spacing and color tokens
* @output Exports XDSDivider component and XDSDividerProps
* @position Divider component; provides visual separation with optional label
*
@@ -12,7 +12,7 @@
'use client';
-import {type HTMLAttributes, forwardRef, type ReactNode} from 'react';
+import {type HTMLAttributes, type ReactNode} from 'react';
import type {XDSBaseProps} from '../XDSBaseProps';
import * as stylex from '@stylexjs/stylex';
import type {StyleXStyles} from '@stylexjs/stylex';
@@ -28,6 +28,8 @@ export interface XDSDividerProps extends Omit<
XDSBaseProps<HTMLDivElement>,
'children'
> {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLElement>;
/**
* Orientation of the divider.
* @default 'horizontal'
@@ -147,69 +149,63 @@ const fullBleedStyles = stylex.create({
* <XDSDivider label="or" />
* ```
*/
-export const XDSDivider = forwardRef<HTMLElement, XDSDividerProps>(
- function XDSDivider(
- {
- orientation = 'horizontal',
- label,
- variant = 'subtle',
- isFullBleed = false,
- xstyle,
- className,
- style,
- ...props
- },
- ref,
- ) {
- const isHorizontal = orientation === 'horizontal';
+export function XDSDivider({
+ orientation = 'horizontal',
+ label,
+ variant = 'subtle',
+ isFullBleed = false,
+ xstyle,
+ className,
+ style,
+ ref,
+ ...props
+}: XDSDividerProps) {
+ const isHorizontal = orientation === 'horizontal';
- return (
+ return (
+ <div
+ ref={ref as React.Ref<HTMLDivElement>}
+ role="separator"
+ aria-orientation={orientation}
+ {...mergeProps(
+ xdsClassName('divider', {variant, orientation}),
+ stylex.props(
+ isHorizontal ? baseStyles.horizontal : baseStyles.vertical,
+ isFullBleed &&
+ (isHorizontal
+ ? fullBleedStyles.horizontal
+ : fullBleedStyles.vertical),
+ xstyle,
+ ),
+ className,
+ style,
+ )}
+ {...props}>
<div
- ref={ref as React.Ref<HTMLDivElement>}
- role="separator"
- aria-orientation={orientation}
- {...mergeProps(
- xdsClassName('divider', {variant, orientation}),
- stylex.props(
- isHorizontal ? baseStyles.horizontal : baseStyles.vertical,
- isFullBleed &&
- (isHorizontal
- ? fullBleedStyles.horizontal
- : fullBleedStyles.vertical),
- xstyle,
- ),
- className,
- style,
+ {...stylex.props(
+ isHorizontal ? lineStyles.horizontalLine : lineStyles.verticalLine,
+ lineStyles[variant],
)}
- {...props}>
+ />
+ {label && (
+ <div
+ {...stylex.props(
+ labelStyles.label,
+ !isHorizontal && labelStyles.verticalLabel,
+ )}>
+ {label}
+ </div>
+ )}
+ {label && (
<div
{...stylex.props(
isHorizontal ? lineStyles.horizontalLine : lineStyles.verticalLine,
lineStyles[variant],
)}
/>
- {label && (
- <div
- {...stylex.props(
- labelStyles.label,
- !isHorizontal && labelStyles.verticalLabel,
- )}>
- {label}
- </div>
- )}
- {label && (
- <div
- {...stylex.props(
- isHorizontal
- ? lineStyles.horizontalLine
- : lineStyles.verticalLine,
- lineStyles[variant],
- )}
- />
- )}
- </div>
- );
- },
-);
+ )}
+ </div>
+ );
+}
XDSDivider.displayName = 'XDSDivider';
diff --git a/packages/core/src/EmptyState/XDSEmptyState.tsx b/packages/core/src/EmptyState/XDSEmptyState.tsx
index 6cc1b44235..86d5e08045 100644
--- a/packages/core/src/EmptyState/XDSEmptyState.tsx
+++ b/packages/core/src/EmptyState/XDSEmptyState.tsx
@@ -1,6 +1,6 @@
/**
* @file XDSEmptyState.tsx
- * @input Uses React forwardRef, HTMLAttributes
+ * @input Uses React, HTMLAttributes
* @output Exports XDSEmptyState component, XDSEmptyStateProps type
* @position Core implementation; consumed by index.ts
*
@@ -11,7 +11,7 @@
* - /apps/storybook/stories/EmptyState.stories.tsx (storybook stories)
*/
-import {forwardRef, type ReactNode} from 'react';
+import {type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {StyleXStyles} from '@stylexjs/stylex';
import {
@@ -80,6 +80,8 @@ const styles = stylex.create({
});
export interface XDSEmptyStateProps {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLDivElement>;
/**
* The primary message displayed in the empty state.
*/
@@ -151,63 +153,56 @@ export interface XDSEmptyStateProps {
* />
* ```
*/
-export const XDSEmptyState = forwardRef<HTMLDivElement, XDSEmptyStateProps>(
- (
- {
- title,
- description,
- icon,
- actions,
- isCompact = false,
- xstyle,
- className,
- style,
- ...props
- },
- ref,
- ) => {
- return (
- <div
- ref={ref}
- role="status"
- {...mergeProps(
- xdsClassName('emptystate'),
- stylex.props(
- styles.container,
- isCompact && styles.containerCompact,
- xstyle,
- ),
- className,
- style,
- )}
- {...props}>
- {icon != null && <div aria-hidden="true">{icon}</div>}
- <div {...stylex.props(styles.textGroup)}>
- <h3 {...stylex.props(styles.title, isCompact && styles.titleCompact)}>
- {title}
- </h3>
- {description != null && (
- <p
- {...stylex.props(
- styles.description,
- isCompact && styles.descriptionCompact,
- )}>
- {description}
- </p>
- )}
- </div>
- {actions != null && (
- <div
+export function XDSEmptyState({
+ title,
+ description,
+ icon,
+ actions,
+ isCompact = false,
+ xstyle,
+ className,
+ style,
+ ref,
+ ...props
+}: XDSEmptyStateProps) {
+ return (
+ <div
+ ref={ref}
+ role="status"
+ {...mergeProps(
+ xdsClassName('emptystate'),
+ stylex.props(
+ styles.container,
+ isCompact && styles.containerCompact,
+ xstyle,
+ ),
+ className,
+ style,
+ )}
+ {...props}>
+ {icon != null && <div aria-hidden="true">{icon}</div>}
+ <div {...stylex.props(styles.textGroup)}>
+ <h3 {...stylex.props(styles.title, isCompact && styles.titleCompact)}>
+ {title}
+ </h3>
+ {description != null && (
+ <p
{...stylex.props(
- styles.actions,
- isCompact && styles.actionsCompact,
+ styles.description,
+ isCompact && styles.descriptionCompact,
)}>
- {actions}
- </div>
+ {description}
+ </p>
)}
</div>
- );
- },
-);
+ {actions != null && (
+ <div
+ {...stylex.props(styles.actions, isCompact && styles.actionsCompact)}>
+ {actions}
+ </div>
+ )}
+ </div>
+ );
+}
XDSEmptyState.displayName = 'XDSEmptyState';
diff --git a/packages/core/src/Field/XDSField.tsx b/packages/core/src/Field/XDSField.tsx
index c11f8a0b8d..820a984176 100644
--- a/packages/core/src/Field/XDSField.tsx
+++ b/packages/core/src/Field/XDSField.tsx
@@ -1,6 +1,6 @@
/**
* @file XDSField.tsx
- * @input Uses React forwardRef, HTMLAttributes, ReactNode, XDSFieldLabel, XDSIconType
+ * @input Uses React, HTMLAttributes, ReactNode, XDSFieldLabel, XDSIconType
* @output Exports XDSField component, XDSFieldProps
* @position Core implementation; consumed by index.ts, tested by XDSField.test.tsx
*
@@ -13,7 +13,7 @@
'use client';
-import {forwardRef, type HTMLAttributes, type ReactNode} from 'react';
+import {type HTMLAttributes, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {StyleXStyles} from '@stylexjs/stylex';
import {XDSFieldLabel} from './XDSFieldLabel';
@@ -98,6 +98,8 @@ export interface XDSFieldProps extends Omit<
HTMLAttributes<HTMLDivElement>,
'children'
> {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLDivElement>;
/**
* Label text for the field (always rendered for accessibility).
*/
@@ -189,85 +191,81 @@ export interface XDSFieldProps extends Omit<
* </XDSField>
* ```
*/
-export const XDSField = forwardRef<HTMLDivElement, XDSFieldProps>(
- (
- {
- label,
- isLabelHidden = false,
- description,
- inputID,
- descriptionID,
- isOptional = false,
- isRequired = false,
- labelIcon,
- status,
- labelTooltip,
- statusVariant = 'attached',
- xstyle,
- children,
- className,
- style,
- ...props
- },
- ref,
- ) => {
- return (
- <div
- ref={ref}
- {...mergeProps(
- xdsClassName('field'),
- stylex.props(styles.container, xstyle),
- className,
- style,
- )}
- {...props}>
- <XDSFieldLabel
- label={label}
- inputID={inputID}
- isLabelHidden={isLabelHidden}
- isOptional={isOptional}
- isRequired={isRequired}
- labelIcon={labelIcon}
- labelTooltip={labelTooltip}
- />
- {description && (
- <span
- id={descriptionID}
- {...stylex.props(
- styles.description,
- isLabelHidden && styles.labelHidden,
- )}>
- {description}
- </span>
- )}
- {statusVariant === 'attached' ? (
- <div {...stylex.props(styles.inputStatusWrapper)}>
- {children}
- {status?.message && (
- <XDSFieldStatus
- type={status.type}
- message={status.message}
- id={status.messageID}
- variant="attached"
- />
- )}
- </div>
- ) : (
- <>
- {children}
- {status?.message && (
- <XDSFieldStatus
- type={status.type}
- message={status.message}
- id={status.messageID}
- variant="detached"
- />
- )}
- </>
- )}
- </div>
- );
- },
-);
+export function XDSField({
+ label,
+ isLabelHidden = false,
+ description,
+ inputID,
+ descriptionID,
+ isOptional = false,
+ isRequired = false,
+ labelIcon,
+ status,
+ labelTooltip,
+ statusVariant = 'attached',
+ xstyle,
+ children,
+ className,
+ style,
+ ref,
+ ...props
+}: XDSFieldProps) {
+ return (
+ <div
+ ref={ref}
+ {...mergeProps(
+ xdsClassName('field'),
+ stylex.props(styles.container, xstyle),
+ className,
+ style,
+ )}
+ {...props}>
+ <XDSFieldLabel
+ label={label}
+ inputID={inputID}
+ isLabelHidden={isLabelHidden}
+ isOptional={isOptional}
+ isRequired={isRequired}
+ labelIcon={labelIcon}
+ labelTooltip={labelTooltip}
+ />
+ {description && (
+ <span
+ id={descriptionID}
+ {...stylex.props(
+ styles.description,
+ isLabelHidden && styles.labelHidden,
+ )}>
+ {description}
+ </span>
+ )}
+ {statusVariant === 'attached' ? (
+ <div {...stylex.props(styles.inputStatusWrapper)}>
+ {children}
+ {status?.message && (
+ <XDSFieldStatus
+ type={status.type}
+ message={status.message}
+ id={status.messageID}
+ variant="attached"
+ />
+ )}
+ </div>
+ ) : (
+ <>
+ {children}
+ {status?.message && (
+ <XDSFieldStatus
+ type={status.type}
+ message={status.message}
+ id={status.messageID}
+ variant="detached"
+ />
+ )}
+ </>
+ )}
+ </div>
+ );
+}
XDSField.displayName = 'XDSField';
diff --git a/packages/core/src/Field/XDSFieldLabel.tsx b/packages/core/src/Field/XDSFieldLabel.tsx
index 007ec92689..bad656defb 100644
--- a/packages/core/src/Field/XDSFieldLabel.tsx
+++ b/packages/core/src/Field/XDSFieldLabel.tsx
@@ -1,6 +1,6 @@
/**
* @file XDSFieldLabel.tsx
- * @input Uses React forwardRef, XDSIcon, XDSIconType
+ * @input Uses React, XDSIcon, XDSIconType
* @output Exports XDSFieldLabel component, XDSFieldLabelProps
* @position Core label implementation; used by XDSField, XDSCheckboxInput
*
@@ -9,7 +9,6 @@
* - /packages/core/src/Field/index.ts (exports if types change)
*/
-import {forwardRef} from 'react';
import * as stylex from '@stylexjs/stylex';
import {xdsClassName, mergeProps} from '../utils';
@@ -63,6 +62,8 @@ const styles = stylex.create({
});
export interface XDSFieldLabelProps {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLLabelElement>;
/**
* Label text (always rendered for accessibility).
*/
@@ -110,61 +111,54 @@ export interface XDSFieldLabelProps {
* <XDSFieldLabel label="Hidden label" inputID={inputId} isLabelHidden />
* ```
*/
-export const XDSFieldLabel = forwardRef<HTMLLabelElement, XDSFieldLabelProps>(
- (
- {
- label,
- inputID,
- isLabelHidden = false,
- isDisabled = false,
- isOptional = false,
- isRequired = false,
- labelIcon,
- labelTooltip,
- },
- ref,
- ) => {
- const statusText = isOptional ? 'Optional' : isRequired ? 'Required' : null;
+export function XDSFieldLabel({
+ label,
+ inputID,
+ isLabelHidden = false,
+ isDisabled = false,
+ isOptional = false,
+ isRequired = false,
+ labelIcon,
+ labelTooltip,
+ ref,
+}: XDSFieldLabelProps) {
+ const statusText = isOptional ? 'Optional' : isRequired ? 'Required' : null;
- return (
- <label
- ref={ref}
- htmlFor={inputID}
- {...mergeProps(
- xdsClassName('field-label'),
- stylex.props(
- styles.label,
- !isDisabled && styles.labelClickable,
- isDisabled && styles.labelDisabled,
- isLabelHidden && styles.labelHidden,
- ),
- )}>
- {labelIcon && (
+ return (
+ <label
+ ref={ref}
+ htmlFor={inputID}
+ {...mergeProps(
+ xdsClassName('field-label'),
+ stylex.props(
+ styles.label,
+ !isDisabled && styles.labelClickable,
+ isDisabled && styles.labelDisabled,
+ isLabelHidden && styles.labelHidden,
+ ),
+ )}>
+ {labelIcon && (
+ <XDSIcon
+ icon={labelIcon}
+ size="sm"
+ color={isDisabled ? 'disabled' : 'primary'}
+ />
+ )}
+ {label}
+ {statusText && (
+ <span {...stylex.props(styles.optionalRequired)}> ∙ {statusText}</span>
+ )}
+ {labelTooltip && (
+ <XDSTooltip content={labelTooltip} placement="above">
<XDSIcon
- icon={labelIcon}
+ icon="info"
size="sm"
- color={isDisabled ? 'disabled' : 'primary'}
+ color={isDisabled ? 'disabled' : 'secondary'}
/>
- )}
- {label}
- {statusText && (
- <span {...stylex.props(styles.optionalRequired)}>
- {' '}
- ∙ {statusText}
- </span>
- )}
- {labelTooltip && (
- <XDSTooltip content={labelTooltip} placement="above">
- <XDSIcon
- icon="info"
- size="sm"
- color={isDisabled ? 'disabled' : 'secondary'}
- />
- </XDSTooltip>
- )}
- </label>
- );
- },
-);
+ </XDSTooltip>
+ )}
+ </label>
+ );
+}
XDSFieldLabel.displayName = 'XDSFieldLabel';
diff --git a/packages/core/src/FormLayout/XDSFormLayout.tsx b/packages/core/src/FormLayout/XDSFormLayout.tsx
index 3e9e831435..12eb4973c2 100644
--- a/packages/core/src/FormLayout/XDSFormLayout.tsx
+++ b/packages/core/src/FormLayout/XDSFormLayout.tsx
@@ -1,6 +1,6 @@
/**
* @file XDSFormLayout.tsx
- * @input Uses React forwardRef, XDSFormLayoutContext, StyleX
+ * @input Uses React, XDSFormLayoutContext, StyleX
* @output Exports XDSFormLayout component and XDSFormLayoutProps
* @position Core implementation; consumed by index.ts, tested by XDSFormLayout.test.tsx
*
@@ -13,7 +13,7 @@
'use client';
-import {forwardRef, useMemo, type ReactNode} from 'react';
+import {useMemo, type ReactNode} from 'react';
import type {XDSBaseProps} from '../XDSBaseProps';
import * as stylex from '@stylexjs/stylex';
import type {StyleXStyles} from '@stylexjs/stylex';
@@ -62,6 +62,8 @@ const styles = stylex.create({
// =============================================================================
export interface XDSFormLayoutProps extends XDSBaseProps<HTMLDivElement> {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLDivElement>;
/**
* Form fields to arrange. Accepts XDS inputs (XDSTextInput, XDSSelector, etc.)
* and XDSField-wrapped custom controls.
@@ -131,34 +133,37 @@ export interface XDSFormLayoutProps extends XDSBaseProps<HTMLDivElement> {
* </XDSFormLayout>
* ```
*/
-export const XDSFormLayout = forwardRef<HTMLDivElement, XDSFormLayoutProps>(
- function XDSFormLayout(
- {children, direction = 'vertical', xstyle, className, style, ...props},
- ref,
- ) {
- const contextValue = useMemo(() => ({direction}), [direction]);
+export function XDSFormLayout({
+ children,
+ direction = 'vertical',
+ xstyle,
+ className,
+ style,
+ ref,
+ ...props
+}: XDSFormLayoutProps) {
+ const contextValue = useMemo(() => ({direction}), [direction]);
- return (
- <XDSFormLayoutContext.Provider value={contextValue}>
- <div
- ref={ref}
- {...mergeProps(
- xdsClassName('form-layout', {direction}),
- stylex.props(
- styles.base,
- direction === 'horizontal' && styles.horizontal,
- direction === 'horizontal-labels' && styles.horizontalLabels,
- xstyle,
- ),
- className,
- style,
- )}
- {...props}>
- {children}
- </div>
- </XDSFormLayoutContext.Provider>
- );
- },
-);
+ return (
+ <XDSFormLayoutContext.Provider value={contextValue}>
+ <div
+ ref={ref}
+ {...mergeProps(
+ xdsClassName('form-layout', {direction}),
+ stylex.props(
+ styles.base,
+ direction === 'horizontal' && styles.horizontal,
+ direction === 'horizontal-labels' && styles.horizontalLabels,
+ xstyle,
+ ),
+ className,
+ style,
+ )}
+ {...props}>
+ {children}
+ </div>
+ </XDSFormLayoutContext.Provider>
+ );
+}
XDSFormLayout.displayName = 'XDSFormLayout';
diff --git a/packages/core/src/Grid/XDSGrid.tsx b/packages/core/src/Grid/XDSGrid.tsx
index d23289ac14..f05aa4f8b3 100644
--- a/packages/core/src/Grid/XDSGrid.tsx
+++ b/packages/core/src/Grid/XDSGrid.tsx
@@ -1,6 +1,6 @@
/**
* @file XDSGrid.tsx
- * @input Uses React forwardRef, stylex, spacing tokens
+ * @input Uses React, stylex, spacing tokens
* @output Exports XDSGrid component and XDSGridProps
* @position Grid component; provides CSS Grid-based layout
*
@@ -12,7 +12,7 @@
'use client';
-import {forwardRef, type ReactNode} from 'react';
+import {type ReactNode} from 'react';
import type {XDSBaseProps} from '../XDSBaseProps';
import * as stylex from '@stylexjs/stylex';
import type {StyleXStyles} from '@stylexjs/stylex';
@@ -28,6 +28,8 @@ import {xdsClassName, mergeProps} from '../utils';
export type GridAlignment = 'start' | 'center' | 'end' | 'stretch';
export interface XDSGridProps extends XDSBaseProps<HTMLDivElement> {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLElement>;
/**
* Maximum number of columns.
* - When only columns is set: creates fixed equal-width columns
@@ -340,25 +342,23 @@ function calculateMaxWidth(
* </XDSGrid>
* ```
*/
-export const XDSGrid = forwardRef<HTMLElement, XDSGridProps>(function XDSGrid(
- {
- columns,
- minChildWidth = 0,
- width,
- height,
- gap,
- rowGap,
- columnGap,
- align,
- justify,
- xstyle,
- className,
- style,
- children,
- ...props
- },
+export function XDSGrid({
+ columns,
+ minChildWidth = 0,
+ width,
+ height,
+ gap,
+ rowGap,
+ columnGap,
+ align,
+ justify,
+ xstyle,
+ className,
+ style,
+ children,
ref,
-) {
+ ...props
+}: XDSGridProps) {
// Determine grid-template-columns value
let gridTemplateColumns: string;
let calculatedMaxWidth: number | undefined;
@@ -417,6 +417,6 @@ export const XDSGrid = forwardRef<HTMLElement, XDSGridProps>(function XDSGrid(
{children}
</div>
);
-});
+}
XDSGrid.displayName = 'XDSGrid';
diff --git a/packages/core/src/Grid/XDSGridSpan.tsx b/packages/core/src/Grid/XDSGridSpan.tsx
index 9648dd97c5..520215fd26 100644
--- a/packages/core/src/Grid/XDSGridSpan.tsx
+++ b/packages/core/src/Grid/XDSGridSpan.tsx
@@ -1,6 +1,6 @@
/**
* @file XDSGridSpan.tsx
- * @input Uses React forwardRef, stylex
+ * @input Uses React, stylex
* @output Exports XDSGridSpan component and XDSGridSpanProps
* @position Grid span component; controls grid item span
*
@@ -10,13 +10,15 @@
* - /apps/storybook/stories/Grid.stories.tsx
*/
-import {forwardRef, type ReactNode} from 'react';
+import {type ReactNode} from 'react';
import type {XDSBaseProps} from '../XDSBaseProps';
import * as stylex from '@stylexjs/stylex';
import type {StyleXStyles} from '@stylexjs/stylex';
import {xdsClassName, mergeProps} from '../utils';
export interface XDSGridSpanProps extends XDSBaseProps<HTMLDivElement> {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLElement>;
/**
* Number of columns to span, or 'full' to span all columns.
* - Number: `grid-column: span N`
@@ -82,35 +84,39 @@ const baseStyles = stylex.create({
* </XDSGrid>
* ```
*/
-export const XDSGridSpan = forwardRef<HTMLElement, XDSGridSpanProps>(
- function XDSGridSpan(
- {columns, rows, xstyle, className, style, children, ...props},
- ref,
- ) {
- // Build inline style for grid spanning
- const inlineStyle: React.CSSProperties = {
- ...(columns != null && {
- gridColumn: columns === 'full' ? '1 / -1' : `span ${columns}`,
- }),
- ...(rows != null && {
- gridRow: `span ${rows}`,
- }),
- };
+export function XDSGridSpan({
+ columns,
+ rows,
+ xstyle,
+ className,
+ style,
+ children,
+ ref,
+ ...props
+}: XDSGridSpanProps) {
+ // Build inline style for grid spanning
+ const inlineStyle: React.CSSProperties = {
+ ...(columns != null && {
+ gridColumn: columns === 'full' ? '1 / -1' : `span ${columns}`,
+ }),
+ ...(rows != null && {
+ gridRow: `span ${rows}`,
+ }),
+ };
- return (
- <div
- ref={ref as React.Ref<HTMLDivElement>}
- {...mergeProps(
- xdsClassName('grid-span'),
- stylex.props(baseStyles.span, xstyle),
- className,
- {...style, ...inlineStyle},
- )}
- {...props}>
- {children}
- </div>
- );
- },
-);
+ return (
+ <div
+ ref={ref as React.Ref<HTMLDivElement>}
+ {...mergeProps(
+ xdsClassName('grid-span'),
+ stylex.props(baseStyles.span, xstyle),
+ className,
+ {...style, ...inlineStyle},
+ )}
+ {...props}>
+ {children}
+ </div>
+ );
+}
XDSGridSpan.displayName = 'XDSGridSpan';
diff --git a/packages/core/src/Icon/XDSIcon.tsx b/packages/core/src/Icon/XDSIcon.tsx
index 31dc8447e5..a74c3fd4d8 100644
--- a/packages/core/src/Icon/XDSIcon.tsx
+++ b/packages/core/src/Icon/XDSIcon.tsx
@@ -1,12 +1,12 @@
/**
* @file XDSIcon.tsx
- * @input Uses React forwardRef/SVGProps, icon components or semantic icon names
+ * @input Uses ReactSVGProps, icon components or semantic icon names
* @output Exports XDSIcon component, XDSIconProps, XDSIconColor, XDSIconSize, XDSIconType types
* @position Core implementation; consumed by index.ts, tested by XDSIcon.test.tsx
*
* Supports two modes:
* - Component mode: Pass an SVG icon component (e.g. from @heroicons/react) — rendered
- * directly with forwardRef and spread SVG props.
+ * directly with and spread SVG props.
* - String mode: Pass a semantic name (e.g. 'close', 'chevronDown') — resolved from the
* theme's icon registry (or built-in fallback SVGs) and wrapped in a styled span.
*
@@ -19,7 +19,7 @@
'use client';
-import {forwardRef, type ComponentType, type SVGProps} from 'react';
+import {type ComponentType, type SVGProps} from 'react';
import * as stylex from '@stylexjs/stylex';
import {colorVars} from '../theme/tokens.stylex';
import {getIcon} from './globalIconRegistry';
@@ -144,6 +144,8 @@ export interface XDSIconProps extends Omit<
SVGProps<SVGSVGElement>,
'ref' | 'color'
> {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<SVGSVGElement>;
/**
* Icon to render. Can be:
* - A semantic name string (e.g. 'close', 'chevronDown') — resolved from theme or built-in fallback
@@ -178,28 +180,32 @@ export interface XDSIconProps extends Omit<
* <XDSIcon icon="close" size="md" color="primary" />
* ```
*/
-export const XDSIcon = forwardRef<SVGSVGElement, XDSIconProps>(
- ({icon, color = 'primary', size = 'md', ...props}, ref) => {
- // String mode: resolve from icon registry, wrap in styled span
- if (typeof icon === 'string') {
- return <IconFromRegistry name={icon} color={color} size={size} />;
- }
-
- // Component mode: render SVG component directly with ref forwarding
- const IconComponent = icon;
- return (
- <IconComponent
- ref={ref}
- aria-hidden="true"
- {...mergeProps(
- xdsClassName('icon', {size, color}),
- stylex.props(styles.root, colorStyles[color], sizeStyles[size]),
- )}
- {...props}
- />
- );
- },
-);
+export function XDSIcon({
+ icon,
+ color = 'primary',
+ size = 'md',
+ ref,
+ ...props
+}: XDSIconProps) {
+ // String mode: resolve from icon registry, wrap in styled span
+ if (typeof icon === 'string') {
+ return <IconFromRegistry name={icon} color={color} size={size} />;
+ }
+
+ // Component mode: render SVG component directly with ref forwarding
+ const IconComponent = icon;
+ return (
+ <IconComponent
+ ref={ref}
+ aria-hidden="true"
+ {...mergeProps(
+ xdsClassName('icon', {size, color}),
+ stylex.props(styles.root, colorStyles[color], sizeStyles[size]),
+ )}
+ {...props}
+ />
+ );
+}
XDSIcon.displayName = 'XDSIcon';
diff --git a/packages/core/src/Layout/XDSLayoutContent.tsx b/packages/core/src/Layout/XDSLayoutContent.tsx
index 8e249e33cb..79f1e792bf 100644
--- a/packages/core/src/Layout/XDSLayoutContent.tsx
+++ b/packages/core/src/Layout/XDSLayoutContent.tsx
@@ -1,6 +1,6 @@
/**
* @file XDSLayoutContent.tsx
- * @input Uses React forwardRef, StyleX, XDSLayoutSlotsContext
+ * @input Uses React, StyleX, XDSLayoutSlotsContext
* @output Exports XDSLayoutContent component and XDSLayoutContentProps
* @position Scrollable main content area for XDSLayout. Wraps the primary body content
* with automatic scroll containment and context-aware padding.
@@ -14,7 +14,7 @@
import type {AriaRole, ReactNode} from 'react';
import type {XDSBaseProps} from '../XDSBaseProps';
-import {forwardRef, useContext} from 'react';
+import {useContext} from 'react';
import * as stylex from '@stylexjs/stylex';
import {spacingVars} from '../theme/tokens.stylex';
import {XDSLayoutSlotsContext} from './XDSLayoutSlotsContext';
@@ -61,6 +61,8 @@ const styles = stylex.create({
});
export interface XDSLayoutContentProps extends XDSBaseProps<HTMLDivElement> {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLElement>;
/**
* Content to render inside the content area.
*/
@@ -129,51 +131,47 @@ export interface XDSLayoutContentProps extends XDSBaseProps<HTMLDivElement> {
* </XDSLayoutContainer>
* ```
*/
-export const XDSLayoutContent = forwardRef<HTMLElement, XDSLayoutContentProps>(
- function XDSLayoutContent(
- {
- children,
- isFullBleed = false,
- isScrollable = true,
- label,
- role,
- xstyle,
- className,
- style,
- ...props
- },
- ref,
- ) {
- const {hasHeader, hasFooter, hasStart, hasEnd} = useContext(
- XDSLayoutSlotsContext,
- );
+export function XDSLayoutContent({
+ children,
+ isFullBleed = false,
+ isScrollable = true,
+ label,
+ role,
+ xstyle,
+ className,
+ style,
+ ref,
+ ...props
+}: XDSLayoutContentProps) {
+ const {hasHeader, hasFooter, hasStart, hasEnd} = useContext(
+ XDSLayoutSlotsContext,
+ );
- return (
- <div
- ref={ref as React.Ref<HTMLDivElement>}
- role={role}
- aria-label={label}
- {...mergeProps(
- xdsClassName('layout-content'),
- stylex.props(
- styles.content,
- // Outer padding on container edges (unless content is full bleed)
- !hasStart && !isFullBleed && styles.noStart,
- !hasEnd && !isFullBleed && styles.noEnd,
- !hasHeader && !isFullBleed && styles.noHeader,
- !hasFooter && !isFullBleed && styles.noFooter,
- isScrollable && styles.scrollable,
- isFullBleed && styles.fullBleed,
- xstyle,
- ),
- className,
- style,
- )}
- {...props}>
- {children}
- </div>
- );
- },
-);
+ return (
+ <div
+ ref={ref as React.Ref<HTMLDivElement>}
+ role={role}
+ aria-label={label}
+ {...mergeProps(
+ xdsClassName('layout-content'),
+ stylex.props(
+ styles.content,
+ // Outer padding on container edges (unless content is full bleed)
+ !hasStart && !isFullBleed && styles.noStart,
+ !hasEnd && !isFullBleed && styles.noEnd,
+ !hasHeader && !isFullBleed && styles.noHeader,
+ !hasFooter && !isFullBleed && styles.noFooter,
+ isScrollable && styles.scrollable,
+ isFullBleed && styles.fullBleed,
+ xstyle,
+ ),
+ className,
+ style,
+ )}
+ {...props}>
+ {children}
+ </div>
+ );
+}
XDSLayoutContent.displayName = 'XDSLayoutContent';
diff --git a/packages/core/src/Layout/XDSLayoutFooter.tsx b/packages/core/src/Layout/XDSLayoutFooter.tsx
index 74f0da5f6a..b8b2fa98e4 100644
--- a/packages/core/src/Layout/XDSLayoutFooter.tsx
+++ b/packages/core/src/Layout/XDSLayoutFooter.tsx
@@ -1,6 +1,6 @@
/**
* @file XDSLayoutFooter.tsx
- * @input Uses React forwardRef, StyleX
+ * @input Uses React, StyleX
* @output Exports XDSLayoutFooter component and XDSLayoutFooterProps
* @position Bottom bar / footer area for XDSLayout. Use for action bars,
* pagination, status bars, or any fixed-height content at the bottom of a layout.
@@ -12,7 +12,6 @@
import type {AriaRole, ReactNode} from 'react';
import type {XDSBaseProps} from '../XDSBaseProps';
-import {forwardRef} from 'react';
import * as stylex from '@stylexjs/stylex';
import {colorVars, spacingVars} from '../theme/tokens.stylex';
import {xdsClassName, mergeProps} from '../utils';
@@ -52,6 +51,8 @@ const dynamicStyles = stylex.create({
});
export interface XDSLayoutFooterProps extends XDSBaseProps<HTMLDivElement> {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLElement>;
/**
* Content to render inside the footer.
*/
@@ -106,48 +107,44 @@ export interface XDSLayoutFooterProps extends XDSBaseProps<HTMLDivElement> {
* </XDSLayoutContainer>
* ```
*/
-export const XDSLayoutFooter = forwardRef<HTMLElement, XDSLayoutFooterProps>(
- function XDSLayoutFooter(
- {
- children,
- hasDivider = false,
- height,
- isFullBleed = false,
- label,
- role,
- xstyle,
- className,
- style,
- ...props
- },
- ref,
- ) {
- // When no divider, collapse spacing for seamless visual flow
- const shouldCollapseSpacing = !hasDivider && !isFullBleed;
+export function XDSLayoutFooter({
+ children,
+ hasDivider = false,
+ height,
+ isFullBleed = false,
+ label,
+ role,
+ xstyle,
+ className,
+ style,
+ ref,
+ ...props
+}: XDSLayoutFooterProps) {
+ // When no divider, collapse spacing for seamless visual flow
+ const shouldCollapseSpacing = !hasDivider && !isFullBleed;
- return (
- <div
- ref={ref as React.Ref<HTMLDivElement>}
- role={role}
- aria-label={label}
- {...mergeProps(
- xdsClassName('layout-footer'),
- stylex.props(
- styles.footer,
- dynamicStyles.sizing(height ?? null),
- isFullBleed && styles.fullBleed,
- hasDivider && styles.divider,
- shouldCollapseSpacing && styles.collapseTop,
- xstyle,
- ),
- className,
- style,
- )}
- {...props}>
- {children}
- </div>
- );
- },
-);
+ return (
+ <div
+ ref={ref as React.Ref<HTMLDivElement>}
+ role={role}
+ aria-label={label}
+ {...mergeProps(
+ xdsClassName('layout-footer'),
+ stylex.props(
+ styles.footer,
+ dynamicStyles.sizing(height ?? null),
+ isFullBleed && styles.fullBleed,
+ hasDivider && styles.divider,
+ shouldCollapseSpacing && styles.collapseTop,
+ xstyle,
+ ),
+ className,
+ style,
+ )}
+ {...props}>
+ {children}
+ </div>
+ );
+}
XDSLayoutFooter.displayName = 'XDSLayoutFooter';
diff --git a/packages/core/src/Layout/XDSLayoutHeader.tsx b/packages/core/src/Layout/XDSLayoutHeader.tsx
index 434b212ff6..2537216037 100644
--- a/packages/core/src/Layout/XDSLayoutHeader.tsx
+++ b/packages/core/src/Layout/XDSLayoutHeader.tsx
@@ -1,6 +1,6 @@
/**
* @file XDSLayoutHeader.tsx
- * @input Uses React forwardRef, StyleX
+ * @input Uses React, StyleX
* @output Exports XDSLayoutHeader component and XDSLayoutHeaderProps
* @position Top bar / header area for XDSLayout. Use for page titles, app bars,
* toolbar areas, or any fixed-height content at the top of a layout.
@@ -12,7 +12,6 @@
import type {AriaRole, ReactNode} from 'react';
import type {XDSBaseProps} from '../XDSBaseProps';
-import {forwardRef} from 'react';
import * as stylex from '@stylexjs/stylex';
import {colorVars, spacingVars} from '../theme/tokens.stylex';
import {xdsClassName, mergeProps} from '../utils';
@@ -52,6 +51,8 @@ const dynamicStyles = stylex.create({
});
export interface XDSLayoutHeaderProps extends XDSBaseProps<HTMLDivElement> {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLElement>;
/**
* Content to render inside the header.
*/
@@ -106,48 +107,44 @@ export interface XDSLayoutHeaderProps extends XDSBaseProps<HTMLDivElement> {
* </XDSLayoutContainer>
* ```
*/
-export const XDSLayoutHeader = forwardRef<HTMLElement, XDSLayoutHeaderProps>(
- function XDSLayoutHeader(
- {
- children,
- hasDivider = false,
- height,
- isFullBleed = false,
- label,
- role,
- xstyle,
- className,
- style,
- ...props
- },
- ref,
- ) {
- // When no divider, collapse spacing for seamless visual flow
- const shouldCollapseSpacing = !hasDivider && !isFullBleed;
+export function XDSLayoutHeader({
+ children,
+ hasDivider = false,
+ height,
+ isFullBleed = false,
+ label,
+ role,
+ xstyle,
+ className,
+ style,
+ ref,
+ ...props
+}: XDSLayoutHeaderProps) {
+ // When no divider, collapse spacing for seamless visual flow
+ const shouldCollapseSpacing = !hasDivider && !isFullBleed;
- return (
- <div
- ref={ref as React.Ref<HTMLDivElement>}
- role={role}
- aria-label={label}
- {...mergeProps(
- xdsClassName('layout-header'),
- stylex.props(
- styles.header,
- dynamicStyles.sizing(height ?? null),
- isFullBleed && styles.fullBleed,
- hasDivider && styles.divider,
- shouldCollapseSpacing && styles.collapseBottom,
- xstyle,
- ),
- className,
- style,
- )}
- {...props}>
- {children}
- </div>
- );
- },
-);
+ return (
+ <div
+ ref={ref as React.Ref<HTMLDivElement>}
+ role={role}
+ aria-label={label}
+ {...mergeProps(
+ xdsClassName('layout-header'),
+ stylex.props(
+ styles.header,
+ dynamicStyles.sizing(height ?? null),
+ isFullBleed && styles.fullBleed,
+ hasDivider && styles.divider,
+ shouldCollapseSpacing && styles.collapseBottom,
+ xstyle,
+ ),
+ className,
+ style,
+ )}
+ {...props}>
+ {children}
+ </div>
+ );
+}
XDSLayoutHeader.displayName = 'XDSLayoutHeader';
diff --git a/packages/core/src/Layout/XDSLayoutPanel.tsx b/packages/core/src/Layout/XDSLayoutPanel.tsx
index 23cf36b08c..111f4e342e 100644
--- a/packages/core/src/Layout/XDSLayoutPanel.tsx
+++ b/packages/core/src/Layout/XDSLayoutPanel.tsx
@@ -1,6 +1,6 @@
/**
* @file XDSLayoutPanel.tsx
- * @input Uses React forwardRef, StyleX, XDSLayoutAreaContext, XDSLayoutSlotsContext
+ * @input Uses React, StyleX, XDSLayoutAreaContext, XDSLayoutSlotsContext
* @output Exports XDSLayoutPanel component and XDSLayoutPanelProps
* @position Sidebar panel for XDSLayout start/end slots. Use for navigation panels,
* settings sidebars, detail panels, or any fixed-width side content.
@@ -14,7 +14,7 @@
import type {AriaRole, ReactNode} from 'react';
import type {XDSBaseProps} from '../XDSBaseProps';
-import {forwardRef, useContext} from 'react';
+import {useContext} from 'react';
import * as stylex from '@stylexjs/stylex';
import {colorVars, spacingVars} from '../theme/tokens.stylex';
import {XDSLayoutAreaContext} from './XDSLayoutAreaContext';
@@ -88,6 +88,8 @@ const dynamicStyles = stylex.create({
});
export interface XDSLayoutPanelProps extends XDSBaseProps<HTMLDivElement> {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLElement>;
/**
* Content to render inside the panel.
*/
@@ -163,76 +165,72 @@ export interface XDSLayoutPanelProps extends XDSBaseProps<HTMLDivElement> {
* </XDSLayoutContainer>
* ```
*/
-export const XDSLayoutPanel = forwardRef<HTMLElement, XDSLayoutPanelProps>(
- function XDSLayoutPanel(
- {
- children,
- hasDivider = false,
- isFullBleed = false,
- isScrollable = true,
- label,
- role,
- width,
- xstyle,
- className,
- style,
- ...props
- },
- ref,
- ) {
- const area = useContext(XDSLayoutAreaContext);
- const {hasHeader, hasFooter} = useContext(XDSLayoutSlotsContext);
-
- // Determine panel position
- const isStartPanel = area === 'start';
- const isEndPanel = area === 'end';
-
- // When no divider, collapse spacing for seamless visual flow
- const shouldCollapseSpacing = !hasDivider && !isFullBleed;
-
- // Select divider style based on position
- const dividerStyle = isStartPanel
- ? styles.dividerEnd
- : isEndPanel
- ? styles.dividerStart
- : null;
-
- // Select collapse style based on position (collapse the side where divider would be)
- const collapseStyle = isStartPanel
- ? styles.collapseEnd
- : isEndPanel
- ? styles.collapseStart
- : null;
-
- return (
- <div
- ref={ref as React.Ref<HTMLDivElement>}
- role={role}
- aria-label={label}
- {...mergeProps(
- xdsClassName('layout-panel'),
- stylex.props(
- styles.panel,
- dynamicStyles.sizing(width ?? null),
- // Outer padding on container edges (unless component is full bleed)
- isStartPanel && !isFullBleed && styles.startPanel,
- isEndPanel && !isFullBleed && styles.endPanel,
- !hasHeader && !isFullBleed && styles.noHeader,
- !hasFooter && !isFullBleed && styles.noFooter,
- isScrollable && styles.scrollable,
- isFullBleed && styles.fullBleed,
- hasDivider && dividerStyle,
- shouldCollapseSpacing && collapseStyle,
- xstyle,
- ),
- className,
- style,
- )}
- {...props}>
- {children}
- </div>
- );
- },
-);
+export function XDSLayoutPanel({
+ children,
+ hasDivider = false,
+ isFullBleed = false,
+ isScrollable = true,
+ label,
+ role,
+ width,
+ xstyle,
+ className,
+ style,
+ ref,
+ ...props
+}: XDSLayoutPanelProps) {
+ const area = useContext(XDSLayoutAreaContext);
+ const {hasHeader, hasFooter} = useContext(XDSLayoutSlotsContext);
+
+ // Determine panel position
+ const isStartPanel = area === 'start';
+ const isEndPanel = area === 'end';
+
+ // When no divider, collapse spacing for seamless visual flow
+ const shouldCollapseSpacing = !hasDivider && !isFullBleed;
+
+ // Select divider style based on position
+ const dividerStyle = isStartPanel
+ ? styles.dividerEnd
+ : isEndPanel
+ ? styles.dividerStart
+ : null;
+
+ // Select collapse style based on position (collapse the side where divider would be)
+ const collapseStyle = isStartPanel
+ ? styles.collapseEnd
+ : isEndPanel
+ ? styles.collapseStart
+ : null;
+
+ return (
+ <div
+ ref={ref as React.Ref<HTMLDivElement>}
+ role={role}
+ aria-label={label}
+ {...mergeProps(
+ xdsClassName('layout-panel'),
+ stylex.props(
+ styles.panel,
+ dynamicStyles.sizing(width ?? null),
+ // Outer padding on container edges (unless component is full bleed)
+ isStartPanel && !isFullBleed && styles.startPanel,
+ isEndPanel && !isFullBleed && styles.endPanel,
+ !hasHeader && !isFullBleed && styles.noHeader,
+ !hasFooter && !isFullBleed && styles.noFooter,
+ isScrollable && styles.scrollable,
+ isFullBleed && styles.fullBleed,
+ hasDivider && dividerStyle,
+ shouldCollapseSpacing && collapseStyle,
+ xstyle,
+ ),
+ className,
+ style,
+ )}
+ {...props}>
+ {children}
+ </div>
+ );
+}
XDSLayoutPanel.displayName = 'XDSLayoutPanel';
diff --git a/packages/core/src/Link/XDSLink.tsx b/packages/core/src/Link/XDSLink.tsx
index ef70678785..23badaf1a5 100644
--- a/packages/core/src/Link/XDSLink.tsx
+++ b/packages/core/src/Link/XDSLink.tsx
@@ -1,6 +1,6 @@
/**
* @file XDSLink.tsx
- * @input Uses React forwardRef, AnchorHTMLAttributes, ReactNode
+ * @input Uses React, AnchorHTMLAttributes, ReactNode
* @output Exports XDSLink component, XDSLinkProps
* @position Core implementation; consumed by index.ts, tested by XDSLink.test.tsx
*
@@ -13,7 +13,7 @@
'use client';
-import {forwardRef, type MouseEventHandler, type ReactNode} from 'react';
+import {type MouseEventHandler, type ReactNode} from 'react';
import type {XDSBaseProps} from '../XDSBaseProps';
import * as stylex from '@stylexjs/stylex';
@@ -108,6 +108,8 @@ const linkColorStyles = stylex.create({
});
export interface XDSLinkProps extends XDSBaseProps<HTMLAnchorElement> {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLAnchorElement>;
/**
* Custom component to render instead of `<a>`.
* Overrides the provider-level default set by XDSLinkProvider.
@@ -221,93 +223,89 @@ export interface XDSLinkProps extends XDSBaseProps<HTMLAnchorElement> {
* <XDSLink label="Privacy Policy" href="/privacy" hasUnderline>Privacy Policy</XDSLink>
* ```
*/
-export const XDSLink = forwardRef<HTMLAnchorElement, XDSLinkProps>(
- (
- {
- as,
- label,
- href,
- hasUnderline = false,
- isDisabled = false,
- isExternalLink = false,
- target,
- onClick,
- tooltip,
- isStandalone = false,
- type = 'body',
- size,
- weight,
- color = 'active',
- display = 'inline',
- maxLines = 0,
- children,
- rel,
- xstyle,
- className,
- style,
- ...props
- },
- ref,
- ) => {
- const LinkComponent = useXDSLinkComponent(as);
- // Determine target and rel based on isExternalLink
- const computedTarget = isExternalLink ? '_blank' : target;
- const computedRel = isExternalLink
- ? rel
- ? `${rel} noopener noreferrer`
- : 'noopener noreferrer'
- : rel;
+export function XDSLink({
+ as,
+ label,
+ href,
+ hasUnderline = false,
+ isDisabled = false,
+ isExternalLink = false,
+ target,
+ onClick,
+ tooltip,
+ isStandalone = false,
+ type = 'body',
+ size,
+ weight,
+ color = 'active',
+ display = 'inline',
+ maxLines = 0,
+ children,
+ rel,
+ xstyle,
+ className,
+ style,
+ ref,
+ ...props
+}: XDSLinkProps) {
+ const LinkComponent = useXDSLinkComponent(as);
+ // Determine target and rel based on isExternalLink
+ const computedTarget = isExternalLink ? '_blank' : target;
+ const computedRel = isExternalLink
+ ? rel
+ ? `${rel} noopener noreferrer`
+ : 'noopener noreferrer'
+ : rel;
- const linkElement = (
- <LinkComponent
- ref={ref}
- href={href}
- target={computedTarget}
- rel={computedRel}
- onClick={onClick}
- aria-label={label}
- aria-disabled={isDisabled || undefined}
- tabIndex={isDisabled ? -1 : undefined}
- {...mergeProps(
- xdsClassName('link', {color}),
- stylex.props(
- styles.base,
- linkColorStyles[color],
- hasUnderline && styles.hasUnderline,
- isStandalone && styles.standalone,
- isDisabled && styles.disabled,
- xstyle,
- ),
- className,
- style,
- )}
- {...props}>
- <XDSText
- type={type}
- size={size}
- weight={weight}
- color={color}
- display={display}
- maxLines={maxLines}>
- {children}
- </XDSText>
- {isExternalLink && (
- <XDSIcon icon="externalLink" size="xsm" color="inherit" />
- )}
- </LinkComponent>
- );
+ const linkElement = (
+ <LinkComponent
+ ref={ref}
+ href={href}
+ target={computedTarget}
+ rel={computedRel}
+ onClick={onClick}
+ aria-label={label}
+ aria-disabled={isDisabled || undefined}
+ tabIndex={isDisabled ? -1 : undefined}
+ {...mergeProps(
+ xdsClassName('link', {color}),
+ stylex.props(
+ styles.base,
+ linkColorStyles[color],
+ hasUnderline && styles.hasUnderline,
+ isStandalone && styles.standalone,
+ isDisabled && styles.disabled,
+ xstyle,
+ ),
+ className,
+ style,
+ )}
+ {...props}>
+ <XDSText
+ type={type}
+ size={size}
+ weight={weight}
+ color={color}
+ display={display}
+ maxLines={maxLines}>
+ {children}
+ </XDSText>
+ {isExternalLink && (
+ <XDSIcon icon="externalLink" size="xsm" color="inherit" />
+ )}
+ </LinkComponent>
+ );
- // Wrap with tooltip if provided
- if (tooltip) {
- return (
- <XDSTooltip content={tooltip} placement="above">
- {linkElement}
- </XDSTooltip>
- );
- }
+ // Wrap with tooltip if provided
+ if (tooltip) {
+ return (
+ <XDSTooltip content={tooltip} placement="above">
+ {linkElement}
+ </XDSTooltip>
+ );
+ }
- return linkElement;
- },
-);
+ return linkElement;
+}
XDSLink.displayName = 'XDSLink';
diff --git a/packages/core/src/List/XDSList.tsx b/packages/core/src/List/XDSList.tsx
index 245bd1adf6..19da35d42d 100644
--- a/packages/core/src/List/XDSList.tsx
+++ b/packages/core/src/List/XDSList.tsx
@@ -1,6 +1,6 @@
/**
* @file XDSList.tsx
- * @input Uses React forwardRef, ReactNode, StyleXStyles, theme tokens, XDSListContext
+ * @input Uses React, ReactNode, StyleXStyles, theme tokens, XDSListContext
* @output Exports XDSList component, XDSListProps, XDSListDensity, XDSListStyle types
* @position Core implementation; consumed by index.ts, tested by XDSList.test.tsx
*
@@ -13,7 +13,7 @@
'use client';
-import {forwardRef, useId, useMemo, Children, type ReactNode} from 'react';
+import {useId, useMemo, Children, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {StyleXStyles} from '@stylexjs/stylex';
import {colorVars, spacingVars} from '../theme/tokens.stylex';
@@ -30,6 +30,8 @@ export type XDSListStyle = 'none' | 'disc' | 'decimal' | 'circle';
export {type XDSListDensity} from './XDSListContext';
export interface XDSListProps {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLUListElement | HTMLOListElement>;
/**
* List items. Should be XDSListItem components.
*/
@@ -151,82 +153,75 @@ const listStyleTypes = stylex.create({
* </XDSList>
* ```
*/
-export const XDSList = forwardRef<
- HTMLUListElement | HTMLOListElement,
- XDSListProps
->(
- (
- {
- children,
- density = 'balanced',
- hasDividers = false,
- header,
- listStyle = 'none',
- xstyle,
- className,
- style,
- 'data-testid': testId,
- },
- ref,
- ) => {
- const headerId = useId();
- const isOrdered = listStyle === 'decimal';
- const hasMarkers = listStyle !== 'none';
- const Tag = isOrdered ? 'ol' : 'ul';
-
- const contextValue = useMemo(
- () => ({density, hasDividers, hasMarkers}),
- [density, hasDividers, hasMarkers],
- );
-
- // Interleave dividers between children when hasDividers is true
- let renderedChildren = children;
- if (hasDividers) {
- const childArray = Children.toArray(children);
- const withDividers: ReactNode[] = [];
- childArray.forEach((child, i) => {
- withDividers.push(child);
- if (i < childArray.length - 1) {
- withDividers.push(
- <hr
- key={`divider-${i}`}
- aria-hidden="true"
- {...stylex.props(styles.divider)}
- />,
- );
- }
- });
- renderedChildren = withDividers;
- }
-
- return (
- <XDSListContext.Provider value={contextValue}>
- {header != null && (
- <div id={headerId} {...stylex.props(styles.header)}>
- {header}
- </div>
- )}
- <Tag
- ref={ref as React.Ref<HTMLUListElement & HTMLOListElement>}
- data-testid={testId}
- aria-labelledby={header != null ? headerId : undefined}
- {...(listStyle === 'none' && !isOrdered ? {role: 'list'} : {})}
- {...mergeProps(
- xdsClassName('list', {density, listStyle}),
- stylex.props(
- styles.list,
- listStyleTypes[listStyle],
- hasMarkers && styles.listWithMarkers,
- xstyle,
- ),
- className,
- style,
- )}>
- {renderedChildren}
- </Tag>
- </XDSListContext.Provider>
- );
- },
-);
+export function XDSList({
+ children,
+ density = 'balanced',
+ hasDividers = false,
+ header,
+ listStyle = 'none',
+ xstyle,
+ className,
+ style,
+ 'data-testid': testId,
+ ref,
+}: XDSListProps) {
+ const headerId = useId();
+ const isOrdered = listStyle === 'decimal';
+ const hasMarkers = listStyle !== 'none';
+ const Tag = isOrdered ? 'ol' : 'ul';
+
+ const contextValue = useMemo(
+ () => ({density, hasDividers, hasMarkers}),
+ [density, hasDividers, hasMarkers],
+ );
+
+ // Interleave dividers between children when hasDividers is true
+ let renderedChildren = children;
+ if (hasDividers) {
+ const childArray = Children.toArray(children);
+ const withDividers: ReactNode[] = [];
+ childArray.forEach((child, i) => {
+ withDividers.push(child);
+ if (i < childArray.length - 1) {
+ withDividers.push(
+ <hr
+ key={`divider-${i}`}
+ aria-hidden="true"
+ {...stylex.props(styles.divider)}
+ />,
+ );
+ }
+ });
+ renderedChildren = withDividers;
+ }
+
+ return (
+ <XDSListContext.Provider value={contextValue}>
+ {header != null && (
+ <div id={headerId} {...stylex.props(styles.header)}>
+ {header}
+ </div>
+ )}
+ <Tag
+ ref={ref as React.Ref<HTMLUListElement & HTMLOListElement>}
+ data-testid={testId}
+ aria-labelledby={header != null ? headerId : undefined}
+ {...(listStyle === 'none' && !isOrdered ? {role: 'list'} : {})}
+ {...mergeProps(
+ xdsClassName('list', {density, listStyle}),
+ stylex.props(
+ styles.list,
+ listStyleTypes[listStyle],
+ hasMarkers && styles.listWithMarkers,
+ xstyle,
+ ),
+ className,
+ style,
+ )}>
+ {renderedChildren}
+ </Tag>
+ </XDSListContext.Provider>
+ );
+}
XDSList.displayName = 'XDSList';
diff --git a/packages/core/src/List/XDSListItem.tsx b/packages/core/src/List/XDSListItem.tsx
index 1cf7b0230d..8a5a850b1b 100644
--- a/packages/core/src/List/XDSListItem.tsx
+++ b/packages/core/src/List/XDSListItem.tsx
@@ -1,6 +1,6 @@
/**
* @file XDSListItem.tsx
- * @input Uses React forwardRef, ReactNode, StyleXStyles, theme tokens
+ * @input Uses React, ReactNode, StyleXStyles, theme tokens
* @output Exports XDSListItem component, XDSListItemProps type
* @position Core implementation; consumed by XDSList, index.ts, tested by XDSList.test.tsx
*
@@ -13,7 +13,7 @@
'use client';
-import {forwardRef, useContext, type ReactNode} from 'react';
+import {useContext, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {StyleXStyles} from '@stylexjs/stylex';
import {
@@ -32,6 +32,8 @@ import {xdsClassName, mergeProps} from '../utils';
// =============================================================================
export interface XDSListItemProps {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLLIElement>;
/**
* Primary text label for the item.
*/
@@ -283,117 +285,110 @@ const descriptionSizeStyles = stylex.create({
* <XDSListItem label="Docs" href="/docs" target="_blank" />
* ```
*/
-export const XDSListItem = forwardRef<HTMLLIElement, XDSListItemProps>(
- (
- {
- label,
- description,
- startContent,
- endContent,
- onClick,
- href,
- target,
- isDisabled = false,
- isSelected = false,
- xstyle,
- className,
- style,
- 'data-testid': testId,
- },
- ref,
- ) => {
- const ctx = useContext(XDSListContext);
- const density = ctx?.density ?? 'balanced';
- const hasDividers = ctx?.hasDividers ?? false;
- const hasMarkers = ctx?.hasMarkers ?? false;
- const isInteractive = onClick != null || href != null;
+export function XDSListItem({
+ label,
+ description,
+ startContent,
+ endContent,
+ onClick,
+ href,
+ target,
+ isDisabled = false,
+ isSelected = false,
+ xstyle,
+ className,
+ style,
+ 'data-testid': testId,
+ ref,
+}: XDSListItemProps) {
+ const ctx = useContext(XDSListContext);
+ const density = ctx?.density ?? 'balanced';
+ const hasDividers = ctx?.hasDividers ?? false;
+ const hasMarkers = ctx?.hasMarkers ?? false;
+ const isInteractive = onClick != null || href != null;
- const labelAndDescription = (
- <>
- <span {...stylex.props(styles.label)}>{label}</span>
- {description != null && (
- <span
- {...stylex.props(
- styles.description,
- descriptionSizeStyles[density],
- )}>
- {description}
- </span>
- )}
- </>
- );
+ const labelAndDescription = (
+ <>
+ <span {...stylex.props(styles.label)}>{label}</span>
+ {description != null && (
+ <span
+ {...stylex.props(styles.description, descriptionSizeStyles[density])}>
+ {description}
+ </span>
+ )}
+ </>
+ );
- const handleContainerClick = (e: React.MouseEvent) => {
- if (isDisabled) return;
- const target = e.target as HTMLElement;
- // Don't fire onClick if click originated from an interactive child
- if (target.closest('button, a, input, select, textarea')) return;
- onClick?.(e);
- };
+ const handleContainerClick = (e: React.MouseEvent) => {
+ if (isDisabled) return;
+ const target = e.target as HTMLElement;
+ // Don't fire onClick if click originated from an interactive child
+ if (target.closest('button, a, input, select, textarea')) return;
+ onClick?.(e);
+ };
- const innerContent = (
- <>
- {startContent != null && (
- <span {...stylex.props(styles.startContent)}>{startContent}</span>
- )}
+ const innerContent = (
+ <>
+ {startContent != null && (
+ <span {...stylex.props(styles.startContent)}>{startContent}</span>
+ )}
- {href != null ? (
- <a
- href={href}
- target={target}
- aria-disabled={isDisabled || undefined}
- tabIndex={isDisabled ? -1 : undefined}
- {...stylex.props(styles.invisibleAnchor)}>
- {labelAndDescription}
- </a>
- ) : onClick != null ? (
- <button
- type="button"
- onClick={onClick}
- disabled={isDisabled}
- {...stylex.props(styles.invisibleButton)}>
- {labelAndDescription}
- </button>
- ) : (
- <span {...stylex.props(styles.content)}>{labelAndDescription}</span>
- )}
+ {href != null ? (
+ <a
+ href={href}
+ target={target}
+ aria-disabled={isDisabled || undefined}
+ tabIndex={isDisabled ? -1 : undefined}
+ {...stylex.props(styles.invisibleAnchor)}>
+ {labelAndDescription}
+ </a>
+ ) : onClick != null ? (
+ <button
+ type="button"
+ onClick={onClick}
+ disabled={isDisabled}
+ {...stylex.props(styles.invisibleButton)}>
+ {labelAndDescription}
+ </button>
+ ) : (
+ <span {...stylex.props(styles.content)}>{labelAndDescription}</span>
+ )}
- {endContent != null && (
- <span {...stylex.props(styles.endContent)}>{endContent}</span>
- )}
- </>
- );
+ {endContent != null && (
+ <span {...stylex.props(styles.endContent)}>{endContent}</span>
+ )}
+ </>
+ );
- return (
- <li
- ref={ref}
- data-testid={testId}
- aria-selected={isSelected || undefined}
- aria-disabled={isDisabled || undefined}
- {...mergeProps(
- xdsClassName('list-item'),
- stylex.props(
- hasMarkers ? styles.itemWithMarker : styles.item,
- densityStyles[density],
- hasDividers ? styles.noRadius : styles.withRadius,
- isInteractive && styles.interactive,
- isInteractive && styles.focusWithinOutline,
- isDisabled && styles.disabled,
- isSelected && styles.selected,
- xstyle,
- ),
- className,
- style,
- )}
- onClick={isInteractive ? handleContainerClick : undefined}>
- {hasMarkers ? (
- <div {...stylex.props(styles.innerWrapper)}>{innerContent}</div>
- ) : (
- innerContent
- )}
- </li>
- );
- },
-);
+ return (
+ <li
+ ref={ref}
+ data-testid={testId}
+ aria-selected={isSelected || undefined}
+ aria-disabled={isDisabled || undefined}
+ {...mergeProps(
+ xdsClassName('list-item'),
+ stylex.props(
+ hasMarkers ? styles.itemWithMarker : styles.item,
+ densityStyles[density],
+ hasDividers ? styles.noRadius : styles.withRadius,
+ isInteractive && styles.interactive,
+ isInteractive && styles.focusWithinOutline,
+ isDisabled && styles.disabled,
+ isSelected && styles.selected,
+ xstyle,
+ ),
+ className,
+ style,
+ )}
+ onClick={isInteractive ? handleContainerClick : undefined}>
+ {hasMarkers ? (
+ <div {...stylex.props(styles.innerWrapper)}>{innerContent}</div>
+ ) : (
+ innerContent
+ )}
+ </li>
+ );
+}
XDSListItem.displayName = 'XDSListItem';
diff --git a/packages/core/src/MobileNav/XDSMobileNav.tsx b/packages/core/src/MobileNav/XDSMobileNav.tsx
index 8a22a4124f..2b9a4110e4 100644
--- a/packages/core/src/MobileNav/XDSMobileNav.tsx
+++ b/packages/core/src/MobileNav/XDSMobileNav.tsx
@@ -1,6 +1,6 @@
/**
* @file XDSMobileNav.tsx
- * @input Uses React forwardRef, useEffect, useRef, useCallback, ReactNode, StyleX
+ * @input Uses React, useEffect, useRef, useCallback, ReactNode, StyleX
* @output Exports XDSMobileNav component and XDSMobileNavProps
* @position Core implementation; consumed by index.ts
*
@@ -23,13 +23,7 @@
'use client';
-import {
- forwardRef,
- useCallback,
- useEffect,
- useRef,
- type ReactNode,
-} from 'react';
+import {useCallback, useEffect, useRef, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import {colorVars, spacingVars} from '../theme/tokens.stylex';
import {XDSButton} from '../Button';
@@ -163,6 +157,8 @@ const dynamicStyles = stylex.create({
// =============================================================================
export interface XDSMobileNavProps extends Omit<XDSBaseProps, 'title'> {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLDialogElement>;
/**
* Whether the drawer is open.
*/
@@ -231,123 +227,118 @@ export interface XDSMobileNavProps extends Omit<XDSBaseProps, 'title'> {
* </XDSMobileNav>
* ```
*/
-export const XDSMobileNav = forwardRef<HTMLDialogElement, XDSMobileNavProps>(
- function XDSMobileNav(
- {
- isOpen,
- onOpenChange,
- children,
- title,
- width = 280,
- side = 'start',
- 'data-testid': testId,
- xstyle,
- className,
- style,
- },
- ref,
- ) {
- const dialogRef = useRef<HTMLDialogElement>(null);
+export function XDSMobileNav({
+ isOpen,
+ onOpenChange,
+ children,
+ title,
+ width = 280,
+ side = 'start',
+ 'data-testid': testId,
+ xstyle,
+ className,
+ style,
+ ref,
+}: XDSMobileNavProps) {
+ const dialogRef = useRef<HTMLDialogElement>(null);
- // Merge refs
- const setRefs = useCallback(
- (element: HTMLDialogElement | null) => {
- (
- dialogRef as React.MutableRefObject<HTMLDialogElement | null>
- ).current = element;
- if (typeof ref === 'function') {
- ref(element);
- } else if (ref) {
- ref.current = element;
- }
- },
- [ref],
- );
+ // Merge refs
+ const setRefs = useCallback(
+ (element: HTMLDialogElement | null) => {
+ (dialogRef as React.MutableRefObject<HTMLDialogElement | null>).current =
+ element;
+ if (typeof ref === 'function') {
+ ref(element);
+ } else if (ref) {
+ ref.current = element;
+ }
+ },
+ [ref],
+ );
- // Open/close the dialog via showModal()/close()
- useEffect(() => {
- const dialog = dialogRef.current;
- if (!dialog) return;
+ // Open/close the dialog via showModal()/close()
+ useEffect(() => {
+ const dialog = dialogRef.current;
+ if (!dialog) return;
- if (isOpen) {
- if (!dialog.open) {
- dialog.showModal();
- }
- } else {
- if (dialog.open) {
- dialog.close();
- }
+ if (isOpen) {
+ if (!dialog.open) {
+ dialog.showModal();
}
- }, [isOpen]);
+ } else {
+ if (dialog.open) {
+ dialog.close();
+ }
+ }
+ }, [isOpen]);
- // Handle native cancel event (Escape key) — prevent default and route through onOpenChange
- const handleCancel = useCallback(
- (event: React.SyntheticEvent<HTMLDialogElement>) => {
- event.preventDefault();
- onOpenChange(false);
- },
- [onOpenChange],
- );
+ // Handle native cancel event (Escape key) — prevent default and route through onOpenChange
+ const handleCancel = useCallback(
+ (event: React.SyntheticEvent<HTMLDialogElement>) => {
+ event.preventDefault();
+ onOpenChange(false);
+ },
+ [onOpenChange],
+ );
- // Handle clicks on the dialog backdrop area (outside the drawer)
- const handleDialogClick = useCallback(
- (event: React.MouseEvent<HTMLDialogElement>) => {
- // Only close if click was directly on the dialog element (the transparent overlay),
- // not on the drawer or its children
- if (event.target === event.currentTarget) {
- onOpenChange(false);
- }
- },
- [onOpenChange],
- );
+ // Handle clicks on the dialog backdrop area (outside the drawer)
+ const handleDialogClick = useCallback(
+ (event: React.MouseEvent<HTMLDialogElement>) => {
+ // Only close if click was directly on the dialog element (the transparent overlay),
+ // not on the drawer or its children
+ if (event.target === event.currentTarget) {
+ onOpenChange(false);
+ }
+ },
+ [onOpenChange],
+ );
- const isStart = side === 'start';
+ const isStart = side === 'start';
- return (
- <dialog
- ref={setRefs}
- data-testid={testId}
- aria-label={title ?? 'Navigation'}
- onClick={handleDialogClick}
- onCancel={handleCancel}
- {...mergeProps(
- xdsClassName('mobile-nav', {side}),
- stylex.props(
- styles.dialog,
- styles.backdrop,
- isOpen && styles.backdropOpen,
- xstyle,
- ),
+ return (
+ <dialog
+ ref={setRefs}
+ data-testid={testId}
+ aria-label={title ?? 'Navigation'}
+ onClick={handleDialogClick}
+ onCancel={handleCancel}
+ {...mergeProps(
+ xdsClassName('mobile-nav', {side}),
+ stylex.props(
+ styles.dialog,
+ styles.backdrop,
+ isOpen && styles.backdropOpen,
+ xstyle,
+ ),
+ )}>
+ xstyle, className, style,
+ {/* Drawer panel */}
+ <div
+ {...stylex.props(
+ styles.drawer,
+ dynamicStyles.width(width),
+ isStart && styles.drawerStart,
+ isStart && isOpen && styles.drawerStartOpen,
+ !isStart && styles.drawerEnd,
+ !isStart && isOpen && styles.drawerEndOpen,
)}>
- xstyle, className, style,
- {/* Drawer panel */}
- <div
- {...stylex.props(
- styles.drawer,
- dynamicStyles.width(width),
- isStart && styles.drawerStart,
- isStart && isOpen && styles.drawerStartOpen,
- !isStart && styles.drawerEnd,
- !isStart && isOpen && styles.drawerEndOpen,
- )}>
- {/* Header with optional title and close button */}
- <div {...stylex.props(styles.header, !title && styles.headerNoTitle)}>
- {title && <XDSHeading level={2}>{title}</XDSHeading>}
- <XDSButton
- variant="ghost"
- label="Close navigation"
- tooltip="Close"
- icon={<XDSIcon icon="close" color="inherit" />}
- onClick={() => onOpenChange(false)}
- />
- </div>
-
- {/* Scrollable content */}
- <div {...stylex.props(styles.content)}>{children}</div>
+ {/* Header with optional title and close button */}
+ <div {...stylex.props(styles.header, !title && styles.headerNoTitle)}>
+ {title && <XDSHeading level={2}>{title}</XDSHeading>}
+ <XDSButton
+ variant="ghost"
+ label="Close navigation"
+ tooltip="Close"
+ icon={<XDSIcon icon="close" color="inherit" />}
+ onClick={() => onOpenChange(false)}
+ />
</div>
- </dialog>
- );
- },
-);
+
+ {/* Scrollable content */}
+ <div {...stylex.props(styles.content)}>{children}</div>
+ </div>
+ </dialog>
+ );
+}
XDSMobileNav.displayName = 'XDSMobileNav';
diff --git a/packages/core/src/MoreMenu/XDSMoreMenu.tsx b/packages/core/src/MoreMenu/XDSMoreMenu.tsx
index 8bd899f72e..b9aa8f35ab 100644
--- a/packages/core/src/MoreMenu/XDSMoreMenu.tsx
+++ b/packages/core/src/MoreMenu/XDSMoreMenu.tsx
@@ -17,7 +17,6 @@
'use client';
import {
- forwardRef,
useCallback,
useId,
useMemo,
@@ -144,6 +143,8 @@ function getSelectableItems(
// =============================================================================
export interface XDSMoreMenuProps {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLButtonElement>;
/**
* Menu items — data array of actions, dividers, and sections.
* Same type as XDSDropdownMenu's `items` prop.
@@ -233,263 +234,258 @@ function DefaultItem({item}: {item: XDSDropdownMenuItemData}) {
* />
* ```
*/
-export const XDSMoreMenu = forwardRef<HTMLButtonElement, XDSMoreMenuProps>(
- (
- {
- items,
- label = 'More options',
- variant = 'ghost',
- size = 'md',
- icon,
- isDisabled = false,
- children,
- 'data-testid': testId,
+export function XDSMoreMenu({
+ items,
+ label = 'More options',
+ variant = 'ghost',
+ size = 'md',
+ icon,
+ isDisabled = false,
+ children,
+ 'data-testid': testId,
+ ref,
+}: XDSMoreMenuProps) {
+ const moreIcon = getIcon('moreHorizontal');
+ const buttonRef = useRef<HTMLButtonElement | null>(null);
+ const menuId = useId();
+ const [highlightedIndex, setHighlightedIndex] = useState(-1);
+
+ const selectableItems = useMemo(() => getSelectableItems(items), [items]);
+
+ const layer = useXDSLayer({
+ mode: 'context',
+ lightDismiss: true,
+ onHide: () => {
+ setHighlightedIndex(-1);
+ buttonRef.current?.focus();
},
- ref,
- ) => {
- const moreIcon = getIcon('moreHorizontal');
- const buttonRef = useRef<HTMLButtonElement | null>(null);
- const menuId = useId();
- const [highlightedIndex, setHighlightedIndex] = useState(-1);
-
- const selectableItems = useMemo(() => getSelectableItems(items), [items]);
-
- const layer = useXDSLayer({
- mode: 'context',
- lightDismiss: true,
- onHide: () => {
- setHighlightedIndex(-1);
- buttonRef.current?.focus();
- },
- });
-
- const handleButtonClick = useCallback(() => {
- if (layer.isOpen) {
- layer.hide();
- } else {
- layer.show();
- }
- }, [layer]);
+ });
- const closeMenu = useCallback(() => {
+ const handleButtonClick = useCallback(() => {
+ if (layer.isOpen) {
layer.hide();
- }, [layer]);
-
- const getItemId = useCallback(
- (index: number) => `${menuId}-item-${index}`,
- [menuId],
- );
-
- const handleItemClick = useCallback(
- (item: XDSDropdownMenuItemData) => {
- if (item.isDisabled) return;
- item.onClick?.();
- closeMenu();
- },
- [closeMenu],
- );
-
- const handleItemMouseEnter = useCallback(
- (item: XDSDropdownMenuItemData, index: number) => {
- if (item.isDisabled) return;
- setHighlightedIndex(index);
- },
- [],
- );
-
- const handleKeyDown = useCallback(
- (e: React.KeyboardEvent) => {
- if (!layer.isOpen) {
- if (e.key === 'ArrowDown' || e.key === 'Enter' || e.key === ' ') {
- e.preventDefault();
- layer.show();
- setHighlightedIndex(0);
- }
- return;
+ } else {
+ layer.show();
+ }
+ }, [layer]);
+
+ const closeMenu = useCallback(() => {
+ layer.hide();
+ }, [layer]);
+
+ const getItemId = useCallback(
+ (index: number) => `${menuId}-item-${index}`,
+ [menuId],
+ );
+
+ const handleItemClick = useCallback(
+ (item: XDSDropdownMenuItemData) => {
+ if (item.isDisabled) return;
+ item.onClick?.();
+ closeMenu();
+ },
+ [closeMenu],
+ );
+
+ const handleItemMouseEnter = useCallback(
+ (item: XDSDropdownMenuItemData, index: number) => {
+ if (item.isDisabled) return;
+ setHighlightedIndex(index);
+ },
+ [],
+ );
+
+ const handleKeyDown = useCallback(
+ (e: React.KeyboardEvent) => {
+ if (!layer.isOpen) {
+ if (e.key === 'ArrowDown' || e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ layer.show();
+ setHighlightedIndex(0);
}
+ return;
+ }
- switch (e.key) {
- case 'ArrowDown':
- e.preventDefault();
- setHighlightedIndex(prev => {
- let next = prev + 1;
- while (
- next < selectableItems.length &&
- selectableItems[next].isDisabled
- ) {
- next++;
- }
- return next < selectableItems.length ? next : prev;
- });
- break;
- case 'ArrowUp':
- e.preventDefault();
- setHighlightedIndex(prev => {
- let next = prev - 1;
- while (next >= 0 && selectableItems[next].isDisabled) {
- next--;
- }
- return next >= 0 ? next : prev;
- });
- break;
- case 'Home':
- e.preventDefault();
- {
- let index = 0;
- while (
- index < selectableItems.length &&
- selectableItems[index].isDisabled
- ) {
- index++;
- }
- setHighlightedIndex(index < selectableItems.length ? index : -1);
+ switch (e.key) {
+ case 'ArrowDown':
+ e.preventDefault();
+ setHighlightedIndex(prev => {
+ let next = prev + 1;
+ while (
+ next < selectableItems.length &&
+ selectableItems[next].isDisabled
+ ) {
+ next++;
}
- break;
- case 'End':
- e.preventDefault();
- {
- let index = selectableItems.length - 1;
- while (index >= 0 && selectableItems[index].isDisabled) {
- index--;
- }
- setHighlightedIndex(index >= 0 ? index : -1);
+ return next < selectableItems.length ? next : prev;
+ });
+ break;
+ case 'ArrowUp':
+ e.preventDefault();
+ setHighlightedIndex(prev => {
+ let next = prev - 1;
+ while (next >= 0 && selectableItems[next].isDisabled) {
+ next--;
}
- break;
- case 'Escape':
- e.preventDefault();
- closeMenu();
- break;
- case 'Enter':
- case ' ':
- e.preventDefault();
- if (
- highlightedIndex >= 0 &&
- highlightedIndex < selectableItems.length
+ return next >= 0 ? next : prev;
+ });
+ break;
+ case 'Home':
+ e.preventDefault();
+ {
+ let index = 0;
+ while (
+ index < selectableItems.length &&
+ selectableItems[index].isDisabled
) {
- handleItemClick(selectableItems[highlightedIndex]);
+ index++;
}
- break;
- }
- },
- [layer, selectableItems, highlightedIndex, closeMenu, handleItemClick],
- );
-
- const renderItem = useCallback(
- (item: XDSDropdownMenuItemData, flatIndex: number) => {
- const isHighlighted = flatIndex === highlightedIndex;
-
- return (
- <div
- key={`${item.label}-${flatIndex}`}
- id={getItemId(flatIndex)}
- role="menuitem"
- tabIndex={-1}
- aria-disabled={item.isDisabled}
- onClick={() => handleItemClick(item)}
- onMouseEnter={() => handleItemMouseEnter(item, flatIndex)}
- {...stylex.props(
- styles.item,
- isHighlighted && styles.itemHighlighted,
- item.isDisabled && styles.itemDisabled,
- )}>
- {children ? children(item) : <DefaultItem item={item} />}
- </div>
- );
- },
- [
- children,
- highlightedIndex,
- getItemId,
- handleItemClick,
- handleItemMouseEnter,
- ],
- );
-
- const renderOptions = useCallback(() => {
- let flatIndex = 0;
- const elements: ReactNode[] = [];
-
- for (let i = 0; i < items.length; i++) {
- const option = items[i];
-
- if (isDivider(option)) {
- elements.push(
- <XDSDivider key={`divider-${i}`} xstyle={styles.divider} />,
- );
- } else if (isSection(option)) {
- const sectionItems: ReactNode[] = [];
- for (const item of option.items) {
- sectionItems.push(renderItem(item, flatIndex));
- flatIndex++;
+ setHighlightedIndex(index < selectableItems.length ? index : -1);
+ }
+ break;
+ case 'End':
+ e.preventDefault();
+ {
+ let index = selectableItems.length - 1;
+ while (index >= 0 && selectableItems[index].isDisabled) {
+ index--;
+ }
+ setHighlightedIndex(index >= 0 ? index : -1);
}
- if (option.title) {
- elements.push(
- <XDSDivider
- key={`section-divider-${i}`}
- label={option.title}
- xstyle={styles.sectionDivider}
- />,
- );
+ break;
+ case 'Escape':
+ e.preventDefault();
+ closeMenu();
+ break;
+ case 'Enter':
+ case ' ':
+ e.preventDefault();
+ if (
+ highlightedIndex >= 0 &&
+ highlightedIndex < selectableItems.length
+ ) {
+ handleItemClick(selectableItems[highlightedIndex]);
}
+ break;
+ }
+ },
+ [layer, selectableItems, highlightedIndex, closeMenu, handleItemClick],
+ );
+
+ const renderItem = useCallback(
+ (item: XDSDropdownMenuItemData, flatIndex: number) => {
+ const isHighlighted = flatIndex === highlightedIndex;
+
+ return (
+ <div
+ key={`${item.label}-${flatIndex}`}
+ id={getItemId(flatIndex)}
+ role="menuitem"
+ tabIndex={-1}
+ aria-disabled={item.isDisabled}
+ onClick={() => handleItemClick(item)}
+ onMouseEnter={() => handleItemMouseEnter(item, flatIndex)}
+ {...stylex.props(
+ styles.item,
+ isHighlighted && styles.itemHighlighted,
+ item.isDisabled && styles.itemDisabled,
+ )}>
+ {children ? children(item) : <DefaultItem item={item} />}
+ </div>
+ );
+ },
+ [
+ children,
+ highlightedIndex,
+ getItemId,
+ handleItemClick,
+ handleItemMouseEnter,
+ ],
+ );
+
+ const renderOptions = useCallback(() => {
+ let flatIndex = 0;
+ const elements: ReactNode[] = [];
+
+ for (let i = 0; i < items.length; i++) {
+ const option = items[i];
+
+ if (isDivider(option)) {
+ elements.push(
+ <XDSDivider key={`divider-${i}`} xstyle={styles.divider} />,
+ );
+ } else if (isSection(option)) {
+ const sectionItems: ReactNode[] = [];
+ for (const item of option.items) {
+ sectionItems.push(renderItem(item, flatIndex));
+ flatIndex++;
+ }
+ if (option.title) {
elements.push(
- <div key={`section-${i}`} role="group" aria-label={option.title}>
- {sectionItems}
- </div>,
+ <XDSDivider
+ key={`section-divider-${i}`}
+ label={option.title}
+ xstyle={styles.sectionDivider}
+ />,
);
- } else if (isItemData(option)) {
- elements.push(renderItem(option, flatIndex));
- flatIndex++;
}
+ elements.push(
+ <div key={`section-${i}`} role="group" aria-label={option.title}>
+ {sectionItems}
+ </div>,
+ );
+ } else if (isItemData(option)) {
+ elements.push(renderItem(option, flatIndex));
+ flatIndex++;
}
+ }
- return elements;
- }, [items, renderItem]);
-
- return (
- <>
- <XDSButton
- ref={el => {
- buttonRef.current = el;
- layer.ref(el);
- if (typeof ref === 'function') {
- ref(el);
- } else if (ref) {
- (
- ref as React.MutableRefObject<HTMLButtonElement | null>
- ).current = el;
- }
- }}
- label={label}
- icon={icon ?? moreIcon}
- variant={variant}
- size={size}
- isDisabled={isDisabled}
- tooltip={layer.isOpen ? undefined : label}
- onClick={handleButtonClick}
- onKeyDown={handleKeyDown}
- aria-haspopup="menu"
- aria-expanded={layer.isOpen}
- aria-controls={menuId}
- aria-activedescendant={
- layer.isOpen && highlightedIndex >= 0
- ? getItemId(highlightedIndex)
- : undefined
+ return elements;
+ }, [items, renderItem]);
+
+ return (
+ <>
+ <XDSButton
+ ref={el => {
+ buttonRef.current = el;
+ layer.ref(el);
+ if (typeof ref === 'function') {
+ ref(el);
+ } else if (ref) {
+ (ref as React.MutableRefObject<HTMLButtonElement | null>).current =
+ el;
}
- data-testid={testId}
- />
- {layer.render(
- <div id={menuId} role="menu" {...stylex.props(styles.dropdown)}>
- {renderOptions()}
- </div>,
- {
- placement: 'below',
- alignment: 'end',
- xstyle: [styles.popover, styles.popoverGap],
- },
- )}
- </>
- );
- },
-);
+ }}
+ label={label}
+ icon={icon ?? moreIcon}
+ variant={variant}
+ size={size}
+ isDisabled={isDisabled}
+ tooltip={layer.isOpen ? undefined : label}
+ onClick={handleButtonClick}
+ onKeyDown={handleKeyDown}
+ aria-haspopup="menu"
+ aria-expanded={layer.isOpen}
+ aria-controls={menuId}
+ aria-activedescendant={
+ layer.isOpen && highlightedIndex >= 0
+ ? getItemId(highlightedIndex)
+ : undefined
+ }
+ data-testid={testId}
+ />
+ {layer.render(
+ <div id={menuId} role="menu" {...stylex.props(styles.dropdown)}>
+ {renderOptions()}
+ </div>,
+ {
+ placement: 'below',
+ alignment: 'end',
+ xstyle: [styles.popover, styles.popoverGap],
+ },
+ )}
+ </>
+ );
+}
XDSMoreMenu.displayName = 'XDSMoreMenu';
diff --git a/packages/core/src/NavIcon/XDSNavIcon.tsx b/packages/core/src/NavIcon/XDSNavIcon.tsx
index 86d0ed396b..e510dd7ffe 100644
--- a/packages/core/src/NavIcon/XDSNavIcon.tsx
+++ b/packages/core/src/NavIcon/XDSNavIcon.tsx
@@ -1,6 +1,6 @@
/**
* @file XDSNavIcon.tsx
- * @input Uses React forwardRef, HTMLAttributes, ReactNode
+ * @input Uses React, HTMLAttributes, ReactNode
* @output Exports XDSNavIcon component and XDSNavIconProps
* @position Shared circular icon container for navigation headers (TopNav, PageNav)
*
@@ -12,7 +12,7 @@
* - /apps/storybook/stories/PageNav.stories.tsx
*/
-import {forwardRef, type ReactNode} from 'react';
+import {type ReactNode} from 'react';
import type {XDSBaseProps} from '../XDSBaseProps';
import * as stylex from '@stylexjs/stylex';
import {colorVars, sizeVars} from '../theme/tokens.stylex';
@@ -36,6 +36,8 @@ const styles = stylex.create({
});
export interface XDSNavIconProps extends XDSBaseProps<HTMLDivElement> {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLSpanElement>;
/**
* The icon element to render inside the circular background.
* Should be an XDSIcon or similar icon component.
@@ -62,22 +64,27 @@ export interface XDSNavIconProps extends XDSBaseProps<HTMLDivElement> {
* />
* ```
*/
-export const XDSNavIcon = forwardRef<HTMLSpanElement, XDSNavIconProps>(
- function XDSNavIcon({icon, xstyle, className, style, ...props}, ref) {
- return (
- <span
- ref={ref}
- {...mergeProps(
- xdsClassName('navicon'),
- stylex.props(styles.base, xstyle),
- className,
- style,
- )}
- {...props}>
- {icon}
- </span>
- );
- },
-);
+export function XDSNavIcon({
+ icon,
+ xstyle,
+ className,
+ style,
+ ref,
+ ...props
+}: XDSNavIconProps) {
+ return (
+ <span
+ ref={ref}
+ {...mergeProps(
+ xdsClassName('navicon'),
+ stylex.props(styles.base, xstyle),
+ className,
+ style,
+ )}
+ {...props}>
+ {icon}
+ </span>
+ );
+}
XDSNavIcon.displayName = 'XDSNavIcon';
diff --git a/packages/core/src/NumberInput/XDSNumberInput.tsx b/packages/core/src/NumberInput/XDSNumberInput.tsx
index fd9759e097..8b435a666b 100644
--- a/packages/core/src/NumberInput/XDSNumberInput.tsx
+++ b/packages/core/src/NumberInput/XDSNumberInput.tsx
@@ -1,6 +1,6 @@
/**
* @file XDSNumberInput.tsx
- * @input Uses React forwardRef, useId, useState, useMemo, useCallback, XDSField, XDSIcon
+ * @input Uses React, useId, useState, useMemo, useCallback, XDSField, XDSIcon
* @output Exports XDSNumberInput component, XDSNumberInputProps
* @position Core implementation; consumed by index.ts, tested by XDSNumberInput.test.tsx
*
@@ -14,7 +14,6 @@
'use client';
import {
- forwardRef,
useId,
useState,
useMemo,
@@ -106,6 +105,8 @@ export interface XDSNumberInputProps extends Omit<
XDSBaseProps,
'onChange' | 'defaultValue'
> {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLInputElement>;
/**
* Label text for the input (always rendered for accessibility).
*/
@@ -275,117 +276,137 @@ function parseNumberInput(
* <XDSNumberInput label="Price" value={price} onChange={setPrice} min={0} step={0.01} />
* ```
*/
-export const XDSNumberInput = forwardRef<HTMLInputElement, XDSNumberInputProps>(
- (
- {
- label,
- isLabelHidden = false,
- description,
- isOptional = false,
- isRequired = false,
- isDisabled = false,
- startIcon,
- labelIcon,
- status,
- size = 'md',
- onChange,
- value,
- placeholder,
- labelTooltip,
- hasAutoFocus = false,
- htmlName,
- autoComplete,
- min,
- max,
- step,
- units,
- isIntegerOnly = false,
- onFocus,
- onBlur,
- onEnter,
- xstyle,
- className,
- style,
- },
- ref,
- ) => {
- const id = useId();
- const descriptionID = useId();
- const statusMessageID = useId();
- const inputRef = useRef<HTMLInputElement | null>(null);
+export function XDSNumberInput({
+ label,
+ isLabelHidden = false,
+ description,
+ isOptional = false,
+ isRequired = false,
+ isDisabled = false,
+ startIcon,
+ labelIcon,
+ status,
+ size = 'md',
+ onChange,
+ value,
+ placeholder,
+ labelTooltip,
+ hasAutoFocus = false,
+ htmlName,
+ autoComplete,
+ min,
+ max,
+ step,
+ units,
+ isIntegerOnly = false,
+ onFocus,
+ onBlur,
+ onEnter,
+ xstyle,
+ className,
+ style,
+ ref,
+}: XDSNumberInputProps) {
+ const id = useId();
+ const descriptionID = useId();
+ const statusMessageID = useId();
+ const inputRef = useRef<HTMLInputElement | null>(null);
- // Pending input while user is typing (null = show formatted value)
- const [pendingInput, setPendingInput] = useState<string | null>(null);
+ // Pending input while user is typing (null = show formatted value)
+ const [pendingInput, setPendingInput] = useState<string | null>(null);
- const statusIconMap: Record<XDSInputStatusType, XDSIconName> = {
- warning: 'warning',
- error: 'xCircle',
- success: 'checkCircle',
- };
+ const statusIconMap: Record<XDSInputStatusType, XDSIconName> = {
+ warning: 'warning',
+ error: 'xCircle',
+ success: 'checkCircle',
+ };
- const statusIconColorMap: Record<
- XDSInputStatusType,
- 'warning' | 'negative' | 'positive'
- > = {
- warning: 'warning',
- error: 'negative',
- success: 'positive',
- };
+ const statusIconColorMap: Record<
+ XDSInputStatusType,
+ 'warning' | 'negative' | 'positive'
+ > = {
+ warning: 'warning',
+ error: 'negative',
+ success: 'positive',
+ };
- const ariaDescribedBy =
- [
- description ? descriptionID : null,
- status?.message ? statusMessageID : null,
- ]
- .filter(Boolean)
- .join(' ') || undefined;
+ const ariaDescribedBy =
+ [
+ description ? descriptionID : null,
+ status?.message ? statusMessageID : null,
+ ]
+ .filter(Boolean)
+ .join(' ') || undefined;
- // Display value: pending input if typing, otherwise the raw value
- // Note: With type="number", we can't use formatted display values
- const displayValue = useMemo(() => {
- if (pendingInput !== null) {
- return pendingInput;
- }
- if (value == null) {
- return '';
- }
- return String(value);
- }, [pendingInput, value]);
+ // Display value: pending input if typing, otherwise the raw value
+ // Note: With type="number", we can't use formatted display values
+ const displayValue = useMemo(() => {
+ if (pendingInput !== null) {
+ return pendingInput;
+ }
+ if (value == null) {
+ return '';
+ }
+ return String(value);
+ }, [pendingInput, value]);
- // Check if current pending input is valid (for styling purposes)
- const isInputValid = useMemo(() => {
- if (pendingInput === null || !pendingInput.trim()) {
- return true;
+ // Check if current pending input is valid (for styling purposes)
+ const isInputValid = useMemo(() => {
+ if (pendingInput === null || !pendingInput.trim()) {
+ return true;
+ }
+ return parseNumberInput(pendingInput, {min, max, isIntegerOnly}) !== null;
+ }, [pendingInput, min, max, isIntegerOnly]);
+
+ // Handle input text change - update immediately if valid
+ const handleInputChange = useCallback(
+ (e: React.ChangeEvent<HTMLInputElement>) => {
+ const newValue = e.target.value;
+ setPendingInput(newValue);
+
+ // If the input is valid, update immediately
+ const parsed = parseNumberInput(newValue, {min, max, isIntegerOnly});
+ if (parsed !== null && parsed !== value) {
+ onChange(parsed);
}
- return parseNumberInput(pendingInput, {min, max, isIntegerOnly}) !== null;
- }, [pendingInput, min, max, isIntegerOnly]);
+ },
+ [value, onChange, min, max, isIntegerOnly],
+ );
- // Handle input text change - update immediately if valid
- const handleInputChange = useCallback(
- (e: React.ChangeEvent<HTMLInputElement>) => {
- const newValue = e.target.value;
- setPendingInput(newValue);
+ // Handle focus
+ const handleFocus = useCallback(
+ (e: FocusEvent<HTMLInputElement>) => {
+ onFocus?.(e);
+ },
+ [onFocus],
+ );
- // If the input is valid, update immediately
- const parsed = parseNumberInput(newValue, {min, max, isIntegerOnly});
+ // Handle blur - validate and clear pending input
+ const handleBlur = useCallback(
+ (e: FocusEvent<HTMLInputElement>) => {
+ if (pendingInput !== null) {
+ const parsed = parseNumberInput(pendingInput, {
+ min,
+ max,
+ isIntegerOnly,
+ });
if (parsed !== null && parsed !== value) {
onChange(parsed);
}
- },
- [value, onChange, min, max, isIntegerOnly],
- );
+ }
- // Handle focus
- const handleFocus = useCallback(
- (e: FocusEvent<HTMLInputElement>) => {
- onFocus?.(e);
- },
- [onFocus],
- );
+ // Clear pending input - display will revert to formatted value
+ setPendingInput(null);
+ onBlur?.(e);
+ },
+ [pendingInput, value, onChange, min, max, isIntegerOnly, onBlur],
+ );
- // Handle blur - validate and clear pending input
- const handleBlur = useCallback(
- (e: FocusEvent<HTMLInputElement>) => {
+ // Handle keyboard events
+ const handleKeyDown = useCallback(
+ (e: KeyboardEvent<HTMLInputElement>) => {
+ if (e.key === 'Enter') {
+ // Validate and commit on Enter
if (pendingInput !== null) {
const parsed = parseNumberInput(pendingInput, {
min,
@@ -396,123 +417,99 @@ export const XDSNumberInput = forwardRef<HTMLInputElement, XDSNumberInputProps>(
onChange(parsed);
}
}
+ onEnter?.();
+ }
+ },
+ [pendingInput, value, onChange, min, max, isIntegerOnly, onEnter],
+ );
- // Clear pending input - display will revert to formatted value
- setPendingInput(null);
- onBlur?.(e);
- },
- [pendingInput, value, onChange, min, max, isIntegerOnly, onBlur],
- );
+ // Combine refs
+ const setRefs = useCallback(
+ (el: HTMLInputElement | null) => {
+ inputRef.current = el;
+ if (typeof ref === 'function') {
+ ref(el);
+ } else if (ref) {
+ ref.current = el;
+ }
+ },
+ [ref],
+ );
- // Handle keyboard events
- const handleKeyDown = useCallback(
- (e: KeyboardEvent<HTMLInputElement>) => {
- if (e.key === 'Enter') {
- // Validate and commit on Enter
- if (pendingInput !== null) {
- const parsed = parseNumberInput(pendingInput, {
- min,
- max,
- isIntegerOnly,
- });
- if (parsed !== null && parsed !== value) {
- onChange(parsed);
+ return (
+ <XDSField
+ label={label}
+ isLabelHidden={isLabelHidden}
+ description={description}
+ inputID={id}
+ descriptionID={description ? descriptionID : undefined}
+ isOptional={isOptional}
+ isRequired={isRequired}
+ labelIcon={labelIcon}
+ status={
+ status
+ ? {
+ type: status.type,
+ message: status.message,
+ messageID: status.message ? statusMessageID : undefined,
}
- }
- onEnter?.();
- }
- },
- [pendingInput, value, onChange, min, max, isIntegerOnly, onEnter],
- );
-
- // Combine refs
- const setRefs = useCallback(
- (el: HTMLInputElement | null) => {
- inputRef.current = el;
- if (typeof ref === 'function') {
- ref(el);
- } else if (ref) {
- ref.current = el;
- }
- },
- [ref],
- );
-
- return (
- <XDSField
- label={label}
- isLabelHidden={isLabelHidden}
- description={description}
- inputID={id}
- descriptionID={description ? descriptionID : undefined}
- isOptional={isOptional}
- isRequired={isRequired}
- labelIcon={labelIcon}
- status={
- status
- ? {
- type: status.type,
- message: status.message,
- messageID: status.message ? statusMessageID : undefined,
- }
- : undefined
- }
- labelTooltip={labelTooltip}>
- <div
- {...mergeProps(
- xdsClassName('number-input', {size}),
- stylex.props(
- inputWrapperStyles.base,
- styles.wrapper,
- sizeStyles[size],
- isDisabled && inputWrapperStyles.disabled,
- status && inputStatusBorderStyles[status.type],
- status && inputStatusHoverShadowStyles[status.type],
- status && inputStatusFocusWithinStyles[status.type],
- xstyle,
- ),
- className,
- style,
- )}>
- {startIcon && <XDSIcon icon={startIcon} size="sm" color="primary" />}
- <input
- ref={setRefs}
- id={id}
- name={htmlName}
- type="number"
- autoComplete={autoComplete}
- value={displayValue}
- onChange={handleInputChange}
- onFocus={handleFocus}
- onBlur={handleBlur}
- onKeyDown={handleKeyDown}
- placeholder={placeholder}
- disabled={isDisabled}
- autoFocus={hasAutoFocus}
- min={min ?? undefined}
- max={max ?? undefined}
- step={step ?? undefined}
- aria-describedby={ariaDescribedBy}
- aria-required={isRequired === true ? 'true' : undefined}
- aria-invalid={status?.type === 'error' ? 'true' : undefined}
- {...stylex.props(
- styles.input,
- isDisabled && styles.inputDisabled,
- !isInputValid && styles.inputInvalid,
- )}
- />
- {units && <span {...stylex.props(styles.units)}>{units}</span>}
- {status && (
- <XDSIcon
- icon={statusIconMap[status.type]}
- size="md"
- color={statusIconColorMap[status.type]}
- />
+ : undefined
+ }
+ labelTooltip={labelTooltip}>
+ <div
+ {...mergeProps(
+ xdsClassName('number-input', {size}),
+ stylex.props(
+ inputWrapperStyles.base,
+ styles.wrapper,
+ sizeStyles[size],
+ isDisabled && inputWrapperStyles.disabled,
+ status && inputStatusBorderStyles[status.type],
+ status && inputStatusHoverShadowStyles[status.type],
+ status && inputStatusFocusWithinStyles[status.type],
+ xstyle,
+ ),
+ className,
+ style,
+ )}>
+ {startIcon && <XDSIcon icon={startIcon} size="sm" color="primary" />}
+ <input
+ ref={setRefs}
+ id={id}
+ name={htmlName}
+ type="number"
+ autoComplete={autoComplete}
+ value={displayValue}
+ onChange={handleInputChange}
+ onFocus={handleFocus}
+ onBlur={handleBlur}
+ onKeyDown={handleKeyDown}
+ placeholder={placeholder}
+ disabled={isDisabled}
+ autoFocus={hasAutoFocus}
+ min={min ?? undefined}
+ max={max ?? undefined}
+ step={step ?? undefined}
+ aria-describedby={ariaDescribedBy}
+ aria-required={isRequired === true ? 'true' : undefined}
+ aria-invalid={status?.type === 'error' ? 'true' : undefined}
+ {...stylex.props(
+ styles.input,
+ isDisabled && styles.inputDisabled,
+ !isInputValid && styles.inputInvalid,
)}
- </div>
- </XDSField>
- );
- },
-);
+ />
+ {units && <span {...stylex.props(styles.units)}>{units}</span>}
+ {status && (
+ <XDSIcon
+ icon={statusIconMap[status.type]}
+ size="md"
+ color={statusIconColorMap[status.type]}
+ />
+ )}
+ </div>
+ </XDSField>
+ );
+}
XDSNumberInput.displayName = 'XDSNumberInput';
diff --git a/packages/core/src/Pagination/XDSPagination.tsx b/packages/core/src/Pagination/XDSPagination.tsx
index 8c68970a77..615be36da9 100644
--- a/packages/core/src/Pagination/XDSPagination.tsx
+++ b/packages/core/src/Pagination/XDSPagination.tsx
@@ -17,7 +17,7 @@
'use client';
-import {forwardRef, useTransition} from 'react';
+import {useTransition} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {StyleXStyles} from '@stylexjs/stylex';
import {
@@ -49,6 +49,8 @@ export type XDSPaginationVariant =
export type XDSPaginationSize = 'sm' | 'md';
export interface XDSPaginationProps {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLElement>;
// --- Core (required) ---
/** Current page number (1-based). Page 1 is the first page. */
page: number;
@@ -316,245 +318,239 @@ export function generatePageRange(
* />
* ```
*/
-export const XDSPagination = forwardRef<HTMLElement, XDSPaginationProps>(
- function XDSPagination(
- {
- page,
- onChange,
- onChangeAction,
- totalItems,
- totalPages: totalPagesProp,
- hasMore,
- pageSize = 10,
- pageSizeOptions,
- onPageSizeChange,
- variant = 'pages',
- siblingCount = 1,
- size = 'md',
- isDisabled = false,
- label = 'Pagination',
- 'data-testid': testId,
- xstyle,
- className,
- style,
- },
- ref,
- ) {
- const [isPending, startTransition] = useTransition();
-
- // Compute pagination state
- const computedTotalPages =
- totalPagesProp ??
- (totalItems != null ? Math.ceil(totalItems / pageSize) : undefined);
-
- const hasPrevious = page > 1;
- const hasNext =
- computedTotalPages != null
- ? page < computedTotalPages
- : (hasMore ?? false);
-
- // Return null for empty state
- if (totalItems != null && totalItems <= 0) {
- return null;
+export function XDSPagination({
+ page,
+ onChange,
+ onChangeAction,
+ totalItems,
+ totalPages: totalPagesProp,
+ hasMore,
+ pageSize = 10,
+ pageSizeOptions,
+ onPageSizeChange,
+ variant = 'pages',
+ siblingCount = 1,
+ size = 'md',
+ isDisabled = false,
+ label = 'Pagination',
+ 'data-testid': testId,
+ xstyle,
+ className,
+ style,
+ ref,
+}: XDSPaginationProps) {
+ const [isPending, startTransition] = useTransition();
+
+ // Compute pagination state
+ const computedTotalPages =
+ totalPagesProp ??
+ (totalItems != null ? Math.ceil(totalItems / pageSize) : undefined);
+
+ const hasPrevious = page > 1;
+ const hasNext =
+ computedTotalPages != null ? page < computedTotalPages : (hasMore ?? false);
+
+ // Return null for empty state
+ if (totalItems != null && totalItems <= 0) {
+ return null;
+ }
+ if (computedTotalPages != null && computedTotalPages <= 0) {
+ return null;
+ }
+
+ const handlePageChange = (newPage: number) => {
+ if (isDisabled || isPending) return;
+ onChange(newPage);
+ if (onChangeAction) {
+ startTransition(async () => {
+ await onChangeAction(newPage);
+ });
}
- if (computedTotalPages != null && computedTotalPages <= 0) {
- return null;
+ };
+
+ const handlePrevious = () => {
+ if (hasPrevious) {
+ handlePageChange(page - 1);
}
+ };
- const handlePageChange = (newPage: number) => {
- if (isDisabled || isPending) return;
- onChange(newPage);
- if (onChangeAction) {
- startTransition(async () => {
- await onChangeAction(newPage);
- });
+ const handleNext = () => {
+ if (hasNext) {
+ handlePageChange(page + 1);
+ }
+ };
+
+ const handlePageSizeChange = (value: string) => {
+ const newSize = Number(value);
+ onPageSizeChange?.(newSize);
+ // Reset to page 1 when page size changes
+ onChange(1);
+ if (onChangeAction) {
+ startTransition(async () => {
+ await onChangeAction(1);
+ });
+ }
+ };
+
+ // Item range for count display
+ const rangeStart = (page - 1) * pageSize + 1;
+ const rangeEnd =
+ totalItems != null
+ ? Math.min(page * pageSize, totalItems)
+ : page * pageSize;
+
+ const buttonSize = size === 'sm' ? 'sm' : 'md';
+ const isSm = size === 'sm';
+
+ const renderIndicator = () => {
+ switch (variant) {
+ case 'pages': {
+ if (computedTotalPages == null) return null;
+ const pageRange = generatePageRange(
+ page,
+ computedTotalPages,
+ siblingCount,
+ );
+ return (
+ <>
+ {pageRange.map((item, index) => {
+ if (item === '...') {
+ return (
+ <span
+ key={`ellipsis-${index}`}
+ aria-hidden="true"
+ {...stylex.props(
+ styles.ellipsis,
+ isSm && styles.ellipsisSm,
+ )}>
+ …
+ </span>
+ );
+ }
+ const isActive = item === page;
+ return (
+ <XDSButton
+ key={item}
+ label={`Go to page ${item}`}
+ aria-label={`Go to page ${item}`}
+ variant={isActive ? 'primary' : 'ghost'}
+ size={buttonSize}
+ onClick={() => handlePageChange(item)}
+ isDisabled={isDisabled}
+ aria-current={isActive ? 'page' : undefined}>
+ {item}
+ </XDSButton>
+ );
+ })}
+ </>
+ );
}
- };
- const handlePrevious = () => {
- if (hasPrevious) {
- handlePageChange(page - 1);
+ case 'count': {
+ if (totalItems == null) return null;
+ return (
+ <span {...stylex.props(styles.infoText)}>
+ <XDSText type="body" size="sm" color="secondary">
+ {`${rangeStart}\u2013${rangeEnd} of ${totalItems}`}
+ </XDSText>
+ </span>
+ );
}
- };
- const handleNext = () => {
- if (hasNext) {
- handlePageChange(page + 1);
+ case 'compact': {
+ if (computedTotalPages == null) return null;
+ return (
+ <span {...stylex.props(styles.infoText)}>
+ <XDSText type="body" size="sm" color="secondary">
+ {`Page ${page} of ${computedTotalPages}`}
+ </XDSText>
+ </span>
+ );
}
- };
-
- const handlePageSizeChange = (value: string) => {
- const newSize = Number(value);
- onPageSizeChange?.(newSize);
- // Reset to page 1 when page size changes
- onChange(1);
- if (onChangeAction) {
- startTransition(async () => {
- await onChangeAction(1);
- });
- }
- };
-
- // Item range for count display
- const rangeStart = (page - 1) * pageSize + 1;
- const rangeEnd =
- totalItems != null
- ? Math.min(page * pageSize, totalItems)
- : page * pageSize;
-
- const buttonSize = size === 'sm' ? 'sm' : 'md';
- const isSm = size === 'sm';
-
- const renderIndicator = () => {
- switch (variant) {
- case 'pages': {
- if (computedTotalPages == null) return null;
- const pageRange = generatePageRange(
- page,
- computedTotalPages,
- siblingCount,
- );
- return (
- <>
- {pageRange.map((item, index) => {
- if (item === '...') {
- return (
- <span
- key={`ellipsis-${index}`}
- aria-hidden="true"
- {...stylex.props(
- styles.ellipsis,
- isSm && styles.ellipsisSm,
- )}>
- …
- </span>
- );
- }
- const isActive = item === page;
- return (
- <XDSButton
- key={item}
- label={`Go to page ${item}`}
- aria-label={`Go to page ${item}`}
- variant={isActive ? 'primary' : 'ghost'}
- size={buttonSize}
- onClick={() => handlePageChange(item)}
- isDisabled={isDisabled}
- aria-current={isActive ? 'page' : undefined}>
- {item}
- </XDSButton>
- );
- })}
- </>
- );
- }
-
- case 'count': {
- if (totalItems == null) return null;
- return (
- <span {...stylex.props(styles.infoText)}>
- <XDSText type="body" size="sm" color="secondary">
- {`${rangeStart}\u2013${rangeEnd} of ${totalItems}`}
- </XDSText>
- </span>
- );
- }
-
- case 'compact': {
- if (computedTotalPages == null) return null;
- return (
- <span {...stylex.props(styles.infoText)}>
- <XDSText type="body" size="sm" color="secondary">
- {`Page ${page} of ${computedTotalPages}`}
- </XDSText>
- </span>
- );
- }
-
- case 'dots': {
- if (computedTotalPages == null) return null;
- return (
- <div
- {...stylex.props(styles.dotsContainer)}
- role="group"
- aria-label="Page indicators">
- {Array.from({length: computedTotalPages}, (_, i) => (
- <button
- key={i + 1}
- type="button"
- aria-label={`Go to page ${i + 1}`}
- aria-current={i + 1 === page ? 'page' : undefined}
- onClick={() => handlePageChange(i + 1)}
- disabled={isDisabled}
- {...stylex.props(
- styles.dot,
- isSm && styles.dotSm,
- i + 1 === page && styles.dotActive,
- isDisabled && styles.dotDisabled,
- )}
- />
- ))}
- </div>
- );
- }
-
- case 'none':
- default:
- return null;
- }
- };
-
- return (
- <nav
- ref={ref}
- aria-label={label}
- data-testid={testId}
- {...mergeProps(
- xdsClassName('pagination', {variant, size}),
- stylex.props(styles.root, xstyle),
- className,
- style,
- )}>
- {pageSizeOptions != null && pageSizeOptions.length > 0 && (
- <div {...stylex.props(styles.pageSizeSelector)}>
- <div {...stylex.props(styles.pageSizeSelectorControl)}>
- <XDSSelector
- label="Items per page"
- isLabelHidden
- options={pageSizeOptions.map(opt => String(opt))}
- value={String(pageSize)}
- onChange={handlePageSizeChange}
- size={buttonSize}
- isDisabled={isDisabled}
+
+ case 'dots': {
+ if (computedTotalPages == null) return null;
+ return (
+ <div
+ {...stylex.props(styles.dotsContainer)}
+ role="group"
+ aria-label="Page indicators">
+ {Array.from({length: computedTotalPages}, (_, i) => (
+ <button
+ key={i + 1}
+ type="button"
+ aria-label={`Go to page ${i + 1}`}
+ aria-current={i + 1 === page ? 'page' : undefined}
+ onClick={() => handlePageChange(i + 1)}
+ disabled={isDisabled}
+ {...stylex.props(
+ styles.dot,
+ isSm && styles.dotSm,
+ i + 1 === page && styles.dotActive,
+ isDisabled && styles.dotDisabled,
+ )}
/>
- </div>
+ ))}
+ </div>
+ );
+ }
+
+ case 'none':
+ default:
+ return null;
+ }
+ };
+
+ return (
+ <nav
+ ref={ref}
+ aria-label={label}
+ data-testid={testId}
+ {...mergeProps(
+ xdsClassName('pagination', {variant, size}),
+ stylex.props(styles.root, xstyle),
+ className,
+ style,
+ )}>
+ {pageSizeOptions != null && pageSizeOptions.length > 0 && (
+ <div {...stylex.props(styles.pageSizeSelector)}>
+ <div {...stylex.props(styles.pageSizeSelectorControl)}>
+ <XDSSelector
+ label="Items per page"
+ isLabelHidden
+ options={pageSizeOptions.map(opt => String(opt))}
+ value={String(pageSize)}
+ onChange={handlePageSizeChange}
+ size={buttonSize}
+ isDisabled={isDisabled}
+ />
</div>
- )}
-
- <div {...stylex.props(styles.controls)}>
- <XDSButton
- label="Go to previous page"
- variant="ghost"
- size={buttonSize}
- icon={<XDSIcon icon="chevronLeft" size={isSm ? 'sm' : 'md'} />}
- onClick={handlePrevious}
- isDisabled={isDisabled || !hasPrevious}
- />
-
- {renderIndicator()}
-
- <XDSButton
- label="Go to next page"
- variant="ghost"
- size={buttonSize}
- icon={<XDSIcon icon="chevronRight" size={isSm ? 'sm' : 'md'} />}
- onClick={handleNext}
- isDisabled={isDisabled || !hasNext}
- />
</div>
- </nav>
- );
- },
-);
+ )}
+
+ <div {...stylex.props(styles.controls)}>
+ <XDSButton
+ label="Go to previous page"
+ variant="ghost"
+ size={buttonSize}
+ icon={<XDSIcon icon="chevronLeft" size={isSm ? 'sm' : 'md'} />}
+ onClick={handlePrevious}
+ isDisabled={isDisabled || !hasPrevious}
+ />
+
+ {renderIndicator()}
+
+ <XDSButton
+ label="Go to next page"
+ variant="ghost"
+ size={buttonSize}
+ icon={<XDSIcon icon="chevronRight" size={isSm ? 'sm' : 'md'} />}
+ onClick={handleNext}
+ isDisabled={isDisabled || !hasNext}
+ />
+ </div>
+ </nav>
+ );
+}
XDSPagination.displayName = 'XDSPagination';
diff --git a/packages/core/src/ProgressBar/XDSProgressBar.tsx b/packages/core/src/ProgressBar/XDSProgressBar.tsx
index ac508766b3..81f57199db 100644
--- a/packages/core/src/ProgressBar/XDSProgressBar.tsx
+++ b/packages/core/src/ProgressBar/XDSProgressBar.tsx
@@ -1,6 +1,6 @@
/**
* @file XDSProgressBar.tsx
- * @input Uses React forwardRef, useId, stylex, color/spacing/radius/transition tokens
+ * @input Uses React, useId, stylex, color/spacing/radius/transition tokens
* @output Exports XDSProgressBar component, XDSProgressBarProps, XDSProgressBarVariant, XDSProgressBarSize types
* @position Core implementation; consumed by index.ts
*
@@ -13,7 +13,7 @@
'use client';
-import {forwardRef, useId} from 'react';
+import {useId} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {StyleXStyles} from '@stylexjs/stylex';
import {
@@ -42,6 +42,8 @@ export type XDSProgressBarVariant =
export type XDSProgressBarSize = 'sm' | 'md' | 'lg';
export interface XDSProgressBarProps {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLDivElement>;
/**
* Current value of the progress bar.
* Ignored when `isIndeterminate` is true.
@@ -248,90 +250,83 @@ function defaultFormatValueLabel(value: number, max: number): string {
* formatValueLabel={(v, m) => `${v} GB / ${m} GB`} />
* ```
*/
-export const XDSProgressBar = forwardRef<HTMLDivElement, XDSProgressBarProps>(
- function XDSProgressBar(
- {
- value = 0,
- max = 100,
- label,
- isLabelHidden = false,
- hasValueLabel = false,
- formatValueLabel = defaultFormatValueLabel,
- variant = 'accent',
- size = 'md',
- isIndeterminate = false,
- xstyle,
- className,
- style,
- 'data-testid': dataTestId,
- },
- ref,
- ) {
- const labelId = useId();
- const clampedValue = Math.min(Math.max(0, value), max);
- const percentage = max > 0 ? (clampedValue / max) * 100 : 0;
- const valueText = formatValueLabel(clampedValue, max);
+export function XDSProgressBar({
+ value = 0,
+ max = 100,
+ label,
+ isLabelHidden = false,
+ hasValueLabel = false,
+ formatValueLabel = defaultFormatValueLabel,
+ variant = 'accent',
+ size = 'md',
+ isIndeterminate = false,
+ xstyle,
+ className,
+ style,
+ 'data-testid': dataTestId,
+ ref,
+}: XDSProgressBarProps) {
+ const labelId = useId();
+ const clampedValue = Math.min(Math.max(0, value), max);
+ const percentage = max > 0 ? (clampedValue / max) * 100 : 0;
+ const valueText = formatValueLabel(clampedValue, max);
- // In indeterminate mode, don't show value label
- const showValueLabel = hasValueLabel && !isIndeterminate;
+ // In indeterminate mode, don't show value label
+ const showValueLabel = hasValueLabel && !isIndeterminate;
- return (
- <div
- ref={ref}
- {...mergeProps(
- xdsClassName('progressbar', {variant, size}),
- stylex.props(styles.container, xstyle),
- className,
- style,
- )}
- data-testid={dataTestId}>
- {/* Label row */}
- {!isLabelHidden || showValueLabel ? (
- <div {...stylex.props(styles.header)}>
- <span
- id={labelId}
- {...stylex.props(
- styles.label,
- isLabelHidden && styles.visuallyHidden,
- )}>
- {label}
- </span>
- {showValueLabel && (
- <span {...stylex.props(styles.valueLabel)}>{valueText}</span>
- )}
- </div>
- ) : (
- <span id={labelId} {...stylex.props(styles.visuallyHidden)}>
+ return (
+ <div
+ ref={ref}
+ {...mergeProps(
+ xdsClassName('progressbar', {variant, size}),
+ stylex.props(styles.container, xstyle),
+ className,
+ style,
+ )}
+ data-testid={dataTestId}>
+ {/* Label row */}
+ {!isLabelHidden || showValueLabel ? (
+ <div {...stylex.props(styles.header)}>
+ <span
+ id={labelId}
+ {...stylex.props(
+ styles.label,
+ isLabelHidden && styles.visuallyHidden,
+ )}>
{label}
</span>
- )}
-
- {/* Progress track */}
- <div
- role={isIndeterminate ? 'progressbar' : 'meter'}
- aria-valuenow={isIndeterminate ? undefined : clampedValue}
- aria-valuemin={isIndeterminate ? undefined : 0}
- aria-valuemax={isIndeterminate ? undefined : max}
- aria-labelledby={labelId}
- aria-valuetext={isIndeterminate ? undefined : valueText}
- {...stylex.props(styles.track, sizeStyles[size])}>
- {isIndeterminate ? (
- <div
- {...stylex.props(
- styles.indeterminateFill,
- variantStyles[variant],
- )}
- />
- ) : (
- <div
- {...stylex.props(styles.fill, variantStyles[variant])}
- style={{width: `${percentage}%`}}
- />
+ {showValueLabel && (
+ <span {...stylex.props(styles.valueLabel)}>{valueText}</span>
)}
</div>
+ ) : (
+ <span id={labelId} {...stylex.props(styles.visuallyHidden)}>
+ {label}
+ </span>
+ )}
+
+ {/* Progress track */}
+ <div
+ role={isIndeterminate ? 'progressbar' : 'meter'}
+ aria-valuenow={isIndeterminate ? undefined : clampedValue}
+ aria-valuemin={isIndeterminate ? undefined : 0}
+ aria-valuemax={isIndeterminate ? undefined : max}
+ aria-labelledby={labelId}
+ aria-valuetext={isIndeterminate ? undefined : valueText}
+ {...stylex.props(styles.track, sizeStyles[size])}>
+ {isIndeterminate ? (
+ <div
+ {...stylex.props(styles.indeterminateFill, variantStyles[variant])}
+ />
+ ) : (
+ <div
+ {...stylex.props(styles.fill, variantStyles[variant])}
+ style={{width: `${percentage}%`}}
+ />
+ )}
</div>
- );
- },
-);
+ </div>
+ );
+}
XDSProgressBar.displayName = 'XDSProgressBar';
diff --git a/packages/core/src/Section/XDSSection.tsx b/packages/core/src/Section/XDSSection.tsx
index 1fd00429b0..7e4c2c0921 100644
--- a/packages/core/src/Section/XDSSection.tsx
+++ b/packages/core/src/Section/XDSSection.tsx
@@ -12,7 +12,7 @@
'use client';
-import {forwardRef, type ReactNode} from 'react';
+import {type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import {colorVars} from '../theme/tokens.stylex';
import {container} from '../Layout/container.stylex';
@@ -107,6 +107,8 @@ const dynamicStyles = stylex.create({
});
export interface XDSSectionProps {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLDivElement>;
/**
* Visual variant of the section.
* - 'section': Surface background color
@@ -181,58 +183,54 @@ export interface XDSSectionProps {
* </XDSSection>
* ```
*/
-export const XDSSection = forwardRef<HTMLDivElement, XDSSectionProps>(
- function XDSSection(
- {
- variant = 'section',
- width,
- height,
- maxWidth,
- minHeight,
- children,
- dividers,
- isFullBleed = false,
- ...props
- },
- ref,
- ) {
- return (
- <div
- ref={ref}
- {...mergeProps(
- xdsClassName('section', {variant}),
- stylex.props(
- nestedStyles.outer,
- dynamicStyles.sizing(
- width ?? null,
- height ?? null,
- maxWidth ?? null,
- minHeight ?? null,
- ),
+export function XDSSection({
+ variant = 'section',
+ width,
+ height,
+ maxWidth,
+ minHeight,
+ children,
+ dividers,
+ isFullBleed = false,
+ ref,
+ ...props
+}: XDSSectionProps) {
+ return (
+ <div
+ ref={ref}
+ {...mergeProps(
+ xdsClassName('section', {variant}),
+ stylex.props(
+ nestedStyles.outer,
+ dynamicStyles.sizing(
+ width ?? null,
+ height ?? null,
+ maxWidth ?? null,
+ minHeight ?? null,
),
- )}
- {...props}>
- <div
- {...stylex.props(
- nestedStyles.inner,
- ...container({
- paddingInnerX: 'spacing4',
- paddingInnerY: 'spacing4',
- paddingOuterX: 'spacing4',
- paddingOuterY: 'spacing4',
- }),
- variantStyles[variant],
- isFullBleed && nestedStyles.fullBleed,
- dividers?.includes('top') && dividerStyles.top,
- dividers?.includes('bottom') && dividerStyles.bottom,
- dividers?.includes('start') && dividerStyles.start,
- dividers?.includes('end') && dividerStyles.end,
- )}>
- {children}
- </div>
+ ),
+ )}
+ {...props}>
+ <div
+ {...stylex.props(
+ nestedStyles.inner,
+ ...container({
+ paddingInnerX: 'spacing4',
+ paddingInnerY: 'spacing4',
+ paddingOuterX: 'spacing4',
+ paddingOuterY: 'spacing4',
+ }),
+ variantStyles[variant],
+ isFullBleed && nestedStyles.fullBleed,
+ dividers?.includes('top') && dividerStyles.top,
+ dividers?.includes('bottom') && dividerStyles.bottom,
+ dividers?.includes('start') && dividerStyles.start,
+ dividers?.includes('end') && dividerStyles.end,
+ )}>
+ {children}
</div>
- );
- },
-);
+ </div>
+ );
+}
XDSSection.displayName = 'XDSSection';
diff --git a/packages/core/src/SideNav/XDSSideNav.tsx b/packages/core/src/SideNav/XDSSideNav.tsx
index 6feb8d2633..6dc55ef57b 100644
--- a/packages/core/src/SideNav/XDSSideNav.tsx
+++ b/packages/core/src/SideNav/XDSSideNav.tsx
@@ -1,6 +1,6 @@
/**
* @file XDSSideNav.tsx
- * @input Uses React forwardRef, HTMLAttributes, ReactNode, StyleX
+ * @input Uses React, HTMLAttributes, ReactNode, StyleX
* @output Exports XDSSideNav component and XDSSideNavProps
* @position Core implementation; consumed by index.ts, tested by XDSSideNav.test.tsx
*
@@ -16,7 +16,7 @@
'use client';
-import {forwardRef, type ReactNode} from 'react';
+import {type ReactNode} from 'react';
import type {XDSBaseProps} from '../XDSBaseProps';
import * as stylex from '@stylexjs/stylex';
import type {StyleXStyles} from '@stylexjs/stylex';
@@ -82,6 +82,8 @@ const styles = stylex.create({
// =============================================================================
export interface XDSSideNavProps extends XDSBaseProps<HTMLElement> {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLElement>;
/**
* Header area — typically XDSSideNavHeading. Sticky at top.
*/
@@ -151,58 +153,54 @@ export interface XDSSideNavProps extends XDSBaseProps<HTMLElement> {
* </XDSSideNav>
* ```
*/
-export const XDSSideNav = forwardRef<HTMLElement, XDSSideNavProps>(
- function XDSSideNav(
- {
- header,
- topContent,
- children,
- footer,
- footerIcons,
- xstyle,
- className,
- style,
- 'data-testid': testId,
- ...props
- },
- ref,
- ) {
- const hasStickyTop = !!(header || topContent);
- const hasStickyBottom = !!(footer || footerIcons);
+export function XDSSideNav({
+ header,
+ topContent,
+ children,
+ footer,
+ footerIcons,
+ xstyle,
+ className,
+ style,
+ 'data-testid': testId,
+ ref,
+ ...props
+}: XDSSideNavProps) {
+ const hasStickyTop = !!(header || topContent);
+ const hasStickyBottom = !!(footer || footerIcons);
- return (
- <nav
- ref={ref}
- role="navigation"
- aria-label="Side navigation"
- data-testid={testId}
- {...mergeProps(
- xdsClassName('side-nav'),
- stylex.props(styles.root, xstyle),
- className,
- style,
- )}
- {...props}>
- {hasStickyTop && (
- <div {...stylex.props(styles.stickyTop)}>
- {header}
- {topContent && (
- <div {...stylex.props(styles.topContent)}>{topContent}</div>
- )}
- </div>
- )}
- <div {...stylex.props(styles.scrollable)}>{children}</div>
- {hasStickyBottom && (
- <div {...stylex.props(styles.stickyBottom)}>
- {footer && <div {...stylex.props(styles.footer)}>{footer}</div>}
- {footerIcons && (
- <div {...stylex.props(styles.footerIcons)}>{footerIcons}</div>
- )}
- </div>
- )}
- </nav>
- );
- },
-);
+ return (
+ <nav
+ ref={ref}
+ role="navigation"
+ aria-label="Side navigation"
+ data-testid={testId}
+ {...mergeProps(
+ xdsClassName('side-nav'),
+ stylex.props(styles.root, xstyle),
+ className,
+ style,
+ )}
+ {...props}>
+ {hasStickyTop && (
+ <div {...stylex.props(styles.stickyTop)}>
+ {header}
+ {topContent && (
+ <div {...stylex.props(styles.topContent)}>{topContent}</div>
+ )}
+ </div>
+ )}
+ <div {...stylex.props(styles.scrollable)}>{children}</div>
+ {hasStickyBottom && (
+ <div {...stylex.props(styles.stickyBottom)}>
+ {footer && <div {...stylex.props(styles.footer)}>{footer}</div>}
+ {footerIcons && (
+ <div {...stylex.props(styles.footerIcons)}>{footerIcons}</div>
+ )}
+ </div>
+ )}
+ </nav>
+ );
+}
XDSSideNav.displayName = 'XDSSideNav';
diff --git a/packages/core/src/SideNav/XDSSideNavHeading.tsx b/packages/core/src/SideNav/XDSSideNavHeading.tsx
index 2e59631863..ee6d3ff8da 100644
--- a/packages/core/src/SideNav/XDSSideNavHeading.tsx
+++ b/packages/core/src/SideNav/XDSSideNavHeading.tsx
@@ -1,6 +1,6 @@
/**
* @file XDSSideNavHeading.tsx
- * @input Uses React forwardRef, useRef, useCallback, ReactNode, StyleX, useXDSPopover
+ * @input Uses React, useRef, useCallback, ReactNode, StyleX, useXDSPopover
* @output Exports XDSSideNavHeading component and XDSSideNavHeadingProps
* @position Core implementation; used inside XDSSideNav header slot
*
@@ -16,7 +16,7 @@
'use client';
-import {forwardRef, useCallback, useRef, type ReactNode} from 'react';
+import {useCallback, useRef, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {StyleXStyles} from '@stylexjs/stylex';
import {
@@ -137,6 +137,8 @@ const styles = stylex.create({
// =============================================================================
export interface XDSSideNavHeadingProps {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLDivElement>;
/**
* Product/app icon.
*/
@@ -257,27 +259,22 @@ function ChevronDownIcon() {
* />
* ```
*/
-export const XDSSideNavHeading = forwardRef<
- HTMLDivElement,
- XDSSideNavHeadingProps
->(function XDSSideNavHeading(
- {
- icon,
- heading,
- headingHref,
- superheading,
- superheadingHref,
- subheading,
- subheadingHref,
- menu,
- xstyle,
- className,
- style,
- 'data-testid': testId,
- ...props
- },
+export function XDSSideNavHeading({
+ icon,
+ heading,
+ headingHref,
+ superheading,
+ superheadingHref,
+ subheading,
+ subheadingHref,
+ menu,
+ xstyle,
+ className,
+ style,
+ 'data-testid': testId,
ref,
-) {
+ ...props
+}: XDSSideNavHeadingProps) {
const rootRef = useRef<HTMLDivElement>(null);
const popover = useXDSPopover({
@@ -543,6 +540,6 @@ export const XDSSideNavHeading = forwardRef<
{chevronElement}
</div>
);
-});
+}
XDSSideNavHeading.displayName = 'XDSSideNavHeading';
diff --git a/packages/core/src/SideNav/XDSSideNavItem.tsx b/packages/core/src/SideNav/XDSSideNavItem.tsx
index 28ef6bbacf..b225d07489 100644
--- a/packages/core/src/SideNav/XDSSideNavItem.tsx
+++ b/packages/core/src/SideNav/XDSSideNavItem.tsx
@@ -1,6 +1,6 @@
/**
* @file XDSSideNavItem.tsx
- * @input Uses React forwardRef, ReactNode, StyleX, XDSIcon, XDSIconType
+ * @input Uses React, ReactNode, StyleX, XDSIcon, XDSIconType
* @output Exports XDSSideNavItem component and XDSSideNavItemProps
* @position Core implementation; used inside XDSSideNav children
*
@@ -15,7 +15,7 @@
'use client';
-import {forwardRef, useId, type ReactNode} from 'react';
+import {useId, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import {
colorVars,
@@ -103,6 +103,8 @@ const styles = stylex.create({
// =============================================================================
export interface XDSSideNavItemProps {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLElement>;
/**
* Custom component to render instead of `<a>` for link items.
* Overrides the provider-level default set by XDSLinkProvider.
@@ -177,112 +179,103 @@ export interface XDSSideNavItemProps {
* </XDSSideNavItem>
* ```
*/
-export const XDSSideNavItem = forwardRef<HTMLElement, XDSSideNavItemProps>(
- function XDSSideNavItem(
- {
- as,
- label,
- icon,
- selectedIcon,
- isSelected = false,
- isDisabled = false,
- href,
- onClick,
- endContent,
- children,
- 'data-testid': testId,
- },
- ref,
- ) {
- const id = useId();
- const hasChildren = !!children;
- const LinkComponent = useXDSLinkComponent(as);
-
- const displayIcon = isSelected && selectedIcon ? selectedIcon : icon;
+export function XDSSideNavItem({
+ as,
+ label,
+ icon,
+ selectedIcon,
+ isSelected = false,
+ isDisabled = false,
+ href,
+ onClick,
+ endContent,
+ children,
+ 'data-testid': testId,
+ ref,
+}: XDSSideNavItemProps) {
+ const id = useId();
+ const hasChildren = !!children;
+ const LinkComponent = useXDSLinkComponent(as);
- const handleClick = (e: React.MouseEvent) => {
- if (isDisabled) {
- e.preventDefault();
- return;
- }
- onClick?.(e);
- };
+ const displayIcon = isSelected && selectedIcon ? selectedIcon : icon;
- const itemContent = (
- <>
- {displayIcon && (
- <XDSIcon
- icon={displayIcon}
- size="sm"
- color={
- isSelected ? 'primary' : isDisabled ? 'disabled' : 'secondary'
- }
- />
- )}
- <span {...stylex.props(styles.label)}>{label}</span>
- {endContent && (
- <span {...stylex.props(styles.endContent)}>{endContent}</span>
- )}
- </>
- );
+ const handleClick = (e: React.MouseEvent) => {
+ if (isDisabled) {
+ e.preventDefault();
+ return;
+ }
+ onClick?.(e);
+ };
- const ariaProps = {
- 'aria-current': isSelected ? ('page' as const) : undefined,
- 'aria-disabled': isDisabled || undefined,
- 'data-testid': testId,
- };
+ const itemContent = (
+ <>
+ {displayIcon && (
+ <XDSIcon
+ icon={displayIcon}
+ size="sm"
+ color={isSelected ? 'primary' : isDisabled ? 'disabled' : 'secondary'}
+ />
+ )}
+ <span {...stylex.props(styles.label)}>{label}</span>
+ {endContent && (
+ <span {...stylex.props(styles.endContent)}>{endContent}</span>
+ )}
+ </>
+ );
- const itemElement =
- href && !isDisabled ? (
- <LinkComponent
- ref={ref as React.Ref<HTMLAnchorElement>}
- href={href}
- onClick={handleClick}
- {...ariaProps}
- {...stylex.props(
- styles.item,
- isSelected && styles.selected,
- isDisabled && styles.disabled,
- )}>
- {itemContent}
- </LinkComponent>
- ) : (
- <button
- ref={ref as React.Ref<HTMLButtonElement>}
- type="button"
- onClick={handleClick}
- disabled={isDisabled}
- {...ariaProps}
- {...stylex.props(
- styles.item,
- isSelected && styles.selected,
- isDisabled && styles.disabled,
- )}>
- {itemContent}
- </button>
- );
+ const ariaProps = {
+ 'aria-current': isSelected ? ('page' as const) : undefined,
+ 'aria-disabled': isDisabled || undefined,
+ 'data-testid': testId,
+ };
- return (
- <div
- {...mergeProps(
- xdsClassName('side-nav-item'),
- stylex.props(styles.root),
+ const itemElement =
+ href && !isDisabled ? (
+ <LinkComponent
+ ref={ref as React.Ref<HTMLAnchorElement>}
+ href={href}
+ onClick={handleClick}
+ {...ariaProps}
+ {...stylex.props(
+ styles.item,
+ isSelected && styles.selected,
+ isDisabled && styles.disabled,
+ )}>
+ {itemContent}
+ </LinkComponent>
+ ) : (
+ <button
+ ref={ref as React.Ref<HTMLButtonElement>}
+ type="button"
+ onClick={handleClick}
+ disabled={isDisabled}
+ {...ariaProps}
+ {...stylex.props(
+ styles.item,
+ isSelected && styles.selected,
+ isDisabled && styles.disabled,
)}>
- {itemElement}
- {hasChildren && (
- <div
- role="group"
- aria-labelledby={`${id}-label`}
- {...stylex.props(styles.children)}>
- <span id={`${id}-label`} hidden>
- {label}
- </span>
- {children}
- </div>
- )}
- </div>
+ {itemContent}
+ </button>
);
- },
-);
+
+ return (
+ <div
+ {...mergeProps(xdsClassName('side-nav-item'), stylex.props(styles.root))}>
+ {itemElement}
+ {hasChildren && (
+ <div
+ role="group"
+ aria-labelledby={`${id}-label`}
+ {...stylex.props(styles.children)}>
+ <span id={`${id}-label`} hidden>
+ {label}
+ </span>
+ {children}
+ </div>
+ )}
+ </div>
+ );
+}
XDSSideNavItem.displayName = 'XDSSideNavItem';
diff --git a/packages/core/src/Skeleton/XDSSkeleton.tsx b/packages/core/src/Skeleton/XDSSkeleton.tsx
index 89c16ab2d7..7a3e0a9dee 100644
--- a/packages/core/src/Skeleton/XDSSkeleton.tsx
+++ b/packages/core/src/Skeleton/XDSSkeleton.tsx
@@ -12,7 +12,6 @@
'use client';
-import {forwardRef} from 'react';
import type {XDSBaseProps} from '../XDSBaseProps';
import * as stylex from '@stylexjs/stylex';
import {colorVars, radiusVars} from '../theme/tokens.stylex';
@@ -113,6 +112,8 @@ export type XDSSkeletonRadius = keyof typeof radiusStyles;
// =============================================================================
export interface XDSSkeletonProps extends XDSBaseProps<HTMLDivElement> {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLDivElement>;
/**
* Width of the skeleton.
* Accepts a number (pixels) or string (any CSS value).
@@ -162,42 +163,38 @@ export interface XDSSkeletonProps extends XDSBaseProps<HTMLDivElement> {
* <XDSSkeleton width={280} height={16} index={1} />
* ```
*/
-export const XDSSkeleton = forwardRef<HTMLDivElement, XDSSkeletonProps>(
- (
- {
- width = '100%',
- height = '100%',
- radius: radiusProp = 'container',
- index = 0,
- 'data-testid': testId,
- xstyle,
- className,
- style,
- ...props
- },
- ref,
- ) => {
- return (
- <div
- ref={ref}
- data-testid={testId}
- {...mergeProps(
- xdsClassName('skeleton'),
- stylex.props(
- styles.root,
- styles.animate,
- radiusStyles[radiusProp],
- dynamicStyles.dimensions(width, height),
- dynamicStyles.animationDelay(index),
- xstyle,
- ),
- className,
- style,
- )}
- {...props}
- />
- );
- },
-);
+export function XDSSkeleton({
+ width = '100%',
+ height = '100%',
+ radius: radiusProp = 'container',
+ index = 0,
+ 'data-testid': testId,
+ xstyle,
+ className,
+ style,
+ ref,
+ ...props
+}: XDSSkeletonProps) {
+ return (
+ <div
+ ref={ref}
+ data-testid={testId}
+ {...mergeProps(
+ xdsClassName('skeleton'),
+ stylex.props(
+ styles.root,
+ styles.animate,
+ radiusStyles[radiusProp],
+ dynamicStyles.dimensions(width, height),
+ dynamicStyles.animationDelay(index),
+ xstyle,
+ ),
+ className,
+ style,
+ )}
+ {...props}
+ />
+ );
+}
XDSSkeleton.displayName = 'XDSSkeleton';
diff --git a/packages/core/src/Slider/XDSSlider.tsx b/packages/core/src/Slider/XDSSlider.tsx
index dd02ee88fb..031b42f2da 100644
--- a/packages/core/src/Slider/XDSSlider.tsx
+++ b/packages/core/src/Slider/XDSSlider.tsx
@@ -1,6 +1,6 @@
/**
* @file XDSSlider.tsx
- * @input Uses React forwardRef, useId, useRef, useCallback, XDSField, XDSTooltip
+ * @input Uses React, useId, useRef, useCallback, XDSField, XDSTooltip
* @output Exports XDSSlider component, XDSSliderProps, XDSSliderSingleProps, XDSSliderRangeProps, XDSSliderBaseProps
* @position Core implementation; consumed by index.ts, tested by XDSSlider.test.tsx
*
@@ -14,7 +14,6 @@
'use client';
import {
- forwardRef,
useId,
useRef,
useCallback,
@@ -40,6 +39,8 @@ import type {XDSInputStatus} from '../Field/types';
// =============================================================================
export interface XDSSliderBaseProps {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLDivElement>;
/** Label text for the slider (always rendered for accessibility). */
label: string;
/** Whether to visually hide the label (still accessible to screen readers). @default false */
@@ -317,437 +318,434 @@ function getPercent(val: number, min: number, max: number): number {
* <XDSSlider label="Price range" value={[20, 80]} onChange={setRange} />
* ```
*/
-export const XDSSlider = forwardRef<HTMLDivElement, XDSSliderProps>(
- (props, ref) => {
- const {
- label,
- isLabelHidden = false,
- description,
- isDisabled = false,
- isOptional = false,
- isRequired = false,
- status,
- labelTooltip,
- min = 0,
- max = 100,
- step = 1,
- orientation = 'horizontal',
- formatValue,
- valueDisplay = 'tooltip',
- marks,
- xstyle,
- className,
- style,
- 'data-testid': testId,
- value,
- onChange,
- onChangeEnd,
- } = props;
-
- const isRange = Array.isArray(value);
- const minStepsBetweenThumbs =
- isRange && 'minStepsBetweenThumbs' in props
- ? ((props as XDSSliderRangeProps).minStepsBetweenThumbs ?? 0)
- : 0;
-
- const isHorizontal = orientation === 'horizontal';
-
- const id = useId();
- const descriptionID = useId();
- const statusMessageID = useId();
-
- const trackRef = useRef<HTMLDivElement>(null);
- const draggingThumbRef = useRef<number | null>(null);
-
- // Build aria-describedby
- const describedByParts: string[] = [];
- if (description) describedByParts.push(descriptionID);
- if (status?.message) describedByParts.push(statusMessageID);
- const ariaDescribedBy =
- describedByParts.length > 0 ? describedByParts.join(' ') : undefined;
-
- // Value helpers
- const values: number[] = isRange
- ? (value as [number, number])
- : [value as number];
-
- const getValueFromPosition = useCallback(
- (clientX: number, clientY: number): number => {
- const track = trackRef.current;
- if (!track) return min;
- const rect = track.getBoundingClientRect();
-
- let percent: number;
- if (isHorizontal) {
- percent = (clientX - rect.left) / rect.width;
- } else {
- // Vertical: bottom = min, top = max
- percent = 1 - (clientY - rect.top) / rect.height;
- }
- percent = clamp(percent, 0, 1);
- const raw = min + percent * (max - min);
- return clamp(snapToStep(raw, min, step), min, max);
- },
- [min, max, step, isHorizontal],
- );
+export function XDSSlider({ref, ...props}: XDSSliderProps) {
+ const {
+ label,
+ isLabelHidden = false,
+ description,
+ isDisabled = false,
+ isOptional = false,
+ isRequired = false,
+ status,
+ labelTooltip,
+ min = 0,
+ max = 100,
+ step = 1,
+ orientation = 'horizontal',
+ formatValue,
+ valueDisplay = 'tooltip',
+ marks,
+ xstyle,
+ className,
+ style,
+ 'data-testid': testId,
+ value,
+ onChange,
+ onChangeEnd,
+ } = props;
+
+ const isRange = Array.isArray(value);
+ const minStepsBetweenThumbs =
+ isRange && 'minStepsBetweenThumbs' in props
+ ? ((props as XDSSliderRangeProps).minStepsBetweenThumbs ?? 0)
+ : 0;
+
+ const isHorizontal = orientation === 'horizontal';
+
+ const id = useId();
+ const descriptionID = useId();
+ const statusMessageID = useId();
+
+ const trackRef = useRef<HTMLDivElement>(null);
+ const draggingThumbRef = useRef<number | null>(null);
+
+ // Build aria-describedby
+ const describedByParts: string[] = [];
+ if (description) describedByParts.push(descriptionID);
+ if (status?.message) describedByParts.push(statusMessageID);
+ const ariaDescribedBy =
+ describedByParts.length > 0 ? describedByParts.join(' ') : undefined;
+
+ // Value helpers
+ const values: number[] = isRange
+ ? (value as [number, number])
+ : [value as number];
+
+ const getValueFromPosition = useCallback(
+ (clientX: number, clientY: number): number => {
+ const track = trackRef.current;
+ if (!track) return min;
+ const rect = track.getBoundingClientRect();
+
+ let percent: number;
+ if (isHorizontal) {
+ percent = (clientX - rect.left) / rect.width;
+ } else {
+ // Vertical: bottom = min, top = max
+ percent = 1 - (clientY - rect.top) / rect.height;
+ }
+ percent = clamp(percent, 0, 1);
+ const raw = min + percent * (max - min);
+ return clamp(snapToStep(raw, min, step), min, max);
+ },
+ [min, max, step, isHorizontal],
+ );
+
+ const getClosestThumb = useCallback(
+ (newValue: number): number => {
+ if (!isRange) return 0;
+ const [v0, v1] = values;
+ const d0 = Math.abs(newValue - v0);
+ const d1 = Math.abs(newValue - v1);
+ // Prefer the lower thumb if equidistant
+ return d0 <= d1 ? 0 : 1;
+ },
+ [isRange, values],
+ );
- const getClosestThumb = useCallback(
- (newValue: number): number => {
- if (!isRange) return 0;
- const [v0, v1] = values;
- const d0 = Math.abs(newValue - v0);
- const d1 = Math.abs(newValue - v1);
- // Prefer the lower thumb if equidistant
- return d0 <= d1 ? 0 : 1;
- },
- [isRange, values],
- );
+ const updateValue = useCallback(
+ (thumbIndex: number, newVal: number) => {
+ if (isDisabled) return;
+ const clamped = clamp(snapToStep(newVal, min, step), min, max);
- const updateValue = useCallback(
- (thumbIndex: number, newVal: number) => {
- if (isDisabled) return;
- const clamped = clamp(snapToStep(newVal, min, step), min, max);
-
- if (isRange) {
- const currentValues = [...values] as [number, number];
- currentValues[thumbIndex] = clamped;
-
- // Enforce minStepsBetweenThumbs
- const minGap = minStepsBetweenThumbs * step;
- if (thumbIndex === 0) {
- currentValues[0] = Math.min(
- currentValues[0],
- currentValues[1] - minGap,
- );
- } else {
- currentValues[1] = Math.max(
- currentValues[1],
- currentValues[0] + minGap,
- );
- }
-
- // Keep within bounds
- currentValues[0] = clamp(currentValues[0], min, max);
- currentValues[1] = clamp(currentValues[1], min, max);
-
- (onChange as XDSSliderRangeProps['onChange'])?.(currentValues);
+ if (isRange) {
+ const currentValues = [...values] as [number, number];
+ currentValues[thumbIndex] = clamped;
+
+ // Enforce minStepsBetweenThumbs
+ const minGap = minStepsBetweenThumbs * step;
+ if (thumbIndex === 0) {
+ currentValues[0] = Math.min(
+ currentValues[0],
+ currentValues[1] - minGap,
+ );
} else {
- (onChange as XDSSliderSingleProps['onChange'])?.(clamped);
+ currentValues[1] = Math.max(
+ currentValues[1],
+ currentValues[0] + minGap,
+ );
}
- },
- [
- isDisabled,
- isRange,
- values,
- min,
- max,
- step,
- minStepsBetweenThumbs,
- onChange,
- ],
- );
- const fireChangeEnd = useCallback(() => {
- if (isRange) {
- (onChangeEnd as XDSSliderRangeProps['onChangeEnd'])?.(
- values as unknown as [number, number],
- );
+ // Keep within bounds
+ currentValues[0] = clamp(currentValues[0], min, max);
+ currentValues[1] = clamp(currentValues[1], min, max);
+
+ (onChange as XDSSliderRangeProps['onChange'])?.(currentValues);
} else {
- (onChangeEnd as XDSSliderSingleProps['onChangeEnd'])?.(values[0]);
+ (onChange as XDSSliderSingleProps['onChange'])?.(clamped);
}
- }, [isRange, values, onChangeEnd]);
-
- // Pointer handlers
- const handlePointerDown = useCallback(
- (e: PointerEvent<HTMLDivElement>) => {
- if (isDisabled) return;
- e.preventDefault();
- const newVal = getValueFromPosition(e.clientX, e.clientY);
- const thumbIndex = getClosestThumb(newVal);
- draggingThumbRef.current = thumbIndex;
- updateValue(thumbIndex, newVal);
- if (
- typeof (e.currentTarget as HTMLElement).setPointerCapture ===
- 'function'
- ) {
- (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId);
- }
- },
- [isDisabled, getValueFromPosition, getClosestThumb, updateValue],
- );
-
- const handlePointerMove = useCallback(
- (e: PointerEvent<HTMLDivElement>) => {
- if (draggingThumbRef.current === null || isDisabled) return;
- const newVal = getValueFromPosition(e.clientX, e.clientY);
- updateValue(draggingThumbRef.current, newVal);
- },
- [isDisabled, getValueFromPosition, updateValue],
- );
-
- const handlePointerUp = useCallback(
- (_e: PointerEvent<HTMLDivElement>) => {
- if (draggingThumbRef.current !== null) {
- draggingThumbRef.current = null;
- fireChangeEnd();
- }
- },
- [fireChangeEnd],
- );
+ },
+ [
+ isDisabled,
+ isRange,
+ values,
+ min,
+ max,
+ step,
+ minStepsBetweenThumbs,
+ onChange,
+ ],
+ );
- // Keyboard handler
- const handleKeyDown = useCallback(
- (thumbIndex: number, e: KeyboardEvent<HTMLDivElement>) => {
- if (isDisabled) return;
- const currentVal = values[thumbIndex];
- let newVal = currentVal;
-
- switch (e.key) {
- case 'ArrowRight':
- case 'ArrowUp':
- newVal = currentVal + step;
- break;
- case 'ArrowLeft':
- case 'ArrowDown':
- newVal = currentVal - step;
- break;
- case 'PageUp':
- newVal = currentVal + step * 10;
- break;
- case 'PageDown':
- newVal = currentVal - step * 10;
- break;
- case 'Home':
- newVal = min;
- break;
- case 'End':
- newVal = max;
- break;
- default:
- return;
- }
+ const fireChangeEnd = useCallback(() => {
+ if (isRange) {
+ (onChangeEnd as XDSSliderRangeProps['onChangeEnd'])?.(
+ values as unknown as [number, number],
+ );
+ } else {
+ (onChangeEnd as XDSSliderSingleProps['onChangeEnd'])?.(values[0]);
+ }
+ }, [isRange, values, onChangeEnd]);
+
+ // Pointer handlers
+ const handlePointerDown = useCallback(
+ (e: PointerEvent<HTMLDivElement>) => {
+ if (isDisabled) return;
+ e.preventDefault();
+ const newVal = getValueFromPosition(e.clientX, e.clientY);
+ const thumbIndex = getClosestThumb(newVal);
+ draggingThumbRef.current = thumbIndex;
+ updateValue(thumbIndex, newVal);
+ if (
+ typeof (e.currentTarget as HTMLElement).setPointerCapture === 'function'
+ ) {
+ (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId);
+ }
+ },
+ [isDisabled, getValueFromPosition, getClosestThumb, updateValue],
+ );
+
+ const handlePointerMove = useCallback(
+ (e: PointerEvent<HTMLDivElement>) => {
+ if (draggingThumbRef.current === null || isDisabled) return;
+ const newVal = getValueFromPosition(e.clientX, e.clientY);
+ updateValue(draggingThumbRef.current, newVal);
+ },
+ [isDisabled, getValueFromPosition, updateValue],
+ );
+
+ const handlePointerUp = useCallback(
+ (_e: PointerEvent<HTMLDivElement>) => {
+ if (draggingThumbRef.current !== null) {
+ draggingThumbRef.current = null;
+ fireChangeEnd();
+ }
+ },
+ [fireChangeEnd],
+ );
+
+ // Keyboard handler
+ const handleKeyDown = useCallback(
+ (thumbIndex: number, e: KeyboardEvent<HTMLDivElement>) => {
+ if (isDisabled) return;
+ const currentVal = values[thumbIndex];
+ let newVal = currentVal;
+
+ switch (e.key) {
+ case 'ArrowRight':
+ case 'ArrowUp':
+ newVal = currentVal + step;
+ break;
+ case 'ArrowLeft':
+ case 'ArrowDown':
+ newVal = currentVal - step;
+ break;
+ case 'PageUp':
+ newVal = currentVal + step * 10;
+ break;
+ case 'PageDown':
+ newVal = currentVal - step * 10;
+ break;
+ case 'Home':
+ newVal = min;
+ break;
+ case 'End':
+ newVal = max;
+ break;
+ default:
+ return;
+ }
- e.preventDefault();
- updateValue(thumbIndex, newVal);
- },
- [isDisabled, values, step, min, max, updateValue],
+ e.preventDefault();
+ updateValue(thumbIndex, newVal);
+ },
+ [isDisabled, values, step, min, max, updateValue],
+ );
+
+ // Format display value
+ const displayValue = (val: number): string => {
+ if (formatValue) return formatValue(val);
+ return String(val);
+ };
+
+ // Render a thumb
+ const renderThumb = (thumbIndex: number) => {
+ const val = values[thumbIndex];
+ const percent = getPercent(val, min, max);
+
+ const positionStyle = isHorizontal
+ ? {left: `${percent}%`}
+ : {bottom: `${percent}%`, left: '50%'};
+
+ const thumbLabel = isRange
+ ? thumbIndex === 0
+ ? 'Minimum value'
+ : 'Maximum value'
+ : label;
+
+ const useTooltip = valueDisplay === 'tooltip';
+ const tooltipPlacement = isHorizontal ? 'above' : 'start';
+
+ const thumbElement = (
+ <div
+ key={thumbIndex}
+ role="slider"
+ tabIndex={isDisabled ? -1 : 0}
+ aria-valuemin={min}
+ aria-valuemax={max}
+ aria-valuenow={val}
+ aria-valuetext={formatValue ? formatValue(val) : undefined}
+ aria-orientation={orientation}
+ aria-disabled={isDisabled || undefined}
+ aria-invalid={status?.type === 'error' ? true : undefined}
+ aria-label={thumbLabel}
+ aria-describedby={ariaDescribedBy}
+ style={positionStyle}
+ onKeyDown={e => handleKeyDown(thumbIndex, e)}
+ {...stylex.props(
+ styles.thumb,
+ isHorizontal ? styles.thumbHorizontal : styles.thumbVertical,
+ !isDisabled && styles.thumbHover,
+ !isDisabled && styles.thumbFocusWithin,
+ isDisabled && styles.thumbDisabled,
+ )}
+ />
);
- // Format display value
- const displayValue = (val: number): string => {
- if (formatValue) return formatValue(val);
- return String(val);
- };
-
- // Render a thumb
- const renderThumb = (thumbIndex: number) => {
- const val = values[thumbIndex];
- const percent = getPercent(val, min, max);
-
- const positionStyle = isHorizontal
- ? {left: `${percent}%`}
- : {bottom: `${percent}%`, left: '50%'};
-
- const thumbLabel = isRange
- ? thumbIndex === 0
- ? 'Minimum value'
- : 'Maximum value'
- : label;
-
- const useTooltip = valueDisplay === 'tooltip';
- const tooltipPlacement = isHorizontal ? 'above' : 'start';
-
- const thumbElement = (
- <div
+ if (useTooltip) {
+ return (
+ <XDSTooltip
key={thumbIndex}
- role="slider"
- tabIndex={isDisabled ? -1 : 0}
- aria-valuemin={min}
- aria-valuemax={max}
- aria-valuenow={val}
- aria-valuetext={formatValue ? formatValue(val) : undefined}
- aria-orientation={orientation}
- aria-disabled={isDisabled || undefined}
- aria-invalid={status?.type === 'error' ? true : undefined}
- aria-label={thumbLabel}
- aria-describedby={ariaDescribedBy}
- style={positionStyle}
- onKeyDown={e => handleKeyDown(thumbIndex, e)}
- {...stylex.props(
- styles.thumb,
- isHorizontal ? styles.thumbHorizontal : styles.thumbVertical,
- !isDisabled && styles.thumbHover,
- !isDisabled && styles.thumbFocusWithin,
- isDisabled && styles.thumbDisabled,
- )}
- />
+ content={displayValue(val)}
+ placement={tooltipPlacement}
+ delay={0}
+ focusTrigger="always">
+ {thumbElement}
+ </XDSTooltip>
);
+ }
- if (useTooltip) {
- return (
- <XDSTooltip
- key={thumbIndex}
- content={displayValue(val)}
- placement={tooltipPlacement}
- delay={0}
- focusTrigger="always">
- {thumbElement}
- </XDSTooltip>
- );
- }
+ return thumbElement;
+ };
- return thumbElement;
- };
-
- // Filled track position
- const filledStyle = (() => {
- if (isRange) {
- const [v0, v1] = values;
- const p0 = getPercent(v0, min, max);
- const p1 = getPercent(v1, min, max);
- if (isHorizontal) {
- return {left: `${p0}%`, width: `${p1 - p0}%`};
- }
- return {bottom: `${p0}%`, height: `${p1 - p0}%`};
- }
- const p = getPercent(values[0], min, max);
+ // Filled track position
+ const filledStyle = (() => {
+ if (isRange) {
+ const [v0, v1] = values;
+ const p0 = getPercent(v0, min, max);
+ const p1 = getPercent(v1, min, max);
if (isHorizontal) {
- return {left: '0%', width: `${p}%`};
+ return {left: `${p0}%`, width: `${p1 - p0}%`};
}
- return {bottom: '0%', height: `${p}%`};
- })();
-
- // Text value display
- const textDisplay =
- valueDisplay === 'text' ? (
- <span {...stylex.props(styles.textValue)}>
- {isRange
- ? `${displayValue(values[0])} – ${displayValue(values[1])}`
- : displayValue(values[0])}
- </span>
- ) : null;
-
- return (
- <XDSField
- data-testid={testId}
- label={label}
- isLabelHidden={isLabelHidden}
- description={description}
- inputID={id}
- descriptionID={description ? descriptionID : undefined}
- isOptional={isOptional}
- isRequired={isRequired}
- status={
- status
- ? {
- type: status.type,
- message: status.message,
- messageID: status.message ? statusMessageID : undefined,
- }
- : undefined
- }
- labelTooltip={labelTooltip}
- statusVariant="detached"
- xstyle={xstyle}
- className={className}
- style={style}>
- <div {...stylex.props(styles.sliderRow)}>
+ return {bottom: `${p0}%`, height: `${p1 - p0}%`};
+ }
+ const p = getPercent(values[0], min, max);
+ if (isHorizontal) {
+ return {left: '0%', width: `${p}%`};
+ }
+ return {bottom: '0%', height: `${p}%`};
+ })();
+
+ // Text value display
+ const textDisplay =
+ valueDisplay === 'text' ? (
+ <span {...stylex.props(styles.textValue)}>
+ {isRange
+ ? `${displayValue(values[0])} – ${displayValue(values[1])}`
+ : displayValue(values[0])}
+ </span>
+ ) : null;
+
+ return (
+ <XDSField
+ data-testid={testId}
+ label={label}
+ isLabelHidden={isLabelHidden}
+ description={description}
+ inputID={id}
+ descriptionID={description ? descriptionID : undefined}
+ isOptional={isOptional}
+ isRequired={isRequired}
+ status={
+ status
+ ? {
+ type: status.type,
+ message: status.message,
+ messageID: status.message ? statusMessageID : undefined,
+ }
+ : undefined
+ }
+ labelTooltip={labelTooltip}
+ statusVariant="detached"
+ xstyle={xstyle}
+ className={className}
+ style={style}>
+ <div {...stylex.props(styles.sliderRow)}>
+ <div
+ ref={node => {
+ // Merge refs
+ (
+ trackRef as React.MutableRefObject<HTMLDivElement | null>
+ ).current = node;
+ if (typeof ref === 'function') {
+ ref(node);
+ } else if (ref) {
+ (ref as React.MutableRefObject<HTMLDivElement | null>).current =
+ node;
+ }
+ }}
+ onPointerDown={handlePointerDown}
+ onPointerMove={handlePointerMove}
+ onPointerUp={handlePointerUp}
+ {...stylex.props(
+ styles.trackContainer,
+ isHorizontal
+ ? styles.trackContainerHorizontal
+ : styles.trackContainerVertical,
+ isDisabled && styles.trackContainerDisabled,
+ )}>
+ {/* Background track */}
<div
- ref={node => {
- // Merge refs
- (
- trackRef as React.MutableRefObject<HTMLDivElement | null>
- ).current = node;
- if (typeof ref === 'function') {
- ref(node);
- } else if (ref) {
- (ref as React.MutableRefObject<HTMLDivElement | null>).current =
- node;
- }
- }}
- onPointerDown={handlePointerDown}
- onPointerMove={handlePointerMove}
- onPointerUp={handlePointerUp}
{...stylex.props(
- styles.trackContainer,
+ styles.track,
+ isHorizontal ? styles.trackHorizontal : styles.trackVertical,
+ )}
+ />
+
+ {/* Filled track */}
+ <div
+ style={filledStyle}
+ {...stylex.props(
+ styles.filledTrack,
isHorizontal
- ? styles.trackContainerHorizontal
- : styles.trackContainerVertical,
- isDisabled && styles.trackContainerDisabled,
- )}>
- {/* Background track */}
- <div
- {...stylex.props(
- styles.track,
- isHorizontal ? styles.trackHorizontal : styles.trackVertical,
- )}
- />
+ ? styles.filledTrackHorizontal
+ : styles.filledTrackVertical,
+ )}
+ />
- {/* Filled track */}
+ {/* Marks */}
+ {marks && (
<div
- style={filledStyle}
{...stylex.props(
- styles.filledTrack,
+ styles.marksContainer,
isHorizontal
- ? styles.filledTrackHorizontal
- : styles.filledTrackVertical,
- )}
- />
-
- {/* Marks */}
- {marks && (
- <div
- {...stylex.props(
- styles.marksContainer,
- isHorizontal
- ? styles.marksContainerHorizontal
- : styles.marksContainerVertical,
- )}>
- {marks.map(mark => {
- const percent = getPercent(mark.value, min, max);
- const markPos = isHorizontal
- ? {left: `${percent}%`}
- : {bottom: `${percent}%`};
- return (
- <div key={mark.value}>
- <div
- data-testid="slider-mark"
+ ? styles.marksContainerHorizontal
+ : styles.marksContainerVertical,
+ )}>
+ {marks.map(mark => {
+ const percent = getPercent(mark.value, min, max);
+ const markPos = isHorizontal
+ ? {left: `${percent}%`}
+ : {bottom: `${percent}%`};
+ return (
+ <div key={mark.value}>
+ <div
+ data-testid="slider-mark"
+ style={markPos}
+ {...stylex.props(
+ styles.mark,
+ isHorizontal
+ ? styles.markHorizontal
+ : styles.markVertical,
+ )}
+ />
+ {mark.label && (
+ <span
+ data-testid="slider-mark-label"
style={markPos}
{...stylex.props(
- styles.mark,
+ styles.markLabel,
isHorizontal
- ? styles.markHorizontal
- : styles.markVertical,
- )}
- />
- {mark.label && (
- <span
- data-testid="slider-mark-label"
- style={markPos}
- {...stylex.props(
- styles.markLabel,
- isHorizontal
- ? styles.markLabelHorizontal
- : styles.markLabelVertical,
- )}>
- {mark.label}
- </span>
- )}
- </div>
- );
- })}
- </div>
- )}
-
- {/* Thumbs */}
- {values.map((_, i) => renderThumb(i))}
- </div>
+ ? styles.markLabelHorizontal
+ : styles.markLabelVertical,
+ )}>
+ {mark.label}
+ </span>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ )}
- {textDisplay}
+ {/* Thumbs */}
+ {values.map((_, i) => renderThumb(i))}
</div>
- </XDSField>
- );
- },
-);
+
+ {textDisplay}
+ </div>
+ </XDSField>
+ );
+}
XDSSlider.displayName = 'XDSSlider';
diff --git a/packages/core/src/Spinner/XDSSpinner.tsx b/packages/core/src/Spinner/XDSSpinner.tsx
index 531e9815fe..2997bc7228 100644
--- a/packages/core/src/Spinner/XDSSpinner.tsx
+++ b/packages/core/src/Spinner/XDSSpinner.tsx
@@ -13,7 +13,7 @@
'use client';
-import {forwardRef, useEffect, useRef} from 'react';
+import {useEffect, useRef} from 'react';
import * as stylex from '@stylexjs/stylex';
import {colorVars} from '../theme/tokens.stylex';
import {xdsClassName, mergeProps} from '../utils';
@@ -71,6 +71,8 @@ export type XDSSpinnerSize = keyof typeof SIZES;
export type XDSSpinnerShade = 'default' | 'onMedia';
export interface XDSSpinnerProps {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLSpanElement>;
/**
* Spinner size.
* - 'sm': 10px diameter
@@ -105,81 +107,83 @@ export interface XDSSpinnerProps {
* <XDSSpinner size="lg" shade="onMedia" />
* ```
*/
-export const XDSSpinner = forwardRef<HTMLSpanElement, XDSSpinnerProps>(
- ({size = 'md', shade = 'default', 'data-testid': testId}, ref) => {
- const canvasRef = useRef<HTMLCanvasElement>(null);
-
- useEffect(() => {
- const canvas = canvasRef.current;
- if (canvas == null) return;
-
- const context = canvas.getContext('2d');
- if (!context) return;
-
- const {border, diameter} = SIZES[size];
- const pixelRatio = window.devicePixelRatio || 1;
-
- // Resolve colors from CSS custom properties
- const computedStyle = getComputedStyle(canvas);
- const activeColor =
- shade === 'onMedia'
- ? computedStyle.getPropertyValue(
- colorVars['--color-icon-on-media'],
- ) || '#FFFFFF'
- : computedStyle.getPropertyValue(colorVars['--color-accent']) ||
- '#0064E0';
- const backgroundColor =
- shade === 'onMedia' ? 'rgba(255, 255, 255, 0.3)' : 'rgba(0, 0, 0, 0.1)';
-
- const radius = (diameter / 2) * pixelRatio;
- const lineWidth = border * pixelRatio;
- const frameSize = (radius + lineWidth) * 2;
-
- canvas.height = canvas.width = frameSize;
- canvas.style.width = canvas.style.height = frameSize / pixelRatio + 'px';
-
- context.lineCap = 'round';
- context.lineWidth = lineWidth;
-
- const center = frameSize / 2;
-
- // Background circle (full ring, faded)
- context.beginPath();
- context.arc(center, center, radius, 0, 2 * Math.PI);
- context.strokeStyle = backgroundColor;
- context.stroke();
-
- // Active arc (partial ring, colored)
- context.beginPath();
- context.arc(
- center,
- center,
- radius,
- START_POINT * Math.PI,
- ((START_POINT + SPREAD) % 2) * Math.PI,
- );
- context.strokeStyle = activeColor;
- context.stroke();
- }, [shade, size]);
+export function XDSSpinner({
+ size = 'md',
+ shade = 'default',
+ 'data-testid': testId,
+ ref,
+}: XDSSpinnerProps) {
+ const canvasRef = useRef<HTMLCanvasElement>(null);
+
+ useEffect(() => {
+ const canvas = canvasRef.current;
+ if (canvas == null) return;
+
+ const context = canvas.getContext('2d');
+ if (!context) return;
const {border, diameter} = SIZES[size];
- const frameSize = diameter + border * 2;
-
- return (
- <span
- ref={ref}
- role="status"
- aria-label="Loading"
- data-testid={testId}
- {...mergeProps(
- xdsClassName('spinner', {size}),
- stylex.props(styles.spinner),
- )}
- style={{width: frameSize, height: frameSize}}>
- <canvas ref={canvasRef} {...stylex.props(styles.canvas)} />
- </span>
+ const pixelRatio = window.devicePixelRatio || 1;
+
+ // Resolve colors from CSS custom properties
+ const computedStyle = getComputedStyle(canvas);
+ const activeColor =
+ shade === 'onMedia'
+ ? computedStyle.getPropertyValue(colorVars['--color-icon-on-media']) ||
+ '#FFFFFF'
+ : computedStyle.getPropertyValue(colorVars['--color-accent']) ||
+ '#0064E0';
+ const backgroundColor =
+ shade === 'onMedia' ? 'rgba(255, 255, 255, 0.3)' : 'rgba(0, 0, 0, 0.1)';
+
+ const radius = (diameter / 2) * pixelRatio;
+ const lineWidth = border * pixelRatio;
+ const frameSize = (radius + lineWidth) * 2;
+
+ canvas.height = canvas.width = frameSize;
+ canvas.style.width = canvas.style.height = frameSize / pixelRatio + 'px';
+
+ context.lineCap = 'round';
+ context.lineWidth = lineWidth;
+
+ const center = frameSize / 2;
+
+ // Background circle (full ring, faded)
+ context.beginPath();
+ context.arc(center, center, radius, 0, 2 * Math.PI);
+ context.strokeStyle = backgroundColor;
+ context.stroke();
+
+ // Active arc (partial ring, colored)
+ context.beginPath();
+ context.arc(
+ center,
+ center,
+ radius,
+ START_POINT * Math.PI,
+ ((START_POINT + SPREAD) % 2) * Math.PI,
);
- },
-);
+ context.strokeStyle = activeColor;
+ context.stroke();
+ }, [shade, size]);
+
+ const {border, diameter} = SIZES[size];
+ const frameSize = diameter + border * 2;
+
+ return (
+ <span
+ ref={ref}
+ role="status"
+ aria-label="Loading"
+ data-testid={testId}
+ {...mergeProps(
+ xdsClassName('spinner', {size}),
+ stylex.props(styles.spinner),
+ )}
+ style={{width: frameSize, height: frameSize}}>
+ <canvas ref={canvasRef} {...stylex.props(styles.canvas)} />
+ </span>
+ );
+}
XDSSpinner.displayName = 'XDSSpinner';
diff --git a/packages/core/src/Stack/XDSHStack.tsx b/packages/core/src/Stack/XDSHStack.tsx
index 58b29291e0..1cd76cd802 100644
--- a/packages/core/src/Stack/XDSHStack.tsx
+++ b/packages/core/src/Stack/XDSHStack.tsx
@@ -9,7 +9,6 @@
* - /packages/core/src/Stack/XDSHStack.test.tsx
*/
-import {forwardRef} from 'react';
import {XDSStack, type XDSStackProps} from './XDSStack';
import type {StackCrossAlignment, StackMainAlignment} from './stack.stylex';
@@ -17,6 +16,8 @@ export interface XDSHStackProps extends Omit<
XDSStackProps,
'direction' | 'hAlign' | 'vAlign'
> {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLElement>;
/**
* Horizontal alignment of items (main-axis for horizontal stack).
* - `start`: Align to start (left in LTR)
@@ -47,10 +48,8 @@ export interface XDSHStackProps extends Omit<
* </XDSHStack>
* ```
*/
-export const XDSHStack = forwardRef<HTMLElement, XDSHStackProps>(
- function XDSHStack(props, ref) {
- return <XDSStack {...props} direction="horizontal" ref={ref} />;
- },
-);
+export function XDSHStack({ref, ...props}: XDSHStackProps) {
+ return <XDSStack {...props} direction="horizontal" ref={ref} />;
+}
XDSHStack.displayName = 'XDSHStack';
diff --git a/packages/core/src/Stack/XDSStack.tsx b/packages/core/src/Stack/XDSStack.tsx
index 016219ae88..4cc6a641f7 100644
--- a/packages/core/src/Stack/XDSStack.tsx
+++ b/packages/core/src/Stack/XDSStack.tsx
@@ -1,6 +1,6 @@
/**
* @file XDSStack.tsx
- * @input Uses React forwardRef, ElementType, stack utility
+ * @input Uses React, ElementType, stack utility
* @output Exports XDSStack polymorphic component and XDSStackProps
* @position Layout/Stack component; uses stack.stylex.ts
*
@@ -11,7 +11,6 @@
*/
import {
- forwardRef,
createElement,
type ElementType,
type HTMLAttributes,
@@ -44,6 +43,8 @@ import {xdsClassName, mergeProps} from '../utils';
export type StackAlignment = StackMainAlignment | StackCrossAlignment;
export interface XDSStackProps extends XDSBaseProps<HTMLDivElement> {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLElement>;
/**
* Direction of the stack layout.
* - `horizontal`: Items flow left-to-right (like XDSHStack)
@@ -141,59 +142,55 @@ export interface XDSStackProps extends XDSBaseProps<HTMLDivElement> {
* </XDSStack>
* ```
*/
-export const XDSStack = forwardRef<HTMLElement, XDSStackProps>(
- function XDSStack(
- {
+export function XDSStack({
+ direction,
+ hAlign,
+ vAlign,
+ gap,
+ wrap,
+ element = 'div',
+ xstyle,
+ className,
+ style,
+ children,
+ ref,
+ ...props
+}: XDSStackProps) {
+ // Map hAlign/vAlign to mainAlign/crossAlign based on direction
+ const mainAlign =
+ direction === 'horizontal'
+ ? (hAlign as StackMainAlignment | undefined)
+ : (vAlign as StackMainAlignment | undefined);
+ const crossAlign =
+ direction === 'horizontal'
+ ? (vAlign as StackCrossAlignment | undefined)
+ : (hAlign as StackCrossAlignment | undefined);
+
+ const stylexProps = stylex.props(
+ ...stack({
direction,
- hAlign,
- vAlign,
+ crossAlign,
+ mainAlign,
gap,
wrap,
- element = 'div',
- xstyle,
- className,
- style,
- children,
- ...props
- },
- ref,
- ) {
- // Map hAlign/vAlign to mainAlign/crossAlign based on direction
- const mainAlign =
- direction === 'horizontal'
- ? (hAlign as StackMainAlignment | undefined)
- : (vAlign as StackMainAlignment | undefined);
- const crossAlign =
- direction === 'horizontal'
- ? (vAlign as StackCrossAlignment | undefined)
- : (hAlign as StackCrossAlignment | undefined);
-
- const stylexProps = stylex.props(
- ...stack({
- direction,
- crossAlign,
- mainAlign,
- gap,
- wrap,
- }),
- xstyle,
- );
+ }),
+ xstyle,
+ );
- return createElement(
- element,
- {
- ref: ref as Ref<Element>,
- ...mergeProps(
- xdsClassName('stack', {direction, gap, wrap}),
- stylexProps,
- className,
- style,
- ),
- ...props,
- },
- children,
- );
- },
-);
+ return createElement(
+ element,
+ {
+ ref: ref as Ref<Element>,
+ ...mergeProps(
+ xdsClassName('stack', {direction, gap, wrap}),
+ stylexProps,
+ className,
+ style,
+ ),
+ ...props,
+ },
+ children,
+ );
+}
XDSStack.displayName = 'XDSStack';
diff --git a/packages/core/src/Stack/XDSStackItem.tsx b/packages/core/src/Stack/XDSStackItem.tsx
index b5bcef2b58..83f2b8c228 100644
--- a/packages/core/src/Stack/XDSStackItem.tsx
+++ b/packages/core/src/Stack/XDSStackItem.tsx
@@ -1,6 +1,6 @@
/**
* @file XDSStackItem.tsx
- * @input Uses React forwardRef, ElementType, stackItem utility
+ * @input Uses React, ElementType, stackItem utility
* @output Exports XDSStackItem polymorphic component and XDSStackItemProps
* @position Layout/Stack component; uses stackItem.stylex.ts
*
@@ -11,7 +11,6 @@
*/
import {
- forwardRef,
createElement,
type ElementType,
type HTMLAttributes,
@@ -29,6 +28,8 @@ import {
import {xdsClassName, mergeProps} from '../utils';
export interface XDSStackItemProps extends XDSBaseProps<HTMLDivElement> {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLElement>;
/**
* Overrides the default cross-alignment for this item.
* (hAlign for VStack, vAlign for HStack)
@@ -92,40 +93,36 @@ export interface XDSStackItemProps extends XDSBaseProps<HTMLDivElement> {
* </XDSHStack>
* ```
*/
-export const XDSStackItem = forwardRef<HTMLElement, XDSStackItemProps>(
- function XDSStackItem(
+export function XDSStackItem({
+ crossAlignSelf,
+ size,
+ element = 'div',
+ xstyle,
+ className,
+ style,
+ children,
+ ref,
+ ...props
+}: XDSStackItemProps) {
+ const stylexProps = stylex.props(
+ ...stackItem({crossAlignSelf, size}),
+ xstyle,
+ );
+
+ return createElement(
+ element,
{
- crossAlignSelf,
- size,
- element = 'div',
- xstyle,
- className,
- style,
- children,
- ...props
+ ref: ref as Ref<Element>,
+ ...mergeProps(
+ xdsClassName('stack-item', {size}),
+ stylexProps,
+ className,
+ style,
+ ),
+ ...props,
},
- ref,
- ) {
- const stylexProps = stylex.props(
- ...stackItem({crossAlignSelf, size}),
- xstyle,
- );
-
- return createElement(
- element,
- {
- ref: ref as Ref<Element>,
- ...mergeProps(
- xdsClassName('stack-item', {size}),
- stylexProps,
- className,
- style,
- ),
- ...props,
- },
- children,
- );
- },
-);
+ children,
+ );
+}
XDSStackItem.displayName = 'XDSStackItem';
diff --git a/packages/core/src/Stack/XDSVStack.tsx b/packages/core/src/Stack/XDSVStack.tsx
index dbd0546608..a6914c1dd5 100644
--- a/packages/core/src/Stack/XDSVStack.tsx
+++ b/packages/core/src/Stack/XDSVStack.tsx
@@ -9,7 +9,6 @@
* - /packages/core/src/Stack/XDSVStack.test.tsx
*/
-import {forwardRef} from 'react';
import {XDSStack, type XDSStackProps} from './XDSStack';
import type {StackCrossAlignment, StackMainAlignment} from './stack.stylex';
@@ -17,6 +16,8 @@ export interface XDSVStackProps extends Omit<
XDSStackProps,
'direction' | 'hAlign' | 'vAlign'
> {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLElement>;
/**
* Horizontal alignment of items (cross-axis for vertical stack).
* @default 'stretch'
@@ -47,10 +48,8 @@ export interface XDSVStackProps extends Omit<
* </XDSVStack>
* ```
*/
-export const XDSVStack = forwardRef<HTMLElement, XDSVStackProps>(
- function XDSVStack(props, ref) {
- return <XDSStack {...props} direction="vertical" ref={ref} />;
- },
-);
+export function XDSVStack({ref, ...props}: XDSVStackProps) {
+ return <XDSStack {...props} direction="vertical" ref={ref} />;
+}
XDSVStack.displayName = 'XDSVStack';
diff --git a/packages/core/src/StatusDot/XDSStatusDot.tsx b/packages/core/src/StatusDot/XDSStatusDot.tsx
index 9c70b6e48d..7e47c879cc 100644
--- a/packages/core/src/StatusDot/XDSStatusDot.tsx
+++ b/packages/core/src/StatusDot/XDSStatusDot.tsx
@@ -1,6 +1,6 @@
/**
* @file XDSStatusDot.tsx
- * @input Uses React forwardRef
+ * @input Uses React
* @output Exports XDSStatusDot component, XDSStatusDotProps, XDSStatusDotVariant, XDSStatusDotSize types
* @position Core implementation; consumed by index.ts
*
@@ -11,7 +11,6 @@
* - /apps/storybook/stories/StatusDot.stories.tsx (storybook stories)
*/
-import {forwardRef} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {StyleXStyles} from '@stylexjs/stylex';
import {colorVars} from '../theme/tokens.stylex';
@@ -94,6 +93,8 @@ export type XDSStatusDotVariant = keyof typeof variants;
export type XDSStatusDotSize = 'sm' | 'md';
export interface XDSStatusDotProps {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLSpanElement>;
/**
* The semantic color variant.
*/
@@ -153,42 +154,38 @@ export interface XDSStatusDotProps {
* <XDSStatusDot variant="positive" label="Live" isPulsing />
* ```
*/
-export const XDSStatusDot = forwardRef<HTMLSpanElement, XDSStatusDotProps>(
- (
- {
- variant,
- size = 'md',
- label,
- isPulsing = false,
- xstyle,
- className,
- style,
- ...props
- },
- ref,
- ) => {
- return (
- <span
- ref={ref}
- role="img"
- aria-label={label}
- {...mergeProps(
- xdsClassName('statusdot', {variant, size}),
- stylex.props(
- styles.base,
- sizes[size],
- variants[variant],
- isPulsing && styles.pulsing,
- isPulsing && styles.reducedMotion,
- xstyle,
- ),
- className,
- style,
- )}
- {...props}
- />
- );
- },
-);
+export function XDSStatusDot({
+ variant,
+ size = 'md',
+ label,
+ isPulsing = false,
+ xstyle,
+ className,
+ style,
+ ref,
+ ...props
+}: XDSStatusDotProps) {
+ return (
+ <span
+ ref={ref}
+ role="img"
+ aria-label={label}
+ {...mergeProps(
+ xdsClassName('statusdot', {variant, size}),
+ stylex.props(
+ styles.base,
+ sizes[size],
+ variants[variant],
+ isPulsing && styles.pulsing,
+ isPulsing && styles.reducedMotion,
+ xstyle,
+ ),
+ className,
+ style,
+ )}
+ {...props}
+ />
+ );
+}
XDSStatusDot.displayName = 'XDSStatusDot';
diff --git a/packages/core/src/Switch/XDSSwitch.tsx b/packages/core/src/Switch/XDSSwitch.tsx
index 5b813c5e0b..3e925e2a6d 100644
--- a/packages/core/src/Switch/XDSSwitch.tsx
+++ b/packages/core/src/Switch/XDSSwitch.tsx
@@ -1,6 +1,6 @@
/**
* @file XDSSwitch.tsx
- * @input Uses React forwardRef, useId, ChangeEvent, XDSFieldLabel, XDSFieldStatus, XDSIconType, XDSInputStatus
+ * @input Uses React, useId, ChangeEvent, XDSFieldLabel, XDSFieldStatus, XDSIconType, XDSInputStatus
* @output Exports XDSSwitch component, XDSSwitchProps, XDSSwitchLabelPosition, XDSSwitchLabelSpacing
* @position Core implementation; consumed by index.ts, tested by XDSSwitch.test.tsx
*
@@ -14,7 +14,6 @@
'use client';
import {
- forwardRef,
useId,
useOptimistic,
useTransition,
@@ -156,6 +155,8 @@ export type XDSSwitchLabelPosition = 'start' | 'end';
export type XDSSwitchLabelSpacing = 'default' | 'spread';
export interface XDSSwitchProps extends Omit<XDSBaseProps, 'onChange'> {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLInputElement>;
/**
* Label text for the switch (always rendered for accessibility).
*/
@@ -259,162 +260,158 @@ export interface XDSSwitchProps extends Omit<XDSBaseProps, 'onChange'> {
* />
* ```
*/
-export const XDSSwitch = forwardRef<HTMLInputElement, XDSSwitchProps>(
- (
- {
- label,
- isLabelHidden = false,
- description,
- onChange,
- onChangeAction,
- isLoading = false,
- value,
- isDisabled = false,
- isOptional = false,
- isRequired = false,
- onFocus,
- onBlur,
- labelIcon,
- labelTooltip,
- labelPosition = 'end',
- labelSpacing = 'default',
- status,
- xstyle,
- className,
- style,
- },
- ref,
- ) => {
- const id = useId();
- const descriptionID = useId();
- const statusMessageID = useId();
-
- const [, startTransition] = useTransition();
- const [optimisticValue, setOptimisticValue] = useOptimistic(value);
- const isBusy = isLoading || optimisticValue !== value;
+export function XDSSwitch({
+ label,
+ isLabelHidden = false,
+ description,
+ onChange,
+ onChangeAction,
+ isLoading = false,
+ value,
+ isDisabled = false,
+ isOptional = false,
+ isRequired = false,
+ onFocus,
+ onBlur,
+ labelIcon,
+ labelTooltip,
+ labelPosition = 'end',
+ labelSpacing = 'default',
+ status,
+ xstyle,
+ className,
+ style,
+ ref,
+}: XDSSwitchProps) {
+ const id = useId();
+ const descriptionID = useId();
+ const statusMessageID = useId();
- const isOn = optimisticValue === true;
+ const [, startTransition] = useTransition();
+ const [optimisticValue, setOptimisticValue] = useOptimistic(value);
+ const isBusy = isLoading || optimisticValue !== value;
- // Build aria-describedby from description and status message
- const describedByParts: string[] = [];
- if (description) describedByParts.push(descriptionID);
- if (status?.message) describedByParts.push(statusMessageID);
- const ariaDescribedBy =
- describedByParts.length > 0 ? describedByParts.join(' ') : undefined;
-
- const switchElement = (
- <div {...stylex.props(styles.switchWrapper)}>
- <input
- ref={ref}
- id={id}
- type="checkbox"
- role="switch"
- checked={isOn}
- disabled={isDisabled}
- required={isRequired}
- onChange={e => {
- const checked = e.target.checked;
- onChange?.(checked, e);
- if (onChangeAction && !e.defaultPrevented) {
- startTransition(async () => {
- setOptimisticValue(checked);
- await onChangeAction(checked, e);
- });
- }
- }}
- onFocus={onFocus}
- onBlur={onBlur}
- aria-describedby={ariaDescribedBy}
- aria-invalid={status?.type === 'error' ? true : undefined}
- aria-busy={isBusy || undefined}
- {...stylex.props(styles.input, isDisabled && styles.inputDisabled)}
- />
- <div
- aria-hidden="true"
- {...mergeProps(
- xdsClassName('switch'),
- stylex.props(
- styles.track,
- isOn ? styles.trackOn : styles.trackOff,
- isDisabled && styles.trackDisabled,
- isDisabled && !isOn && styles.trackDisabledOff,
- ),
- )}>
- <div
- {...stylex.props(
- styles.thumb,
- isOn ? styles.thumbOn : styles.thumbOff,
- )}
- style={{
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- }}>
- {isBusy && <XDSSpinner size="sm" />}
- </div>
- </div>
- </div>
- );
+ const isOn = optimisticValue === true;
- const labelElement = (
- <div {...stylex.props(styles.labelWrapper)}>
- <XDSFieldLabel
- label={label}
- inputID={id}
- isLabelHidden={isLabelHidden}
- isDisabled={isDisabled}
- isOptional={isOptional}
- isRequired={isRequired}
- labelIcon={labelIcon}
- labelTooltip={labelTooltip}
- />
- {description && !isLabelHidden && (
- <span id={descriptionID} {...stylex.props(styles.description)}>
- {description}
- </span>
- )}
- </div>
- );
+ // Build aria-describedby from description and status message
+ const describedByParts: string[] = [];
+ if (description) describedByParts.push(descriptionID);
+ if (status?.message) describedByParts.push(statusMessageID);
+ const ariaDescribedBy =
+ describedByParts.length > 0 ? describedByParts.join(' ') : undefined;
- return (
+ const switchElement = (
+ <div {...stylex.props(styles.switchWrapper)}>
+ <input
+ ref={ref}
+ id={id}
+ type="checkbox"
+ role="switch"
+ checked={isOn}
+ disabled={isDisabled}
+ required={isRequired}
+ onChange={e => {
+ const checked = e.target.checked;
+ onChange?.(checked, e);
+ if (onChangeAction && !e.defaultPrevented) {
+ startTransition(async () => {
+ setOptimisticValue(checked);
+ await onChangeAction(checked, e);
+ });
+ }
+ }}
+ onFocus={onFocus}
+ onBlur={onBlur}
+ aria-describedby={ariaDescribedBy}
+ aria-invalid={status?.type === 'error' ? true : undefined}
+ aria-busy={isBusy || undefined}
+ {...stylex.props(styles.input, isDisabled && styles.inputDisabled)}
+ />
<div
+ aria-hidden="true"
{...mergeProps(
- xdsClassName('switch-field'),
- stylex.props(xstyle),
- className,
- style,
+ xdsClassName('switch'),
+ stylex.props(
+ styles.track,
+ isOn ? styles.trackOn : styles.trackOff,
+ isDisabled && styles.trackDisabled,
+ isDisabled && !isOn && styles.trackDisabledOff,
+ ),
)}>
<div
{...stylex.props(
- styles.container,
- labelSpacing === 'spread' && styles.containerSpread,
- !isDisabled && stylex.defaultMarker(),
- )}>
- {labelPosition === 'start' ? (
- <>
- {labelElement}
- {switchElement}
- </>
- ) : (
- <>
- {switchElement}
- {labelElement}
- </>
+ styles.thumb,
+ isOn ? styles.thumbOn : styles.thumbOff,
)}
+ style={{
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ }}>
+ {isBusy && <XDSSpinner size="sm" />}
</div>
- {status?.message && (
- <div {...stylex.props(styles.statusGap)}>
- <XDSFieldStatus
- type={status.type}
- message={status.message}
- id={statusMessageID}
- variant="detached"
- />
- </div>
+ </div>
+ </div>
+ );
+
+ const labelElement = (
+ <div {...stylex.props(styles.labelWrapper)}>
+ <XDSFieldLabel
+ label={label}
+ inputID={id}
+ isLabelHidden={isLabelHidden}
+ isDisabled={isDisabled}
+ isOptional={isOptional}
+ isRequired={isRequired}
+ labelIcon={labelIcon}
+ labelTooltip={labelTooltip}
+ />
+ {description && !isLabelHidden && (
+ <span id={descriptionID} {...stylex.props(styles.description)}>
+ {description}
+ </span>
+ )}
+ </div>
+ );
+
+ return (
+ <div
+ {...mergeProps(
+ xdsClassName('switch-field'),
+ stylex.props(xstyle),
+ className,
+ style,
+ )}>
+ <div
+ {...stylex.props(
+ styles.container,
+ labelSpacing === 'spread' && styles.containerSpread,
+ !isDisabled && stylex.defaultMarker(),
+ )}>
+ {labelPosition === 'start' ? (
+ <>
+ {labelElement}
+ {switchElement}
+ </>
+ ) : (
+ <>
+ {switchElement}
+ {labelElement}
+ </>
)}
</div>
- );
- },
-);
+ {status?.message && (
+ <div {...stylex.props(styles.statusGap)}>
+ <XDSFieldStatus
+ type={status.type}
+ message={status.message}
+ id={statusMessageID}
+ variant="detached"
+ />
+ </div>
+ )}
+ </div>
+ );
+}
XDSSwitch.displayName = 'XDSSwitch';
diff --git a/packages/core/src/Table/XDSBaseTable.tsx b/packages/core/src/Table/XDSBaseTable.tsx
index 0871df46b2..3591d9159f 100644
--- a/packages/core/src/Table/XDSBaseTable.tsx
+++ b/packages/core/src/Table/XDSBaseTable.tsx
@@ -10,13 +10,7 @@
* - /packages/core/src/Table/index.ts (exports if types change)
*/
-import {
- forwardRef,
- memo,
- type ReactElement,
- type ReactNode,
- type Ref,
-} from 'react';
+import {memo, type ReactElement, type ReactNode, type Ref} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {
XDSBaseTableProps,
@@ -184,18 +178,16 @@ const MemoizedTableRow = memo(TableRowInner, areRowPropsEqual) as <
/**
* Inner XDSBaseTable implementation (generic-preserving).
*/
-function XDSBaseTableInner<T extends Record<string, unknown>>(
- {
- data,
- columns: columnsProp,
- idKey,
- plugins: pluginsProp,
- components,
- children,
- tableProps: userTableProps,
- }: XDSBaseTableProps<T>,
- ref: Ref<HTMLTableElement>,
-): ReactElement {
+function XDSBaseTableInner<T extends Record<string, unknown>>({
+ data,
+ columns: columnsProp,
+ idKey,
+ plugins: pluginsProp,
+ components,
+ children,
+ tableProps: userTableProps,
+ ref,
+}: XDSBaseTableProps<T> & {ref?: Ref<HTMLTableElement>}): ReactElement {
// Use stable empty array when no plugins provided
const plugins = pluginsProp ?? (EMPTY_PLUGINS as TablePlugin<T>[]);
@@ -327,7 +319,7 @@ function XDSBaseTableInner<T extends Record<string, unknown>>(
* />
* ```
*/
-export const XDSBaseTable = forwardRef(XDSBaseTableInner) as <
+export const XDSBaseTable = XDSBaseTableInner as <
T extends Record<string, unknown>,
>(
props: XDSBaseTableProps<T> & {ref?: Ref<HTMLTableElement>},
diff --git a/packages/core/src/Table/XDSTable.tsx b/packages/core/src/Table/XDSTable.tsx
index 4a7bea1684..69d207f38a 100644
--- a/packages/core/src/Table/XDSTable.tsx
+++ b/packages/core/src/Table/XDSTable.tsx
@@ -13,7 +13,7 @@
'use client';
-import {forwardRef, useMemo, type ReactElement, type Ref} from 'react';
+import {useMemo, type ReactElement, type Ref} from 'react';
import * as stylex from '@stylexjs/stylex';
import {colorVars} from '../theme/tokens.stylex';
import {XDSBaseTable} from './XDSBaseTable';
@@ -109,19 +109,17 @@ const xdsComponents = {
// XDSTable Component
// =============================================================================
-function XDSTableInner<T extends Record<string, unknown>>(
- {
- density = 'balanced',
- dividers = 'rows',
- isStriped = false,
- hasHover = false,
- plugins: userPlugins,
- columns,
- data,
- ...rest
- }: XDSTableProps<T>,
- ref: Ref<HTMLTableElement>,
-): ReactElement {
+function XDSTableInner<T extends Record<string, unknown>>({
+ density = 'balanced',
+ dividers = 'rows',
+ isStriped = false,
+ hasHover = false,
+ plugins: userPlugins,
+ columns,
+ data,
+ ref,
+ ...rest
+}: XDSTableProps<T> & {ref?: Ref<HTMLTableElement>}): ReactElement {
// Table-level styling plugin (just adds font/color to <table>)
const tablePlugin = useMemo(() => buildTableStylePlugin<T>(), []);
const basePlugins = useMemo(() => [tablePlugin], [tablePlugin]);
@@ -184,9 +182,7 @@ function XDSTableInner<T extends Record<string, unknown>>(
* />
* ```
*/
-export const XDSTable = forwardRef(XDSTableInner) as <
- T extends Record<string, unknown>,
->(
+export const XDSTable = XDSTableInner as <T extends Record<string, unknown>>(
props: XDSTableProps<T> & {ref?: Ref<HTMLTableElement>},
) => ReactElement;
diff --git a/packages/core/src/Table/XDSTableCell.tsx b/packages/core/src/Table/XDSTableCell.tsx
index 80ecf970ea..9e69d36257 100644
--- a/packages/core/src/Table/XDSTableCell.tsx
+++ b/packages/core/src/Table/XDSTableCell.tsx
@@ -11,7 +11,7 @@
'use client';
-import {forwardRef, useContext, type ReactNode} from 'react';
+import {useContext, type ReactNode} from 'react';
import type {XDSBaseProps} from '../XDSBaseProps';
import * as stylex from '@stylexjs/stylex';
import {colorVars, spacingVars, textSizeVars} from '../theme/tokens.stylex';
@@ -21,6 +21,8 @@ import {xdsClassName, mergeProps} from '../utils';
/** Props for XDSTableCell — thin `<td>` wrapper */
export interface XDSTableCellProps extends XDSBaseProps<HTMLTableCellElement> {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLTableCellElement>;
/** Specifies which cells this cell relates to (used on `<td>` acting as a row header). */
scope?: 'col' | 'row' | 'colgroup' | 'rowgroup';
/** Space-separated list of header cell IDs this cell is described by. */
@@ -83,51 +85,51 @@ const dividerColumnStyles = stylex.create({
* </XDSTableRow>
* ```
*/
-export const XDSTableCell = forwardRef<HTMLTableCellElement, XDSTableCellProps>(
- ({children, xstyle, ...props}, ref) => {
- const ctx = useContext(XDSTableContext);
-
- if (!ctx) {
- return (
- <td
- ref={ref}
- {...props}
- {...mergeProps(xdsClassName('table-cell'), stylex.props(xstyle))}>
- {children}
- </td>
- );
- }
-
- const cellStyles: StyleXStyles[] = [densityStyles[ctx.density]];
-
- if (ctx.dividers === 'rows' || ctx.dividers === 'grid') {
- cellStyles.push(dividerRowStyles.cell);
- }
-
- if (ctx.dividers === 'columns' || ctx.dividers === 'grid') {
- cellStyles.push(dividerColumnStyles.cell);
- }
-
- if (xstyle) {
- if (Array.isArray(xstyle)) {
- cellStyles.push(...xstyle);
- } else {
- cellStyles.push(xstyle);
- }
- }
+export function XDSTableCell({
+ children,
+ xstyle,
+ ref,
+ ...props
+}: XDSTableCellProps) {
+ const ctx = useContext(XDSTableContext);
+ if (!ctx) {
return (
<td
ref={ref}
{...props}
- {...mergeProps(
- xdsClassName('table-cell'),
- stylex.props(...cellStyles),
- )}>
+ {...mergeProps(xdsClassName('table-cell'), stylex.props(xstyle))}>
{children}
</td>
);
- },
-);
+ }
+
+ const cellStyles: StyleXStyles[] = [densityStyles[ctx.density]];
+
+ if (ctx.dividers === 'rows' || ctx.dividers === 'grid') {
+ cellStyles.push(dividerRowStyles.cell);
+ }
+
+ if (ctx.dividers === 'columns' || ctx.dividers === 'grid') {
+ cellStyles.push(dividerColumnStyles.cell);
+ }
+
+ if (xstyle) {
+ if (Array.isArray(xstyle)) {
+ cellStyles.push(...xstyle);
+ } else {
+ cellStyles.push(xstyle);
+ }
+ }
+
+ return (
+ <td
+ ref={ref}
+ {...props}
+ {...mergeProps(xdsClassName('table-cell'), stylex.props(...cellStyles))}>
+ {children}
+ </td>
+ );
+}
XDSTableCell.displayName = 'XDSTableCell';
diff --git a/packages/core/src/Table/XDSTableHeaderCell.tsx b/packages/core/src/Table/XDSTableHeaderCell.tsx
index 2ca3270737..c8c9758649 100644
--- a/packages/core/src/Table/XDSTableHeaderCell.tsx
+++ b/packages/core/src/Table/XDSTableHeaderCell.tsx
@@ -11,7 +11,7 @@
'use client';
-import {forwardRef, useContext, type ReactNode} from 'react';
+import {useContext, type ReactNode} from 'react';
import type {XDSBaseProps} from '../XDSBaseProps';
import * as stylex from '@stylexjs/stylex';
import {
@@ -26,6 +26,8 @@ import {xdsClassName, mergeProps} from '../utils';
/** Props for XDSTableHeaderCell — `<th>` wrapper with context-aware styling */
export interface XDSTableHeaderCellProps extends XDSBaseProps<HTMLTableCellElement> {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLTableCellElement>;
/** Specifies which cells this header relates to. */
scope?: 'col' | 'row' | 'colgroup' | 'rowgroup';
children?: ReactNode;
@@ -99,10 +101,12 @@ const dividerColumnStyles = stylex.create({
* </thead>
* ```
*/
-export const XDSTableHeaderCell = forwardRef<
- HTMLTableCellElement,
- XDSTableHeaderCellProps
->(({children, xstyle, ...props}, ref) => {
+export function XDSTableHeaderCell({
+ children,
+ xstyle,
+ ref,
+ ...props
+}: XDSTableHeaderCellProps) {
const ctx = useContext(XDSTableContext);
if (!ctx) {
@@ -148,6 +152,6 @@ export const XDSTableHeaderCell = forwardRef<
{children}
</th>
);
-});
+}
XDSTableHeaderCell.displayName = 'XDSTableHeaderCell';
diff --git a/packages/core/src/Table/XDSTableRow.tsx b/packages/core/src/Table/XDSTableRow.tsx
index 4dd3d17b00..f3e898b82f 100644
--- a/packages/core/src/Table/XDSTableRow.tsx
+++ b/packages/core/src/Table/XDSTableRow.tsx
@@ -11,7 +11,7 @@
'use client';
-import {forwardRef, useContext, type ReactNode} from 'react';
+import {useContext, type ReactNode} from 'react';
import type {XDSBaseProps} from '../XDSBaseProps';
import * as stylex from '@stylexjs/stylex';
import {colorVars, transitionVars} from '../theme/tokens.stylex';
@@ -21,6 +21,8 @@ import {xdsClassName, mergeProps} from '../utils';
/** Props for XDSTableRow — thin `<tr>` wrapper */
export interface XDSTableRowProps extends XDSBaseProps<HTMLTableRowElement> {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLTableRowElement>;
children: ReactNode;
xstyle?: StyleXStyles[];
}
@@ -86,50 +88,53 @@ const _lastBodyRowStyles = stylex.create({
* </XDSTable>
* ```
*/
-export const XDSTableRow = forwardRef<HTMLTableRowElement, XDSTableRowProps>(
- ({children, xstyle, ...props}, ref) => {
- const ctx = useContext(XDSTableContext);
-
- if (!ctx) {
- return (
- <tr
- ref={ref}
- {...props}
- {...mergeProps(xdsClassName('table-row'), stylex.props(xstyle))}>
- {children}
- </tr>
- );
- }
-
- const rowStyles: StyleXStyles[] = [];
-
- // Handle striped + hover combination to avoid backgroundColor conflicts
- if (ctx.isStriped && ctx.hasHover) {
- rowStyles.push(stripedHoverRowStyles.row);
- } else if (ctx.isStriped) {
- rowStyles.push(stripedRowStyles.row);
- } else if (ctx.hasHover) {
- rowStyles.push(hoverRowStyles.row);
- }
-
- if (ctx.dividers === 'rows' || ctx.dividers === 'grid') {
- // Note: last-body-row border removal is handled by XDSTableCell
- // to avoid affecting the header row in <thead>.
- }
-
- if (xstyle) {
- rowStyles.push(...xstyle);
- }
+export function XDSTableRow({
+ children,
+ xstyle,
+ ref,
+ ...props
+}: XDSTableRowProps) {
+ const ctx = useContext(XDSTableContext);
+ if (!ctx) {
return (
<tr
ref={ref}
{...props}
- {...mergeProps(xdsClassName('table-row'), stylex.props(...rowStyles))}>
+ {...mergeProps(xdsClassName('table-row'), stylex.props(xstyle))}>
{children}
</tr>
);
- },
-);
+ }
+
+ const rowStyles: StyleXStyles[] = [];
+
+ // Handle striped + hover combination to avoid backgroundColor conflicts
+ if (ctx.isStriped && ctx.hasHover) {
+ rowStyles.push(stripedHoverRowStyles.row);
+ } else if (ctx.isStriped) {
+ rowStyles.push(stripedRowStyles.row);
+ } else if (ctx.hasHover) {
+ rowStyles.push(hoverRowStyles.row);
+ }
+
+ if (ctx.dividers === 'rows' || ctx.dividers === 'grid') {
+ // Note: last-body-row border removal is handled by XDSTableCell
+ // to avoid affecting the header row in <thead>.
+ }
+
+ if (xstyle) {
+ rowStyles.push(...xstyle);
+ }
+
+ return (
+ <tr
+ ref={ref}
+ {...props}
+ {...mergeProps(xdsClassName('table-row'), stylex.props(...rowStyles))}>
+ {children}
+ </tr>
+ );
+}
XDSTableRow.displayName = 'XDSTableRow';
diff --git a/packages/core/src/Text/XDSHeading.tsx b/packages/core/src/Text/XDSHeading.tsx
index a07f915d79..2c3fb237a8 100644
--- a/packages/core/src/Text/XDSHeading.tsx
+++ b/packages/core/src/Text/XDSHeading.tsx
@@ -1,6 +1,6 @@
/**
* @file XDSHeading.tsx
- * @input Uses React forwardRef, HTMLAttributes, ReactNode
+ * @input Uses React, HTMLAttributes, ReactNode
* @output Exports XDSHeading component, XDSHeadingProps, XDSHeadingLevel, XDSHeadingVariant types
* @position Core implementation; consumed by index.ts, tested by XDSHeading.test.tsx
*
@@ -13,14 +13,7 @@
'use client';
-import {
- forwardRef,
- lazy,
- Suspense,
- useCallback,
- useRef,
- type ReactNode,
-} from 'react';
+import {lazy, Suspense, useCallback, useRef, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {StyleXStyles} from '@stylexjs/stylex';
import type {
@@ -58,6 +51,8 @@ export type XDSHeadingLevel = 1 | 2 | 3 | 4 | 5 | 6;
export type XDSHeadingVariant = 'default' | 'editorial';
export interface XDSHeadingProps {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLHeadingElement>;
/**
* Visual heading level (1-6). Determines styling from theme.
* Required to ensure intentional visual hierarchy.
@@ -194,126 +189,122 @@ const levelToTag = {
* <XDSHeading level={3} color="secondary">Muted Heading</XDSHeading>
* ```
*/
-export const XDSHeading = forwardRef<HTMLHeadingElement, XDSHeadingProps>(
- function XDSHeading(
- {
- level,
- accessibilityLevel,
- variant = 'default',
- color = 'primary',
- display = 'block',
- maxLines = 0,
- hasTruncateTooltip = true,
- wordBreak,
- textWrap,
- hasCapsize = false,
- hasStrikethrough = false,
- xstyle,
- className,
- style,
- children,
- ...props
- },
- forwardedRef,
- ) {
- const Component = levelToTag[level];
+export function XDSHeading({
+ level,
+ accessibilityLevel,
+ variant = 'default',
+ color = 'primary',
+ display = 'block',
+ maxLines = 0,
+ hasTruncateTooltip = true,
+ wordBreak,
+ textWrap,
+ hasCapsize = false,
+ hasStrikethrough = false,
+ xstyle,
+ className,
+ style,
+ children,
+ ref,
+ ...props
+}: XDSHeadingProps) {
+ const Component = levelToTag[level];
- // If accessibilityLevel differs from visual level, use aria-level
- const ariaProps =
- accessibilityLevel && accessibilityLevel !== level
- ? {'aria-level': accessibilityLevel}
- : {};
+ // If accessibilityLevel differs from visual level, use aria-level
+ const ariaProps =
+ accessibilityLevel && accessibilityLevel !== level
+ ? {'aria-level': accessibilityLevel}
+ : {};
- // Resolve wordBreak with smart default
- const resolvedWordBreak =
- wordBreak ?? (maxLines === 1 ? 'break-all' : 'break-word');
+ // Resolve wordBreak with smart default
+ const resolvedWordBreak =
+ wordBreak ?? (maxLines === 1 ? 'break-all' : 'break-word');
- // Resolve display - force block when maxLines > 0 or hasCapsize
- const resolvedDisplay = maxLines > 0 || hasCapsize ? 'block' : display;
+ // Resolve display - force block when maxLines > 0 or hasCapsize
+ const resolvedDisplay = maxLines > 0 || hasCapsize ? 'block' : display;
- // Truncation detection
- const truncation = useTruncation({maxLines});
+ // Truncation detection
+ const truncation = useTruncation({maxLines});
- // Tooltip for truncated text
- const tooltipPlacement: LayerPlacement =
- typeof hasTruncateTooltip === 'string' ? hasTruncateTooltip : 'above';
- const tooltipEnabled =
- maxLines > 0 && hasTruncateTooltip !== false && truncation.isTruncated;
+ // Tooltip for truncated text
+ const tooltipPlacement: LayerPlacement =
+ typeof hasTruncateTooltip === 'string' ? hasTruncateTooltip : 'above';
+ const tooltipEnabled =
+ maxLines > 0 && hasTruncateTooltip !== false && truncation.isTruncated;
- // Ref for the heading element (used as tooltip anchor)
- const headingRef = useRef<HTMLHeadingElement>(null);
+ // Ref for the heading element (used as tooltip anchor)
+ const headingRef = useRef<HTMLHeadingElement>(null);
- // Merge refs: forwardedRef, truncation.ref, headingRef
- const mergedRef = useCallback(
- (element: HTMLHeadingElement | null) => {
- // Forward ref
- if (typeof forwardedRef === 'function') {
- forwardedRef(element);
- } else if (forwardedRef) {
- forwardedRef.current = element;
- }
- // Truncation ref
- truncation.ref(element);
- // Local ref for tooltip anchor
- (
- headingRef as React.MutableRefObject<HTMLHeadingElement | null>
- ).current = element;
- },
- [forwardedRef, truncation.ref],
- );
+ // Merge refs: ref, truncation.ref, headingRef
+ const mergedRef = useCallback(
+ (element: HTMLHeadingElement | null) => {
+ // Forward ref
+ if (typeof ref === 'function') {
+ ref(element);
+ } else if (ref) {
+ ref.current = element;
+ }
+ // Truncation ref
+ truncation.ref(element);
+ // Local ref for tooltip anchor
+ (
+ headingRef as React.MutableRefObject<HTMLHeadingElement | null>
+ ).current = element;
+ },
+ [ref, truncation.ref],
+ );
- // Build inline style for -webkit-line-clamp (dynamic value)
- const inlineStyle = maxLines > 1 ? {WebkitLineClamp: maxLines} : undefined;
+ // Build inline style for -webkit-line-clamp (dynamic value)
+ const inlineStyle = maxLines > 1 ? {WebkitLineClamp: maxLines} : undefined;
- return (
- <>
- <Component
- ref={mergedRef}
- {...mergeProps(
- xdsClassName('heading', {variant, level}),
- stylex.props(
- colorStyles[color],
- // Display: use truncation styles when maxLines > 0
- maxLines === 1
- ? truncationStyles.singleLine
- : maxLines > 1
- ? truncationStyles.multiLine
- : displayStyles[resolvedDisplay],
- // Word break when truncating
- maxLines > 0 && wordBreakStyles[resolvedWordBreak],
- // Text wrap
- textWrap && textWrapStyles[textWrap],
- // Capsize
- hasCapsize && capsizeStyles.enabled,
- // Decorations
- hasStrikethrough && decorationStyles.strikethrough,
- // User xstyle
- xstyle,
- ),
- className,
- {...style, ...inlineStyle},
- )}
- title={tooltipEnabled ? truncation.fullText : undefined}
- {...ariaProps}
- {...props}>
- {children}
- </Component>
- {tooltipEnabled && (
- <Suspense fallback={null}>
- <LazyXDSTooltip
- anchorRef={headingRef}
- content={
- <span {...stylex.props(truncationTooltipStyles.content)}>
- {truncation.fullText}
- </span>
- }
- placement={tooltipPlacement}
- />
- </Suspense>
+ return (
+ <>
+ <Component
+ ref={mergedRef}
+ {...mergeProps(
+ xdsClassName('heading', {variant, level}),
+ stylex.props(
+ colorStyles[color],
+ // Display: use truncation styles when maxLines > 0
+ maxLines === 1
+ ? truncationStyles.singleLine
+ : maxLines > 1
+ ? truncationStyles.multiLine
+ : displayStyles[resolvedDisplay],
+ // Word break when truncating
+ maxLines > 0 && wordBreakStyles[resolvedWordBreak],
+ // Text wrap
+ textWrap && textWrapStyles[textWrap],
+ // Capsize
+ hasCapsize && capsizeStyles.enabled,
+ // Decorations
+ hasStrikethrough && decorationStyles.strikethrough,
+ // User xstyle
+ xstyle,
+ ),
+ className,
+ {...style, ...inlineStyle},
)}
- </>
- );
- },
-);
+ title={tooltipEnabled ? truncation.fullText : undefined}
+ {...ariaProps}
+ {...props}>
+ {children}
+ </Component>
+ {tooltipEnabled && (
+ <Suspense fallback={null}>
+ <LazyXDSTooltip
+ anchorRef={headingRef}
+ content={
+ <span {...stylex.props(truncationTooltipStyles.content)}>
+ {truncation.fullText}
+ </span>
+ }
+ placement={tooltipPlacement}
+ />
+ </Suspense>
+ )}
+ </>
+ );
+}
XDSHeading.displayName = 'XDSHeading';
diff --git a/packages/core/src/Text/XDSText.tsx b/packages/core/src/Text/XDSText.tsx
index ce14b56ef6..093f99209a 100644
--- a/packages/core/src/Text/XDSText.tsx
+++ b/packages/core/src/Text/XDSText.tsx
@@ -1,6 +1,6 @@
/**
* @file XDSText.tsx
- * @input Uses React forwardRef, HTMLAttributes, ReactNode
+ * @input Uses React, HTMLAttributes, ReactNode
* @output Exports XDSText component, XDSTextProps, XDSTextType, XDSTextSize types
* @position Core implementation; consumed by index.ts, tested by XDSText.test.tsx
*
@@ -13,14 +13,7 @@
'use client';
-import {
- forwardRef,
- lazy,
- Suspense,
- useCallback,
- useRef,
- type ReactNode,
-} from 'react';
+import {lazy, Suspense, useCallback, useRef, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {StyleXStyles} from '@stylexjs/stylex';
import type {
@@ -55,6 +48,8 @@ const LazyXDSTooltip = lazy(() =>
export type {XDSTextType, XDSTextSize};
export interface XDSTextProps {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLElement>;
/**
* Semantic text type. Determines size, weight, and line-height from theme.
* Required to ensure semantic usage.
@@ -195,29 +190,27 @@ const defaultColorByType: Record<XDSTextType, XDSTextColor> = {
* <XDSText type="body" color="secondary" weight="bold">Styled text</XDSText>
* ```
*/
-export const XDSText = forwardRef<HTMLElement, XDSTextProps>(function XDSText(
- {
- type,
- size: _size,
- color,
- weight,
- display = 'inline',
- maxLines = 0,
- hasTruncateTooltip = true,
- wordBreak,
- textWrap,
- hasCapsize = false,
- hasStrikethrough = false,
- hasTabularNumbers = false,
- xstyle,
- className,
- style,
- as: Component = 'span',
- children,
- ...props
- },
- forwardedRef,
-) {
+export function XDSText({
+ type,
+ size: _size,
+ color,
+ weight,
+ display = 'inline',
+ maxLines = 0,
+ hasTruncateTooltip = true,
+ wordBreak,
+ textWrap,
+ hasCapsize = false,
+ hasStrikethrough = false,
+ hasTabularNumbers = false,
+ xstyle,
+ className,
+ style,
+ as: Component = 'span',
+ children,
+ ref,
+ ...props
+}: XDSTextProps) {
// Resolve color with type-based default
const resolvedColor = color ?? defaultColorByType[type];
@@ -240,21 +233,21 @@ export const XDSText = forwardRef<HTMLElement, XDSTextProps>(function XDSText(
// Ref for the text element (used as tooltip anchor)
const textRef = useRef<HTMLElement>(null);
- // Merge refs: forwardedRef, truncation.ref, textRef
+ // Merge refs: ref, truncation.ref, textRef
const mergedRef = useCallback(
(element: HTMLElement | null) => {
// Forward ref
- if (typeof forwardedRef === 'function') {
- forwardedRef(element);
- } else if (forwardedRef) {
- forwardedRef.current = element;
+ if (typeof ref === 'function') {
+ ref(element);
+ } else if (ref) {
+ ref.current = element;
}
// Truncation ref
truncation.ref(element);
// Local ref for tooltip anchor
(textRef as React.MutableRefObject<HTMLElement | null>).current = element;
},
- [forwardedRef, truncation.ref],
+ [ref, truncation.ref],
);
// Build inline style for -webkit-line-clamp (dynamic value)
@@ -309,6 +302,6 @@ export const XDSText = forwardRef<HTMLElement, XDSTextProps>(function XDSText(
)}
</>
);
-});
+}
XDSText.displayName = 'XDSText';
diff --git a/packages/core/src/TextArea/XDSTextArea.tsx b/packages/core/src/TextArea/XDSTextArea.tsx
index 64594b885b..7e30c76050 100644
--- a/packages/core/src/TextArea/XDSTextArea.tsx
+++ b/packages/core/src/TextArea/XDSTextArea.tsx
@@ -1,6 +1,6 @@
/**
* @file XDSTextArea.tsx
- * @input Uses React forwardRef, useId, ChangeEvent, ClipboardEvent, XDSField, XDSIcon
+ * @input Uses React, useId, ChangeEvent, ClipboardEvent, XDSField, XDSIcon
* @output Exports XDSTextArea component, XDSTextAreaProps, XDSTextAreaStatus, XDSTextAreaStatusType
* @position Core implementation; consumed by index.ts, tested by XDSTextArea.test.tsx
*
@@ -14,7 +14,6 @@
'use client';
import {
- forwardRef,
useId,
useOptimistic,
useTransition,
@@ -95,6 +94,8 @@ export interface XDSTextAreaStatus {
}
export interface XDSTextAreaProps {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLTextAreaElement>;
/**
* Label text for the textarea (always rendered for accessibility).
*/
@@ -197,146 +198,142 @@ export interface XDSTextAreaProps {
* <XDSTextArea label="Notes" rows={5} value={notes} onChange={setNotes} />
* ```
*/
-export const XDSTextArea = forwardRef<HTMLTextAreaElement, XDSTextAreaProps>(
- (
- {
- label,
- isLabelHidden = false,
- description,
- isOptional = false,
- isRequired = false,
- onChange,
- onChangeAction,
- isLoading = false,
- value,
- placeholder,
- rows = 3,
- isDisabled = false,
- status,
- labelTooltip,
- startIcon,
- hasSpellCheck = true,
- onPaste,
- maxLength,
- hasAutoFocus = false,
- htmlName,
- },
- ref,
- ) => {
- const id = useId();
- const descriptionID = useId();
- const statusMessageID = useId();
+export function XDSTextArea({
+ label,
+ isLabelHidden = false,
+ description,
+ isOptional = false,
+ isRequired = false,
+ onChange,
+ onChangeAction,
+ isLoading = false,
+ value,
+ placeholder,
+ rows = 3,
+ isDisabled = false,
+ status,
+ labelTooltip,
+ startIcon,
+ hasSpellCheck = true,
+ onPaste,
+ maxLength,
+ hasAutoFocus = false,
+ htmlName,
+ ref,
+}: XDSTextAreaProps) {
+ const id = useId();
+ const descriptionID = useId();
+ const statusMessageID = useId();
- const [, startTransition] = useTransition();
- const [optimisticValue, setOptimisticValue] = useOptimistic(value);
- const isBusy = isLoading || optimisticValue !== value;
+ const [, startTransition] = useTransition();
+ const [optimisticValue, setOptimisticValue] = useOptimistic(value);
+ const isBusy = isLoading || optimisticValue !== value;
- const statusIconMap: Record<XDSTextAreaStatusType, XDSIconName> = {
- warning: 'warning',
- error: 'xCircle',
- success: 'checkCircle',
- };
+ const statusIconMap: Record<XDSTextAreaStatusType, XDSIconName> = {
+ warning: 'warning',
+ error: 'xCircle',
+ success: 'checkCircle',
+ };
- const statusIconColorMap: Record<
- XDSTextAreaStatusType,
- 'warning' | 'negative' | 'positive'
- > = {
- warning: 'warning',
- error: 'negative',
- success: 'positive',
- };
+ const statusIconColorMap: Record<
+ XDSTextAreaStatusType,
+ 'warning' | 'negative' | 'positive'
+ > = {
+ warning: 'warning',
+ error: 'negative',
+ success: 'positive',
+ };
- const ariaDescribedBy =
- [
- description ? descriptionID : null,
- status?.message ? statusMessageID : null,
- ]
- .filter(Boolean)
- .join(' ') || undefined;
+ const ariaDescribedBy =
+ [
+ description ? descriptionID : null,
+ status?.message ? statusMessageID : null,
+ ]
+ .filter(Boolean)
+ .join(' ') || undefined;
- const handleChange = (e: ChangeEvent<HTMLTextAreaElement>) => {
- const newValue = e.target.value;
- onChange?.(newValue, e);
- if (onChangeAction && !e.defaultPrevented) {
- startTransition(async () => {
- setOptimisticValue(newValue);
- await onChangeAction(newValue, e);
- });
- }
- };
+ const handleChange = (e: ChangeEvent<HTMLTextAreaElement>) => {
+ const newValue = e.target.value;
+ onChange?.(newValue, e);
+ if (onChangeAction && !e.defaultPrevented) {
+ startTransition(async () => {
+ setOptimisticValue(newValue);
+ await onChangeAction(newValue, e);
+ });
+ }
+ };
- return (
- <XDSField
- label={label}
- isLabelHidden={isLabelHidden}
- description={description}
- inputID={id}
- descriptionID={description ? descriptionID : undefined}
- isOptional={isOptional}
- isRequired={isRequired}
- status={
- status
- ? {
- type: status.type,
- message: status.message,
- messageID: status.message ? statusMessageID : undefined,
- }
- : undefined
- }
- labelTooltip={labelTooltip}>
+ return (
+ <XDSField
+ label={label}
+ isLabelHidden={isLabelHidden}
+ description={description}
+ inputID={id}
+ descriptionID={description ? descriptionID : undefined}
+ isOptional={isOptional}
+ isRequired={isRequired}
+ status={
+ status
+ ? {
+ type: status.type,
+ message: status.message,
+ messageID: status.message ? statusMessageID : undefined,
+ }
+ : undefined
+ }
+ labelTooltip={labelTooltip}>
+ <div
+ {...stylex.props(
+ inputWrapperStyles.base,
+ styles.wrapper,
+ isDisabled && inputWrapperStyles.disabled,
+ status && inputStatusBorderStyles[status.type],
+ status && inputStatusHoverShadowStyles[status.type],
+ status && inputStatusFocusWithinStyles[status.type],
+ )}>
+ {startIcon && <XDSIcon icon={startIcon} size="sm" color="primary" />}
+ <textarea
+ ref={ref}
+ id={id}
+ name={htmlName}
+ value={String(optimisticValue)}
+ onChange={handleChange}
+ onPaste={onPaste}
+ placeholder={placeholder}
+ rows={rows}
+ disabled={isDisabled}
+ spellCheck={hasSpellCheck}
+ maxLength={maxLength}
+ autoFocus={hasAutoFocus}
+ aria-describedby={ariaDescribedBy}
+ aria-required={isRequired === true ? 'true' : undefined}
+ aria-invalid={status?.type === 'error' ? 'true' : undefined}
+ aria-busy={isBusy || undefined}
+ {...stylex.props(
+ styles.textarea,
+ isDisabled && styles.textareaDisabled,
+ )}
+ />
+ {isBusy && <XDSSpinner size="sm" />}
+ {status && (
+ <XDSIcon
+ icon={statusIconMap[status.type]}
+ size="md"
+ color={statusIconColorMap[status.type]}
+ />
+ )}
+ </div>
+ {maxLength != null && (
<div
{...stylex.props(
- inputWrapperStyles.base,
- styles.wrapper,
- isDisabled && inputWrapperStyles.disabled,
- status && inputStatusBorderStyles[status.type],
- status && inputStatusHoverShadowStyles[status.type],
- status && inputStatusFocusWithinStyles[status.type],
+ styles.counter,
+ value.length > maxLength && styles.counterError,
)}>
- {startIcon && <XDSIcon icon={startIcon} size="sm" color="primary" />}
- <textarea
- ref={ref}
- id={id}
- name={htmlName}
- value={String(optimisticValue)}
- onChange={handleChange}
- onPaste={onPaste}
- placeholder={placeholder}
- rows={rows}
- disabled={isDisabled}
- spellCheck={hasSpellCheck}
- maxLength={maxLength}
- autoFocus={hasAutoFocus}
- aria-describedby={ariaDescribedBy}
- aria-required={isRequired === true ? 'true' : undefined}
- aria-invalid={status?.type === 'error' ? 'true' : undefined}
- aria-busy={isBusy || undefined}
- {...stylex.props(
- styles.textarea,
- isDisabled && styles.textareaDisabled,
- )}
- />
- {isBusy && <XDSSpinner size="sm" />}
- {status && (
- <XDSIcon
- icon={statusIconMap[status.type]}
- size="md"
- color={statusIconColorMap[status.type]}
- />
- )}
+ {value.length}/{maxLength}
</div>
- {maxLength != null && (
- <div
- {...stylex.props(
- styles.counter,
- value.length > maxLength && styles.counterError,
- )}>
- {value.length}/{maxLength}
- </div>
- )}
- </XDSField>
- );
- },
-);
+ )}
+ </XDSField>
+ );
+}
XDSTextArea.displayName = 'XDSTextArea';
diff --git a/packages/core/src/TextInput/XDSTextInput.tsx b/packages/core/src/TextInput/XDSTextInput.tsx
index c11fe9f510..7ec54984bd 100644
--- a/packages/core/src/TextInput/XDSTextInput.tsx
+++ b/packages/core/src/TextInput/XDSTextInput.tsx
@@ -1,6 +1,6 @@
/**
* @file XDSTextInput.tsx
- * @input Uses React forwardRef, useId, ChangeEvent, XDSField, XDSIcon
+ * @input Uses React, useId, ChangeEvent, XDSField, XDSIcon
* @output Exports XDSTextInput component, XDSTextInputProps
* @position Core implementation; consumed by index.ts, tested by XDSTextInput.test.tsx
*
@@ -13,13 +13,7 @@
'use client';
-import {
- forwardRef,
- useId,
- useOptimistic,
- useTransition,
- type ChangeEvent,
-} from 'react';
+import {useId, useOptimistic, useTransition, type ChangeEvent} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {XDSIconName} from '../Icon';
import {
@@ -94,6 +88,8 @@ export interface XDSTextInputProps extends Omit<
XDSBaseProps,
'onChange' | 'defaultValue'
> {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLInputElement>;
/**
* Label text for the input (always rendered for accessibility).
*/
@@ -184,138 +180,134 @@ export interface XDSTextInputProps extends Omit<
* <XDSTextInput label="Search" isLabelHidden value={query} onChange={setQuery} />
* ```
*/
-export const XDSTextInput = forwardRef<HTMLInputElement, XDSTextInputProps>(
- (
- {
- label,
- isLabelHidden = false,
- description,
- isOptional = false,
- isRequired = false,
- isDisabled = false,
- startIcon,
- status,
- size = 'md',
- onChange,
- onChangeAction,
- isLoading = false,
- value,
- placeholder,
- labelTooltip,
- hasAutoFocus = false,
- htmlName,
- xstyle,
- className,
- style,
- },
- ref,
- ) => {
- const id = useId();
- const descriptionID = useId();
- const statusMessageID = useId();
+export function XDSTextInput({
+ label,
+ isLabelHidden = false,
+ description,
+ isOptional = false,
+ isRequired = false,
+ isDisabled = false,
+ startIcon,
+ status,
+ size = 'md',
+ onChange,
+ onChangeAction,
+ isLoading = false,
+ value,
+ placeholder,
+ labelTooltip,
+ hasAutoFocus = false,
+ htmlName,
+ xstyle,
+ className,
+ style,
+ ref,
+}: XDSTextInputProps) {
+ const id = useId();
+ const descriptionID = useId();
+ const statusMessageID = useId();
- const [, startTransition] = useTransition();
- const [optimisticValue, setOptimisticValue] = useOptimistic(value);
- const isBusy = isLoading || optimisticValue !== value;
+ const [, startTransition] = useTransition();
+ const [optimisticValue, setOptimisticValue] = useOptimistic(value);
+ const isBusy = isLoading || optimisticValue !== value;
- const statusIconMap: Record<XDSInputStatusType, XDSIconName> = {
- warning: 'warning',
- error: 'xCircle',
- success: 'checkCircle',
- };
+ const statusIconMap: Record<XDSInputStatusType, XDSIconName> = {
+ warning: 'warning',
+ error: 'xCircle',
+ success: 'checkCircle',
+ };
- const statusIconColorMap: Record<
- XDSInputStatusType,
- 'warning' | 'negative' | 'positive'
- > = {
- warning: 'warning',
- error: 'negative',
- success: 'positive',
- };
+ const statusIconColorMap: Record<
+ XDSInputStatusType,
+ 'warning' | 'negative' | 'positive'
+ > = {
+ warning: 'warning',
+ error: 'negative',
+ success: 'positive',
+ };
- const ariaDescribedBy =
- [
- description ? descriptionID : null,
- status?.message ? statusMessageID : null,
- ]
- .filter(Boolean)
- .join(' ') || undefined;
+ const ariaDescribedBy =
+ [
+ description ? descriptionID : null,
+ status?.message ? statusMessageID : null,
+ ]
+ .filter(Boolean)
+ .join(' ') || undefined;
- const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
- const newValue = e.target.value;
- onChange?.(newValue, e);
- if (onChangeAction && !e.defaultPrevented) {
- startTransition(async () => {
- setOptimisticValue(newValue);
- await onChangeAction(newValue, e);
- });
- }
- };
+ const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
+ const newValue = e.target.value;
+ onChange?.(newValue, e);
+ if (onChangeAction && !e.defaultPrevented) {
+ startTransition(async () => {
+ setOptimisticValue(newValue);
+ await onChangeAction(newValue, e);
+ });
+ }
+ };
- return (
- <XDSField
- label={label}
- isLabelHidden={isLabelHidden}
- description={description}
- inputID={id}
- descriptionID={description ? descriptionID : undefined}
- isOptional={isOptional}
- isRequired={isRequired}
- status={
- status
- ? {
- type: status.type,
- message: status.message,
- messageID: status.message ? statusMessageID : undefined,
- }
- : undefined
- }
- labelTooltip={labelTooltip}>
- <div
- {...mergeProps(
- xdsClassName('text-input', {size}),
- stylex.props(
- inputWrapperStyles.base,
- styles.wrapper,
- sizeStyles[size],
- isDisabled && inputWrapperStyles.disabled,
- status && inputStatusBorderStyles[status.type],
- status && inputStatusHoverShadowStyles[status.type],
- status && inputStatusFocusWithinStyles[status.type],
- xstyle,
- ),
- className,
- style,
- )}>
- {startIcon && <XDSIcon icon={startIcon} size="sm" color="primary" />}
- <input
- ref={ref}
- id={id}
- name={htmlName}
- type="text"
- value={String(optimisticValue)}
- onChange={handleChange}
- placeholder={placeholder}
- disabled={isDisabled}
- autoFocus={hasAutoFocus}
- aria-describedby={ariaDescribedBy}
- aria-required={isRequired === true ? 'true' : undefined}
- aria-invalid={status?.type === 'error' ? 'true' : undefined}
- aria-busy={isBusy || undefined}
- {...stylex.props(styles.input, isDisabled && styles.inputDisabled)}
+ return (
+ <XDSField
+ label={label}
+ isLabelHidden={isLabelHidden}
+ description={description}
+ inputID={id}
+ descriptionID={description ? descriptionID : undefined}
+ isOptional={isOptional}
+ isRequired={isRequired}
+ status={
+ status
+ ? {
+ type: status.type,
+ message: status.message,
+ messageID: status.message ? statusMessageID : undefined,
+ }
+ : undefined
+ }
+ labelTooltip={labelTooltip}>
+ <div
+ {...mergeProps(
+ xdsClassName('text-input', {size}),
+ stylex.props(
+ inputWrapperStyles.base,
+ styles.wrapper,
+ sizeStyles[size],
+ isDisabled && inputWrapperStyles.disabled,
+ status && inputStatusBorderStyles[status.type],
+ status && inputStatusHoverShadowStyles[status.type],
+ status && inputStatusFocusWithinStyles[status.type],
+ xstyle,
+ ),
+ className,
+ style,
+ )}>
+ {startIcon && <XDSIcon icon={startIcon} size="sm" color="primary" />}
+ <input
+ ref={ref}
+ id={id}
+ name={htmlName}
+ type="text"
+ value={String(optimisticValue)}
+ onChange={handleChange}
+ placeholder={placeholder}
+ disabled={isDisabled}
+ autoFocus={hasAutoFocus}
+ aria-describedby={ariaDescribedBy}
+ aria-required={isRequired === true ? 'true' : undefined}
+ aria-invalid={status?.type === 'error' ? 'true' : undefined}
+ aria-busy={isBusy || undefined}
+ {...stylex.props(styles.input, isDisabled && styles.inputDisabled)}
+ />
+ {isBusy && <XDSSpinner size="sm" />}
+ {status && (
+ <XDSIcon
+ icon={statusIconMap[status.type]}
+ size="md"
+ color={statusIconColorMap[status.type]}
/>
- {isBusy && <XDSSpinner size="sm" />}
- {status && (
- <XDSIcon
- icon={statusIconMap[status.type]}
- size="md"
- color={statusIconColorMap[status.type]}
- />
- )}
- </div>
- </XDSField>
- );
- },
-);
+ )}
+ </div>
+ </XDSField>
+ );
+}
XDSTextInput.displayName = 'XDSTextInput';
diff --git a/packages/core/src/TimeInput/XDSTimeInput.tsx b/packages/core/src/TimeInput/XDSTimeInput.tsx
index 2c7b0cc509..f81c08faa0 100644
--- a/packages/core/src/TimeInput/XDSTimeInput.tsx
+++ b/packages/core/src/TimeInput/XDSTimeInput.tsx
@@ -1,6 +1,6 @@
/**
* @file XDSTimeInput.tsx
- * @input Uses React forwardRef, useId, useState, useEffect, useCallback, useRef, XDSField, XDSIcon
+ * @input Uses React, useId, useState, useEffect, useCallback, useRef, XDSField, XDSIcon
* @output Exports XDSTimeInput component, XDSTimeInputProps
* @position Core implementation; consumed by index.ts, tested by XDSTimeInput.test.tsx
*
@@ -14,7 +14,6 @@
'use client';
import {
- forwardRef,
useId,
useState,
useCallback,
@@ -129,6 +128,8 @@ export type {
} from '../Field';
export interface XDSTimeInputProps {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLInputElement>;
/**
* Label text for the input (required for accessibility).
*/
@@ -262,294 +263,290 @@ export interface XDSTimeInputProps {
* />
* ```
*/
-export const XDSTimeInput = forwardRef<HTMLInputElement, XDSTimeInputProps>(
- (
- {
- label,
- isLabelHidden = false,
- description,
- isOptional = false,
- isRequired = false,
- isDisabled = false,
- value,
- onChange,
- onChangeAction,
- isLoading = false,
- min,
- max,
- hasSeconds = false,
- hasClear = false,
- hourFormat = '12h',
- increment = 1,
- placeholder = 'Select a time',
- size = 'md',
- status,
- labelTooltip,
- },
- ref,
- ) => {
- const id = useId();
- const descriptionID = useId();
- const statusMessageID = useId();
- const inputRef = useRef<HTMLInputElement | null>(null);
-
- const [, startTransition] = useTransition();
- const [optimisticValue, setOptimisticValue] = useOptimistic(value);
- const isBusy = isLoading || optimisticValue !== value;
-
- // Status icon mapping
- const statusIconMap: Record<XDSInputStatusType, XDSIconName> = {
- warning: 'warning',
- error: 'xCircle',
- success: 'checkCircle',
- };
-
- const statusIconColorMap: Record<
- XDSInputStatusType,
- 'warning' | 'negative' | 'positive'
- > = {
- warning: 'warning',
- error: 'negative',
- success: 'positive',
- };
-
- const ariaDescribedBy =
- [
- description ? descriptionID : null,
- status?.message ? statusMessageID : null,
- ]
- .filter(Boolean)
- .join(' ') || undefined;
-
- // Pending input while user is typing (null = show formatted value)
- const [pendingInput, setPendingInput] = useState<string | null>(null);
- const [isFocused, setIsFocused] = useState(false);
-
- // Format function based on hourFormat
- const formatDisplayTime =
- hourFormat === '12h' ? formatDisplayTime12h : formatDisplayTime24h;
-
- // Unified change handler that fires both onChange and onChangeAction
- const fireChange = useCallback(
- (newValue: ISOTimeString | undefined) => {
- onChange?.(newValue);
- if (onChangeAction) {
- startTransition(async () => {
- setOptimisticValue(newValue);
- await onChangeAction(newValue);
- });
- }
- },
- [onChange, onChangeAction, startTransition, setOptimisticValue],
- );
-
- // Display value: pending input if typing, otherwise formatted value
- const displayValue = useMemo(() => {
- if (pendingInput !== null) {
- return pendingInput;
+export function XDSTimeInput({
+ label,
+ isLabelHidden = false,
+ description,
+ isOptional = false,
+ isRequired = false,
+ isDisabled = false,
+ value,
+ onChange,
+ onChangeAction,
+ isLoading = false,
+ min,
+ max,
+ hasSeconds = false,
+ hasClear = false,
+ hourFormat = '12h',
+ increment = 1,
+ placeholder = 'Select a time',
+ size = 'md',
+ status,
+ labelTooltip,
+ ref,
+}: XDSTimeInputProps) {
+ const id = useId();
+ const descriptionID = useId();
+ const statusMessageID = useId();
+ const inputRef = useRef<HTMLInputElement | null>(null);
+
+ const [, startTransition] = useTransition();
+ const [optimisticValue, setOptimisticValue] = useOptimistic(value);
+ const isBusy = isLoading || optimisticValue !== value;
+
+ // Status icon mapping
+ const statusIconMap: Record<XDSInputStatusType, XDSIconName> = {
+ warning: 'warning',
+ error: 'xCircle',
+ success: 'checkCircle',
+ };
+
+ const statusIconColorMap: Record<
+ XDSInputStatusType,
+ 'warning' | 'negative' | 'positive'
+ > = {
+ warning: 'warning',
+ error: 'negative',
+ success: 'positive',
+ };
+
+ const ariaDescribedBy =
+ [
+ description ? descriptionID : null,
+ status?.message ? statusMessageID : null,
+ ]
+ .filter(Boolean)
+ .join(' ') || undefined;
+
+ // Pending input while user is typing (null = show formatted value)
+ const [pendingInput, setPendingInput] = useState<string | null>(null);
+ const [isFocused, setIsFocused] = useState(false);
+
+ // Format function based on hourFormat
+ const formatDisplayTime =
+ hourFormat === '12h' ? formatDisplayTime12h : formatDisplayTime24h;
+
+ // Unified change handler that fires both onChange and onChangeAction
+ const fireChange = useCallback(
+ (newValue: ISOTimeString | undefined) => {
+ onChange?.(newValue);
+ if (onChangeAction) {
+ startTransition(async () => {
+ setOptimisticValue(newValue);
+ await onChangeAction(newValue);
+ });
}
- return optimisticValue
- ? formatDisplayTime(optimisticValue, hasSeconds)
- : '';
- }, [pendingInput, value, formatDisplayTime, hasSeconds]);
-
- // Check if current input is valid (for styling purposes)
- const isInputValid = useMemo(() => {
- // Only check pending input for validity styling
- if (pendingInput === null || !pendingInput.trim()) {
- return true;
+ },
+ [onChange, onChangeAction, startTransition, setOptimisticValue],
+ );
+
+ // Display value: pending input if typing, otherwise formatted value
+ const displayValue = useMemo(() => {
+ if (pendingInput !== null) {
+ return pendingInput;
+ }
+ return optimisticValue
+ ? formatDisplayTime(optimisticValue, hasSeconds)
+ : '';
+ }, [pendingInput, value, formatDisplayTime, hasSeconds]);
+
+ // Check if current input is valid (for styling purposes)
+ const isInputValid = useMemo(() => {
+ // Only check pending input for validity styling
+ if (pendingInput === null || !pendingInput.trim()) {
+ return true;
+ }
+ const parsed = parseTimeInput(pendingInput, hasSeconds);
+ if (!parsed) {
+ return false;
+ }
+ // Also check min/max range
+ return isTimeInRange(parsed, min, max);
+ }, [pendingInput, hasSeconds, min, max]);
+
+ // Placeholder that shows format hint when focused and empty
+ const displayPlaceholder = useMemo(() => {
+ if (isFocused && !displayValue) {
+ return hourFormat === '12h' ? 'e.g., 2:30 PM' : 'e.g., 14:30';
+ }
+ return placeholder;
+ }, [isFocused, displayValue, hourFormat, placeholder]);
+
+ // Handle input text change - update immediately if valid
+ const handleInputChange = useCallback(
+ (e: React.ChangeEvent<HTMLInputElement>) => {
+ const newValue = e.target.value;
+ setPendingInput(newValue);
+
+ // If the input is valid, update immediately (don't wait for blur)
+ const parsed = parseTimeInput(newValue, hasSeconds);
+ if (parsed && isTimeInRange(parsed, min, max) && parsed !== value) {
+ fireChange(parsed);
}
- const parsed = parseTimeInput(pendingInput, hasSeconds);
- if (!parsed) {
- return false;
+ },
+ [hasSeconds, min, max, value, fireChange],
+ );
+
+ // Handle focus
+ const handleFocus = useCallback(() => {
+ setIsFocused(true);
+ }, []);
+
+ // Handle blur - validate and clear pending input
+ const handleBlur = useCallback(
+ (_e: FocusEvent<HTMLInputElement>) => {
+ setIsFocused(false);
+
+ if (pendingInput === null) {
+ return;
}
- // Also check min/max range
- return isTimeInRange(parsed, min, max);
- }, [pendingInput, hasSeconds, min, max]);
-
- // Placeholder that shows format hint when focused and empty
- const displayPlaceholder = useMemo(() => {
- if (isFocused && !displayValue) {
- return hourFormat === '12h' ? 'e.g., 2:30 PM' : 'e.g., 14:30';
+
+ if (!pendingInput.trim()) {
+ // Empty input clears the value
+ if (value !== undefined) {
+ fireChange(undefined);
+ }
+ setPendingInput(null);
+ return;
}
- return placeholder;
- }, [isFocused, displayValue, hourFormat, placeholder]);
-
- // Handle input text change - update immediately if valid
- const handleInputChange = useCallback(
- (e: React.ChangeEvent<HTMLInputElement>) => {
- const newValue = e.target.value;
- setPendingInput(newValue);
-
- // If the input is valid, update immediately (don't wait for blur)
- const parsed = parseTimeInput(newValue, hasSeconds);
- if (parsed && isTimeInRange(parsed, min, max) && parsed !== value) {
+
+ const parsed = parseTimeInput(pendingInput, hasSeconds);
+ if (parsed && isTimeInRange(parsed, min, max)) {
+ // Valid time - update if different
+ if (parsed !== value) {
fireChange(parsed);
}
- },
- [hasSeconds, min, max, value, fireChange],
- );
-
- // Handle focus
- const handleFocus = useCallback(() => {
- setIsFocused(true);
- }, []);
-
- // Handle blur - validate and clear pending input
- const handleBlur = useCallback(
- (_e: FocusEvent<HTMLInputElement>) => {
- setIsFocused(false);
-
- if (pendingInput === null) {
- return;
+ }
+ // Clear pending input - display will revert to formatted value
+ setPendingInput(null);
+ },
+ [pendingInput, value, fireChange, hasSeconds, min, max],
+ );
+
+ // Handle keyboard navigation on input
+ const handleInputKeyDown = useCallback(
+ (e: KeyboardEvent<HTMLInputElement>) => {
+ if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {
+ e.preventDefault();
+
+ // Get current time or default to now
+ let currentTime = value;
+ if (!currentTime) {
+ const now = new Date();
+ currentTime = formatISOTime(
+ {
+ hour: now.getHours(),
+ minute: now.getMinutes(),
+ second: now.getSeconds(),
+ },
+ hasSeconds,
+ );
}
- if (!pendingInput.trim()) {
- // Empty input clears the value
- if (value !== undefined) {
- fireChange(undefined);
- }
- setPendingInput(null);
- return;
- }
+ const delta = e.key === 'ArrowUp' ? increment : -increment;
+ const newTime = adjustTime(currentTime, delta, hasSeconds);
- const parsed = parseTimeInput(pendingInput, hasSeconds);
- if (parsed && isTimeInRange(parsed, min, max)) {
- // Valid time - update if different
- if (parsed !== value) {
- fireChange(parsed);
- }
+ // Check if within range
+ if (isTimeInRange(newTime, min, max)) {
+ fireChange(newTime);
}
- // Clear pending input - display will revert to formatted value
- setPendingInput(null);
- },
- [pendingInput, value, fireChange, hasSeconds, min, max],
- );
-
- // Handle keyboard navigation on input
- const handleInputKeyDown = useCallback(
- (e: KeyboardEvent<HTMLInputElement>) => {
- if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {
- e.preventDefault();
-
- // Get current time or default to now
- let currentTime = value;
- if (!currentTime) {
- const now = new Date();
- currentTime = formatISOTime(
- {
- hour: now.getHours(),
- minute: now.getMinutes(),
- second: now.getSeconds(),
- },
- hasSeconds,
- );
- }
-
- const delta = e.key === 'ArrowUp' ? increment : -increment;
- const newTime = adjustTime(currentTime, delta, hasSeconds);
-
- // Check if within range
- if (isTimeInRange(newTime, min, max)) {
- fireChange(newTime);
- }
- }
- },
- [value, hasSeconds, increment, min, max, fireChange],
- );
-
- // Handle clear button click
- const handleClear = useCallback(() => {
- fireChange(undefined);
- inputRef.current?.focus();
- }, [fireChange]);
-
- // Combine refs
- const setRefs = useCallback(
- (el: HTMLInputElement | null) => {
- inputRef.current = el;
- if (typeof ref === 'function') {
- ref(el);
- } else if (ref) {
- ref.current = el;
- }
- },
- [ref],
- );
-
- return (
- <XDSField
- label={label}
- isLabelHidden={isLabelHidden}
- description={description}
- inputID={id}
- descriptionID={description ? descriptionID : undefined}
- isOptional={isOptional}
- isRequired={isRequired}
- status={
- status
- ? {
- type: status.type,
- message: status.message,
- messageID: status.message ? statusMessageID : undefined,
- }
- : undefined
- }
- labelTooltip={labelTooltip}>
- <div
+ }
+ },
+ [value, hasSeconds, increment, min, max, fireChange],
+ );
+
+ // Handle clear button click
+ const handleClear = useCallback(() => {
+ fireChange(undefined);
+ inputRef.current?.focus();
+ }, [fireChange]);
+
+ // Combine refs
+ const setRefs = useCallback(
+ (el: HTMLInputElement | null) => {
+ inputRef.current = el;
+ if (typeof ref === 'function') {
+ ref(el);
+ } else if (ref) {
+ ref.current = el;
+ }
+ },
+ [ref],
+ );
+
+ return (
+ <XDSField
+ label={label}
+ isLabelHidden={isLabelHidden}
+ description={description}
+ inputID={id}
+ descriptionID={description ? descriptionID : undefined}
+ isOptional={isOptional}
+ isRequired={isRequired}
+ status={
+ status
+ ? {
+ type: status.type,
+ message: status.message,
+ messageID: status.message ? statusMessageID : undefined,
+ }
+ : undefined
+ }
+ labelTooltip={labelTooltip}>
+ <div
+ {...stylex.props(
+ inputWrapperStyles.base,
+ sizeStyles[size],
+ isDisabled && inputWrapperStyles.disabled,
+ status && inputStatusBorderStyles[status.type],
+ status && inputStatusHoverShadowStyles[status.type],
+ status && inputStatusFocusWithinStyles[status.type],
+ )}>
+ <div {...stylex.props(styles.icon)}>
+ <XDSIcon icon="clock" size="sm" color="secondary" />
+ </div>
+ <input
+ ref={setRefs}
+ id={id}
+ type="text"
+ value={displayValue}
+ onChange={handleInputChange}
+ onFocus={handleFocus}
+ onBlur={handleBlur}
+ onKeyDown={handleInputKeyDown}
+ placeholder={displayPlaceholder}
+ disabled={isDisabled}
+ aria-describedby={ariaDescribedBy}
+ aria-required={isRequired === true ? 'true' : undefined}
+ aria-invalid={status?.type === 'error' ? 'true' : undefined}
+ aria-busy={isBusy || undefined}
{...stylex.props(
- inputWrapperStyles.base,
- sizeStyles[size],
- isDisabled && inputWrapperStyles.disabled,
- status && inputStatusBorderStyles[status.type],
- status && inputStatusHoverShadowStyles[status.type],
- status && inputStatusFocusWithinStyles[status.type],
- )}>
- <div {...stylex.props(styles.icon)}>
- <XDSIcon icon="clock" size="sm" color="secondary" />
- </div>
- <input
- ref={setRefs}
- id={id}
- type="text"
- value={displayValue}
- onChange={handleInputChange}
- onFocus={handleFocus}
- onBlur={handleBlur}
- onKeyDown={handleInputKeyDown}
- placeholder={displayPlaceholder}
- disabled={isDisabled}
- aria-describedby={ariaDescribedBy}
- aria-required={isRequired === true ? 'true' : undefined}
- aria-invalid={status?.type === 'error' ? 'true' : undefined}
- aria-busy={isBusy || undefined}
- {...stylex.props(
- styles.input,
- isDisabled && styles.inputDisabled,
- !isInputValid && styles.inputInvalid,
- )}
- />
- {isBusy && <XDSSpinner size="sm" />}
- {hasClear && value && !isDisabled && (
- <button
- type="button"
- onClick={handleClear}
- aria-label="Clear time"
- {...stylex.props(styles.clearButton)}>
- <XDSIcon icon="close" size="sm" color="secondary" />
- </button>
- )}
- {status && (
- <XDSIcon
- icon={statusIconMap[status.type]}
- size="md"
- color={statusIconColorMap[status.type]}
- />
+ styles.input,
+ isDisabled && styles.inputDisabled,
+ !isInputValid && styles.inputInvalid,
)}
- </div>
- </XDSField>
- );
- },
-);
+ />
+ {isBusy && <XDSSpinner size="sm" />}
+ {hasClear && value && !isDisabled && (
+ <button
+ type="button"
+ onClick={handleClear}
+ aria-label="Clear time"
+ {...stylex.props(styles.clearButton)}>
+ <XDSIcon icon="close" size="sm" color="secondary" />
+ </button>
+ )}
+ {status && (
+ <XDSIcon
+ icon={statusIconMap[status.type]}
+ size="md"
+ color={statusIconColorMap[status.type]}
+ />
+ )}
+ </div>
+ </XDSField>
+ );
+}
XDSTimeInput.displayName = 'XDSTimeInput';
diff --git a/packages/core/src/Token/XDSToken.tsx b/packages/core/src/Token/XDSToken.tsx
index 5e06be3334..dc90ead3c3 100644
--- a/packages/core/src/Token/XDSToken.tsx
+++ b/packages/core/src/Token/XDSToken.tsx
@@ -1,6 +1,6 @@
/**
* @file XDSToken.tsx
- * @input Uses React forwardRef, ReactNode, StyleXStyles
+ * @input Uses React, ReactNode, StyleXStyles
* @output Exports XDSToken component, XDSTokenProps, XDSTokenColor types
* @position Core implementation; consumed by index.ts, tested by XDSToken.test.tsx
*
@@ -11,7 +11,7 @@
* - /apps/storybook/stories/Token.stories.tsx (storybook stories)
*/
-import {forwardRef, type ReactNode} from 'react';
+import {type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {StyleXStyles} from '@stylexjs/stylex';
import {
@@ -50,6 +50,8 @@ export type XDSTokenColor =
export type XDSTokenSize = 'sm' | 'md';
export interface XDSTokenProps {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLElement>;
/**
* The text label displayed in the token.
*/
@@ -316,143 +318,90 @@ const colorStyles = stylex.create({
* <XDSToken label="Link" href="/path" />
* ```
*/
-export const XDSToken = forwardRef<HTMLElement, XDSTokenProps>(
- (
- {
- label,
- size = 'md',
- color = 'default',
- icon,
- isDisabled = false,
- onRemove,
- onClick,
- href,
- description,
- endContent,
- isLabelHidden = false,
- xstyle,
- className,
- style,
- 'data-testid': testId,
- },
- ref,
- ) => {
- const content = (
- <>
- {icon}
- <span
- {...stylex.props(styles.label, isLabelHidden && styles.labelHidden)}>
- {label}
- </span>
- {endContent}
- {onRemove != null && (
- <button
- type="button"
- aria-label={`Remove ${label}`}
- onClick={e => {
- e.stopPropagation();
- onRemove(e);
- }}
- disabled={isDisabled}
- {...stylex.props(styles.removeButton)}>
- <XDSIcon icon="close" size="xsm" color="inherit" />
- </button>
- )}
- </>
- );
-
- const sharedProps = {
- 'data-testid': testId,
- 'aria-label': isLabelHidden ? label : undefined,
- 'aria-description': description,
- };
+export function XDSToken({
+ label,
+ size = 'md',
+ color = 'default',
+ icon,
+ isDisabled = false,
+ onRemove,
+ onClick,
+ href,
+ description,
+ endContent,
+ isLabelHidden = false,
+ xstyle,
+ className,
+ style,
+ 'data-testid': testId,
+ ref,
+}: XDSTokenProps) {
+ const content = (
+ <>
+ {icon}
+ <span
+ {...stylex.props(styles.label, isLabelHidden && styles.labelHidden)}>
+ {label}
+ </span>
+ {endContent}
+ {onRemove != null && (
+ <button
+ type="button"
+ aria-label={`Remove ${label}`}
+ onClick={e => {
+ e.stopPropagation();
+ onRemove(e);
+ }}
+ disabled={isDisabled}
+ {...stylex.props(styles.removeButton)}>
+ <XDSIcon icon="close" size="xsm" color="inherit" />
+ </button>
+ )}
+ </>
+ );
- if (href != null) {
- return (
- <a
- ref={ref as React.Ref<HTMLAnchorElement>}
- href={href}
- aria-disabled={isDisabled || undefined}
- {...sharedProps}
- {...mergeProps(
- xdsClassName('token', {color}),
- stylex.props(
- styles.base,
- sizeStyles[size],
- colorStyles[color],
- styles.interactive,
- isDisabled && styles.disabled,
- xstyle,
- ),
- className,
- style,
- )}>
- {content}
- </a>
- );
- }
+ const sharedProps = {
+ 'data-testid': testId,
+ 'aria-label': isLabelHidden ? label : undefined,
+ 'aria-description': description,
+ };
- if (onClick != null) {
- const handleContainerClick = (e: React.MouseEvent) => {
- const target = e.target as HTMLElement;
- if (target.closest('button, a')) return;
- onClick(e);
- };
+ if (href != null) {
+ return (
+ <a
+ ref={ref as React.Ref<HTMLAnchorElement>}
+ href={href}
+ aria-disabled={isDisabled || undefined}
+ {...sharedProps}
+ {...mergeProps(
+ xdsClassName('token', {color}),
+ stylex.props(
+ styles.base,
+ sizeStyles[size],
+ colorStyles[color],
+ styles.interactive,
+ isDisabled && styles.disabled,
+ xstyle,
+ ),
+ className,
+ style,
+ )}>
+ {content}
+ </a>
+ );
+ }
- return (
- <span
- ref={ref as React.Ref<HTMLSpanElement>}
- onClick={isDisabled ? undefined : handleContainerClick}
- {...sharedProps}
- {...mergeProps(
- xdsClassName('token', {color}),
- stylex.props(
- styles.base,
- sizeStyles[size],
- colorStyles[color],
- styles.interactive,
- styles.focusWithinOutline,
- isDisabled && styles.disabled,
- xstyle,
- ),
- className,
- style,
- )}>
- {icon}
- <button
- type="button"
- onClick={onClick}
- disabled={isDisabled}
- {...stylex.props(styles.invisibleButton)}>
- <span
- {...stylex.props(
- styles.label,
- isLabelHidden && styles.labelHidden,
- )}>
- {label}
- </span>
- </button>
- {endContent}
- {onRemove != null && (
- <button
- type="button"
- aria-label={`Remove ${label}`}
- onClick={e => {
- e.stopPropagation();
- onRemove(e);
- }}
- disabled={isDisabled}
- {...stylex.props(styles.removeButton)}>
- <XDSIcon icon="close" size="xsm" color="inherit" />
- </button>
- )}
- </span>
- );
- }
+ if (onClick != null) {
+ const handleContainerClick = (e: React.MouseEvent) => {
+ const target = e.target as HTMLElement;
+ if (target.closest('button, a')) return;
+ onClick(e);
+ };
return (
<span
ref={ref as React.Ref<HTMLSpanElement>}
+ onClick={isDisabled ? undefined : handleContainerClick}
{...sharedProps}
{...mergeProps(
xdsClassName('token', {color}),
@@ -460,16 +409,65 @@ export const XDSToken = forwardRef<HTMLElement, XDSTokenProps>(
styles.base,
sizeStyles[size],
colorStyles[color],
+ styles.interactive,
+ styles.focusWithinOutline,
isDisabled && styles.disabled,
xstyle,
),
className,
style,
)}>
- {content}
+ {icon}
+ <button
+ type="button"
+ onClick={onClick}
+ disabled={isDisabled}
+ {...stylex.props(styles.invisibleButton)}>
+ <span
+ {...stylex.props(
+ styles.label,
+ isLabelHidden && styles.labelHidden,
+ )}>
+ {label}
+ </span>
+ </button>
+ {endContent}
+ {onRemove != null && (
+ <button
+ type="button"
+ aria-label={`Remove ${label}`}
+ onClick={e => {
+ e.stopPropagation();
+ onRemove(e);
+ }}
+ disabled={isDisabled}
+ {...stylex.props(styles.removeButton)}>
+ <XDSIcon icon="close" size="xsm" color="inherit" />
+ </button>
+ )}
</span>
);
- },
-);
+ }
+
+ return (
+ <span
+ ref={ref as React.Ref<HTMLSpanElement>}
+ {...sharedProps}
+ {...mergeProps(
+ xdsClassName('token', {color}),
+ stylex.props(
+ styles.base,
+ sizeStyles[size],
+ colorStyles[color],
+ isDisabled && styles.disabled,
+ xstyle,
+ ),
+ className,
+ style,
+ )}>
+ {content}
+ </span>
+ );
+}
XDSToken.displayName = 'XDSToken';
diff --git a/packages/core/src/TopNav/XDSTopNav.tsx b/packages/core/src/TopNav/XDSTopNav.tsx
index e341238e31..cc704f1300 100644
--- a/packages/core/src/TopNav/XDSTopNav.tsx
+++ b/packages/core/src/TopNav/XDSTopNav.tsx
@@ -1,6 +1,6 @@
/**
* @file XDSTopNav.tsx
- * @input Uses React forwardRef, HTMLAttributes, ReactNode
+ * @input Uses React, HTMLAttributes, ReactNode
* @output Exports XDSTopNav component and XDSTopNavProps
* @position Core implementation; consumed by index.ts
*
@@ -13,7 +13,7 @@
'use client';
-import {forwardRef, type ReactNode} from 'react';
+import {type ReactNode} from 'react';
import type {XDSBaseProps} from '../XDSBaseProps';
import * as stylex from '@stylexjs/stylex';
import {colorVars, spacingVars} from '../theme/tokens.stylex';
@@ -84,6 +84,8 @@ const styles = stylex.create({
});
export interface XDSTopNavProps extends XDSBaseProps<HTMLElement> {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLElement>;
/**
* Heading slot content — typically XDSTopNavHeading with logo and text.
* Positioned at the left edge of the nav bar.
@@ -130,62 +132,58 @@ export interface XDSTopNavProps extends XDSBaseProps<HTMLElement> {
* />
* ```
*/
-export const XDSTopNav = forwardRef<HTMLElement, XDSTopNavProps>(
- function XDSTopNav(
- {
- heading,
- startContent,
- centerContent,
- endContent,
- label,
- xstyle,
- className,
- style,
- ...props
- },
- ref,
- ) {
- const hasCenterContent = centerContent != null;
+export function XDSTopNav({
+ heading,
+ startContent,
+ centerContent,
+ endContent,
+ label,
+ xstyle,
+ className,
+ style,
+ ref,
+ ...props
+}: XDSTopNavProps) {
+ const hasCenterContent = centerContent != null;
- return (
- <nav
- ref={ref}
- role="navigation"
- aria-label={label}
- {...mergeProps(
- xdsClassName('top-nav'),
- stylex.props(
- styles.base,
- hasCenterContent ? styles.baseGrid : styles.baseFlex,
- xstyle,
- ),
- className,
- style,
+ return (
+ <nav
+ ref={ref}
+ role="navigation"
+ aria-label={label}
+ {...mergeProps(
+ xdsClassName('top-nav'),
+ stylex.props(
+ styles.base,
+ hasCenterContent ? styles.baseGrid : styles.baseFlex,
+ xstyle,
+ ),
+ className,
+ style,
+ )}
+ {...props}>
+ <div {...stylex.props(styles.leftSection, edgeSignals.start)}>
+ {heading && <div {...stylex.props(styles.heading)}>{heading}</div>}
+ {startContent && (
+ <div {...stylex.props(styles.startContent)}>{startContent}</div>
)}
- {...props}>
- <div {...stylex.props(styles.leftSection, edgeSignals.start)}>
- {heading && <div {...stylex.props(styles.heading)}>{heading}</div>}
- {startContent && (
- <div {...stylex.props(styles.startContent)}>{startContent}</div>
- )}
+ </div>
+ {hasCenterContent && (
+ <div {...stylex.props(styles.centerContent)}>{centerContent}</div>
+ )}
+ {hasCenterContent ? (
+ <div {...stylex.props(styles.rightSection, edgeSignals.end)}>
+ {endContent}
</div>
- {hasCenterContent && (
- <div {...stylex.props(styles.centerContent)}>{centerContent}</div>
- )}
- {hasCenterContent ? (
- <div {...stylex.props(styles.rightSection, edgeSignals.end)}>
+ ) : (
+ endContent && (
+ <div {...stylex.props(styles.endContent, edgeSignals.end)}>
{endContent}
</div>
- ) : (
- endContent && (
- <div {...stylex.props(styles.endContent, edgeSignals.end)}>
- {endContent}
- </div>
- )
- )}
- </nav>
- );
- },
-);
+ )
+ )}
+ </nav>
+ );
+}
XDSTopNav.displayName = 'XDSTopNav';
diff --git a/packages/core/src/TopNav/XDSTopNavHeading.tsx b/packages/core/src/TopNav/XDSTopNavHeading.tsx
index e68307085d..115e507eb0 100644
--- a/packages/core/src/TopNav/XDSTopNavHeading.tsx
+++ b/packages/core/src/TopNav/XDSTopNavHeading.tsx
@@ -1,6 +1,6 @@
/**
* @file XDSTopNavHeading.tsx
- * @input Uses React forwardRef, HTMLAttributes, ReactNode
+ * @input Uses React, HTMLAttributes, ReactNode
* @output Exports XDSTopNavHeading component and XDSTopNavHeadingProps
* @position Companion component for XDSTopNav heading slot
*
@@ -11,7 +11,7 @@
* - /apps/storybook/stories/TopNav.stories.tsx
*/
-import {forwardRef, type ReactNode} from 'react';
+import {type ReactNode} from 'react';
import type {XDSBaseProps} from '../XDSBaseProps';
import * as stylex from '@stylexjs/stylex';
import {
@@ -52,6 +52,8 @@ const styles = stylex.create({
});
export interface XDSTopNavHeadingProps extends XDSBaseProps<HTMLElement> {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLElement>;
/**
* The heading text to display.
*/
@@ -88,31 +90,33 @@ export interface XDSTopNavHeadingProps extends XDSBaseProps<HTMLElement> {
* <XDSTopNavHeading logo={<BrandLogo />} href="/" />
* ```
*/
-export const XDSTopNavHeading = forwardRef<HTMLElement, XDSTopNavHeadingProps>(
- function XDSTopNavHeading(
- {heading, logo, href, xstyle, className, style, ...props},
- ref,
- ) {
- const Element = href ? 'a' : 'div';
+export function XDSTopNavHeading({
+ heading,
+ logo,
+ href,
+ xstyle,
+ className,
+ style,
+ ref,
+ ...props
+}: XDSTopNavHeadingProps) {
+ const Element = href ? 'a' : 'div';
- return (
- <Element
- ref={ref as React.Ref<HTMLAnchorElement & HTMLDivElement>}
- href={href}
- {...mergeProps(
- xdsClassName('top-nav-heading'),
- stylex.props(styles.base, href != null && styles.clickable, xstyle),
- className,
- style,
- )}
- {...props}>
- {logo && <span {...stylex.props(styles.logo)}>{logo}</span>}
- {heading && (
- <span {...stylex.props(styles.headingText)}>{heading}</span>
- )}
- </Element>
- );
- },
-);
+ return (
+ <Element
+ ref={ref as React.Ref<HTMLAnchorElement & HTMLDivElement>}
+ href={href}
+ {...mergeProps(
+ xdsClassName('top-nav-heading'),
+ stylex.props(styles.base, href != null && styles.clickable, xstyle),
+ className,
+ style,
+ )}
+ {...props}>
+ {logo && <span {...stylex.props(styles.logo)}>{logo}</span>}
+ {heading && <span {...stylex.props(styles.headingText)}>{heading}</span>}
+ </Element>
+ );
+}
XDSTopNavHeading.displayName = 'XDSTopNavHeading';
diff --git a/packages/core/src/TopNav/XDSTopNavItem.tsx b/packages/core/src/TopNav/XDSTopNavItem.tsx
index dcaf3e9b59..923a81027b 100644
--- a/packages/core/src/TopNav/XDSTopNavItem.tsx
+++ b/packages/core/src/TopNav/XDSTopNavItem.tsx
@@ -1,6 +1,6 @@
/**
* @file XDSTopNavItem.tsx
- * @input Uses React forwardRef, AnchorHTMLAttributes, ReactNode
+ * @input Uses React, AnchorHTMLAttributes, ReactNode
* @output Exports XDSTopNavItem component and XDSTopNavItemProps
* @position Navigation item component for XDSTopNav startContent
*
@@ -13,7 +13,7 @@
'use client';
-import {forwardRef, type ReactNode} from 'react';
+import {type ReactNode} from 'react';
import type {XDSBaseProps} from '../XDSBaseProps';
import * as stylex from '@stylexjs/stylex';
import {
@@ -86,6 +86,8 @@ const styles = stylex.create({
});
export interface XDSTopNavItemProps extends XDSBaseProps<HTMLAnchorElement> {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLAnchorElement>;
/** Link destination URL. */
href?: string;
/** Where to open the linked document. */
@@ -148,51 +150,47 @@ export interface XDSTopNavItemProps extends XDSBaseProps<HTMLAnchorElement> {
* />
* ```
*/
-export const XDSTopNavItem = forwardRef<HTMLAnchorElement, XDSTopNavItemProps>(
- function XDSTopNavItem(
- {
- as,
- label,
- isSelected = false,
- isDisabled = false,
- icon,
- children,
- xstyle,
- className,
- style,
- ...props
- },
- ref,
- ) {
- const LinkComponent = useXDSLinkComponent(as);
- const isIconOnly = icon != null && children == null && !label;
- const showLabel = !isIconOnly;
+export function XDSTopNavItem({
+ as,
+ label,
+ isSelected = false,
+ isDisabled = false,
+ icon,
+ children,
+ xstyle,
+ className,
+ style,
+ ref,
+ ...props
+}: XDSTopNavItemProps) {
+ const LinkComponent = useXDSLinkComponent(as);
+ const isIconOnly = icon != null && children == null && !label;
+ const showLabel = !isIconOnly;
- return (
- <LinkComponent
- ref={ref}
- aria-label={isIconOnly ? label : undefined}
- aria-current={isSelected ? 'page' : undefined}
- aria-disabled={isDisabled || undefined}
- tabIndex={isDisabled ? -1 : undefined}
- {...mergeProps(
- xdsClassName('top-nav-item'),
- stylex.props(
- styles.base,
- isSelected && styles.selected,
- isDisabled && styles.disabled,
- isIconOnly && styles.iconOnly,
- xstyle,
- ),
- className,
- style,
- )}
- {...props}>
- {icon}
- {showLabel && (children ?? label)}
- </LinkComponent>
- );
- },
-);
+ return (
+ <LinkComponent
+ ref={ref}
+ aria-label={isIconOnly ? label : undefined}
+ aria-current={isSelected ? 'page' : undefined}
+ aria-disabled={isDisabled || undefined}
+ tabIndex={isDisabled ? -1 : undefined}
+ {...mergeProps(
+ xdsClassName('top-nav-item'),
+ stylex.props(
+ styles.base,
+ isSelected && styles.selected,
+ isDisabled && styles.disabled,
+ isIconOnly && styles.iconOnly,
+ xstyle,
+ ),
+ className,
+ style,
+ )}
+ {...props}>
+ {icon}
+ {showLabel && (children ?? label)}
+ </LinkComponent>
+ );
+}
XDSTopNavItem.displayName = 'XDSTopNavItem';
diff --git a/packages/core/src/Typeahead/XDSBaseTypeahead.tsx b/packages/core/src/Typeahead/XDSBaseTypeahead.tsx
index ef3b380920..7c9b1b0bf3 100644
--- a/packages/core/src/Typeahead/XDSBaseTypeahead.tsx
+++ b/packages/core/src/Typeahead/XDSBaseTypeahead.tsx
@@ -16,7 +16,6 @@
'use client';
import React, {
- forwardRef,
useCallback,
useEffect,
useId,
@@ -249,31 +248,29 @@ const styles = stylex.create({
* />
* ```
*/
-export const XDSBaseTypeahead = forwardRef(function XDSBaseTypeahead<
+export const XDSBaseTypeahead = function XDSBaseTypeahead<
T extends XDSSearchableItem,
->(
- {
- searchSource,
- value,
- onChange,
- renderItem,
- placeholder = 'Search...',
- hasEntriesOnFocus = false,
- maxMenuItems = 10,
- emptySearchResultsText = 'No results found',
- isDisabled = false,
- hasAutoFocus = false,
- onChangeQuery,
- onOpenChange,
- inputId: externalInputId,
- ariaDescribedBy,
- inputXStyle,
- anchorRef,
- onKeyDown: externalOnKeyDown,
- debounceMs = 150,
- }: XDSBaseTypeaheadProps<T>,
- ref: React.ForwardedRef<HTMLInputElement>,
-) {
+>({
+ searchSource,
+ value,
+ onChange,
+ renderItem,
+ placeholder = 'Search...',
+ hasEntriesOnFocus = false,
+ maxMenuItems = 10,
+ emptySearchResultsText = 'No results found',
+ isDisabled = false,
+ hasAutoFocus = false,
+ onChangeQuery,
+ onOpenChange,
+ inputId: externalInputId,
+ ariaDescribedBy,
+ inputXStyle,
+ anchorRef,
+ onKeyDown: externalOnKeyDown,
+ debounceMs = 150,
+ ref,
+}: XDSBaseTypeaheadProps<T> & {ref?: React.Ref<HTMLInputElement>}) {
const generatedId = useId();
const inputId = externalInputId ?? generatedId;
const listboxId = useId();
@@ -619,7 +616,7 @@ export const XDSBaseTypeahead = forwardRef(function XDSBaseTypeahead<
)}
</>
);
-}) as <T extends XDSSearchableItem>(
+} as <T extends XDSSearchableItem>(
props: XDSBaseTypeaheadProps<T> & {ref?: React.Ref<HTMLInputElement>},
) => React.ReactElement;