Skip to content
Open
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
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%'
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Locked height to picker button height. Enough for our use case as we don't have anything larger than the button that should cause it to resize.

});

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 @@ -377,6 +385,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 @@ -483,7 +492,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 @@ -499,7 +508,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 @@ -531,8 +541,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;}'))
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was quite restrictive in allowing us our own layouts. This should allow custom layouts only through renderValue and not via slot manipulation.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this makes sense.

}>
{({selectedItems, defaultChildren}) => {
const selectedValues = selectedItems.filter((item): item is T => item != null);
const defaultRenderedValue = selectedValues.length <= 1
? defaultChildren
: <Text slot="label">{stringFormatter.format('picker.selectedCount', {count: selectedValues.length})}</Text>;
const renderedValue = selectedValues.length > 0 && renderValue
? renderValue(selectedValues)
: defaultRenderedValue;

return (
<Provider
values={[
Expand Down Expand Up @@ -577,10 +599,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
37 changes: 37 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,40 @@ return (
}
}
};


type ExampleIconItem = IExampleItem & { icon: string };
const exampleIconItems: ExampleIconItem[] = [
{id: 'chocolate', label: 'Chocolate', icon: SRC_URL_1},
{id: 'strawberry', label: 'Strawberry', icon: SRC_URL_2},
{id: 'vanilla', label: 'Vanilla', icon: SRC_URL_1},
{id: 'mint', label: 'Mint', icon: SRC_URL_2},
{id: 'cookie-dough', label: 'Chocolate Chip Cookie Dough', icon: SRC_URL_1}
];

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: {
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
37 changes: 37 additions & 0 deletions packages/dev/s2-docs/pages/s2/Picker.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,43 @@ 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 docs={docs.exports.Picker} links={docs.links} props={['selectionMode']} wide
"use client";
import {Picker, PickerItem} from '@react-spectrum/s2';
import {style} from '@react-spectrum/s2/style' with {type: 'macro'};
import {useState} from 'react';

function Example(props) {
let [animal, setAnimal] = useState("bison");

return (
<div>
<Picker
{...props}
label="Pick an animal"
///- begin highlight -///
/* PROPS */
value={animal}
onChange={setAnimal}
///- end highlight -///
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like this example is missing renderValue?

>
<PickerItem id="koala">Koala</PickerItem>
<PickerItem id="kangaroo">Kangaroo</PickerItem>
<PickerItem id="platypus" isDisabled>Platypus</PickerItem>
<PickerItem id="eagle">Bald Eagle</PickerItem>
<PickerItem id="bison">Bison</PickerItem>
<PickerItem id="skunk">Skunk</PickerItem>
</Picker>
<pre className={style({font: 'body'})}>Current selection: {JSON.stringify(animal)}</pre>
</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