Skip to content

Commit

Permalink
feat: 🎸 [Selecet]Change autoSort prop
Browse files Browse the repository at this point in the history
✅ Closes: #405
  • Loading branch information
CrisGrud committed Apr 3, 2024
1 parent c0f35a7 commit b7808cb
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 4 deletions.
2 changes: 1 addition & 1 deletion src/components/Select/index.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ export const AutocompleteChange: Story = {
export const AutoSort: Story = {
args: {
...Primary.args,
autoSort: true,
autoSort: "asc",
},
};

Expand Down
18 changes: 16 additions & 2 deletions src/components/Select/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export const SUBPARTS_MAP = {

const Select = <T extends SelectDataAllowed>({
autoComplete = true,
autoSort = false,
autoSort = undefined,
customOptionRendering,
dataCy = DATA_CY_DEFAULT,
disabled = false,
Expand Down Expand Up @@ -157,14 +157,28 @@ const Select = <T extends SelectDataAllowed>({
});
}

if (autoSort) {
if (typeof autoSort === "function") {
options = options.sort((one: SelectData<T>, another: SelectData<T>) => {
return autoSort(one, another);
});
}

if (autoSort === "asc") {
options = options.sort((one: SelectData<T>, another: SelectData<T>) => {
const oneLabel = getOptionLabel(one);
const anotherLabel = getOptionLabel(another);
return oneLabel.localeCompare(anotherLabel);
});
}

if (autoSort === "desc") {
options = options.sort((one: SelectData<T>, another: SelectData<T>) => {
const oneLabel = getOptionLabel(one);
const anotherLabel = getOptionLabel(another);
return anotherLabel.localeCompare(oneLabel);
});
}

return options;
}, [autoSort, externalOptions, getOptionLabel, groupBy]);

Expand Down
2 changes: 1 addition & 1 deletion src/types/Select.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ interface SelectBaseProps<T extends SelectDataAllowed> extends SelectPopperProps
/**
* Automatically sorts options in alphabetical order (localeCompare)
*/
autoSort?: boolean;
autoSort?: "asc" | "desc" | ((opt1: T, opt2: T) => number);
/**
* Method to allow custom rendering of each option
*/
Expand Down

0 comments on commit b7808cb

Please sign in to comment.