This is an automated email from the ASF dual-hosted git repository.

villebro pushed a commit to branch 7.0
in repository https://gitbox.apache.org/repos/asf/superset.git

commit 1463000ff989993956f09c26d727bf1633979f68
Author: Francesco Castaldi <[email protected]>
AuthorDate: Fri Oct 30 13:58:37 2026 +0100

    fix(select): comprehensive hardening for option deduplication and new 
option handling (#44894)
    
    Signed-off-by: Francesco Castaldi <[email protected]>
    Co-authored-by: Francesco Castaldi <[email protected]>
    (cherry picked from commit a57c3d35096c4dba5ca105fdb2a5cbbaeaa90e39)
---
 .../src/components/Select/AsyncSelect.stories.tsx  |  48 +++++++
 .../src/components/Select/AsyncSelect.test.tsx     | 141 +++++++++++++++++++++
 .../src/components/Select/AsyncSelect.tsx          |  62 ++++++++-
 .../src/components/Select/Select.stories.tsx       |  23 ++++
 .../src/components/Select/Select.test.tsx          |  17 +++
 .../src/components/Select/Select.tsx               |  22 +++-
 .../src/components/Select/styles.tsx               |  15 +++
 .../src/components/Select/types.ts                 |  19 ++-
 .../src/components/Select/utils.test.ts            |  75 +++++++++++
 .../src/components/Select/utils.tsx                |  77 +++++++++--
 10 files changed, 472 insertions(+), 27 deletions(-)

diff --git 
a/superset-frontend/packages/superset-ui-core/src/components/Select/AsyncSelect.stories.tsx
 
b/superset-frontend/packages/superset-ui-core/src/components/Select/AsyncSelect.stories.tsx
index 862319a2a1d..9c80d9d7cc7 100644
--- 
a/superset-frontend/packages/superset-ui-core/src/components/Select/AsyncSelect.stories.tsx
+++ 
b/superset-frontend/packages/superset-ui-core/src/components/Select/AsyncSelect.stories.tsx
@@ -318,3 +318,51 @@ AsynchronousSelect.argTypes = {
     },
   },
 };
+
+const createMockUserFetcher =
+  (responseTime = 0.3) =>
+  (
+    search: string,
+    page: number,
+    pageSize: number,
+  ): Promise<SelectOptionsTypePage> => {
+    const username = search.trim().toLowerCase();
+    const all = USERS.filter(
+      u => !username || u.toLowerCase().includes(username),
+    );
+    const totalCount = all.length;
+    const start = page * pageSize;
+    const deleteCount =
+      start + pageSize < totalCount ? pageSize : totalCount - start;
+    const pageData = all.slice(start, start + deleteCount).map(u => ({
+      label: u,
+      value: u,
+    }));
+    return new Promise(resolve => {
+      setTimeout(() => {
+        resolve({ data: pageData, totalCount });
+      }, responseTime * 1000);
+    });
+  };
+
+/**
+ * Demonstrates allowNewOptions in AsyncSelect. Optimistic custom options 
appear
+ * with a [new] badge and are automatically dropped if the server returns a 
matching
+ * option upon search completion.
+ */
+export const WithAllowNewOptions = (args: Omit<AsyncSelectProps, 'ref'>) => (
+  <div style={{ width: DEFAULT_WIDTH }}>
+    <AsyncSelect
+      {...args}
+      allowNewOptions
+      ariaLabel="async-select-allow-new-options"
+      options={createMockUserFetcher(0.3)}
+    />
+  </div>
+);
+
+WithAllowNewOptions.args = {
+  ...AsynchronousSelect.args,
+  allowNewOptions: true,
+  placeholder: 'Type a name or create a new one...',
+};
diff --git 
a/superset-frontend/packages/superset-ui-core/src/components/Select/AsyncSelect.test.tsx
 
b/superset-frontend/packages/superset-ui-core/src/components/Select/AsyncSelect.test.tsx
index 154a2858010..9f967eb660b 100644
--- 
a/superset-frontend/packages/superset-ui-core/src/components/Select/AsyncSelect.test.tsx
+++ 
b/superset-frontend/packages/superset-ui-core/src/components/Select/AsyncSelect.test.tsx
@@ -489,6 +489,43 @@ test('clear all the values', async () => {
   expect(values.length).toBe(0);
 });
 
+test('cleans up temporary new option when clearAll is called in 
allowNewOptions mode', async () => {
+  const onClear = jest.fn();
+  render(
+    <AsyncSelect
+      {...defaultProps}
+      mode="multiple"
+      allowNewOptions
+      value={[
+        { label: 'Custom Item', value: 'Custom Item', isNewOption: true },
+      ]}
+      onClear={onClear}
+    />,
+  );
+  await clearAll();
+  expect(onClear).toHaveBeenCalled();
+  const values = await findAllSelectValues();
+  expect(values.length).toBe(0);
+});
+
+test('deduplicates pasted values against loaded options when allowNewOptions 
is enabled', async () => {
+  render(<AsyncSelect {...defaultProps} mode="multiple" allowNewOptions />);
+  await open();
+  const input = getElementByClassName('.ant-select-input');
+  const paste = createEvent.paste(input, {
+    clipboardData: {
+      getData: () => `${OPTIONS[0].label},${OPTIONS[0].label},BrandNewItem`,
+    },
+  });
+  fireEvent(input, paste);
+  await waitFor(async () => {
+    const values = await findAllSelectValues();
+    expect(values.length).toBe(2);
+    expect(values[0]).toHaveTextContent(OPTIONS[0].label);
+    expect(values[1]).toHaveTextContent('BrandNewItem');
+  });
+});
+
 test('does not add a new option if allowNewOptions is false', async () => {
   render(<AsyncSelect {...defaultProps} />);
   await open();
@@ -1156,6 +1193,110 @@ test('preserves new option entry across search fetch 
when allowNewOptions is on'
   expect(screen.queryByText('Option 0')).not.toBeInTheDocument();
 });
 
+test('drops new option entry when fetched search options contain a matching 
label (regression for #44873)', async () => {
+  const page0Data = Array.from({ length: 10 }, (_, i) => ({
+    label: `Option ${i}`,
+    value: i,
+  }));
+  const searchData = [{ label: 'Matching Option', value: 42 }];
+  const loadOptions = jest.fn(async (search: string) => {
+    if (search === '') {
+      return { data: page0Data, totalCount: 100 };
+    }
+    return { data: searchData, totalCount: 1 };
+  });
+
+  render(
+    <AsyncSelect {...defaultProps} options={loadOptions} allowNewOptions />,
+  );
+  await open();
+  await waitFor(() => expect(loadOptions).toHaveBeenCalledTimes(1));
+
+  await type('Matching Option');
+  await waitFor(() => expect(loadOptions).toHaveBeenCalledTimes(2));
+
+  const options = await findAllSelectOptions();
+  // Drops optimistic new option entry when server returns a match for the 
label
+  expect(options).toHaveLength(1);
+  expect(options[0]).toHaveTextContent('Matching Option');
+  expect(screen.queryByText('Option 0')).not.toBeInTheDocument();
+});
+
+test('drops optimistic new option when paginated mergeData contains matching 
label', async () => {
+  const initialData = [{ label: 'Existing 1', value: 1 }];
+  const nextPageData = [{ label: 'Created Later', value: 99 }];
+  const loadOptions = jest.fn(async (_search: string, page: number) => {
+    if (page === 0) {
+      return { data: initialData, totalCount: 20 };
+    }
+    return { data: nextPageData, totalCount: 20 };
+  });
+
+  render(
+    <AsyncSelect {...defaultProps} options={loadOptions} allowNewOptions />,
+  );
+  await open();
+  await waitFor(() => expect(loadOptions).toHaveBeenCalledTimes(1));
+
+  // Type a term that will match next page's label
+  await type('Created Later');
+  await waitFor(() => expect(loadOptions).toHaveBeenCalledTimes(2));
+
+  // Optimistic option is present with "new" badge before pagination
+  const optionsBefore = await findAllSelectOptions();
+  expect(
+    Array.from(optionsBefore).some(opt =>
+      opt.textContent?.includes('Created Later'),
+    ),
+  ).toBe(true);
+  expect(screen.getByTestId('new-option-badge')).toBeInTheDocument();
+
+  // Wait for loading to finish so handlePagination's `!isLoading` gate is open
+  await waitFor(() =>
+    expect(document.querySelector('.ant-select-suffix .ant-spin')).toBeNull(),
+  );
+
+  // Trigger pagination by dispatching a scroll event on the virtual-list 
container
+  const holder = document.querySelector(
+    '.ant-select-dropdown-list-holder',
+  ) as HTMLElement | null;
+  if (!holder) throw new Error('virtual-list holder not rendered');
+  Object.defineProperty(holder, 'scrollHeight', {
+    configurable: true,
+    get: () => 1000,
+  });
+  Object.defineProperty(holder, 'offsetHeight', {
+    configurable: true,
+    get: () => 200,
+  });
+  Object.defineProperty(holder, 'clientHeight', {
+    configurable: true,
+    get: () => 200,
+  });
+  Object.defineProperty(holder, 'scrollTop', {
+    configurable: true,
+    get: () => 900,
+    set: () => {},
+  });
+  fireEvent.scroll(holder);
+
+  await waitFor(() =>
+    expect(loadOptions).toHaveBeenCalledWith(
+      'Created Later',
+      1,
+      expect.anything(),
+    ),
+  );
+
+  // After next page loads and mergeData fires, duplicate optimistic
+  // option is dropped and server option (without "new" badge) remains.
+  await waitFor(async () => {
+    const matchingOptions = screen.getAllByText('Created Later');
+    expect(matchingOptions).toHaveLength(1);
+    expect(screen.queryByTestId('new-option-badge')).not.toBeInTheDocument();
+  });
+});
+
 test('restores base options when search is cleared', async () => {
   const page0Data = Array.from({ length: 10 }, (_, i) => ({
     label: `Option ${i}`,
diff --git 
a/superset-frontend/packages/superset-ui-core/src/components/Select/AsyncSelect.tsx
 
b/superset-frontend/packages/superset-ui-core/src/components/Select/AsyncSelect.tsx
index fb147d79253..a61a4c09e87 100644
--- 
a/superset-frontend/packages/superset-ui-core/src/components/Select/AsyncSelect.tsx
+++ 
b/superset-frontend/packages/superset-ui-core/src/components/Select/AsyncSelect.tsx
@@ -52,6 +52,7 @@ import {
   getValue,
   hasOption,
   isLabeledValue,
+  isNewOption,
   sortSelectedFirstHelper,
   sortComparatorWithSearchHelper,
   sortComparatorForNoSearchHelper,
@@ -81,6 +82,7 @@ import {
   StyledError,
   StyledErrorMessage,
   StyledHeader,
+  StyledNewOptionBadge,
   StyledSelect,
   StyledStopOutlined,
 } from './styles';
@@ -350,10 +352,12 @@ const AsyncSelect = forwardRef(
           setSelectValue(array.filter(element => element !== value));
         }
         // removes new option
-        if (option.isNewOption) {
+        if (isNewOption(option)) {
+          const targetVal = getValue(value);
           setSelectOptions(
             fullSelectOptions.filter(
-              option => getValue(option.value) !== getValue(value),
+              opt =>
+                getValue(opt.value) !== targetVal && opt.label !== targetVal,
             ),
           );
         }
@@ -377,6 +381,30 @@ const AsyncSelect = forwardRef(
 
     fullSelectOptionsRef.current = fullSelectOptions;
 
+    const isRedundantNewOption = (
+      opt: DefaultOptionType | AntdLabeledValue,
+      incomingData: SelectOptionsType,
+    ) => {
+      if (!isNewOption(opt)) {
+        return false;
+      }
+      const label =
+        typeof opt.label === 'string' || typeof opt.label === 'number'
+          ? opt.label
+          : undefined;
+      return (
+        label !== undefined &&
+        incomingData.some(item => {
+          if (isObject(item) && Array.isArray((item as any).options)) {
+            return (item as any).options.some((child: any) =>
+              utilsIsEqual(child, label, 'label'),
+            );
+          }
+          return utilsIsEqual(item, label, 'label');
+        })
+      );
+    };
+
     const mergeData = useCallback(
       (data: SelectOptionsType) => {
         let mergedData: SelectOptionsType = [];
@@ -386,7 +414,15 @@ const AsyncSelect = forwardRef(
           // merges with existing and creates unique options
           setSelectOptions(prevOptions => {
             mergedData = prevOptions
-              .filter(previousOption => !dataValues.has(previousOption.value))
+              .filter(previousOption => {
+                if (dataValues.has(previousOption.value)) {
+                  return false;
+                }
+                if (isRedundantNewOption(previousOption, data)) {
+                  return false;
+                }
+                return true;
+              })
               .concat(data)
               // Forward-compat: TS 6.0 infers stricter antd option types; 
widen
               // the comparator to accept the broader DefaultOptionType shape.
@@ -483,7 +519,10 @@ const AsyncSelect = forwardRef(
               setSelectOptions(prevOptions => {
                 const dataValues = new Set(data.map(opt => opt.value));
                 const preservedNew = prevOptions.filter(
-                  opt => opt.isNewOption && !dataValues.has(opt.value),
+                  opt =>
+                    isNewOption(opt) &&
+                    !dataValues.has(opt.value) &&
+                    !isRedundantNewOption(opt, data),
                 );
                 return preservedNew
                   .concat(data)
@@ -584,7 +623,7 @@ const AsyncSelect = forwardRef(
                 isNewOption: true,
               };
             const cleanSelectOptions = fullSelectOptions.filter(
-              opt => !opt.isNewOption || hasOption(opt.value, selectValue),
+              opt => !isNewOption(opt) || hasOption(opt.value, selectValue),
             );
             const newOptions = newOption
               ? [newOption, ...cleanSelectOptions]
@@ -911,7 +950,18 @@ const AsyncSelect = forwardRef(
           }
           onClear={handleClear}
           options={fullSelectOptions}
-          optionRender={option => option.label || option.value}
+          optionRender={option =>
+            isNewOption(option.data) || isNewOption(option) ? (
+              <>
+                {option.label || option.value}
+                <StyledNewOptionBadge data-test="new-option-badge">
+                  {t('New')}
+                </StyledNewOptionBadge>
+              </>
+            ) : (
+              option.label || option.value
+            )
+          }
           placeholder={placeholder}
           showSearch={shouldShowSearch}
           tokenSeparators={quoteAwareTokenSeparators}
diff --git 
a/superset-frontend/packages/superset-ui-core/src/components/Select/Select.stories.tsx
 
b/superset-frontend/packages/superset-ui-core/src/components/Select/Select.stories.tsx
index 238f9c5edee..b19eaeefc20 100644
--- 
a/superset-frontend/packages/superset-ui-core/src/components/Select/Select.stories.tsx
+++ 
b/superset-frontend/packages/superset-ui-core/src/components/Select/Select.stories.tsx
@@ -468,3 +468,26 @@ AdvancedPlayground.argTypes = {
     control: { type: 'number' },
   },
 };
+
+/**
+ * Demonstrates the allowNewOptions feature, allowing users to type and create
+ * custom options that are rendered with a subtle [new] visual badge, while
+ * ensuring existing options are deduplicated against typed terms.
+ */
+export const WithAllowNewOptions = (args: SelectProps) => (
+  <div style={{ width: DEFAULT_WIDTH }}>
+    <Select
+      {...args}
+      allowNewOptions
+      ariaLabel="select-allow-new-options"
+      options={options}
+    />
+  </div>
+);
+
+WithAllowNewOptions.args = {
+  ...AdvancedPlayground.args,
+  allowNewOptions: true,
+  mode: 'multiple',
+  placeholder: 'Type a custom value or pick existing...',
+};
diff --git 
a/superset-frontend/packages/superset-ui-core/src/components/Select/Select.test.tsx
 
b/superset-frontend/packages/superset-ui-core/src/components/Select/Select.test.tsx
index 077cb4eb830..5bb59a92e59 100644
--- 
a/superset-frontend/packages/superset-ui-core/src/components/Select/Select.test.tsx
+++ 
b/superset-frontend/packages/superset-ui-core/src/components/Select/Select.test.tsx
@@ -582,6 +582,23 @@ test('clear all the values', async () => {
   expect(values.length).toBe(0);
 });
 
+test('cleans up temporary new option when clearAll is called in 
allowNewOptions mode', async () => {
+  const onClear = jest.fn();
+  render(
+    <Select
+      {...defaultProps}
+      mode="multiple"
+      allowNewOptions
+      value={[{ label: 'Custom Tag', value: 'Custom Tag', isNewOption: true }]}
+      onClear={onClear}
+    />,
+  );
+  await clearAll();
+  expect(onClear).toHaveBeenCalled();
+  const values = await findAllSelectValues();
+  expect(values.length).toBe(0);
+});
+
 test('does not add a new option if allowNewOptions is false', async () => {
   render(<Select {...defaultProps} options={OPTIONS} />);
   await open();
diff --git 
a/superset-frontend/packages/superset-ui-core/src/components/Select/Select.tsx 
b/superset-frontend/packages/superset-ui-core/src/components/Select/Select.tsx
index 8a6e0855954..187f82cb476 100644
--- 
a/superset-frontend/packages/superset-ui-core/src/components/Select/Select.tsx
+++ 
b/superset-frontend/packages/superset-ui-core/src/components/Select/Select.tsx
@@ -50,6 +50,7 @@ import {
   handleFilterOptionHelper,
   hasOption,
   isLabeledValue,
+  isNewOption,
   isObject,
   makeQuoteAwareTokenizer,
   mapOptions,
@@ -66,6 +67,7 @@ import {
   StyledCheckOutlined,
   StyledContainer,
   StyledHeader,
+  StyledNewOptionBadge,
   StyledSelect,
   StyledStopOutlined,
 } from './styles';
@@ -519,9 +521,10 @@ const Select = forwardRef(
         setSelectValue(array);
 
         // removes new option
-        if (option.isNewOption) {
+        if (isNewOption(option)) {
+          const targetVal = getValue(value);
           const updatedOptions = fullSelectOptions.filter(
-            option => getValue(option.value) !== getValue(value),
+            opt => getValue(opt.value) !== targetVal && opt.label !== 
targetVal,
           );
           setSelectOptions(updatedOptions);
           setVisibleOptions(updatedOptions);
@@ -586,7 +589,7 @@ const Select = forwardRef(
               isNewOption: true,
             };
             const cleanSelectOptions = ensureIsArray(fullSelectOptions).filter(
-              opt => !opt.isNewOption || hasOption(opt.value, selectValue),
+              opt => !isNewOption(opt) || hasOption(opt.value, selectValue),
             );
             updatedOptions = newOption
               ? [newOption, ...cleanSelectOptions]
@@ -1062,7 +1065,18 @@ const Select = forwardRef(
             )
           }
           options={visibleOptions}
-          optionRender={option => option.label || option.value}
+          optionRender={option =>
+            isNewOption(option.data) || isNewOption(option) ? (
+              <>
+                {option.label || option.value}
+                <StyledNewOptionBadge data-test="new-option-badge">
+                  {t('New')}
+                </StyledNewOptionBadge>
+              </>
+            ) : (
+              option.label || option.value
+            )
+          }
           oneLine={oneLine}
           popupMatchSelectWidth={oneLine ? dropdownWidth : true}
           builtinPlacements={DROPDOWN_BUILTIN_PLACEMENTS}
diff --git 
a/superset-frontend/packages/superset-ui-core/src/components/Select/styles.tsx 
b/superset-frontend/packages/superset-ui-core/src/components/Select/styles.tsx
index 0c6f9294013..8cf7981b5b7 100644
--- 
a/superset-frontend/packages/superset-ui-core/src/components/Select/styles.tsx
+++ 
b/superset-frontend/packages/superset-ui-core/src/components/Select/styles.tsx
@@ -157,3 +157,18 @@ export const StyledBulkActionsContainer = styled(Flex)`
     }
   `}
 `;
+
+export const StyledNewOptionBadge = styled.span`
+  ${({ theme }) => `
+    display: inline-block;
+    padding: 0 ${theme.sizeUnit}px;
+    font-size: ${theme.fontSizeSM - 2}px;
+    line-height: ${theme.sizeUnit * 4}px;
+    color: ${theme.colorTextSecondary};
+    background-color: ${theme.colorFillTertiary};
+    border-radius: ${theme.borderRadiusSM}px;
+    margin-left: ${theme.sizeUnit}px;
+    vertical-align: middle;
+    text-transform: lowercase;
+  `}
+`;
diff --git 
a/superset-frontend/packages/superset-ui-core/src/components/Select/types.ts 
b/superset-frontend/packages/superset-ui-core/src/components/Select/types.ts
index 15f66280df7..4214e681a70 100644
--- a/superset-frontend/packages/superset-ui-core/src/components/Select/types.ts
+++ b/superset-frontend/packages/superset-ui-core/src/components/Select/types.ts
@@ -29,13 +29,26 @@ export type RawValue = string | number;
 
 export type V = string | number | null | undefined;
 
-export type LabeledValue = AntdLabeledValue;
+export type LabeledValue = AntdLabeledValue & {
+  isNewOption?: boolean;
+};
 
-export type CustomLabeledValue = { label?: ReactNode; value?: V };
+export type CustomLabeledValue = {
+  label?: ReactNode;
+  value?: V;
+  /** Flag identifying optimistic custom options created when allowNewOptions 
is enabled */
+  isNewOption?: boolean;
+};
 
 export type AntdProps = AntdSelectProps<AntdSelectValue>;
 
-export type SelectValue = AntdSelectValue | null;
+export type SelectValue =
+  | RawValue
+  | RawValue[]
+  | LabeledValue
+  | LabeledValue[]
+  | null
+  | undefined;
 
 export type { RefSelectProps };
 
diff --git 
a/superset-frontend/packages/superset-ui-core/src/components/Select/utils.test.ts
 
b/superset-frontend/packages/superset-ui-core/src/components/Select/utils.test.ts
index 3d4c932b9d1..622d54fa536 100644
--- 
a/superset-frontend/packages/superset-ui-core/src/components/Select/utils.test.ts
+++ 
b/superset-frontend/packages/superset-ui-core/src/components/Select/utils.test.ts
@@ -22,6 +22,10 @@ import {
   stripSurroundingQuotes,
   makeQuoteAwareTokenizer,
   propertyComparator,
+  isNewOption,
+  isEqual,
+  getOption,
+  hasOption,
 } from './utils';
 
 test('stripSurroundingQuotes removes matching surrounding double quotes', () 
=> {
@@ -184,3 +188,74 @@ test('propertyComparator sorts mixed bigint and number 
properties numerically',
     bigHundred,
   ]);
 });
+
+test('isEqual handles matching numbers and strings', () => {
+  expect(isEqual(1, 1, 'value')).toBe(true);
+  expect(isEqual(1, '1', 'value')).toBe(true);
+  expect(isEqual({ value: 1 }, 1, 'value')).toBe(true);
+  expect(isEqual({ value: 1 }, '1', 'value')).toBe(true);
+  expect(isEqual(' test ', 'test', 'value')).toBe(false);
+  expect(isEqual(' test ', 'test', 'label')).toBe(true);
+  expect(isEqual({ value: 'abc' }, { value: 'abc' }, 'value')).toBe(true);
+  expect(isEqual({ value: 'abc' }, { value: 'def' }, 'value')).toBe(false);
+});
+
+test('isEqual distinguishes empty strings and whitespace while preserving 
deduplication', () => {
+  expect(isEqual('', ' ', 'value')).toBe(false);
+  expect(isEqual(' ', '', 'value')).toBe(false);
+  expect(isEqual('', '   ', 'value')).toBe(false);
+  expect(isEqual(' ', '   ', 'value')).toBe(false);
+  expect(isEqual('', '', 'value')).toBe(true);
+  expect(isEqual(' ', ' ', 'value')).toBe(true);
+  expect(isEqual(' test ', 'test', 'value')).toBe(false);
+  expect(isEqual(' test ', 'test', 'label')).toBe(true);
+  expect(isEqual(' Sales ', 'Sales', 'value')).toBe(false);
+  expect(isEqual(' Sales ', 'Sales', 'label')).toBe(true);
+  expect(isEqual('Sales', ' Sales ', 'value')).toBe(false);
+  expect(isEqual('Sales', ' Sales ', 'label')).toBe(true);
+  expect(isEqual('Sales', 'sales', 'value')).toBe(false);
+  expect(isEqual(0, '', 'value')).toBe(false);
+  expect(isEqual(0, ' ', 'value')).toBe(false);
+  expect(isEqual(0, '0', 'value')).toBe(true);
+  expect(isEqual(1, '1', 'value')).toBe(true);
+  expect(isEqual(null, undefined, 'value')).toBe(true);
+  expect(isEqual(null, '', 'value')).toBe(false);
+  expect(isEqual({ value: 0 }, '', 'value')).toBe(false);
+  expect(isEqual({ value: 0 }, '0', 'value')).toBe(true);
+  expect(isEqual({ label: ' Sales ' }, 'Sales', 'label')).toBe(true);
+});
+
+test('getOption and hasOption locate options by value or label', () => {
+  const options = [
+    { label: 'Option 1', value: 1 },
+    { label: 'Option 2', value: 2 },
+    { label: 'New Option', value: 'New Option', isNewOption: true },
+  ];
+  expect(hasOption(1, options)).toBe(true);
+  expect(hasOption(99, options)).toBe(false);
+  expect(hasOption('Option 2', options, true)).toBe(true);
+  expect(hasOption('Option 2', options, false)).toBe(false);
+  expect(getOption(2, options)).toEqual({ label: 'Option 2', value: 2 });
+  expect(getOption('Option 1', options, true)).toEqual({
+    label: 'Option 1',
+    value: 1,
+  });
+  expect(getOption({ value: 2 }, options)).toEqual({
+    label: 'Option 2',
+    value: 2,
+  });
+  expect(getOption({ label: 'Option 1' }, options, true)).toEqual({
+    label: 'Option 1',
+    value: 1,
+  });
+});
+
+test('isNewOption detects temporary new option flag safely', () => {
+  expect(isNewOption({ label: 'test', value: 'test', isNewOption: true 
})).toBe(
+    true,
+  );
+  expect(isNewOption({ label: 'test', value: 'test' })).toBe(false);
+  expect(isNewOption(null)).toBe(false);
+  expect(isNewOption('string')).toBe(false);
+  expect(isNewOption(123)).toBe(false);
+});
diff --git 
a/superset-frontend/packages/superset-ui-core/src/components/Select/utils.tsx 
b/superset-frontend/packages/superset-ui-core/src/components/Select/utils.tsx
index 9a6739b6db7..574b9511d52 100644
--- 
a/superset-frontend/packages/superset-ui-core/src/components/Select/utils.tsx
+++ 
b/superset-frontend/packages/superset-ui-core/src/components/Select/utils.tsx
@@ -36,6 +36,10 @@ export function isLabeledValue(value: unknown): value is 
AntdLabeledValue {
   return isObject(value) && 'value' in value && 'label' in value;
 }
 
+export function isNewOption(option: unknown): boolean {
+  return isObject(option) && Boolean(option.isNewOption);
+}
+
 export function getValue(
   option: string | number | AntdLabeledValue | null | undefined,
 ) {
@@ -51,26 +55,68 @@ export function isEqual(
     isObject(a) && key in a ? a[key as keyof CustomLabeledValue] : a;
   const actualB =
     isObject(b) && key in b ? b[key as keyof CustomLabeledValue] : b;
+
+  if (
+    (typeof actualA === 'number' &&
+      typeof actualB === 'string' &&
+      actualB.trim() === '') ||
+    (typeof actualB === 'number' &&
+      typeof actualA === 'string' &&
+      actualA.trim() === '')
+  ) {
+    return false;
+  }
+
   // When comparing the values we use the equality
   // operator to automatically convert different types
   // eslint-disable-next-line eqeqeq
-  return actualA == actualB;
+  if (actualA == actualB) {
+    return true;
+  }
+  if (
+    key === 'label' &&
+    typeof actualA === 'string' &&
+    typeof actualB === 'string'
+  ) {
+    const trimmedA = actualA.trim();
+    const trimmedB = actualB.trim();
+    return trimmedA.length > 0 && trimmedA === trimmedB;
+  }
+  return false;
 }
 
 export function getOption(
-  value: V,
+  value: V | CustomLabeledValue,
   options?: V | CustomLabeledValue | (V | CustomLabeledValue)[],
   checkLabel = false,
 ): V | CustomLabeledValue {
   const optionsArray = ensureIsArray(options);
-  return optionsArray.find(
-    x =>
-      isEqual(x, value, 'value') || (checkLabel && isEqual(x, value, 'label')),
-  );
+  const targetValue = (isObject(value) ? value.value : value) as V;
+  const targetLabel = (isObject(value) ? value.label : value) as V;
+  for (const x of optionsArray) {
+    if (
+      isEqual(x, targetValue, 'value') ||
+      (checkLabel &&
+        (isEqual(x, targetLabel, 'label') || isEqual(x, targetValue, 'label')))
+    ) {
+      return x;
+    }
+    if (isObject(x) && Array.isArray((x as any).options)) {
+      const child = getOption(
+        value,
+        (x as any).options as (V | CustomLabeledValue)[],
+        checkLabel,
+      );
+      if (child !== undefined) {
+        return child;
+      }
+    }
+  }
+  return undefined;
 }
 
 export function hasOption(
-  value: V,
+  value: V | CustomLabeledValue,
   options?: V | CustomLabeledValue | (V | CustomLabeledValue)[],
   checkLabel = false,
 ): boolean {
@@ -83,8 +129,12 @@ export function hasOption(
  * */
 export const propertyComparator =
   (property: string) => (a: AntdLabeledValue, b: AntdLabeledValue) => {
-    const propertyA = a[property as keyof CustomLabeledValue];
-    const propertyB = b[property as keyof CustomLabeledValue];
+    const propertyA = (a as CustomLabeledValue)[
+      property as keyof CustomLabeledValue
+    ];
+    const propertyB = (b as CustomLabeledValue)[
+      property as keyof CustomLabeledValue
+    ];
     if (typeof propertyA === 'string' && typeof propertyB === 'string') {
       return propertyA.localeCompare(propertyB);
     }
@@ -240,11 +290,10 @@ export const handleFilterOptionHelper = (
     const searchValue = stripSurroundingQuotes(search).toLowerCase();
     if (optionFilterProps?.length) {
       return optionFilterProps.some(prop => {
-        const optionProp = option?.[prop as keyof CustomLabeledValue]
-          ? String(option[prop as keyof CustomLabeledValue])
-              .trim()
-              .toLowerCase()
-          : '';
+        const propVal = (option as CustomLabeledValue)?.[
+          prop as keyof CustomLabeledValue
+        ];
+        const optionProp = propVal ? String(propVal).trim().toLowerCase() : '';
         return optionProp.includes(searchValue);
       });
     }

Reply via email to