Skip to content

Commit

Permalink
add addAction
Browse files Browse the repository at this point in the history
  • Loading branch information
kyledurand committed Mar 16, 2024
1 parent e06cf36 commit 7fd7213
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
1 change: 1 addition & 0 deletions polaris-react/playground/Playground.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ export function Playground() {
activator={{label: 'Product', placeholder: 'Select a product'}}
options={options}
onSelect={(selected) => console.log(selected)}
addAction={{value: 'add', children: 'Add product'}}
/>
</BlockStack>
</Card>
Expand Down
18 changes: 16 additions & 2 deletions polaris-react/src/components/Picker/Picker.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ export interface PickerProps extends Omit<ListboxProps, 'children'> {
allowMultiple?: boolean;
/** The options to be listed within the picker */
options?: OptionProps[];
/** Used to add a new picker option that isn't listed */
addAction?: OptionProps;
/** Whether or not more options are available to lazy load when the bottom of the listbox reached. Use the hasMoreResults boolean provided by the GraphQL API of the paginated data. */
willLoadMoreOptions?: boolean;
/** Height to set on the Popover Pane. */
Expand All @@ -47,13 +49,19 @@ export interface PickerProps extends Omit<ListboxProps, 'children'> {
onClose?(): void;
}

const filterRegex = (value: string) => new RegExp(value, 'i');

// regex match string exact upper or lower case
const filterRegexExact = (value: string) => new RegExp(`^${value}$`, 'i');

export function Picker({
activator,
allowMultiple,
searchField,
options = [],
willLoadMoreOptions,
height,
addAction,
onScrolledToBottom,
onClose,
...listboxProps
Expand Down Expand Up @@ -173,9 +181,8 @@ export function Picker({
return;
}

const filterRegex = new RegExp(value, 'i');
const resultOptions = options?.filter((option) =>
reactChildrenText(option.children)?.match(filterRegex),
filterRegex(value).exec(reactChildrenText(option.children)),
);
setFilteredOptions(resultOptions ?? []);
},
Expand All @@ -189,6 +196,10 @@ export function Picker({
? firstSelectedOption?.toString()
: activator.placeholder;

const queryMatchesExistingOption = options.some((option) =>
filterRegexExact(query).exec(reactChildrenText(option.children)),
);

return (
<Popover
ref={popoverRef}
Expand Down Expand Up @@ -250,6 +261,9 @@ export function Picker({
{...option}
/>
))}
{addAction && query !== '' && !queryMatchesExistingOption ? (
<Listbox.Action {...addAction} />
) : null}
</Listbox>
</Box>
</ComboboxListboxOptionContext.Provider>
Expand Down

0 comments on commit 7fd7213

Please sign in to comment.