From b7808cbb1c35e536b5b539d77aab279bab291ec6 Mon Sep 17 00:00:00 2001 From: CrisGrud Date: Wed, 3 Apr 2024 14:49:59 +0200 Subject: [PATCH] =?UTF-8?q?feat:=20=F0=9F=8E=B8=20[Selecet]Change=20autoSo?= =?UTF-8?q?rt=20prop?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ✅ Closes: #405 --- src/components/Select/index.stories.tsx | 2 +- src/components/Select/index.tsx | 18 ++++++++++++++++-- src/types/Select.ts | 2 +- 3 files changed, 18 insertions(+), 4 deletions(-) diff --git a/src/components/Select/index.stories.tsx b/src/components/Select/index.stories.tsx index 45358dbc..f6b72a19 100644 --- a/src/components/Select/index.stories.tsx +++ b/src/components/Select/index.stories.tsx @@ -112,7 +112,7 @@ export const AutocompleteChange: Story = { export const AutoSort: Story = { args: { ...Primary.args, - autoSort: true, + autoSort: "asc", }, }; diff --git a/src/components/Select/index.tsx b/src/components/Select/index.tsx index 881a22fb..604a3b20 100644 --- a/src/components/Select/index.tsx +++ b/src/components/Select/index.tsx @@ -44,7 +44,7 @@ export const SUBPARTS_MAP = { const Select = ({ autoComplete = true, - autoSort = false, + autoSort = undefined, customOptionRendering, dataCy = DATA_CY_DEFAULT, disabled = false, @@ -157,7 +157,13 @@ const Select = ({ }); } - if (autoSort) { + if (typeof autoSort === "function") { + options = options.sort((one: SelectData, another: SelectData) => { + return autoSort(one, another); + }); + } + + if (autoSort === "asc") { options = options.sort((one: SelectData, another: SelectData) => { const oneLabel = getOptionLabel(one); const anotherLabel = getOptionLabel(another); @@ -165,6 +171,14 @@ const Select = ({ }); } + if (autoSort === "desc") { + options = options.sort((one: SelectData, another: SelectData) => { + const oneLabel = getOptionLabel(one); + const anotherLabel = getOptionLabel(another); + return anotherLabel.localeCompare(oneLabel); + }); + } + return options; }, [autoSort, externalOptions, getOptionLabel, groupBy]); diff --git a/src/types/Select.ts b/src/types/Select.ts index e017e146..87eaa2fb 100644 --- a/src/types/Select.ts +++ b/src/types/Select.ts @@ -22,7 +22,7 @@ interface SelectBaseProps 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 */