Skip to content

Commit

Permalink
Added getItemTextValue util (deephaven#2065)
Browse files Browse the repository at this point in the history
  • Loading branch information
bmingles committed Jun 12, 2024
1 parent 42009d4 commit 8c20753
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
35 changes: 35 additions & 0 deletions packages/components/src/spectrum/utils/itemUtils.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -37,6 +39,39 @@ describe('getItemKey', () => {
);
});

describe('getItemTextValue', () => {
it.each([
[<Item key="">string</Item>, 'string'],
[<Item key="">{4}</Item>, '4'],
[<Item key="">{true}</Item>, 'true'],
[<Item key="">{false}</Item>, 'false'],
[
<Item key="" textValue="textValue">
string
</Item>,
'textValue',
],
[
<Item key="" textValue="">
string
</Item>,
ITEM_EMPTY_STRING_TEXT_VALUE,
],
[
<Item key="">
<span>object</span>
</Item>,
undefined,
],
])(
'should return the expected `textValue`: %s, %s',
(item, expectedValue) => {
const actual = getItemTextValue(item);
expect(actual).toBe(expectedValue);
}
);
});

describe('getPositionOfSelectedItemElement', () => {
const items = [
<Item key="1">A</Item>,
Expand Down
18 changes: 18 additions & 0 deletions packages/components/src/spectrum/utils/itemUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<T>(item: ItemElement<T>): 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
Expand Down

0 comments on commit 8c20753

Please sign in to comment.