You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by jl...@apache.org on 2025/08/28 16:52:44 UTC

(superset) branch 6.0 updated (160a8fe16c -> b16d6ed224)

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

jli pushed a change to branch 6.0
in repository https://gitbox.apache.org/repos/asf/superset.git


    from 160a8fe16c fix(tests): Mock MessageChannel to prevent Jest hanging from rc-overflow (#34871)
     new c80b8fea85 fix: Undefined error when viewing query in Explore + visual fixes (#34869)
     new 0c0dfc0601 fix: SelectControl default sort numeric choices by value (#34858)
     new 18e8b064de fix(tests): Improve MessageChannel mocking to prevent worker force exits (#34878)
     new b16d6ed224 fix(ConfirmStatusChange): remove deprecated event.persist() to fix headless browser crashes (#34864)

The 4 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 .../ConfirmStatusChange.test.jsx                   |  66 -------
 .../ConfirmStatusChange.test.tsx                   | 177 ++++++++++++++++++
 .../src/components/ConfirmStatusChange/index.tsx   |   5 +-
 .../spec/helpers/jsDomWithFetchAPI.ts              |   4 +-
 .../explore/components/controls/SelectControl.jsx  |  45 ++++-
 .../components/controls/SelectControl.test.jsx     | 208 +++++++++++++++++++++
 .../explore/components/controls/ViewQuery.test.tsx |  74 ++++++++
 .../src/explore/components/controls/ViewQuery.tsx  |  61 +++---
 .../components/controls/ViewQueryModalFooter.tsx   |   7 +-
 .../src/features/queries/QueryPreviewModal.tsx     |   8 +-
 .../features/queries/SavedQueryPreviewModal.tsx    |   5 +-
 .../src/features/queries/SyntaxHighlighterCopy.tsx |   1 -
 .../src/pages/QueryHistoryList/index.tsx           |  11 +-
 13 files changed, 560 insertions(+), 112 deletions(-)
 delete mode 100644 superset-frontend/packages/superset-ui-core/src/components/ConfirmStatusChange/ConfirmStatusChange.test.jsx
 create mode 100644 superset-frontend/packages/superset-ui-core/src/components/ConfirmStatusChange/ConfirmStatusChange.test.tsx


(superset) 03/04: fix(tests): Improve MessageChannel mocking to prevent worker force exits (#34878)

Posted by jl...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

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

commit 18e8b064de6ec0f6e2f6d987dd43b2d513b78924
Author: Joe Li <jo...@preset.io>
AuthorDate: Thu Aug 28 09:31:50 2025 -0700

    fix(tests): Improve MessageChannel mocking to prevent worker force exits (#34878)
    
    Co-authored-by: Claude <no...@anthropic.com>
    (cherry picked from commit 7946ec003f4ba6a381d94aed78d26165da51ef66)
---
 superset-frontend/spec/helpers/jsDomWithFetchAPI.ts | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/superset-frontend/spec/helpers/jsDomWithFetchAPI.ts b/superset-frontend/spec/helpers/jsDomWithFetchAPI.ts
index beff7da952..81279356c3 100644
--- a/superset-frontend/spec/helpers/jsDomWithFetchAPI.ts
+++ b/superset-frontend/spec/helpers/jsDomWithFetchAPI.ts
@@ -36,7 +36,7 @@ export default class FixJSDOMEnvironment extends JSDOMEnvironment {
     // Forces rc-overflow to use requestAnimationFrame fallback instead
     // Can be removed when rc-overflow properly cleans up MessagePorts in test environments
     // See: https://github.com/apache/superset/pull/34871
-    delete (this.global as any).MessageChannel;
-    delete (this.global as any).MessagePort;
+    this.global.MessageChannel = undefined as any;
+    this.global.MessagePort = undefined as any;
   }
 }


(superset) 02/04: fix: SelectControl default sort numeric choices by value (#34858)

Posted by jl...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

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

commit 0c0dfc060124d10a59051c0bbb85b6c54350de80
Author: Kamil Gabryjelski <ka...@gmail.com>
AuthorDate: Thu Aug 28 15:14:45 2025 +0200

    fix: SelectControl default sort numeric choices by value (#34858)
    
    (cherry picked from commit 665a11f8217ae2c007338accfbb37e66c5a0c5d1)
---
 .../explore/components/controls/SelectControl.jsx  |  45 ++++-
 .../components/controls/SelectControl.test.jsx     | 208 +++++++++++++++++++++
 2 files changed, 252 insertions(+), 1 deletion(-)

diff --git a/superset-frontend/src/explore/components/controls/SelectControl.jsx b/superset-frontend/src/explore/components/controls/SelectControl.jsx
index f75d67dedc..efe1989e7f 100644
--- a/superset-frontend/src/explore/components/controls/SelectControl.jsx
+++ b/superset-frontend/src/explore/components/controls/SelectControl.jsx
@@ -87,6 +87,44 @@ const defaultProps = {
   valueKey: 'value',
 };
 
+const numberComparator = (a, b) => a.value - b.value;
+
+export const areAllValuesNumbers = (items, valueKey = 'value') => {
+  if (!items || items.length === 0) {
+    return false;
+  }
+  return items.every(item => {
+    if (Array.isArray(item)) {
+      const [value] = item;
+      return typeof value === 'number';
+    }
+    if (typeof item === 'object' && item !== null) {
+      return typeof item[valueKey] === 'number';
+    }
+    return typeof item === 'number';
+  });
+};
+
+export const getSortComparator = (
+  choices,
+  options,
+  valueKey,
+  explicitComparator,
+) => {
+  if (explicitComparator) {
+    return explicitComparator;
+  }
+
+  if (
+    (options && areAllValuesNumbers(options, valueKey)) ||
+    (choices && areAllValuesNumbers(choices, valueKey))
+  ) {
+    return numberComparator;
+  }
+
+  return undefined;
+};
+
 export const innerGetOptions = props => {
   const { choices, optionRenderer, valueKey } = props;
   let options = [];
@@ -252,7 +290,12 @@ export default class SelectControl extends PureComponent {
       onDeselect,
       options: this.state.options,
       placeholder,
-      sortComparator: this.props.sortComparator,
+      sortComparator: getSortComparator(
+        this.props.choices,
+        this.props.options,
+        this.props.valueKey,
+        this.props.sortComparator,
+      ),
       value: getValue(),
       tokenSeparators,
       notFoundContent,
diff --git a/superset-frontend/src/explore/components/controls/SelectControl.test.jsx b/superset-frontend/src/explore/components/controls/SelectControl.test.jsx
index b4b2b0b8d1..25d88a8eb2 100644
--- a/superset-frontend/src/explore/components/controls/SelectControl.test.jsx
+++ b/superset-frontend/src/explore/components/controls/SelectControl.test.jsx
@@ -27,6 +27,8 @@ import {
 } from 'spec/helpers/testing-library';
 import SelectControl, {
   innerGetOptions,
+  areAllValuesNumbers,
+  getSortComparator,
 } from 'src/explore/components/controls/SelectControl';
 
 const defaultProps = {
@@ -235,4 +237,210 @@ describe('SelectControl', () => {
       expect(innerGetOptions(defaultProps)).toEqual(options);
     });
   });
+
+  describe('areAllValuesNumbers', () => {
+    it('returns true when all values are numbers (array format)', () => {
+      const items = [
+        [1, 'One'],
+        [2, 'Two'],
+        [3, 'Three'],
+      ];
+      expect(areAllValuesNumbers(items)).toBe(true);
+    });
+
+    it('returns false when some values are not numbers (array format)', () => {
+      const items = [
+        [1, 'One'],
+        ['two', 'Two'],
+        [3, 'Three'],
+      ];
+      expect(areAllValuesNumbers(items)).toBe(false);
+    });
+
+    it('returns true when all values are numbers (object format)', () => {
+      const items = [
+        { value: 1, label: 'One' },
+        { value: 2, label: 'Two' },
+        { value: 3, label: 'Three' },
+      ];
+      expect(areAllValuesNumbers(items)).toBe(true);
+    });
+
+    it('returns false when some values are not numbers (object format)', () => {
+      const items = [
+        { value: 1, label: 'One' },
+        { value: 'two', label: 'Two' },
+        { value: 3, label: 'Three' },
+      ];
+      expect(areAllValuesNumbers(items)).toBe(false);
+    });
+
+    it('returns true when all values are numbers (primitive format)', () => {
+      const items = [1, 2, 3];
+      expect(areAllValuesNumbers(items)).toBe(true);
+    });
+
+    it('returns false when some values are not numbers (primitive format)', () => {
+      const items = [1, 'two', 3];
+      expect(areAllValuesNumbers(items)).toBe(false);
+    });
+
+    it('works with custom valueKey', () => {
+      const items = [
+        { id: 1, label: 'One' },
+        { id: 2, label: 'Two' },
+        { id: 3, label: 'Three' },
+      ];
+      expect(areAllValuesNumbers(items, 'id')).toBe(true);
+    });
+
+    it('returns false for empty items', () => {
+      expect(areAllValuesNumbers([])).toBe(false);
+      expect(areAllValuesNumbers(null)).toBe(false);
+      expect(areAllValuesNumbers(undefined)).toBe(false);
+    });
+  });
+
+  describe('getSortComparator', () => {
+    const mockExplicitComparator = (a, b) => a.label.localeCompare(b.label);
+
+    it('returns explicit comparator when provided', () => {
+      const choices = [
+        [1, 'One'],
+        [2, 'Two'],
+      ];
+      const result = getSortComparator(
+        choices,
+        null,
+        'value',
+        mockExplicitComparator,
+      );
+      expect(result).toBe(mockExplicitComparator);
+    });
+
+    it('returns number comparator for numeric choices', () => {
+      const choices = [
+        [1, 'One'],
+        [2, 'Two'],
+      ];
+      const result = getSortComparator(choices, null, 'value', null);
+      expect(typeof result).toBe('function');
+      expect(result).not.toBe(mockExplicitComparator);
+    });
+
+    it('returns number comparator for numeric options', () => {
+      const options = [
+        { value: 1, label: 'One' },
+        { value: 2, label: 'Two' },
+      ];
+      const result = getSortComparator(null, options, 'value', null);
+      expect(typeof result).toBe('function');
+      expect(result).not.toBe(mockExplicitComparator);
+    });
+
+    it('prioritizes options over choices when both are numeric', () => {
+      const choices = [
+        [1, 'One'],
+        [2, 'Two'],
+      ];
+      const options = [
+        { value: 3, label: 'Three' },
+        { value: 4, label: 'Four' },
+      ];
+      const result = getSortComparator(choices, options, 'value', null);
+      expect(typeof result).toBe('function');
+    });
+
+    it('returns undefined for non-numeric choices', () => {
+      const choices = [
+        ['one', 'One'],
+        ['two', 'Two'],
+      ];
+      const result = getSortComparator(choices, null, 'value', null);
+      expect(result).toBeUndefined();
+    });
+
+    it('returns undefined for non-numeric options', () => {
+      const options = [
+        { value: 'one', label: 'One' },
+        { value: 'two', label: 'Two' },
+      ];
+      const result = getSortComparator(null, options, 'value', null);
+      expect(result).toBeUndefined();
+    });
+
+    it('returns undefined when no choices or options provided', () => {
+      const result = getSortComparator(null, null, 'value', null);
+      expect(result).toBeUndefined();
+    });
+  });
+
+  describe('numeric sorting integration', () => {
+    it('applies numeric sorting to choices automatically', () => {
+      const numericChoices = [
+        [3, 'Three'],
+        [1, 'One'],
+        [2, 'Two'],
+      ];
+      renderSelectControl({ choices: numericChoices });
+
+      // The SelectControl should receive a sortComparator for numeric values
+      // This is tested by verifying the component renders without errors
+      const selectorWrapper = screen.getByLabelText('Row Limit', {
+        selector: 'div',
+      });
+      expect(selectorWrapper).toBeInTheDocument();
+    });
+
+    it('applies numeric sorting to options automatically', () => {
+      const numericOptions = [
+        { value: 3, label: 'Three' },
+        { value: 1, label: 'One' },
+        { value: 2, label: 'Two' },
+      ];
+      renderSelectControl({ options: numericOptions, choices: undefined });
+
+      // The SelectControl should receive a sortComparator for numeric values
+      const selectorWrapper = screen.getByLabelText('Row Limit', {
+        selector: 'div',
+      });
+      expect(selectorWrapper).toBeInTheDocument();
+    });
+
+    it('does not apply numeric sorting to mixed-type choices', () => {
+      const mixedChoices = [
+        [1, 'One'],
+        ['two', 'Two'],
+        [3, 'Three'],
+      ];
+      renderSelectControl({ choices: mixedChoices });
+
+      // Should render without errors and not apply numeric sorting
+      const selectorWrapper = screen.getByLabelText('Row Limit', {
+        selector: 'div',
+      });
+      expect(selectorWrapper).toBeInTheDocument();
+    });
+
+    it('respects explicit sortComparator over automatic numeric sorting', () => {
+      const numericChoices = [
+        [3, 'Three'],
+        [1, 'One'],
+        [2, 'Two'],
+      ];
+      const explicitComparator = jest.fn((a, b) =>
+        a.label.localeCompare(b.label),
+      );
+
+      renderSelectControl({
+        choices: numericChoices,
+        sortComparator: explicitComparator,
+      });
+
+      const selectorWrapper = screen.getByLabelText('Row Limit', {
+        selector: 'div',
+      });
+      expect(selectorWrapper).toBeInTheDocument();
+    });
+  });
 });


(superset) 04/04: fix(ConfirmStatusChange): remove deprecated event.persist() to fix headless browser crashes (#34864)

Posted by jl...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

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

commit b16d6ed2244e4cefcba9ba51114edbfa4a22908d
Author: Joe Li <jo...@preset.io>
AuthorDate: Thu Aug 28 09:36:15 2025 -0700

    fix(ConfirmStatusChange): remove deprecated event.persist() to fix headless browser crashes (#34864)
    
    Co-authored-by: Claude <no...@anthropic.com>
    (cherry picked from commit ebfb14c3534826086e6797dcea974fce3b69f0ff)
---
 .../ConfirmStatusChange.test.jsx                   |  66 --------
 .../ConfirmStatusChange.test.tsx                   | 177 +++++++++++++++++++++
 .../src/components/ConfirmStatusChange/index.tsx   |   5 +-
 3 files changed, 178 insertions(+), 70 deletions(-)

diff --git a/superset-frontend/packages/superset-ui-core/src/components/ConfirmStatusChange/ConfirmStatusChange.test.jsx b/superset-frontend/packages/superset-ui-core/src/components/ConfirmStatusChange/ConfirmStatusChange.test.jsx
deleted file mode 100644
index bd84ca1a28..0000000000
--- a/superset-frontend/packages/superset-ui-core/src/components/ConfirmStatusChange/ConfirmStatusChange.test.jsx
+++ /dev/null
@@ -1,66 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-import { fireEvent, render, waitFor } from '@superset-ui/core/spec';
-import { Button } from '../Button';
-import { ConfirmStatusChange } from '.';
-
-const mockedProps = {
-  title: 'please confirm',
-  description: 'are you sure?',
-  onConfirm: jest.fn(),
-};
-
-test('opens a confirm modal', () => {
-  const { getByTestId } = render(
-    <ConfirmStatusChange {...mockedProps}>
-      {confirm => (
-        <>
-          <Button data-test="btn1" onClick={confirm} />
-        </>
-      )}
-    </ConfirmStatusChange>,
-  );
-
-  fireEvent.click(getByTestId('btn1'));
-
-  expect(getByTestId(`${mockedProps.title}-modal`)).toBeInTheDocument();
-});
-
-test('calls the function on confirm', async () => {
-  const { getByTestId, getByRole } = render(
-    <ConfirmStatusChange {...mockedProps}>
-      {confirm => (
-        <>
-          <Button data-test="btn1" onClick={() => confirm('foo')} />
-        </>
-      )}
-    </ConfirmStatusChange>,
-  );
-
-  fireEvent.click(getByTestId('btn1'));
-
-  const confirmInput = getByTestId('delete-modal-input');
-  fireEvent.change(confirmInput, { target: { value: 'DELETE' } });
-
-  const confirmButton = getByRole('button', { name: 'Delete' });
-  fireEvent.click(confirmButton);
-
-  await waitFor(() => expect(mockedProps.onConfirm).toHaveBeenCalledTimes(1));
-  expect(mockedProps.onConfirm).toHaveBeenCalledWith('foo');
-});
diff --git a/superset-frontend/packages/superset-ui-core/src/components/ConfirmStatusChange/ConfirmStatusChange.test.tsx b/superset-frontend/packages/superset-ui-core/src/components/ConfirmStatusChange/ConfirmStatusChange.test.tsx
new file mode 100644
index 0000000000..5ac2036f2b
--- /dev/null
+++ b/superset-frontend/packages/superset-ui-core/src/components/ConfirmStatusChange/ConfirmStatusChange.test.tsx
@@ -0,0 +1,177 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { fireEvent, render, waitFor } from '@superset-ui/core/spec';
+import { Button } from '../Button';
+import { ConfirmStatusChange } from '.';
+import type { ConfirmStatusChangeProps } from './types';
+
+const mockedProps: Omit<ConfirmStatusChangeProps, 'children'> = {
+  title: 'please confirm',
+  description: 'are you sure?',
+  onConfirm: jest.fn(),
+};
+
+test('renders children with showConfirm function', () => {
+  const childrenSpy = jest.fn().mockReturnValue(<div>test content</div>);
+
+  render(
+    <ConfirmStatusChange {...mockedProps}>{childrenSpy}</ConfirmStatusChange>,
+  );
+
+  expect(childrenSpy).toHaveBeenCalledWith(expect.any(Function));
+});
+
+test('opens modal when showConfirm is called', () => {
+  const { getByTestId } = render(
+    <ConfirmStatusChange {...mockedProps}>
+      {confirm => <Button data-test="trigger" onClick={confirm} />}
+    </ConfirmStatusChange>,
+  );
+
+  fireEvent.click(getByTestId('trigger'));
+
+  expect(getByTestId(`${mockedProps.title}-modal`)).toBeInTheDocument();
+});
+
+test('stores and passes arguments to onConfirm callback', async () => {
+  const testArgs = ['arg1', { data: 'test' }, 42];
+  const { getByTestId, getByRole } = render(
+    <ConfirmStatusChange {...mockedProps}>
+      {confirm => (
+        <Button data-test="trigger" onClick={() => confirm(...testArgs)} />
+      )}
+    </ConfirmStatusChange>,
+  );
+
+  fireEvent.click(getByTestId('trigger'));
+
+  const confirmInput = getByTestId('delete-modal-input');
+  fireEvent.change(confirmInput, { target: { value: 'DELETE' } });
+
+  const confirmButton = getByRole('button', { name: 'Delete' });
+  fireEvent.click(confirmButton);
+
+  await waitFor(() => expect(mockedProps.onConfirm).toHaveBeenCalledTimes(1));
+  expect(mockedProps.onConfirm).toHaveBeenCalledWith(...testArgs);
+});
+
+test('calls preventDefault on event-like arguments', () => {
+  const mockEvent = {
+    preventDefault: jest.fn(),
+    stopPropagation: jest.fn(),
+  };
+
+  const { getByTestId } = render(
+    <ConfirmStatusChange {...mockedProps}>
+      {confirm => (
+        <Button data-test="trigger" onClick={() => confirm(mockEvent)} />
+      )}
+    </ConfirmStatusChange>,
+  );
+
+  fireEvent.click(getByTestId('trigger'));
+
+  expect(mockEvent.preventDefault).toHaveBeenCalled();
+  expect(mockEvent.stopPropagation).toHaveBeenCalled();
+});
+
+test('skips event handling on non-event arguments', () => {
+  const regularArg = { someData: 'value' };
+  const mockFunc = jest.fn();
+
+  const { getByTestId } = render(
+    <ConfirmStatusChange {...mockedProps}>
+      {confirm => (
+        <Button
+          data-test="trigger"
+          onClick={() => confirm(regularArg, mockFunc)}
+        />
+      )}
+    </ConfirmStatusChange>,
+  );
+
+  // Should not throw when processing non-event arguments
+  expect(() => {
+    fireEvent.click(getByTestId('trigger'));
+  }).not.toThrow();
+
+  expect(getByTestId(`${mockedProps.title}-modal`)).toBeInTheDocument();
+});
+
+test('ignores null and undefined arguments', () => {
+  const { getByTestId } = render(
+    <ConfirmStatusChange {...mockedProps}>
+      {confirm => (
+        <Button
+          data-test="trigger"
+          onClick={() => confirm(null, undefined, 'valid')}
+        />
+      )}
+    </ConfirmStatusChange>,
+  );
+
+  expect(() => {
+    fireEvent.click(getByTestId('trigger'));
+  }).not.toThrow();
+
+  expect(getByTestId(`${mockedProps.title}-modal`)).toBeInTheDocument();
+});
+
+test('handles partial event objects gracefully', () => {
+  const partialEvent1 = { preventDefault: jest.fn() }; // Only preventDefault
+  const partialEvent2 = { stopPropagation: jest.fn() }; // Only stopPropagation
+
+  const { getByTestId } = render(
+    <ConfirmStatusChange {...mockedProps}>
+      {confirm => (
+        <Button
+          data-test="trigger"
+          onClick={() => confirm(partialEvent1, partialEvent2)}
+        />
+      )}
+    </ConfirmStatusChange>,
+  );
+
+  fireEvent.click(getByTestId('trigger'));
+
+  expect(partialEvent1.preventDefault).toHaveBeenCalled();
+  expect(partialEvent2.stopPropagation).toHaveBeenCalled();
+  expect(getByTestId(`${mockedProps.title}-modal`)).toBeInTheDocument();
+});
+
+test('closes modal when onHide is called', () => {
+  const { getByTestId, getByRole } = render(
+    <ConfirmStatusChange {...mockedProps}>
+      {confirm => <Button data-test="trigger" onClick={confirm} />}
+    </ConfirmStatusChange>,
+  );
+
+  // Open modal
+  fireEvent.click(getByTestId('trigger'));
+  const modal = getByTestId(`${mockedProps.title}-modal`);
+  expect(modal).toBeInTheDocument();
+  expect(modal).toBeVisible();
+
+  // Close modal
+  const cancelButton = getByRole('button', { name: 'Cancel' });
+  fireEvent.click(cancelButton);
+
+  // Modal should be hidden (not visible)
+  expect(modal).not.toBeVisible();
+});
diff --git a/superset-frontend/packages/superset-ui-core/src/components/ConfirmStatusChange/index.tsx b/superset-frontend/packages/superset-ui-core/src/components/ConfirmStatusChange/index.tsx
index dd52b99fd6..9aac9c01e3 100644
--- a/superset-frontend/packages/superset-ui-core/src/components/ConfirmStatusChange/index.tsx
+++ b/superset-frontend/packages/superset-ui-core/src/components/ConfirmStatusChange/index.tsx
@@ -31,14 +31,11 @@ export function ConfirmStatusChange({
   const [currentCallbackArgs, setCurrentCallbackArgs] = useState<any[]>([]);
 
   const showConfirm = (...callbackArgs: any[]) => {
-    // check if any args are DOM events, if so, call persist
+    // check if any args are DOM events, if so, handle them
     callbackArgs.forEach(arg => {
       if (!arg) {
         return;
       }
-      if (typeof arg.persist === 'function') {
-        arg.persist();
-      }
       if (typeof arg.preventDefault === 'function') {
         arg.preventDefault();
       }


(superset) 01/04: fix: Undefined error when viewing query in Explore + visual fixes (#34869)

Posted by jl...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

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

commit c80b8fea85949067b16aae86967c29c2ec530916
Author: Kamil Gabryjelski <ka...@gmail.com>
AuthorDate: Thu Aug 28 12:40:29 2025 +0200

    fix: Undefined error when viewing query in Explore + visual fixes (#34869)
    
    (cherry picked from commit 5566eb8dd625d79227cb0bb9e2f6284852993bc3)
---
 .../explore/components/controls/ViewQuery.test.tsx | 74 ++++++++++++++++++++++
 .../src/explore/components/controls/ViewQuery.tsx  | 61 ++++++++++--------
 .../components/controls/ViewQueryModalFooter.tsx   |  7 +-
 .../src/features/queries/QueryPreviewModal.tsx     |  8 +--
 .../features/queries/SavedQueryPreviewModal.tsx    |  5 +-
 .../src/features/queries/SyntaxHighlighterCopy.tsx |  1 -
 .../src/pages/QueryHistoryList/index.tsx           | 11 ++--
 7 files changed, 128 insertions(+), 39 deletions(-)

diff --git a/superset-frontend/src/explore/components/controls/ViewQuery.test.tsx b/superset-frontend/src/explore/components/controls/ViewQuery.test.tsx
index a7f655b3b4..1340c1af10 100644
--- a/superset-frontend/src/explore/components/controls/ViewQuery.test.tsx
+++ b/superset-frontend/src/explore/components/controls/ViewQuery.test.tsx
@@ -191,3 +191,77 @@ test('hides View in SQL Lab button when user does not have SQL Lab access', () =
   expect(screen.queryByText('View in SQL Lab')).not.toBeInTheDocument();
   expect(screen.getByText('Copy')).toBeInTheDocument(); // Copy button should still be visible
 });
+
+test('handles undefined datasource without crashing', () => {
+  const propsWithUndefinedDatasource = {
+    ...mockProps,
+    datasource: undefined as any,
+  };
+
+  expect(() => setup(propsWithUndefinedDatasource)).not.toThrow();
+});
+
+test('handles dataset API error gracefully when no exploreBackend', async () => {
+  const stateWithoutBackend = {
+    ...mockState(),
+    explore: undefined,
+  };
+
+  fetchMock.get(
+    datasetApiEndpoint,
+    { throws: new Error('API Error') },
+    { overwriteRoutes: true },
+  );
+
+  setup(mockProps, stateWithoutBackend);
+
+  await waitFor(() => {
+    expect(screen.queryByRole('progressbar')).not.toBeInTheDocument();
+  });
+
+  expect(fetchMock.calls(formatSqlEndpoint)).toHaveLength(0);
+});
+
+test('handles SQL formatting API error gracefully', async () => {
+  const stateWithoutBackend = {
+    ...mockState(),
+    explore: undefined,
+  };
+
+  fetchMock.post(
+    formatSqlEndpoint,
+    { throws: new Error('Format Error') },
+    { overwriteRoutes: true },
+  );
+
+  setup(mockProps, stateWithoutBackend);
+
+  await waitFor(() => {
+    expect(screen.queryByRole('progressbar')).not.toBeInTheDocument();
+  });
+});
+
+test('uses exploreBackend from Redux state when available', async () => {
+  const stateWithBackend = {
+    ...mockState(),
+    explore: {
+      datasource: {
+        database: {
+          backend: 'postgresql',
+        },
+      },
+    },
+  };
+
+  setup(mockProps, stateWithBackend);
+
+  await waitFor(() => {
+    expect(fetchMock.calls(formatSqlEndpoint)).toHaveLength(1);
+  });
+
+  const formatCallBody = JSON.parse(
+    fetchMock.lastCall(formatSqlEndpoint)?.[1]?.body as string,
+  );
+  expect(formatCallBody.engine).toBe('postgresql');
+  expect(fetchMock.calls(datasetApiEndpoint)).toHaveLength(0);
+});
diff --git a/superset-frontend/src/explore/components/controls/ViewQuery.tsx b/superset-frontend/src/explore/components/controls/ViewQuery.tsx
index 048413af46..ed9cd7d9de 100644
--- a/superset-frontend/src/explore/components/controls/ViewQuery.tsx
+++ b/superset-frontend/src/explore/components/controls/ViewQuery.tsx
@@ -43,6 +43,7 @@ import CodeSyntaxHighlighter, {
   preloadLanguages,
 } from '@superset-ui/core/components/CodeSyntaxHighlighter';
 import { useHistory } from 'react-router-dom';
+import { ExplorePageState } from 'src/explore/types';
 
 export interface ViewQueryProps {
   sql: string;
@@ -74,7 +75,10 @@ const DATASET_BACKEND_QUERY = {
 const ViewQuery: FC<ViewQueryProps> = props => {
   const { sql, language = 'sql', datasource } = props;
   const theme = useTheme();
-  const datasetId = datasource.split('__')[0];
+  const datasetId = datasource?.split('__')[0];
+  const exploreBackend = useSelector(
+    (state: ExplorePageState) => state.explore?.datasource?.database?.backend,
+  );
   const [formattedSQL, setFormattedSQL] = useState<string>();
   const [showFormatSQL, setShowFormatSQL] = useState(true);
   const history = useHistory();
@@ -88,31 +92,37 @@ const ViewQuery: FC<ViewQueryProps> = props => {
     preloadLanguages([language]);
   }, [language]);
 
-  const formatCurrentQuery = useCallback(() => {
+  const formatCurrentQuery = useCallback(async () => {
     if (formattedSQL) {
       setShowFormatSQL(val => !val);
-    } else {
-      const queryParams = rison.encode(DATASET_BACKEND_QUERY);
-      SupersetClient.get({
-        endpoint: `/api/v1/dataset/${datasetId}?q=${queryParams}`,
-      })
-        .then(({ json }) =>
-          SupersetClient.post({
-            endpoint: `/api/v1/sqllab/format_sql/`,
-            body: JSON.stringify({
-              sql,
-              engine: json.result.database.backend,
-            }),
-            headers: { 'Content-Type': 'application/json' },
-          }),
-        )
-        .then(({ json }) => {
-          setFormattedSQL(json.result);
-          setShowFormatSQL(true);
-        })
-        .catch(() => {
-          setShowFormatSQL(true);
+      return;
+    }
+    try {
+      let backend = exploreBackend;
+
+      // Fetch backend info if not available in Redux state
+      if (!backend) {
+        const queryParams = rison.encode(DATASET_BACKEND_QUERY);
+        const response = await SupersetClient.get({
+          endpoint: `/api/v1/dataset/${datasetId}?q=${queryParams}`,
         });
+        backend = response.json.result.database;
+      }
+
+      // Format the SQL query
+      const formatResponse = await SupersetClient.post({
+        endpoint: `/api/v1/sqllab/format_sql/`,
+        body: JSON.stringify({
+          sql,
+          engine: backend,
+        }),
+        headers: { 'Content-Type': 'application/json' },
+      });
+
+      setFormattedSQL(formatResponse.json.result);
+      setShowFormatSQL(true);
+    } catch (error) {
+      setShowFormatSQL(false);
     }
   }, [sql, datasetId, formattedSQL]);
 
@@ -142,8 +152,9 @@ const ViewQuery: FC<ViewQueryProps> = props => {
   return (
     <Card bodyStyle={{ padding: theme.sizeUnit * 4 }}>
       <StyledSyntaxContainer key={sql}>
-        {!formattedSQL && <Skeleton active />}
-        {formattedSQL && (
+        {!formattedSQL && showFormatSQL ? (
+          <Skeleton active />
+        ) : (
           <StyledThemedSyntaxHighlighter
             language={language}
             customStyle={{ flex: 1, marginBottom: theme.sizeUnit * 3 }}
diff --git a/superset-frontend/src/explore/components/controls/ViewQueryModalFooter.tsx b/superset-frontend/src/explore/components/controls/ViewQueryModalFooter.tsx
index 3fa59a9a5e..5834cbd16e 100644
--- a/superset-frontend/src/explore/components/controls/ViewQueryModalFooter.tsx
+++ b/superset-frontend/src/explore/components/controls/ViewQueryModalFooter.tsx
@@ -76,6 +76,7 @@ const ViewQueryModalFooter: FC<ViewQueryModalFooterProps> = (props: {
   return (
     <div>
       <Button
+        buttonStyle="secondary"
         onClick={() => {
           props?.closeModal?.();
           props?.changeDatasource?.();
@@ -83,11 +84,13 @@ const ViewQueryModalFooter: FC<ViewQueryModalFooterProps> = (props: {
       >
         {SAVE_AS_DATASET}
       </Button>
-      <Button onClick={({ metaKey }) => openSQL(Boolean(metaKey))}>
+      <Button
+        buttonStyle="secondary"
+        onClick={({ metaKey }) => openSQL(Boolean(metaKey))}
+      >
         {OPEN_IN_SQL_LAB}
       </Button>
       <Button
-        buttonStyle="primary"
         onClick={() => {
           props?.closeModal?.();
         }}
diff --git a/superset-frontend/src/features/queries/QueryPreviewModal.tsx b/superset-frontend/src/features/queries/QueryPreviewModal.tsx
index 447b3e7d8a..1f7f7a0db9 100644
--- a/superset-frontend/src/features/queries/QueryPreviewModal.tsx
+++ b/superset-frontend/src/features/queries/QueryPreviewModal.tsx
@@ -40,11 +40,10 @@ const QueryLabel = styled.div`
 `;
 
 const QueryViewToggle = styled.div`
-  margin: 0 0 ${({ theme }) => theme.sizeUnit * 6}px 0;
+  display: flex;
 `;
 
 const TabButton = styled.div`
-  display: inline;
   font-size: ${({ theme }) => theme.fontSizeSM}px;
   padding: ${({ theme }) => theme.sizeUnit * 2}px
     ${({ theme }) => theme.sizeUnit * 4}px;
@@ -55,9 +54,7 @@ const TabButton = styled.div`
   &:focus,
   &:hover {
     background: ${({ theme }) => theme.colorPrimaryBg};
-    border-bottom: none;
     border-radius: ${({ theme }) => theme.borderRadius}px;
-    margin-bottom: ${({ theme }) => theme.sizeUnit * 2}px;
   }
 
   &:hover:not(.active) {
@@ -110,6 +107,7 @@ function QueryPreviewModal({
             <Button
               data-test="previous-query"
               key="previous-query"
+              buttonStyle="secondary"
               disabled={disablePrevious}
               onClick={() => handleDataChange(true)}
             >
@@ -118,6 +116,7 @@ function QueryPreviewModal({
             <Button
               data-test="next-query"
               key="next-query"
+              buttonStyle="secondary"
               disabled={disableNext}
               onClick={() => handleDataChange(false)}
             >
@@ -126,7 +125,6 @@ function QueryPreviewModal({
             <Button
               data-test="open-in-sql-lab"
               key="open-in-sql-lab"
-              buttonStyle="primary"
               onClick={() => openInSqlLab(id)}
             >
               {t('Open in SQL Lab')}
diff --git a/superset-frontend/src/features/queries/SavedQueryPreviewModal.tsx b/superset-frontend/src/features/queries/SavedQueryPreviewModal.tsx
index ce888945e0..9e6b69a6d6 100644
--- a/superset-frontend/src/features/queries/SavedQueryPreviewModal.tsx
+++ b/superset-frontend/src/features/queries/SavedQueryPreviewModal.tsx
@@ -34,7 +34,7 @@ const QueryTitle = styled.div`
 const QueryLabel = styled.div`
   color: ${({ theme }) => theme.colorTextLabel};
   font-size: ${({ theme }) => theme.fontSize}px;
-  padding: 4px 0 16px 0;
+  padding-top: ${({ theme }) => theme.sizeUnit}px;
 `;
 
 const StyledModal = styled(Modal)`
@@ -89,6 +89,7 @@ const SavedQueryPreviewModal: FunctionComponent<
             <Button
               data-test="previous-saved-query"
               key="previous-saved-query"
+              buttonStyle="secondary"
               disabled={disablePrevious}
               onClick={() => handleDataChange(true)}
             >
@@ -97,6 +98,7 @@ const SavedQueryPreviewModal: FunctionComponent<
             <Button
               data-test="next-saved-query"
               key="next-saved-query"
+              buttonStyle="secondary"
               disabled={disableNext}
               onClick={() => handleDataChange(false)}
             >
@@ -105,7 +107,6 @@ const SavedQueryPreviewModal: FunctionComponent<
             <Button
               data-test="open-in-sql-lab"
               key="open-in-sql-lab"
-              buttonStyle="primary"
               onClick={({ metaKey }) =>
                 openInSqlLab(savedQuery.id, Boolean(metaKey))
               }
diff --git a/superset-frontend/src/features/queries/SyntaxHighlighterCopy.tsx b/superset-frontend/src/features/queries/SyntaxHighlighterCopy.tsx
index 4b38e381a3..5262548f48 100644
--- a/superset-frontend/src/features/queries/SyntaxHighlighterCopy.tsx
+++ b/superset-frontend/src/features/queries/SyntaxHighlighterCopy.tsx
@@ -29,7 +29,6 @@ import copyTextToClipboard from 'src/utils/copy';
 
 const SyntaxHighlighterWrapper = styled.div`
   position: relative;
-  margin-top: -24px;
 
   &:hover {
     .copy-button {
diff --git a/superset-frontend/src/pages/QueryHistoryList/index.tsx b/superset-frontend/src/pages/QueryHistoryList/index.tsx
index dc4de5b309..e2291678ff 100644
--- a/superset-frontend/src/pages/QueryHistoryList/index.tsx
+++ b/superset-frontend/src/pages/QueryHistoryList/index.tsx
@@ -190,7 +190,7 @@ function QueryList({ addDangerToast }: QueryListProps) {
           ) {
             statusConfig.name = (
               <Icons.CloseOutlined
-                iconSize="xs"
+                iconSize="m"
                 iconColor={
                   status === QueryState.Failed
                     ? theme.colorError
@@ -201,19 +201,22 @@ function QueryList({ addDangerToast }: QueryListProps) {
             statusConfig.label = t('Failed');
           } else if (status === QueryState.Running) {
             statusConfig.name = (
-              <Icons.Running iconColor={theme.colorPrimary} />
+              <Icons.LoadingOutlined
+                iconSize="m"
+                iconColor={theme.colorPrimary}
+              />
             );
             statusConfig.label = t('Running');
           } else if (status === QueryState.TimedOut) {
             statusConfig.name = (
-              <Icons.CircleSolid iconColor={theme.colorIcon} />
+              <Icons.CircleSolid iconSize="m" iconColor={theme.colorIcon} />
             );
             statusConfig.label = t('Offline');
           } else if (
             status === QueryState.Scheduled ||
             status === QueryState.Pending
           ) {
-            statusConfig.name = <Icons.Queued />;
+            statusConfig.name = <Icons.Queued iconSize="m" />;
             statusConfig.label = t('Scheduled');
           }
           return (