An open source design system that's fully customizable and agent ready
TypeScript
fix(typeahead): guard selected state for missing ids (#2828)
Cindy Zhang69ddf74708e4
diff --git a/.changeset/typeahead-idless-selection.md b/.changeset/typeahead-idless-selection.mdnew file mode 100644index 0000000000..0d1392fe6f--- /dev/null+++ b/.changeset/typeahead-idless-selection.md@@ -0,0 +1,5 @@+---+'@xds/core': patch+---++`XDSBaseTypeahead` now uses a shared key fallback for runtime search results without `id` values, so id-less rows no longer all render as selected.diff --git a/apps/docsite/src/app/(site)/community/page.tsx b/apps/docsite/src/app/(site)/community/page.tsxindex b1e758d06d..daaed0ca7d 100644--- a/apps/docsite/src/app/(site)/community/page.tsx+++ b/apps/docsite/src/app/(site)/community/page.tsx@@ -36,6 +36,7 @@ import {XDSList, XDSListItem} from '@xds/core/List';import {XDSSection} from '@xds/core/Section';import {XDSHeading, XDSText} from '@xds/core/Text';import {XDSButton} from '@xds/core/Button';+import {getKey} from '@xds/core/utils';import {GITHUB_REPO} from '../../../constants';const WIKI_BASE = `${GITHUB_REPO}/wiki`;@@ -566,7 +567,7 @@ function WallCard({contributors}: {contributors: ReadonlyArray<Contributor>}) {// remaining slots so the card always looks fully populated.const avatars = AVATAR_SLOTS.map((slot, i) => ({src: contributors[i]?.avatar_url ?? FALLBACK_AVATARS[i],- key: contributors[i]?.login ?? `fallback-${i}`,+ key: getKey(contributors[i]?.login, i),slot,}));diff --git a/packages/core/src/Chat/XDSChatToolCalls.tsx b/packages/core/src/Chat/XDSChatToolCalls.tsxindex 2662442665..a156d75c21 100644--- a/packages/core/src/Chat/XDSChatToolCalls.tsx+++ b/packages/core/src/Chat/XDSChatToolCalls.tsx@@ -31,7 +31,7 @@ import {durationVars,easeVars,} from '../theme/tokens.stylex';-import {mergeProps} from '../utils';+import {getKey, mergeProps} from '../utils';import {XDSBadge} from '../Badge';import {XDSIcon, type XDSIconName} from '../Icon';import {XDSSpinner} from '../Spinner';@@ -334,20 +334,18 @@ const STATUS_STYLES: Record<};function getToolCallKey(call: XDSChatToolCallItem): string {- if (call.key != null) {- return call.key;- }-- return [- call.name,- call.status ?? 'complete',- call.target ?? '',- call.node ?? '',- call.duration ?? '',- call.additions?.toString() ?? '',- call.deletions?.toString() ?? '',- call.errorMessage ?? '',- ].join('\u001F');+ return getKey(call.key, () =>+ [+ call.name,+ call.status ?? 'complete',+ call.target ?? '',+ call.node ?? '',+ call.duration ?? '',+ call.additions?.toString() ?? '',+ call.deletions?.toString() ?? '',+ call.errorMessage ?? '',+ ].join('\u001F'),+ );}// =============================================================================diff --git a/packages/core/src/Typeahead/XDSBaseTypeahead.tsx b/packages/core/src/Typeahead/XDSBaseTypeahead.tsxindex af6014d41d..05e469e6d0 100644--- a/packages/core/src/Typeahead/XDSBaseTypeahead.tsx+++ b/packages/core/src/Typeahead/XDSBaseTypeahead.tsx@@ -39,7 +39,7 @@ import {fontWeightVars,typeScaleVars,} from '../theme/tokens.stylex';-import {mergeProps, mergeRefs} from '../utils';+import {getKey, mergeProps, mergeRefs} from '../utils';import type {XDSBaseProps} from '../XDSBaseProps';import type {XDSSearchableItem, XDSSearchSource} from './types';import {xdsThemeProps} from '../utils/xdsThemeProps';@@ -615,6 +615,9 @@ export const XDSBaseTypeahead = function XDSBaseTypeahead<[listboxId],);+ const selectedKey =+ value == null ? null : getKey(value.id, () => results.indexOf(value));+// Cleanup timeout and cancel in-flight searches on unmountuseEffect(() => {return () => {@@ -689,33 +692,37 @@ export const XDSBaseTypeahead = function XDSBaseTypeahead<{emptySearchResultsText}</div>) : (- results.map((item, index) => (- <div- key={item.id}- id={getItemId(index)}- role="option"- aria-selected={value?.id === item.id}- tabIndex={-1}- onClick={() => handleSelect(item)}- onMouseEnter={() => setHighlightedIndex(index)}- {...stylex.props(- styles.item,- itemSizeStyles[size],- index === highlightedIndex && styles.itemHighlighted,- value?.id === item.id && styles.itemSelected,- )}>- <span {...stylex.props(styles.itemContent)}>- {renderItem ? (- renderItem(item)- ) : (- <XDSTypeaheadItem item={item} />+ results.map((item, index) => {+ const itemKey = getKey(item.id, index);+ const isSelected = itemKey === selectedKey;+ return (+ <div+ key={itemKey}+ id={getItemId(index)}+ role="option"+ aria-selected={isSelected}+ tabIndex={-1}+ onClick={() => handleSelect(item)}+ onMouseEnter={() => setHighlightedIndex(index)}+ {...stylex.props(+ styles.item,+ itemSizeStyles[size],+ index === highlightedIndex && styles.itemHighlighted,+ isSelected && styles.itemSelected,+ )}>+ <span {...stylex.props(styles.itemContent)}>+ {renderItem ? (+ renderItem(item)+ ) : (+ <XDSTypeaheadItem item={item} />+ )}+ </span>+ {isSelected && (+ <XDSIcon icon="check" size="sm" color="primary" />)}- </span>- {value?.id === item.id && (- <XDSIcon icon="check" size="sm" color="primary" />- )}- </div>- ))+ </div>+ );+ }))}</div>,{diff --git a/packages/core/src/Typeahead/XDSTypeahead.test.tsx b/packages/core/src/Typeahead/XDSTypeahead.test.tsxindex f220ba5625..9b5aed6e77 100644--- a/packages/core/src/Typeahead/XDSTypeahead.test.tsx+++ b/packages/core/src/Typeahead/XDSTypeahead.test.tsx@@ -147,6 +147,37 @@ describe('XDSBaseTypeahead', () => {// Component renders without error — anchor is wired up internallyexpect(screen.getByRole('combobox')).toBeInTheDocument();});++ it('does not select every result when items lack ids', async () => {+ const idlessItems = [+ {label: 'Alpha'},+ {label: 'Beta'},+ ] as unknown as XDSSearchableItem[];+ const idlessSource: XDSSearchSource = {+ search: () => idlessItems,+ bootstrap: () => idlessItems,+ };++ render(+ <XDSBaseTypeahead+ searchSource={idlessSource}+ value={idlessItems[0]}+ onChange={() => {}}+ hasEntriesOnFocus+ debounceMs={0}+ />,+ );++ fireEvent.focus(screen.getByRole('combobox'));++ await waitFor(() => {+ expect(screen.getAllByRole('option', {hidden: true})).toHaveLength(2);+ });++ const options = screen.getAllByRole('option', {hidden: true});+ expect(options[0]).toHaveAttribute('aria-selected', 'true');+ expect(options[1]).toHaveAttribute('aria-selected', 'false');+ });});describe('XDSTypeahead', () => {diff --git a/packages/core/src/utils/getKey.test.ts b/packages/core/src/utils/getKey.test.tsnew file mode 100644index 0000000000..4a70166a42--- /dev/null+++ b/packages/core/src/utils/getKey.test.ts@@ -0,0 +1,25 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, expect, it} from 'vitest';+import {getKey} from './getKey';++describe('getKey', () => {+ it('uses the id key when present', () => {+ expect(getKey('alpha', 0)).toBe('id:alpha');+ expect(getKey(0, 1)).toBe('id:0');+ });++ it('uses the fallback key only when the id key is missing', () => {+ expect(getKey(undefined, 0)).toBe('fallback:0');+ expect(getKey(null, 'empty')).toBe('fallback:empty');+ expect(getKey(undefined, () => 2)).toBe('fallback:2');+ });++ it('does not read lazy fallback keys when the id key is present', () => {+ expect(+ getKey('alpha', () => {+ throw new Error('Fallback should not be read');+ }),+ ).toBe('id:alpha');+ });+});diff --git a/packages/core/src/utils/getKey.ts b/packages/core/src/utils/getKey.tsnew file mode 100644index 0000000000..df56a9c83a--- /dev/null+++ b/packages/core/src/utils/getKey.ts@@ -0,0 +1,23 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file getKey.ts+ * @input Receives an optional id key and required fallback key+ * @output Exports getKey for stable React list keys+ * @position Shared utility; consumed by components that render keyed lists+ */++export type XDSKey = string | number;+export type XDSKeyFallback = XDSKey | (() => XDSKey);++export function getKey(+ idKey: XDSKey | null | undefined,+ fallback: XDSKeyFallback,+): string {+ if (idKey != null) {+ return `id:${idKey}`;+ }++ const fallbackKey = typeof fallback === 'function' ? fallback() : fallback;+ return `fallback:${fallbackKey}`;+}diff --git a/packages/core/src/utils/index.ts b/packages/core/src/utils/index.tsindex bfff45382c..b52d632b36 100644--- a/packages/core/src/utils/index.ts+++ b/packages/core/src/utils/index.ts@@ -64,6 +64,7 @@ export {export type {ISOTimeString, ParsedTime} from './timeParser';export {parseStyleKey} from './parseStyleKey';+export {getKey, type XDSKey, type XDSKeyFallback} from './getKey';export {mergeProps} from './mergeProps';export {mergeRefs} from './mergeRefs';