diff --git a/packages/components/src/spectrum/utils/itemUtils.test.tsx b/packages/components/src/spectrum/utils/itemUtils.test.tsx index 3389b8c90..51c6932a9 100644 --- a/packages/components/src/spectrum/utils/itemUtils.test.tsx +++ b/packages/components/src/spectrum/utils/itemUtils.test.tsx @@ -14,6 +14,8 @@ import { itemSelectionToStringSet, getPositionOfSelectedItemElement, isItemElementWithDescription, + getItemTextValue, + ITEM_EMPTY_STRING_TEXT_VALUE, } from './itemUtils'; import { Item, ItemElementOrPrimitive, Section } from '../shared'; import { Text } from '../Text'; @@ -37,6 +39,39 @@ describe('getItemKey', () => { ); }); +describe('getItemTextValue', () => { + it.each([ + [string, 'string'], + [{4}, '4'], + [{true}, 'true'], + [{false}, 'false'], + [ + + string + , + 'textValue', + ], + [ + + string + , + ITEM_EMPTY_STRING_TEXT_VALUE, + ], + [ + + object + , + undefined, + ], + ])( + 'should return the expected `textValue`: %s, %s', + (item, expectedValue) => { + const actual = getItemTextValue(item); + expect(actual).toBe(expectedValue); + } + ); +}); + describe('getPositionOfSelectedItemElement', () => { const items = [ A, diff --git a/packages/components/src/spectrum/utils/itemUtils.ts b/packages/components/src/spectrum/utils/itemUtils.ts index 515f182be..021edac73 100644 --- a/packages/components/src/spectrum/utils/itemUtils.ts +++ b/packages/components/src/spectrum/utils/itemUtils.ts @@ -132,6 +132,24 @@ export function getItemKey< return (item?.item?.key ?? item?.key) as TKey; } +/** + * Determine Item `textValue` based on the `textValue` prop or primitive children + * value. + * @param item The item to get the text value for + * @returns The text value of the item + */ +export function getItemTextValue(item: ItemElement): string | undefined { + if (item.props.textValue == null) { + return ['string', 'boolean', 'number'].includes(typeof item.props.children) + ? String(item.props.children) + : undefined; + } + + return item.props.textValue === '' + ? ITEM_EMPTY_STRING_TEXT_VALUE + : item.props.textValue; +} + /** * Get the position of the item with the given selected key in a list of items. * @param items The items to search