Skip to content

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

TypeScript

Adopt handleRef for imperative component handles (#2363)

Andrey Goder0308f604636f
diff --git a/apps/sandbox/src/app/(fullscreen)/pages/dictation-lab/page.tsx b/apps/sandbox/src/app/(fullscreen)/pages/dictation-lab/page.tsx
index 72cdf15525..1fa151352b 100644
--- a/apps/sandbox/src/app/(fullscreen)/pages/dictation-lab/page.tsx
+++ b/apps/sandbox/src/app/(fullscreen)/pages/dictation-lab/page.tsx
@@ -483,7 +483,7 @@ export default function DictationLabPage() {
<XDSChatComposer
onSubmit={handleSubmit}
- input={<XDSChatComposerInput ref={inputRef} />}
+ input={<XDSChatComposerInput handleRef={inputRef} />}
sendActions={<XDSChatDictationButton dictation={dictation} />}
/>
diff --git a/apps/storybook/stories/ChartStreamGL.stories.tsx b/apps/storybook/stories/ChartStreamGL.stories.tsx
index 7fd14122ae..7ea3c35c7f 100644
--- a/apps/storybook/stories/ChartStreamGL.stories.tsx
+++ b/apps/storybook/stories/ChartStreamGL.stories.tsx
@@ -73,7 +73,7 @@ export const StockPrice: StoryObj = {
<XDSChartAxis position="bottom" />
<XDSChartAxis position="left" />
<XDSChartStreamGL
- ref={streamRef}
+ handleRef={streamRef}
color={colors.categorical(1)[0]}
bufferSize={400}
lineWidth={1.5}
@@ -192,7 +192,7 @@ export const ServerDashboard: StoryObj = {
<XDSChartAxis position="bottom" />
<XDSChartAxis position="left" />
<XDSChartStreamGL
- ref={cpuRef}
+ handleRef={cpuRef}
color={colors.categorical(3)[0]}
bufferSize={300}
lineWidth={1.5}
@@ -206,7 +206,7 @@ export const ServerDashboard: StoryObj = {
<XDSChartAxis position="bottom" />
<XDSChartAxis position="left" />
<XDSChartStreamGL
- ref={memRef}
+ handleRef={memRef}
color={colors.categorical(3)[1]}
bufferSize={300}
lineWidth={1.5}
@@ -220,7 +220,7 @@ export const ServerDashboard: StoryObj = {
<XDSChartAxis position="bottom" />
<XDSChartAxis position="left" />
<XDSChartStreamGL
- ref={netRef}
+ handleRef={netRef}
color={colors.categorical(3)[2]}
bufferSize={300}
lineWidth={1.5}
@@ -292,7 +292,7 @@ export const SeismographDemo: StoryObj = {
<XDSChartAxis position="bottom" />
<XDSChartAxis position="left" />
<XDSChartStreamGL
- ref={streamRef}
+ handleRef={streamRef}
color={colors.categorical(5)[3]}
bufferSize={600}
lineWidth={1}
@@ -368,21 +368,21 @@ export const MultiSensorOverlay: StoryObj = {
<XDSChartAxis position="bottom" />
<XDSChartAxis position="left" />
<XDSChartStreamGL
- ref={s1Ref}
+ handleRef={s1Ref}
color={colors.categorical(3)[0]}
bufferSize={400}
lineWidth={1.5}
opacity={0.8}
/>
<XDSChartStreamGL
- ref={s2Ref}
+ handleRef={s2Ref}
color={colors.categorical(3)[1]}
bufferSize={400}
lineWidth={1.5}
opacity={0.8}
/>
<XDSChartStreamGL
- ref={s3Ref}
+ handleRef={s3Ref}
color={colors.categorical(3)[2]}
bufferSize={400}
lineWidth={1.5}
diff --git a/apps/storybook/stories/ChartStreamPerf.stories.tsx b/apps/storybook/stories/ChartStreamPerf.stories.tsx
index 8cf0e0a674..2b918cac26 100644
--- a/apps/storybook/stories/ChartStreamPerf.stories.tsx
+++ b/apps/storybook/stories/ChartStreamPerf.stories.tsx
@@ -94,7 +94,7 @@ export const XDomainUpdateCost: StoryObj = {
<XDSChartAxis position="bottom" />
<XDSChartAxis position="left" />
<XDSChartStreamGL
- ref={streamRef}
+ handleRef={streamRef}
color={colors.categorical(1)[0]}
bufferSize={300}
lineWidth={1.5}
@@ -184,7 +184,7 @@ export const ThrottledXDomain: StoryObj = {
<XDSChartAxis position="bottom" />
<XDSChartAxis position="left" />
<XDSChartStreamGL
- ref={streamRef}
+ handleRef={streamRef}
color={colors.categorical(1)[0]}
bufferSize={300}
lineWidth={1.5}
@@ -277,21 +277,21 @@ export const StressTest: StoryObj = {
<XDSChartAxis position="bottom" />
<XDSChartAxis position="left" />
<XDSChartStreamGL
- ref={s1}
+ handleRef={s1}
color={c[0]}
bufferSize={400}
lineWidth={1.5}
opacity={0.8}
/>
<XDSChartStreamGL
- ref={s2}
+ handleRef={s2}
color={c[1]}
bufferSize={400}
lineWidth={1.5}
opacity={0.8}
/>
<XDSChartStreamGL
- ref={s3}
+ handleRef={s3}
color={c[2]}
bufferSize={400}
lineWidth={1.5}
diff --git a/apps/storybook/stories/ChatDictation.stories.tsx b/apps/storybook/stories/ChatDictation.stories.tsx
index 4d78ec7d94..1480849084 100644
--- a/apps/storybook/stories/ChatDictation.stories.tsx
+++ b/apps/storybook/stories/ChatDictation.stories.tsx
@@ -179,7 +179,7 @@ export const Interactive: Story = {
onSubmit={v => {
console.log('Submit:', v);
}}
- input={<XDSChatComposerInput ref={inputRef} />}
+ input={<XDSChatComposerInput handleRef={inputRef} />}
sendActions={<XDSChatDictationButton dictation={dictation} />}
/>
{dictation.isListening && (
diff --git a/apps/storybook/stories/ChatLayout.stories.tsx b/apps/storybook/stories/ChatLayout.stories.tsx
index 9529016b4c..2af3122638 100644
--- a/apps/storybook/stories/ChatLayout.stories.tsx
+++ b/apps/storybook/stories/ChatLayout.stories.tsx
@@ -467,7 +467,7 @@ export const FullAIChat: StoryObj = {
}
input={
<XDSChatComposerInput
- ref={inputRef}
+ handleRef={inputRef}
triggers={triggers}
placeholder="Ask about the codebase..."
/>
@@ -761,7 +761,7 @@ export const PanelView: StoryObj = {
}
input={
<XDSChatComposerInput
- ref={inputRef}
+ handleRef={inputRef}
triggers={triggers}
placeholder="Ask something..."
/>
diff --git a/apps/storybook/stories/useXDSChartRange.stories.tsx b/apps/storybook/stories/useXDSChartRange.stories.tsx
index 7825b34c65..c11d947afd 100644
--- a/apps/storybook/stories/useXDSChartRange.stories.tsx
+++ b/apps/storybook/stories/useXDSChartRange.stories.tsx
@@ -59,7 +59,7 @@ export const KnownRange: StoryObj = {
<XDSChartAxis position="bottom" />
<XDSChartAxis position="left" />
<XDSChartStreamGL
- ref={streamRef}
+ handleRef={streamRef}
color={colors.categorical(1)[0]}
bufferSize={300}
lineWidth={1.5}
@@ -110,7 +110,7 @@ export const UnknownRange: StoryObj = {
<XDSChartAxis position="bottom" />
<XDSChartAxis position="left" />
<XDSChartStreamGL
- ref={streamRef}
+ handleRef={streamRef}
color={colors.categorical(2)[1]}
bufferSize={300}
lineWidth={1.5}
@@ -175,7 +175,7 @@ export const ZeroCentered: StoryObj = {
<XDSChartAxis position="bottom" />
<XDSChartAxis position="left" />
<XDSChartStreamGL
- ref={streamRef}
+ handleRef={streamRef}
color={colors.categorical(5)[3]}
bufferSize={600}
lineWidth={1}
diff --git a/packages/cli/src/codemods/__tests__/rename-imperative-ref-to-handleRef.test.mjs b/packages/cli/src/codemods/__tests__/rename-imperative-ref-to-handleRef.test.mjs
new file mode 100644
index 0000000000..23b625c4d7
--- /dev/null
+++ b/packages/cli/src/codemods/__tests__/rename-imperative-ref-to-handleRef.test.mjs
@@ -0,0 +1,65 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, expect, test} from 'vitest';
+import {applyTransform} from 'jscodeshift/dist/testUtils.js';
+import transform from '../transforms/v0.0.15/rename-imperative-ref-to-handleRef.mjs';
+
+const opts = {parser: 'tsx'};
+
+describe('rename-imperative-ref-to-handleRef', () => {
+ test.each([
+ 'XDSCalendar',
+ 'XDSChatComposerInput',
+ 'XDSPowerSearch',
+ 'XDSTokenizer',
+ 'XDSChartStreamGL',
+ ])('renames ref on %s', componentName => {
+ const input = `<${componentName} ref={handleRef} />`;
+ const output = applyTransform({default: transform, parser: 'tsx'}, opts, {
+ source: input,
+ });
+
+ expect(output).toContain('handleRef={handleRef}');
+ expect(output).not.toContain('ref={handleRef}');
+ });
+
+ test('renames sideNavRef on XDSSideNavCollapseButton', () => {
+ const input = `<XDSSideNavCollapseButton sideNavRef={sideNavRef} />`;
+ const output = applyTransform({default: transform, parser: 'tsx'}, opts, {
+ source: input,
+ });
+
+ expect(output).toContain('handleRef={sideNavRef}');
+ expect(output).not.toContain('sideNavRef=');
+ });
+
+ test('does not rename ref on DOM elements or unrelated components', () => {
+ const input = `
+ <>
+ <div ref={rootRef} />
+ <XDSButton ref={buttonRef} label="Save" />
+ </>
+ `;
+ const output = applyTransform({default: transform, parser: 'tsx'}, opts, {
+ source: input,
+ });
+
+ expect(output).toBe('');
+ });
+
+ test('renames multiple affected props in one file', () => {
+ const input = `
+ <>
+ <XDSCalendar ref={calendarRef} />
+ <XDSSideNavCollapseButton sideNavRef={sideNavRef} />
+ </>
+ `;
+ const output = applyTransform({default: transform, parser: 'tsx'}, opts, {
+ source: input,
+ });
+
+ expect(output.match(/handleRef=/g)).toHaveLength(2);
+ expect(output).not.toContain('sideNavRef=');
+ expect(output).not.toContain('ref={calendarRef}');
+ });
+});
diff --git a/packages/cli/src/codemods/transforms/v0.0.15/index.mjs b/packages/cli/src/codemods/transforms/v0.0.15/index.mjs
index bd3c88ac1d..2d0caa49fc 100644
--- a/packages/cli/src/codemods/transforms/v0.0.15/index.mjs
+++ b/packages/cli/src/codemods/transforms/v0.0.15/index.mjs
@@ -14,6 +14,10 @@ import renameIsStreamingToIsStopShown, {
meta as renameIsStreamingToIsStopShownMeta,
} from './rename-isStreaming-to-isStopShown.mjs';
+import renameImperativeRefToHandleRef, {
+ meta as renameImperativeRefToHandleRefMeta,
+} from './rename-imperative-ref-to-handleRef.mjs';
+
export default [
{
name: 'rename-date-picker-to-input',
@@ -25,4 +29,9 @@ export default [
transform: renameIsStreamingToIsStopShown,
meta: renameIsStreamingToIsStopShownMeta,
},
+ {
+ name: 'rename-imperative-ref-to-handleRef',
+ transform: renameImperativeRefToHandleRef,
+ meta: renameImperativeRefToHandleRefMeta,
+ },
];
diff --git a/packages/cli/src/codemods/transforms/v0.0.15/rename-imperative-ref-to-handleRef.mjs b/packages/cli/src/codemods/transforms/v0.0.15/rename-imperative-ref-to-handleRef.mjs
new file mode 100644
index 0000000000..35fd8ea2eb
--- /dev/null
+++ b/packages/cli/src/codemods/transforms/v0.0.15/rename-imperative-ref-to-handleRef.mjs
@@ -0,0 +1,67 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Codemod: Rename imperative ref props to handleRef
+ *
+ * XDS components reserve `ref` for DOM elements. Components with imperative
+ * handles now expose those handles through `handleRef`.
+ *
+ * Handles:
+ * - JSX prop: `ref` → `handleRef` on XDSCalendar, XDSChatComposerInput,
+ * XDSPowerSearch, XDSTokenizer, and XDSChartStreamGL
+ * - JSX prop: `sideNavRef` → `handleRef` on XDSSideNavCollapseButton
+ */
+
+export const meta = {
+ title: 'Rename imperative ref props to handleRef',
+ description:
+ 'Renames imperative `ref` usages to `handleRef` on XDS components whose ' +
+ '`ref` prop now points at the root DOM element. Also renames ' +
+ '`XDSSideNavCollapseButton` `sideNavRef` to `handleRef`.',
+ issue: '#2359',
+};
+
+const IMPERATIVE_REF_COMPONENTS = new Set([
+ 'XDSCalendar',
+ 'XDSChatComposerInput',
+ 'XDSPowerSearch',
+ 'XDSTokenizer',
+ 'XDSChartStreamGL',
+]);
+
+export default function transformer(file, api) {
+ const j = api.jscodeshift;
+ const root = j(file.source);
+ let hasChanges = false;
+
+ root.find(j.JSXOpeningElement).forEach(path => {
+ const name = path.node.name;
+ const componentName = name.type === 'JSXIdentifier' ? name.name : null;
+ if (componentName == null) return;
+
+ for (const attr of path.node.attributes) {
+ if (attr.type !== 'JSXAttribute') continue;
+
+ if (
+ IMPERATIVE_REF_COMPONENTS.has(componentName) &&
+ attr.name?.type === 'JSXIdentifier' &&
+ attr.name.name === 'ref'
+ ) {
+ attr.name.name = 'handleRef';
+ hasChanges = true;
+ }
+
+ if (
+ componentName === 'XDSSideNavCollapseButton' &&
+ attr.name?.type === 'JSXIdentifier' &&
+ attr.name.name === 'sideNavRef'
+ ) {
+ attr.name.name = 'handleRef';
+ hasChanges = true;
+ }
+ }
+ });
+
+ if (!hasChanges) return undefined;
+ return root.toSource({quote: 'single'});
+}
diff --git a/packages/cli/templates/blocks/components/ChatDictationButton/ChatDictationButtonShowcase.tsx b/packages/cli/templates/blocks/components/ChatDictationButton/ChatDictationButtonShowcase.tsx
index 148c188e7b..c8fe7df437 100644
--- a/packages/cli/templates/blocks/components/ChatDictationButton/ChatDictationButtonShowcase.tsx
+++ b/packages/cli/templates/blocks/components/ChatDictationButton/ChatDictationButtonShowcase.tsx
@@ -33,7 +33,7 @@ export default function ChatDictationButtonShowcase() {
<XDSChatComposer
onSubmit={(v) => console.log('Submit:', v)}
- input={<XDSChatComposerInput ref={inputRef} />}
+ input={<XDSChatComposerInput handleRef={inputRef} />}
sendActions={<XDSChatDictationButton dictation={dictation} />}
/>
diff --git a/packages/cli/templates/pages/ai-chat-landing/page.tsx b/packages/cli/templates/pages/ai-chat-landing/page.tsx
index 94e440f9c4..cb3ddf7203 100644
--- a/packages/cli/templates/pages/ai-chat-landing/page.tsx
+++ b/packages/cli/templates/pages/ai-chat-landing/page.tsx
@@ -503,7 +503,7 @@ export default function AIChatTemplate() {
placeholder="Ask anything"
input={
<XDSChatComposerInput
- ref={composerInputRef}
+ handleRef={composerInputRef}
triggers={composerTriggers}
style={{minHeight: inputMinHeight}}
/>
diff --git a/packages/core/src/Calendar/Calendar.doc.mjs b/packages/core/src/Calendar/Calendar.doc.mjs
index eb4ee134c3..32cd6b6cdd 100644
--- a/packages/core/src/Calendar/Calendar.doc.mjs
+++ b/packages/core/src/Calendar/Calendar.doc.mjs
@@ -76,6 +76,11 @@ export const docs = {
type: '(focusDate: ISODateString) => void',
description: 'Navigation callback.',
},
+ {
+ name: 'handleRef',
+ type: 'React.Ref<XDSCalendarHandle>',
+ description: 'Imperative handle for calendar navigation, including navigateTo().',
+ },
{
name: 'hasOutsideDays',
type: 'boolean',
@@ -135,6 +140,7 @@ export const docsZh = {
{name: 'dateConstraints', type: 'Array<(date: Date) => boolean>', description: '自定义约束函数。'},
{name: 'focusDate', type: 'ISODateString', description: '受控可见月份。'},
{name: 'onFocusDateChange', type: '(focusDate: ISODateString) => void', description: '导航回调函数。'},
+ {name: 'handleRef', type: 'React.Ref<XDSCalendarHandle>', description: '日历导航的命令式句柄,包括 navigateTo()。'},
{name: 'hasOutsideDays', type: 'boolean', description: '显示相邻月份的日期。', default: 'true'},
{name: 'hasWeekNumbers', type: 'boolean', description: '显示 ISO 周数。', default: 'false'},
{name: 'hasVariableRowCount', type: 'boolean', description: '可变行数与固定 6 行网格。', default: 'false'},
@@ -185,6 +191,7 @@ export const docsDense = {
dateConstraints: 'custom constraint fns',
focusDate: 'controlled visible month',
onFocusDateChange: 'navigation callback',
+ handleRef: 'imperative navigation handle',
hasOutsideDays: 'show days from adjacent months',
hasWeekNumbers: 'show ISO week numbers',
hasVariableRowCount: 'variable vs fixed 6-row grid',
diff --git a/packages/core/src/Calendar/XDSCalendar.test.tsx b/packages/core/src/Calendar/XDSCalendar.test.tsx
index 38866bcc26..113664627f 100644
--- a/packages/core/src/Calendar/XDSCalendar.test.tsx
+++ b/packages/core/src/Calendar/XDSCalendar.test.tsx
@@ -10,9 +10,10 @@
*/
import {describe, it, expect, vi} from 'vitest';
-import {render, screen} from '@testing-library/react';
+import {act, render, screen} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {XDSCalendar} from './XDSCalendar';
+import type {XDSCalendarHandle} from './XDSCalendar';
/**
* Helper to find a day button by its day number.
@@ -26,6 +27,34 @@ function getDayButton(day: number, month = 'January', year = 2026) {
describe('XDSCalendar', () => {
// ─── Basic Rendering ─────────────────────────────────────────
+ it('forwards ref to the calendar root element', () => {
+ let root: HTMLDivElement | null = null;
+ render(
+ <XDSCalendar
+ ref={el => {
+ root = el;
+ }}
+ />,
+ );
+ expect(root).toBeInstanceOf(HTMLDivElement);
+ });
+
+ it('exposes navigation through handleRef', () => {
+ let handle: XDSCalendarHandle | null = null;
+ render(
+ <XDSCalendar
+ handleRef={h => {
+ handle = h;
+ }}
+ />,
+ );
+
+ act(() => {
+ handle?.navigateTo('2026-03-01');
+ });
+
+ expect(screen.getByText('March 2026')).toBeInTheDocument();
+ });
it('renders current month by default', () => {
render(<XDSCalendar />);
diff --git a/packages/core/src/Calendar/XDSCalendar.tsx b/packages/core/src/Calendar/XDSCalendar.tsx
index 7e25ac9f0e..30067eab67 100644
--- a/packages/core/src/Calendar/XDSCalendar.tsx
+++ b/packages/core/src/Calendar/XDSCalendar.tsx
@@ -6,7 +6,8 @@
* @file XDSCalendar.tsx
* @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
+ * @position Core implementation; forwards DOM ref and exposes navigation via
+ * handleRef
*
* SYNC: When modified, update these files to stay in sync:
* - /packages/core/src/Calendar/Calendar.doc.mjs (props table, features, implementation notes)
@@ -67,7 +68,7 @@ import {xdsClassName, mergeProps} from '../utils';
export type {ISODateString, DayOfWeek, DateRange} from '../utils/dateTypes';
import type {ISODateString, DayOfWeek, DateRange} from '../utils/dateTypes';
-/** Imperative handle for XDSCalendar ref */
+/** Imperative handle for XDSCalendar handleRef */
export interface XDSCalendarHandle {
/** Navigate the calendar to show the month containing the given date */
@@ -80,8 +81,10 @@ interface XDSCalendarBaseProps extends Omit<
XDSBaseProps<HTMLDivElement>,
'onChange' | 'defaultValue'
> {
- /** Ref forwarded to the calendar (imperative handle) */
- ref?: React.Ref<XDSCalendarHandle>;
+ /** Ref forwarded to the calendar root element. */
+ ref?: React.Ref<HTMLDivElement>;
+ /** Imperative handle ref for calendar navigation. */
+ handleRef?: React.Ref<XDSCalendarHandle>;
/** Number of months to display (default: 1) */
numberOfMonths?: 1 | 2;
@@ -177,6 +180,7 @@ export type XDSCalendarProps = XDSCalendarSingleProps | XDSCalendarRangeProps;
*/
export function XDSCalendar({ref, ...props}: XDSCalendarProps) {
const {
+ handleRef,
mode = 'single',
value,
defaultValue,
@@ -242,7 +246,7 @@ export function XDSCalendar({ref, ...props}: XDSCalendarProps) {
// Expose imperative handle for external navigation
useImperativeHandle(
- ref,
+ handleRef,
() => ({
navigateTo: (date: ISODateString) => {
if (isControlledFocus) {
@@ -386,6 +390,7 @@ export function XDSCalendar({ref, ...props}: XDSCalendarProps) {
return (
<div
+ ref={ref}
{...mergeProps(
xdsClassName('calendar', {mode}),
stylex.props(calendarStyles.calendar, xstyle),
diff --git a/packages/core/src/Chat/Chat.doc.mjs b/packages/core/src/Chat/Chat.doc.mjs
index 60a0b987e4..c13240991e 100644
--- a/packages/core/src/Chat/Chat.doc.mjs
+++ b/packages/core/src/Chat/Chat.doc.mjs
@@ -143,7 +143,7 @@ export const docs = {
name: 'XDSChatComposerInput',
description: 'Rich text input for the chat composer. Supports trigger menus (type @ or / to open a typeahead), inline tokens rendered as badges, message history recall with ArrowUp/Down, paste/drop file handling, and a 16px touch-device font-size floor to prevent iOS input zoom. Pass it to XDSChatComposer\'s input slot when you need more than a plain textarea.',
props: [
- {name: 'ref', type: 'React.Ref<XDSChatComposerInputHandle>', description: 'Imperative handle for programmatic control — insertToken, insertText, focus, and getValue.'},
+ {name: 'handleRef', type: 'React.Ref<XDSChatComposerInputHandle>', description: 'Imperative handle for programmatic control — insertToken, insertText, focus, and getValue.'},
{name: 'value', type: 'string', description: 'Controlled input value. Pair with onChange for two-way binding.'},
{name: 'onChange', type: '(value: string) => void', description: 'Called when the input value changes. The serialized string includes token placeholders.'},
{name: 'placeholder', type: 'string', description: 'Placeholder text shown when the input is empty.', default: "'Type a message\u2026'"},
@@ -376,7 +376,7 @@ export const docsZh = {
description:
'聊天编写器的富文本输入。支持触发菜单(输入 @ 或 / 打开 typeahead)、内联标记徽章、ArrowUp/Down 消息历史回溯、粘贴/拖放文件处理,并在触控设备上将字体大小保持至少 16px 以避免 iOS 输入缩放。当需要普通文本区域以外的功能时,传入 XDSChatComposer 的 input 插槽。',
propDescriptions: {
- ref: '命令式句柄,用于编程式控制 — insertToken、insertText、focus 和 getValue。',
+ handleRef: '命令式句柄,用于编程式控制 — insertToken、insertText、focus 和 getValue。',
value: '受控输入值。与 onChange 配对实现双向绑定。',
onChange: '输入值变更时调用。序列化字符串包含标记占位符。',
placeholder: '输入为空时显示的占位文本。',
@@ -556,7 +556,7 @@ export const docsDense = {
name: 'XDSChatComposerInput',
description: 'rich input for composer; trigger menus (@/commands), inline tokens, msg history, paste/drop files, 16px touch font-size floor to prevent iOS zoom. Use in XDSChatComposer input slot when you need more than plain textarea.',
propDescriptions: {
- ref: 'imperative handle (insertToken/insertText/focus/getValue)',
+ handleRef: 'imperative handle (insertToken/insertText/focus/getValue)',
value: 'controlled value; pair w/ onChange for two-way binding',
onChange: 'value change handler; serialized string includes token placeholders',
placeholder: 'placeholder when empty',
diff --git a/packages/core/src/Chat/XDSChatComposerInput.test.tsx b/packages/core/src/Chat/XDSChatComposerInput.test.tsx
index 9e9b2946c3..1ab2b53b82 100644
--- a/packages/core/src/Chat/XDSChatComposerInput.test.tsx
+++ b/packages/core/src/Chat/XDSChatComposerInput.test.tsx
@@ -201,7 +201,7 @@ describe('XDSChatComposerInput', () => {
let handle: XDSChatComposerInputHandle | null = null;
render(
<XDSChatComposerInput
- ref={h => {
+ handleRef={h => {
handle = h;
}}
/>,
@@ -224,7 +224,7 @@ describe('XDSChatComposerInput', () => {
let handle: XDSChatComposerInputHandle | null = null;
render(
<XDSChatComposerInput
- ref={h => {
+ handleRef={h => {
handle = h;
}}
/>,
@@ -333,10 +333,23 @@ describe('XDSChatComposerInput', () => {
});
});
- describe('ref (imperative handle)', () => {
- it('exposes imperative handle via ref', () => {
+ describe('refs', () => {
+ it('forwards ref to the root element', () => {
+ let root: HTMLDivElement | null = null;
+ render(
+ <XDSChatComposerInput
+ ref={el => {
+ root = el;
+ }}
+ />,
+ );
+ expect(root).toBeInstanceOf(HTMLDivElement);
+ expect(root).toHaveClass('xds-chat-composer-input');
+ });
+
+ it('exposes imperative handle via handleRef', () => {
const ref = vi.fn();
- render(<XDSChatComposerInput ref={ref} />);
+ render(<XDSChatComposerInput handleRef={ref} />);
expect(ref).toHaveBeenCalledWith(
expect.objectContaining({
insertToken: expect.any(Function),
@@ -351,7 +364,7 @@ describe('XDSChatComposerInput', () => {
let handle: XDSChatComposerInputHandle | null = null;
render(
<XDSChatComposerInput
- ref={h => {
+ handleRef={h => {
handle = h;
}}
/>,
@@ -366,7 +379,7 @@ describe('XDSChatComposerInput', () => {
const onChange = vi.fn();
render(
<XDSChatComposerInput
- ref={h => {
+ handleRef={h => {
handle = h;
}}
onChange={onChange}
@@ -418,7 +431,7 @@ describe('XDSChatComposerInput', () => {
const onChange = vi.fn();
render(
<XDSChatComposerInput
- ref={h => {
+ handleRef={h => {
handle = h;
}}
onChange={onChange}
@@ -573,7 +586,7 @@ describe('XDSChatComposerInput', () => {
const onChange = vi.fn();
render(
<XDSChatComposerInput
- ref={h => {
+ handleRef={h => {
handle = h;
}}
triggers={triggers}
diff --git a/packages/core/src/Chat/XDSChatComposerInput.tsx b/packages/core/src/Chat/XDSChatComposerInput.tsx
index efc085845d..32f27b1b33 100644
--- a/packages/core/src/Chat/XDSChatComposerInput.tsx
+++ b/packages/core/src/Chat/XDSChatComposerInput.tsx
@@ -6,7 +6,8 @@
* @file XDSChatComposerInput.tsx
* @input Uses React, StyleX, useTriggerMenu, XDSSearchSource
* @output Exports XDSChatComposerInput rich input + trigger types
- * @position Core implementation; consumed by index.ts, XDSChatComposer
+ * @position Core implementation; consumed by index.ts, XDSChatComposer;
+ * forwards DOM ref and exposes editor control via handleRef
*
* ContentEditable-based rich input for the chat composer.
* Supports trigger menus (@ mentions, / commands) via XDSSearchSource,
@@ -59,7 +60,7 @@ import {useXDSChatComposerContext} from './XDSChatContext';
// Types
// =============================================================================
-/** Imperative handle exposed by XDSChatComposerInput via ref */
+/** Imperative handle exposed by XDSChatComposerInput via handleRef */
export interface XDSChatComposerInputHandle {
/** Insert a token (badge chip) at the current cursor position */
insertToken: (token: XDSChatComposerToken) => string | undefined;
@@ -148,8 +149,10 @@ export interface XDSChatComposerInputProps extends Omit<
XDSBaseProps<HTMLDivElement>,
'onChange' | 'onPaste' | 'onSubmit'
> {
- /** Imperative handle ref for programmatic control */
- ref?: React.Ref<XDSChatComposerInputHandle>;
+ /** Ref forwarded to the root element. */
+ ref?: React.Ref<HTMLDivElement>;
+ /** Imperative handle ref for programmatic control. */
+ handleRef?: React.Ref<XDSChatComposerInputHandle>;
/** Controlled value */
value?: string;
/** Change handler */
@@ -282,6 +285,7 @@ export function XDSChatComposerInput(props: XDSChatComposerInputProps) {
const {
ref,
+ handleRef,
value: controlledValue = composerCtx?.value,
onChange = composerCtx?.onChange,
placeholder = composerCtx?.placeholder ?? 'Type a message\u2026',
@@ -330,7 +334,7 @@ export function XDSChatComposerInput(props: XDSChatComposerInputProps) {
serialize(editableRef.current ?? document.createElement('div')),
};
selfRef.current = handle;
- useImperativeHandle(ref, () => handle);
+ useImperativeHandle(handleRef, () => handle);
useEffect(() => {
if (controlledValue !== undefined && editableRef.current) {
@@ -568,6 +572,7 @@ export function XDSChatComposerInput(props: XDSChatComposerInputProps) {
return (
<div
+ ref={ref}
{...mergeProps(
xdsClassName('chat-composer-input'),
stylex.props(styles.root, isDisabled && styles.disabled, xstyle),
diff --git a/packages/core/src/DateInput/XDSDateInput.tsx b/packages/core/src/DateInput/XDSDateInput.tsx
index 11d7fa604a..e29d8f2557 100644
--- a/packages/core/src/DateInput/XDSDateInput.tsx
+++ b/packages/core/src/DateInput/XDSDateInput.tsx
@@ -577,7 +577,7 @@ export function XDSDateInput({
</div>
{popover.render(
<XDSCalendar
- ref={calendarRef}
+ handleRef={calendarRef}
mode="single"
value={optimisticValue}
onChange={handleDateSelect}
diff --git a/packages/core/src/DateTimeInput/XDSDateTimeInput.tsx b/packages/core/src/DateTimeInput/XDSDateTimeInput.tsx
index 8045c860cd..0c4cf1be3e 100644
--- a/packages/core/src/DateTimeInput/XDSDateTimeInput.tsx
+++ b/packages/core/src/DateTimeInput/XDSDateTimeInput.tsx
@@ -898,7 +898,7 @@ export function XDSDateTimeInput({
{popover.render(
<XDSCalendar
- ref={calendarRef}
+ handleRef={calendarRef}
mode="single"
value={valueParts.date}
onChange={(d: ISODateString) => handleDateChange(d, 'calendar')}
diff --git a/packages/core/src/PowerSearch/PowerSearch.doc.mjs b/packages/core/src/PowerSearch/PowerSearch.doc.mjs
index e597d0409a..013a35384c 100644
--- a/packages/core/src/PowerSearch/PowerSearch.doc.mjs
+++ b/packages/core/src/PowerSearch/PowerSearch.doc.mjs
@@ -93,7 +93,7 @@ export const docs = {
description: 'Timezone ID for date formatting (e.g. "America/New_York").',
},
{
- name: 'ref',
+ name: 'handleRef',
type: 'Ref<XDSPowerSearchHandle>',
description:
'Imperative handle with focusTypeahead() and blurTypeahead() methods.',
@@ -232,7 +232,7 @@ export const docsZh = {
description: '用于日期格式化的时区 ID(例如 "America/New_York")。',
},
{
- name: 'ref',
+ name: 'handleRef',
type: 'Ref<XDSPowerSearchHandle>',
description: '提供 focusTypeahead() 和 blurTypeahead() 方法的命令式句柄。',
},
@@ -298,7 +298,7 @@ export const docsDense = {
maxTokenLength: 'Max char length for filter value display in tokens.',
popoverSaveButtonLabel: 'Label for save button in edit popover.',
timezoneID: 'Timezone ID for date formatting (e.g. "America/New_York").',
- ref: 'Imperative handle w/ focusTypeahead() + blurTypeahead() methods.',
+ handleRef: 'Imperative handle w/ focusTypeahead() + blurTypeahead() methods.',
endContent: 'Content at end of input row. Useful for action buttons or controls.',
resultCount: 'Result count matching current filters. Number formatted as "N results"; string displayed as-is.',
size: 'Search input+token size.',
diff --git a/packages/core/src/PowerSearch/XDSPowerSearch.test.tsx b/packages/core/src/PowerSearch/XDSPowerSearch.test.tsx
index f03c54d72e..f0e9d35a15 100644
--- a/packages/core/src/PowerSearch/XDSPowerSearch.test.tsx
+++ b/packages/core/src/PowerSearch/XDSPowerSearch.test.tsx
@@ -113,6 +113,43 @@ function PowerSearchWrapper(props: {config: PowerSearchConfig}) {
// =============================================================================
describe('XDSPowerSearch', () => {
+ it('forwards ref to the root element', () => {
+ let root: HTMLDivElement | null = null;
+ render(
+ <XDSPowerSearch
+ ref={el => {
+ root = el;
+ }}
+ config={config}
+ filters={[]}
+ onChange={() => {}}
+ />,
+ );
+ expect(root).toBeInstanceOf(HTMLDivElement);
+ expect(root).toHaveClass('xds-power-search');
+ });
+
+ it('exposes typeahead focus through handleRef', () => {
+ let handle: {focusTypeahead: () => void; blurTypeahead: () => void} | null =
+ null;
+ render(
+ <XDSPowerSearch
+ handleRef={h => {
+ handle = h;
+ }}
+ config={config}
+ filters={[]}
+ onChange={() => {}}
+ />,
+ );
+
+ act(() => {
+ handle?.focusTypeahead();
+ });
+
+ expect(screen.getByRole('combobox')).toHaveFocus();
+ });
+
describe('paste behavior', () => {
it('pasting a field name shows matching field suggestions', async () => {
const user = userEvent.setup();
diff --git a/packages/core/src/PowerSearch/XDSPowerSearch.tsx b/packages/core/src/PowerSearch/XDSPowerSearch.tsx
index 3a36380f5e..79bcb86d9f 100644
--- a/packages/core/src/PowerSearch/XDSPowerSearch.tsx
+++ b/packages/core/src/PowerSearch/XDSPowerSearch.tsx
@@ -6,7 +6,8 @@
* @file XDSPowerSearch.tsx
* @input PowerSearchConfig, filters, onChange
* @output Structured filter bar with token-based filter management
- * @position Main component; composed from XDSTokenizer + edit popover
+ * @position Main component; forwards DOM ref and exposes tokenizer control via
+ * handleRef
*
* SYNC: When modified, update:
* - /packages/core/src/PowerSearch/index.ts
@@ -43,7 +44,7 @@ import {
typeScaleVars,
fontWeightVars,
} from '../theme/tokens.stylex';
-import {xdsClassName} from '../utils';
+import {xdsClassName, mergeRefs} from '../utils';
import {useXDSSize} from '../SizeContext/XDSSizeContext';
import {useInternalConfig} from './useInternalConfig';
import {usePowerSearchSource} from './usePowerSearchSource';
@@ -393,8 +394,10 @@ export interface XDSPowerSearchProps extends Omit<
* When a number, formatted as "N results". When a string, displayed as-is.
*/
resultCount?: number | string;
+ /** Ref forwarded to the root element. */
+ ref?: React.Ref<HTMLDivElement>;
/** Imperative handle ref. */
- ref?: React.Ref<XDSPowerSearchHandle>;
+ handleRef?: React.Ref<XDSPowerSearchHandle>;
/**
* Size of the search input.
* @default 'md'
@@ -515,6 +518,7 @@ export function XDSPowerSearch({
endContent,
resultCount,
ref,
+ handleRef,
size: sizeProp,
'data-testid': testId,
xstyle,
@@ -563,7 +567,7 @@ export function XDSPowerSearch({
);
// Expose imperative handle
- useImperativeHandle(ref, () => ({
+ useImperativeHandle(handleRef, () => ({
focusTypeahead() {
tokenizerRef.current?.focus();
},
@@ -959,9 +963,11 @@ export function XDSPowerSearch({
return (
<>
- <div ref={popover.triggerRef} className={xdsClassName('power-search')}>
+ <div
+ ref={mergeRefs(ref, popover.triggerRef as React.Ref<HTMLDivElement>)}
+ className={xdsClassName('power-search')}>
<XDSTokenizer
- ref={tokenizerRef}
+ handleRef={tokenizerRef}
label={label}
isLabelHidden={isLabelHidden}
searchSource={searchSource}
diff --git a/packages/core/src/Tokenizer/Tokenizer.doc.mjs b/packages/core/src/Tokenizer/Tokenizer.doc.mjs
index 1c9984457f..9659cb135a 100644
--- a/packages/core/src/Tokenizer/Tokenizer.doc.mjs
+++ b/packages/core/src/Tokenizer/Tokenizer.doc.mjs
@@ -161,6 +161,11 @@ export const docs = {
{__element: 'XDSBadge', props: {label: '3'}},
],
},
+ {
+ name: 'handleRef',
+ type: 'React.Ref<XDSTokenizerHandle>',
+ description: 'Imperative handle for focus() and blur() control.',
+ },
{
name: 'xstyle',
type: 'StyleXStyles',
@@ -344,6 +349,11 @@ export const docsZh = {
description:
'\u5728\u8f93\u5165\u884c\u672b\u5c3e\u663e\u793a\u7684\u5185\u5bb9\u3002\u9002\u7528\u4e8e\u6309\u94ae\u3001\u7ed3\u679c\u8ba1\u6570\u6216\u5176\u4ed6\u63a7\u4ef6\u3002',
},
+ {
+ name: 'handleRef',
+ type: 'React.Ref<XDSTokenizerHandle>',
+ description: '用于 focus() 和 blur() 控制的命令式句柄。',
+ },
{
name: 'xstyle',
type: 'StyleXStyles',
@@ -421,6 +431,7 @@ export const docsDense = {
debounceMs: 'Search debounce delay ms. 0 for sync sources.',
onChangeQuery: 'Fired on search query text change.',
endContent: 'Content at input row end. For buttons, counts, controls.',
+ handleRef: 'Imperative handle for focus() and blur() control.',
xstyle: 'StyleX layout styles (margins, positioning). Must be stylex.create() value.',
},
};
diff --git a/packages/core/src/Tokenizer/XDSTokenizer.test.tsx b/packages/core/src/Tokenizer/XDSTokenizer.test.tsx
index 68a3705689..a2040613cc 100644
--- a/packages/core/src/Tokenizer/XDSTokenizer.test.tsx
+++ b/packages/core/src/Tokenizer/XDSTokenizer.test.tsx
@@ -75,6 +75,44 @@ const userSource: XDSSearchSource = {
};
describe('XDSTokenizer', () => {
+ it('forwards ref to the root field element', () => {
+ let root: HTMLDivElement | null = null;
+ render(
+ <XDSTokenizer
+ ref={el => {
+ root = el;
+ }}
+ label="Members"
+ searchSource={userSource}
+ value={[]}
+ onChange={() => {}}
+ />,
+ );
+ expect(root).toBeInstanceOf(HTMLDivElement);
+ expect(root).toHaveClass('xds-field');
+ });
+
+ it('exposes focus control through handleRef', () => {
+ let handle: {focus: () => void; blur: () => void} | null = null;
+ render(
+ <XDSTokenizer
+ handleRef={h => {
+ handle = h;
+ }}
+ label="Members"
+ searchSource={userSource}
+ value={[]}
+ onChange={() => {}}
+ />,
+ );
+
+ act(() => {
+ handle?.focus();
+ });
+
+ expect(screen.getByRole('combobox')).toHaveFocus();
+ });
+
it('renders with label', () => {
render(
<XDSTokenizer
diff --git a/packages/core/src/Tokenizer/XDSTokenizer.tsx b/packages/core/src/Tokenizer/XDSTokenizer.tsx
index 093a47115e..54fce63468 100644
--- a/packages/core/src/Tokenizer/XDSTokenizer.tsx
+++ b/packages/core/src/Tokenizer/XDSTokenizer.tsx
@@ -6,7 +6,8 @@
* @file XDSTokenizer.tsx
* @input Uses React, XDSBaseTypeahead, XDSField, XDSToken
* @output Exports XDSTokenizer multi-select typeahead component
- * @position Composed component; uses XDSBaseTypeahead for search + XDSToken for chips
+ * @position Composed component; forwards DOM ref and exposes focus control via
+ * handleRef
*
* SYNC: When modified, update:
* - /packages/core/src/Tokenizer/index.ts
@@ -82,7 +83,7 @@ export type XDSTokenizerOverflowBehavior =
| 'unfocusedLayer';
/**
- * Imperative handle for XDSTokenizer.
+ * Imperative handle for XDSTokenizer handleRef.
*/
export interface XDSTokenizerHandle {
/** Focus the typeahead input. */
@@ -174,8 +175,10 @@ export interface XDSTokenizerProps<T extends XDSSearchableItem> extends Omit<
onFocus?: (e: React.FocusEvent) => void;
/** Fires when focus leaves the tokenizer entirely. */
onBlur?: (e: React.FocusEvent) => void;
+ /** Ref forwarded to the root field element. */
+ ref?: React.Ref<HTMLDivElement>;
/** Imperative handle ref for focus/blur control. */
- ref?: React.Ref<XDSTokenizerHandle>;
+ handleRef?: React.Ref<XDSTokenizerHandle>;
}
// =============================================================================
@@ -366,6 +369,7 @@ export function XDSTokenizer<T extends XDSSearchableItem>({
style,
'data-testid': testId,
ref,
+ handleRef,
}: XDSTokenizerProps<T>) {
const size = useXDSSize(sizeProp, 'md');
const inputId = useId();
@@ -374,7 +378,7 @@ export function XDSTokenizer<T extends XDSSearchableItem>({
const inputRef = useRef<HTMLInputElement>(null);
const wrapperRef = useRef<HTMLDivElement>(null);
- useImperativeHandle(ref, () => ({
+ useImperativeHandle(handleRef, () => ({
focus() {
inputRef.current?.focus();
},
@@ -791,6 +795,7 @@ export function XDSTokenizer<T extends XDSSearchableItem>({
return (
<XDSField
+ ref={ref}
label={label}
isLabelHidden={isLabelHidden}
description={description}
diff --git a/packages/lab/src/Chart/XDSChartStreamGL.tsx b/packages/lab/src/Chart/XDSChartStreamGL.tsx
index 20a10c9c10..74cf28a6ab 100644
--- a/packages/lab/src/Chart/XDSChartStreamGL.tsx
+++ b/packages/lab/src/Chart/XDSChartStreamGL.tsx
@@ -9,13 +9,9 @@
* For streaming, the parent should update xDomain as new data arrives.
*/
-import {
- useRef,
- useEffect,
- useImperativeHandle,
- forwardRef,
- useCallback,
-} from 'react';
+import {useRef, useEffect, useImperativeHandle, useCallback} from 'react';
+import type {Ref} from 'react';
+import {mergeRefs} from '@xds/core/utils';
import {useChart} from './ChartContext';
import {
hexToGL,
@@ -27,6 +23,10 @@ import {
} from './webgl';
export interface XDSChartStreamGLProps {
+ /** Ref forwarded to the SVG marker element used to position the canvas. */
+ ref?: Ref<SVGGElement>;
+ /** Imperative handle ref for streaming data control. */
+ handleRef?: Ref<XDSChartStreamGLHandle>;
color: string;
bufferSize?: number;
lineWidth?: number;
@@ -57,13 +57,14 @@ const FRAG = `
}
`;
-export const XDSChartStreamGL = forwardRef<
- XDSChartStreamGLHandle,
- XDSChartStreamGLProps
->(function XDSChartStreamGL(
- {color, bufferSize = 500, lineWidth = 2, opacity = 1},
+export function XDSChartStreamGL({
ref,
-) {
+ handleRef,
+ color,
+ bufferSize = 500,
+ lineWidth = 2,
+ opacity = 1,
+}: XDSChartStreamGLProps) {
const {width, height, xScale, yScale} = useChart();
const canvasRef = useRef<HTMLCanvasElement | null>(null);
const glRef = useRef<WebGLRenderingContext | null>(null);
@@ -157,7 +158,7 @@ export const XDSChartStreamGL = forwardRef<
}, [width, height, color, lineWidth, opacity, bufferSize, xScale, yScale]);
useImperativeHandle(
- ref,
+ handleRef,
() => ({
push(x: number, y: number) {
const r = ring.current;
@@ -184,5 +185,5 @@ export const XDSChartStreamGL = forwardRef<
if (width <= 0 || height <= 0) {
return null;
}
- return <g ref={markerRef} />;
-});
+ return <g ref={mergeRefs(markerRef, ref)} />;
+}
diff --git a/packages/lab/src/Chart/useXDSChartRange.ts b/packages/lab/src/Chart/useXDSChartRange.ts
index 39c417e958..f6dd890540 100644
--- a/packages/lab/src/Chart/useXDSChartRange.ts
+++ b/packages/lab/src/Chart/useXDSChartRange.ts
@@ -62,7 +62,7 @@ export interface UseXDSChartRangeReturn {
* const {xDomain, yDomain, push} = useXDSChartRange({xWindow: 300, yPadding: 0.1});
*
* <XDSChart xDomain={xDomain} yDomain={yDomain} ...>
- * <XDSChartStreamGL ref={streamRef} ... />
+ * <XDSChartStreamGL handleRef={streamRef} ... />
* </XDSChart>
* ```
*/