An open source design system that's fully customizable and agent ready
TypeScript
feat(core): add XDSInteractiveRoleContext and useXDSInteractiveRole (#2399)
Cindy Zhang0b7106eae6fb
diff --git a/apps/storybook/stories/Popover.stories.tsx b/apps/storybook/stories/Popover.stories.tsxindex eb2038fa94..ca8d9c1217 100644--- a/apps/storybook/stories/Popover.stories.tsx+++ b/apps/storybook/stories/Popover.stories.tsx@@ -3,7 +3,10 @@import React from 'react';import type {Meta, StoryObj} from '@storybook/react';import {XDSPopover} from '@xds/core/Popover';+import type {PopoverTriggerRenderProps} from '@xds/core/Popover';import {XDSButton} from '@xds/core/Button';+import {XDSToken} from '@xds/core/Token';+import {XDSLink} from '@xds/core/Link';import {XDSVStack, XDSHStack} from '@xds/core/Layout';import {XDSText, XDSHeading} from '@xds/core/Text';import {XDSSwitch} from '@xds/core/Switch';@@ -309,3 +312,97 @@ export const Disabled: Story = {children: <XDSButton label="Disabled popover">Disabled</XDSButton>,},};++// =============================================================================+// Token as Popover Trigger (via XDSInteractiveRoleContext)+// =============================================================================++export const TokenTrigger: Story = {+ render: () => (+ <XDSPopover+ placement="below"+ label="Token options"+ width={220}+ content={+ <XDSVStack gap={2}>+ <XDSHeading level={4} tabIndex={-1}>+ Filter options+ </XDSHeading>+ <XDSDivider />+ <XDSText type="body">+ The token automatically renders as a button via context.+ </XDSText>+ </XDSVStack>+ }>+ <XDSToken label="Status: Active" icon="filter" />+ </XDSPopover>+ ),+};++// =============================================================================+// Link as Popover Trigger (no href → renders as button)+// =============================================================================++export const LinkTrigger: Story = {+ render: () => (+ <XDSPopover+ placement="below"+ label="Link actions"+ width={220}+ content={+ <XDSVStack gap={2}>+ <XDSHeading level={4} tabIndex={-1}>+ Quick actions+ </XDSHeading>+ <XDSDivider />+ <XDSText type="body">+ XDSLink without href renders as a button, suitable for triggers.+ </XDSText>+ </XDSVStack>+ }>+ <XDSLink>More options</XDSLink>+ </XDSPopover>+ ),+};++// =============================================================================+// Render Prop Pattern (explicit trigger wiring)+// =============================================================================++export const RenderProp: Story = {+ render: () => (+ <XDSPopover+ placement="below"+ label="Custom trigger"+ width={260}+ content={+ <XDSVStack gap={2}>+ <XDSHeading level={4} tabIndex={-1}>+ Custom trigger+ </XDSHeading>+ <XDSDivider />+ <XDSText type="body">+ The render prop gives full control over the trigger element.+ </XDSText>+ </XDSVStack>+ }>+ {(triggerProps: PopoverTriggerRenderProps) => (+ <button+ ref={triggerProps.ref}+ onClick={triggerProps.onClick}+ aria-haspopup={triggerProps['aria-haspopup']}+ aria-expanded={triggerProps['aria-expanded']}+ aria-controls={triggerProps['aria-controls']}+ style={{+ padding: '8px 16px',+ border: '1px dashed currentColor',+ borderRadius: 4,+ background: 'transparent',+ cursor: 'pointer',+ }}>+ Custom trigger element+ </button>+ )}+ </XDSPopover>+ ),+};diff --git a/packages/core/package.json b/packages/core/package.jsonindex fa03b7b66a..d47013173a 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -273,6 +273,11 @@"types": "./dist/InputGroup/index.d.ts","default": "./dist/InputGroup/index.js"},+ "./InteractiveRoleContext": {+ "source": "./src/InteractiveRoleContext/index.ts",+ "types": "./dist/InteractiveRoleContext/index.d.ts",+ "default": "./dist/InteractiveRoleContext/index.js"+ },"./Item": {"source": "./src/Item/index.ts","types": "./dist/Item/index.d.ts",diff --git a/packages/core/src/InteractiveRoleContext/XDSInteractiveRoleContext.ts b/packages/core/src/InteractiveRoleContext/XDSInteractiveRoleContext.tsnew file mode 100644index 0000000000..7356f62fb1--- /dev/null+++ b/packages/core/src/InteractiveRoleContext/XDSInteractiveRoleContext.ts@@ -0,0 +1,53 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file XDSInteractiveRoleContext.ts+ * @input React createContext, use+ * @output Exports XDSInteractiveRoleContext, useXDSInteractiveRoleContext+ * @position Context primitive; consumed by useXDSInteractiveRole hook+ *+ * Provides a role override to optionally-interactive child components.+ * When a parent (Popover, DropdownMenu, etc.) needs its child to render+ * as a button, it wraps the child in this context with role = 'button'.+ *+ * Components don't consume this directly — they use `useXDSInteractiveRole`+ * which checks this context as one of its decision inputs.+ *+ * Follows the same pattern as XDSSizeContext:+ * XDSSizeContext provides size → useXDSSize resolves it+ * XDSInteractiveRoleContext provides role → useXDSInteractiveRole resolves it+ *+ * SYNC: When modified, update:+ * - /packages/core/src/InteractiveRoleContext/index.ts+ */++import {createContext, use} from 'react';+import type {XDSInteractiveRole} from '../hooks/useXDSInteractiveRole';++/**+ * Context that provides a role override to child components.+ *+ * Provided by containers that need their child to be interactive:+ * - XDSPopover → 'button' (click to open popover)+ * - XDSDropdownMenu → 'button' (click to open menu)+ * - Any future component that wraps an optionally-interactive trigger+ *+ * `null` means no parent is overriding — resolve based on own props.+ */+export const XDSInteractiveRoleContext =+ createContext<XDSInteractiveRole | null>(null);+XDSInteractiveRoleContext.displayName = 'XDSInteractiveRoleContext';++/**+ * Read the role override from context, if any.+ *+ * Most components should use `useXDSInteractiveRole` instead of calling+ * this directly — it incorporates this signal alongside href/onClick.+ *+ * @returns The overridden role, or `null` if no parent is providing one.+ */+export function useXDSInteractiveRoleContext(): XDSInteractiveRole | null {+ return use(XDSInteractiveRoleContext);+}diff --git a/packages/core/src/InteractiveRoleContext/index.ts b/packages/core/src/InteractiveRoleContext/index.tsnew file mode 100644index 0000000000..bac312995a--- /dev/null+++ b/packages/core/src/InteractiveRoleContext/index.ts@@ -0,0 +1,15 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file index.ts+ * @input XDSInteractiveRoleContext+ * @output Exports InteractiveRoleContext module public API+ * @position Entry point for InteractiveRoleContext module+ */++export {+ XDSInteractiveRoleContext,+ useXDSInteractiveRoleContext,+} from './XDSInteractiveRoleContext';diff --git a/packages/core/src/Link/XDSLink.tsx b/packages/core/src/Link/XDSLink.tsxindex d5c6d7ad23..1929e50181 100644--- a/packages/core/src/Link/XDSLink.tsx+++ b/packages/core/src/Link/XDSLink.tsx@@ -41,6 +41,7 @@ import {useXDSLinkComponent} from './useXDSLinkComponent';import type {XDSLinkComponentType} from './types';import {xdsClassName, mergeProps} from '../utils';import {computeTargetAndRel} from './computeTargetAndRel';+import {useXDSInteractiveRole} from '../hooks/useXDSInteractiveRole';/*** Base link styles@@ -274,14 +275,16 @@ export function XDSLink({...props}: XDSLinkProps) {const LinkComponent = useXDSLinkComponent(as);+ const role = useXDSInteractiveRole({href, onClick, isDisabled});// Determine target and rel based on isExternalLinkconst {target, rel} = computeTargetAndRel(isExternalLink ? '_blank' : targetFromProps,relFromProps,);- // When href is undefined, render as a <button> for semantic correctness- const renderAsButton = href == null;+ // When role resolves to 'button' (no href, or context-provided),+ // render as a <button> with link styling for semantic correctness.+ const renderAsButton = role === 'button' || (role === 'inert' && href == null);const sharedContent = (<>@@ -307,9 +310,7 @@ export function XDSLink({<buttonref={ref as React.Ref<HTMLButtonElement>}type="button"- onClick={- onClick- }+ onClick={onClick}aria-label={label || undefined}aria-disabled={isDisabled || undefined}tabIndex={isDisabled ? -1 : undefined}@@ -328,7 +329,7 @@ export function XDSLink({className,style,)}- {...(props)}>+ {...props}>{sharedContent}</button>);@@ -339,9 +340,7 @@ export function XDSLink({href={href}target={target}rel={rel}- onClick={- onClick- }+ onClick={onClick}aria-label={label || undefined}aria-disabled={isDisabled || undefined}tabIndex={isDisabled ? -1 : undefined}diff --git a/packages/core/src/Popover/XDSPopover.tsx b/packages/core/src/Popover/XDSPopover.tsxindex 538fb9fcd5..b83246c697 100644--- a/packages/core/src/Popover/XDSPopover.tsx+++ b/packages/core/src/Popover/XDSPopover.tsx@@ -31,6 +31,7 @@ import {useXDSPopover} from './useXDSPopover';import type {LayerAlignment, LayerPlacement} from '../Layer/useXDSLayer';import {layerAnimations} from '../Layer/layerAnimations.stylex';import {spacingVars} from '../theme/tokens.stylex';+import {XDSInteractiveRoleContext} from '../InteractiveRoleContext/XDSInteractiveRoleContext';// =============================================================================// Helpers@@ -54,14 +55,39 @@ function findTriggerButton(el: HTMLElement): HTMLElement | null {// Types// =============================================================================+/**+ * Props passed to render-prop children for explicit trigger wiring.+ */+export interface PopoverTriggerRenderProps {+ /** Ref callback — attach to the trigger element for anchor positioning. */+ ref: (el: HTMLElement | null) => void;+ /** Toggle the popover open/closed. */+ onClick: () => void;+ /** ARIA attribute: indicates the element triggers a dialog. */+ 'aria-haspopup': 'dialog';+ /** ARIA attribute: whether the popover is currently open. */+ 'aria-expanded': boolean;+ /** ARIA attribute: ID of the controlled popover element. */+ 'aria-controls': string;+}+export interface XDSPopoverProps extends Pick<XDSBaseProps,'xstyle' | 'className' | 'style'> {/**- * The trigger element. Must contain a `<button>` or `[role="button"]`- * element — the popover locates it and applies click/keydown handlers- * and ARIA attributes (`aria-haspopup`, `aria-expanded`, `aria-controls`).+ * The trigger element. Accepts either:+ *+ * **ReactNode (automatic mode):** Must contain a `<button>` or+ * `[role="button"]` element — the popover locates it and applies+ * click/keydown handlers and ARIA attributes automatically.+ * Components that consume `XDSInteractiveRoleContext` (e.g., XDSToken)+ * will render as a button automatically when placed here.+ *+ * **Render function (explicit mode):** Receives `PopoverTriggerRenderProps`+ * with ref, onClick, and ARIA attributes. The consumer is responsible+ * for attaching these to their trigger element. Use this for custom+ * triggers or third-party components.** The trigger is rendered inside an anchor wrapper used for CSS anchor* positioning. The wrapper is stable (no pressed-state transforms),@@ -69,8 +95,22 @@ export interface XDSPopoverProps extends Pick<** When `anchorRef` is provided, children can be omitted and the popover* attaches to the external ref element as a sibling.+ *+ * @example+ * ```+ * // Automatic — XDSButton already renders a <button>+ * <XDSPopover content={...}><XDSButton label="Open" /></XDSPopover>+ *+ * // Automatic — XDSToken renders as <button> via context+ * <XDSPopover content={...}><XDSToken label="Filter" /></XDSPopover>+ *+ * // Explicit — render prop for full control+ * <XDSPopover content={...}>+ * {(triggerProps) => <MyCustomTrigger {...triggerProps} />}+ * </XDSPopover>+ * ```*/- children?: ReactNode;+ children?: ReactNode | ((props: PopoverTriggerRenderProps) => ReactNode);/*** External ref to use as the popover anchor.@@ -380,6 +420,9 @@ export function XDSPopover({if (anchorRef) {return;} // Skip if using anchorRef mode+ if (typeof children === 'function') {+ return;+ } // Skip if using render prop modeconst wrapper = wrapperRef.current;if (!wrapper) {@@ -450,11 +493,50 @@ export function XDSPopover({);}+ // Render prop mode: children is a function — pass trigger props directly+ const isRenderProp = typeof children === 'function';++ if (isRenderProp) {+ const triggerProps: PopoverTriggerRenderProps = {+ ref: popover.triggerRef,+ onClick: handleTriggerClick,+ 'aria-haspopup': 'dialog',+ 'aria-expanded': popover.isOpen,+ 'aria-controls': popover.id,+ };++ return (+ <>+ {children(triggerProps)}+ {popover.render(+ <div+ data-testid={testId}+ {...mergeProps(+ xdsClassName('popover'),+ stylex.props(styles.contentPadding, xstyle),+ className,+ style,+ )}>+ {content}+ </div>,+ {+ placement,+ alignment,+ xstyle: [popoverXstyle, styles.gap, layerAnimations[placement]],+ },+ )}+ </>+ );+ }++ // Automatic mode: wrap children in context + anchor wrapperreturn (<>- <div ref={wrapperRef} {...stylex.props(styles.anchorWrapper)}>- {children}- </div>+ <XDSInteractiveRoleContext value="button">+ <div ref={wrapperRef} {...stylex.props(styles.anchorWrapper)}>+ {children}+ </div>+ </XDSInteractiveRoleContext>{popover.render(<divdata-testid={testId}diff --git a/packages/core/src/Popover/index.ts b/packages/core/src/Popover/index.tsindex 40348bf111..86f0bb7271 100644--- a/packages/core/src/Popover/index.ts+++ b/packages/core/src/Popover/index.ts@@ -17,4 +17,4 @@ export type {UseXDSPopoverOptions, UseXDSPopoverReturn} from './useXDSPopover';// Popover componentexport {XDSPopover} from './XDSPopover';-export type {XDSPopoverProps} from './XDSPopover';+export type {XDSPopoverProps, PopoverTriggerRenderProps} from './XDSPopover';diff --git a/packages/core/src/Token/XDSToken.tsx b/packages/core/src/Token/XDSToken.tsxindex 21066fd326..5c51f5ed0c 100644--- a/packages/core/src/Token/XDSToken.tsx+++ b/packages/core/src/Token/XDSToken.tsx@@ -31,6 +31,7 @@ import {import {XDSIcon} from '../Icon';import {xdsClassName, mergeProps} from '../utils';import {useXDSLinkComponent} from '../Link/useXDSLinkComponent';+import {useXDSInteractiveRole} from '../hooks/useXDSInteractiveRole';import type {XDSBaseProps} from '../XDSBaseProps';// =============================================================================@@ -323,6 +324,12 @@ export function XDSToken({ref,}: XDSTokenProps) {const LinkComponent = useXDSLinkComponent();+ const role = useXDSInteractiveRole({href, onClick, isDisabled});++ // When role is 'button' via context (no explicit onClick), treat as+ // if onClick was provided — the popover attaches its own handler.+ const effectiveOnClick = onClick ?? (role === 'button' ? () => {} : null);+const content = (<>{icon}@@ -353,11 +360,11 @@ export function XDSToken({'aria-description': description,};- if (href != null) {+ if (role === 'link') {return (<LinkComponentref={ref as React.Ref<HTMLAnchorElement>}- href={href}+ href={href as string}aria-disabled={isDisabled || undefined}{...sharedProps}{...mergeProps(@@ -378,13 +385,13 @@ export function XDSToken({);}- if (onClick != null) {+ if (effectiveOnClick != null) {const handleContainerClick = (e: React.MouseEvent) => {const target = e.target as HTMLElement;if (target.closest('button, a')) {return;}- onClick(e);+ effectiveOnClick(e);};return (@@ -409,7 +416,7 @@ export function XDSToken({{icon}<buttontype="button"- onClick={onClick}+ onClick={effectiveOnClick}disabled={isDisabled}{...stylex.props(styles.invisibleButton)}><spandiff --git a/packages/core/src/hooks/index.ts b/packages/core/src/hooks/index.tsindex a8d4546346..d972799b57 100644--- a/packages/core/src/hooks/index.ts+++ b/packages/core/src/hooks/index.ts@@ -49,3 +49,9 @@ export type {export {useInputContainer} from './useInputContainer';export type {UseInputContainerOptions} from './useInputContainer';++export {useXDSInteractiveRole} from './useXDSInteractiveRole';+export type {+ XDSInteractiveRole,+ UseXDSInteractiveRoleOptions,+} from './useXDSInteractiveRole';diff --git a/packages/core/src/hooks/useXDSInteractiveRole.ts b/packages/core/src/hooks/useXDSInteractiveRole.tsnew file mode 100644index 0000000000..e38e4711b4--- /dev/null+++ b/packages/core/src/hooks/useXDSInteractiveRole.ts@@ -0,0 +1,103 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file useXDSInteractiveRole.ts+ * @input Uses useXDSInteractiveTrigger+ * @output Exports useXDSInteractiveRole hook and XDSInteractiveRole type+ * @position Hook utility; consumed by Token, Thumbnail, Item, ClickableCard, etc.+ *+ * Centralizes the "what element should I render as?" decision for+ * polymorphic components. The priority order:+ *+ * 1. href → 'link' (navigation always wins)+ * 2. onClick → 'button' (explicit interactivity)+ * 3. interactive trigger context → 'button' (implicit via parent)+ * 4. else → 'inert' (non-interactive)+ *+ * This hook is the single place to add new context-based triggers+ * (e.g., Popover, DropdownMenu, Disclosure). Components that consume+ * this hook never need updating when new trigger contexts are added.+ *+ * SYNC: When modified, update:+ * - /packages/core/src/hooks/index.ts (export)+ */++import {useXDSInteractiveRoleContext} from '../InteractiveRoleContext/XDSInteractiveRoleContext';++/**+ * The resolved interactive role for a polymorphic component.+ *+ * - `'link'` — render as `<a>` (via LinkComponent)+ * - `'button'` — render as `<button>`+ * - `'inert'` — render as `<span>` or `<div>` (non-interactive)+ */+export type XDSInteractiveRole = 'link' | 'button' | 'inert';++export interface UseXDSInteractiveRoleOptions {+ /**+ * URL for link navigation. When provided, the component renders as a link.+ * Takes highest priority — a link always navigates.+ */+ href?: string;++ /**+ * Click handler. When provided, the component renders as a button.+ * Takes priority over context-based triggers.+ */+ onClick?: ((...args: never[]) => unknown) | null;++ /**+ * Whether the component is disabled. When true and href is provided,+ * falls back to button (disabled links are an a11y anti-pattern).+ * @default false+ */+ isDisabled?: boolean;+}++/**+ * Determines the interactive role for a polymorphic component.+ *+ * Centralizes the element-type decision so that adding new context-based+ * triggers (popover, dropdown, etc.) only requires updating this hook —+ * all consuming components inherit the new behavior automatically.+ *+ * @example+ * ```ts+ * function XDSToken({ href, onClick, ... }) {+ * const role = useXDSInteractiveRole({ href, onClick });+ *+ * switch (role) {+ * case 'link': return <LinkComponent href={href} ...>{content}</LinkComponent>;+ * case 'button': return <button ...>{content}</button>;+ * case 'inert': return <span ...>{content}</span>;+ * }+ * }+ * ```+ */+export function useXDSInteractiveRole({+ href,+ onClick,+ isDisabled = false,+}: UseXDSInteractiveRoleOptions): XDSInteractiveRole {+ const contextRole = useXDSInteractiveRoleContext();++ // 1. href → link (unless disabled — disabled links fall through to button)+ if (href != null && !isDisabled) {+ return 'link';+ }++ // 2. Explicit onClick → button+ if (onClick != null) {+ return 'button';+ }++ // 3. Context-provided role override (e.g., Popover provides 'button')+ if (contextRole != null) {+ return contextRole;+ }++ // 4. Nothing interactive → inert+ return 'inert';+}