Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@
"babel-plugin-react-remove-properties": "^0.3.0",
"babel-plugin-transform-glob-import": "^1.0.1",
"chalk": "^4.1.2",
"chromatic": "^13.1.3",
"chromatic": "^15.0.0",
"clsx": "^2.0.0",
"color-space": "^1.16.0",
"concurrently": "^6.0.2",
Expand Down
37 changes: 28 additions & 9 deletions packages/@react-spectrum/s2/src/Picker.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,13 @@ export interface PickerProps<T extends object, M extends SelectionMode = 'single
/** Width of the menu. By default, matches width of the trigger. Note that the minimum width of the dropdown is always equal to the trigger's width. */
menuWidth?: number,
/** The current loading state of the Picker. */
loadingState?: LoadingState
loadingState?: LoadingState,
/**
* Custom renderer for the picker value. Allows one to provide a custom element to render selected items.
*
* @note The returned ReactNode should not have interactable elements as it will break accessibility.
*/
renderValue?: (selectedItems: T[]) => ReactNode
}

interface PickerButtonProps extends PickerStyleProps, ButtonRenderProps {}
Expand Down Expand Up @@ -227,7 +233,8 @@ const valueStyles = style({
},
truncate: true,
display: 'flex',
alignItems: 'center'
alignItems: 'center',
height: '100%'
});

const iconStyles = style({
Expand Down Expand Up @@ -298,6 +305,7 @@ export const Picker = /*#__PURE__*/ (forwardRef as forwardRefType)(function Pick
placeholder = stringFormatter.format('picker.placeholder'),
isQuiet,
loadingState,
renderValue,
onLoadMore,
...pickerProps
} = props;
Expand Down Expand Up @@ -376,6 +384,7 @@ export const Picker = /*#__PURE__*/ (forwardRef as forwardRefType)(function Pick
</FieldLabel>
<PickerButton
loadingState={loadingState}
renderValue={renderValue}
isOpen={isOpen}
isQuiet={isQuiet}
isFocusVisible={isFocusVisible}
Expand Down Expand Up @@ -482,7 +491,7 @@ const avatarSize = {
XL: 26
} as const;

interface PickerButtonInnerProps<T extends object> extends PickerStyleProps, Omit<AriaSelectRenderProps, 'isRequired' | 'isFocused'>, Pick<PickerProps<T>, 'loadingState'> {
interface PickerButtonInnerProps<T extends object> extends PickerStyleProps, Omit<AriaSelectRenderProps, 'isRequired' | 'isFocused'>, Pick<PickerProps<T>, 'loadingState' | 'renderValue'> {
loadingCircle: ReactNode,
buttonRef: RefObject<HTMLButtonElement | null>
}
Expand All @@ -498,7 +507,8 @@ const PickerButton = createHideableComponent(function PickerButton<T extends obj
isDisabled,
loadingState,
loadingCircle,
buttonRef
buttonRef,
renderValue
} = props;
let stringFormatter = useLocalizedStringFormatter(intlMessages, '@react-spectrum/s2');

Expand Down Expand Up @@ -533,8 +543,20 @@ const PickerButton = createHideableComponent(function PickerButton<T extends obj
})}>
{(renderProps) => (
<>
<SelectValue className={valueStyles({isQuiet}) + ' ' + raw('&> :not([slot=icon], [slot=avatar], [slot=label], [data-slot=label]) {display: none;}')}>
<SelectValue
className={
valueStyles({isQuiet}) +
(renderValue ? '' : ' ' + raw('&> :not([slot=icon], [slot=avatar], [slot=label], [data-slot=label]) {display: none;}'))
}>
{({selectedItems, defaultChildren}) => {
const selectedValues = selectedItems.filter((item): item is T => item != null);
const defaultRenderedValue = selectedItems.length <= 1
? defaultChildren
: <Text slot="label">{stringFormatter.format('picker.selectedCount', {count: selectedItems.length})}</Text>;
const renderedValue = selectedItems.length > 0 && renderValue
? renderValue(selectedValues)
: defaultRenderedValue;

return (
<Provider
values={[
Expand Down Expand Up @@ -579,10 +601,7 @@ const PickerButton = createHideableComponent(function PickerButton<T extends obj
}],
[InsideSelectValueContext, true]
]}>
{selectedItems.length <= 1
? defaultChildren
: <Text slot="label">{stringFormatter.format('picker.selectedCount', {count: selectedItems.length})}</Text>
}
{renderedValue}
</Provider>
);
}}
Expand Down
36 changes: 36 additions & 0 deletions packages/@react-spectrum/s2/stories/Picker.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -331,3 +331,39 @@ return (
}
}
};


type ExampleIconItem = IExampleItem & { icon: string };
const exampleIconItems: ExampleIconItem[] = Array.from({length: 5}, (_, i) => ({
id: `user${i + 1}`,
label: `User ${i + 1}`,
icon: 'https://mir-s3-cdn-cf.behance.net/project_modules/disp/690bc6105945313.5f84bfc9de488.png'
}));

const CustomRenderValuePicker = (args: PickerProps<ExampleIconItem, 'multiple'>): ReactElement => (
<Picker {...args}>
{(item: ExampleIconItem) => (
<PickerItem id={item.id} textValue={item.label}>
<Avatar slot="avatar" src={item.icon} />
<Text slot="label">{item.label}</Text>
</PickerItem>
)}
</Picker>
);

export type CustomRenderValuePickerStoryType = typeof CustomRenderValuePicker;
export const CustomRenderValue: StoryObj<CustomRenderValuePickerStoryType> = {
render: CustomRenderValuePicker,
args: {
label: 'Pick users',
selectionMode: 'multiple',
items: exampleIconItems,
renderValue: (selectedItems) => (
<div style={{display: 'flex', gap: 4, height: '80%'}}>
{selectedItems.map(item => (
<img key={item.id} src={item.icon} alt={item.label} />
))}
</div>
)
}
};
36 changes: 36 additions & 0 deletions packages/@react-spectrum/s2/test/Picker.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,42 @@ describe('Picker', () => {
}
});

it('should support custom renderValue output', async () => {
let items = [
{id: 'chocolate', name: 'Chocolate'},
{id: 'strawberry', name: 'Strawberry'},
{id: 'vanilla', name: 'Vanilla'}
];
let renderValue = jest.fn((selectedItems) => (
<span data-testid="custom-value">
{selectedItems.map((item) => item.name).join(', ')}
</span>
));
let tree = render(
<Picker
label="Test picker"
selectionMode="multiple"
items={items}
renderValue={renderValue}>
{(item: any) => <PickerItem id={item.id} textValue={item.name}>{item.name}</PickerItem>}
</Picker>
);

// expect the placeholder to be rendered when no items are selected
expect(tree.queryByTestId('custom-value')).toBeNull();

let selectTester = testUtilUser.createTester('Select', {root: tree.container, interactionType: 'mouse'});
await selectTester.open();
await selectTester.selectOption({option: 0});
await selectTester.selectOption({option: 2});
await selectTester.close();

// check that the clicked items are rendered in the custom renderValue output
let lastSelectedItems = renderValue.mock.calls[renderValue.mock.calls.length - 1][0];
expect(lastSelectedItems.map((item) => item.name)).toEqual(['Chocolate', 'Vanilla']);
expect(tree.getByTestId('custom-value')).toHaveTextContent('Chocolate, Vanilla');
});

it('should support contextual help', async () => {
// Issue with how we don't render the contextual help button in the fake DOM since PressResponder isn't using createHideableComponent
let warn = jest.spyOn(global.console, 'warn').mockImplementation();
Expand Down
46 changes: 46 additions & 0 deletions packages/dev/s2-docs/pages/s2/Picker.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,52 @@ function Example(props) {
}
```

### Custom Render Value

Use the `renderValue` prop to provide a custom element to display selected items. The callback is given an array of the selected user-defined objects.

```tsx render
"use client";
import {Avatar, Picker, PickerItem, Text} from '@react-spectrum/s2';
import {style} from '@react-spectrum/s2/style' with {type: 'macro'};

let users = [
{id: 'abraham-baker', avatar: 'https://www.untitledui.com/images/avatars/abraham-baker', name: 'Abraham Baker', email: 'abraham@example.com'},
{id: 'adriana-sullivan', avatar: 'https://www.untitledui.com/images/avatars/adriana-sullivan', name: 'Adriana Sullivan', email: 'adriana@example.com'},
{id: 'jonathan-kelly', avatar: 'https://www.untitledui.com/images/avatars/jonathan-kelly', name: 'Jonathan Kelly', email: 'jonathan@example.com'},
{id: 'zara-bush', avatar: 'https://www.untitledui.com/images/avatars/zara-bush', name: 'Zara Bush', email: 'zara@example.com'}
];

function Example() {
return (
<div>
<Picker
label="Pick users"
items={users}
selectionMode={"multiple"}
///- begin highlight -///
renderValue={(selectedItems) => (
<div className={style({ display: 'flex', gap: 4, height: '80%' })}>
{selectedItems.map(item => (
<Avatar slot={null} key={item.id} src={item.avatar} alt={item.name} />
))}
</div>
)}
///- end highlight -///
>
{(item) =>
<PickerItem textValue={item.name}>
<Avatar slot="avatar" src={item.avatar} />
<Text slot="label">{item.name}</Text>
<Text slot="description">{item.email}</Text>
</PickerItem>
}
</Picker>
</div>
);
}
```

## Forms

Use the `name` prop to submit the `id` of the selected item to the server. Set the `isRequired` prop to validate that the user selects an option, or implement custom client or server-side validation. See the [Forms](forms) guide to learn more.
Expand Down
10 changes: 5 additions & 5 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -13197,9 +13197,9 @@ __metadata:
languageName: node
linkType: hard

"chromatic@npm:^13.1.3":
version: 13.1.3
resolution: "chromatic@npm:13.1.3"
"chromatic@npm:^15.0.0":
version: 15.1.0
resolution: "chromatic@npm:15.1.0"
peerDependencies:
"@chromatic-com/cypress": ^0.*.* || ^1.0.0
"@chromatic-com/playwright": ^0.*.* || ^1.0.0
Expand All @@ -13212,7 +13212,7 @@ __metadata:
chroma: dist/bin.js
chromatic: dist/bin.js
chromatic-cli: dist/bin.js
checksum: 10c0/5fa2d381e06d1b089ecb790247844cfb510b063c4d8f8c0d2a3d0620ff94864003158e34338246bb1d07504d554e73dc8d5b639dc3e176ce3c88816fdc853285
checksum: 10c0/aea449b3c07e599e9b4c1cd866ffa57a5fc6b158b7c1ae4c462f74133869927d0932a077191011bdb841ab81a2dde54b0a35370736ef1986b6854453f01086de
languageName: node
linkType: hard

Expand Down Expand Up @@ -24902,7 +24902,7 @@ __metadata:
babel-plugin-react-remove-properties: "npm:^0.3.0"
babel-plugin-transform-glob-import: "npm:^1.0.1"
chalk: "npm:^4.1.2"
chromatic: "npm:^13.1.3"
chromatic: "npm:^15.0.0"
clsx: "npm:^2.0.0"
color-space: "npm:^1.16.0"
concurrently: "npm:^6.0.2"
Expand Down
Loading