You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by en...@apache.org on 2026/10/20 20:07:29 UTC
(superset) branch master updated: fix(chart): keep the chart on screen during a dashboard auto-refresh (#45234)
This is an automated email from the ASF dual-hosted git repository.
EnxDev pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/superset.git
The following commit(s) were added to refs/heads/master by this push:
new 25186586572 fix(chart): keep the chart on screen during a dashboard auto-refresh (#45234)
25186586572 is described below
commit 251865865722864b55f10a61627c2fab034f741c
Author: Enzo Martellucci <52...@users.noreply.github.com>
AuthorDate: Tue Oct 20 22:07:21 2026 +0200
fix(chart): keep the chart on screen during a dashboard auto-refresh (#45234)
Co-authored-by: Claude Opus 5.5 (1M context) <no...@anthropic.com>
---
.../src/components/OlChartMap.tsx | 18 +-
.../test/components/OlChartMap.test.tsx | 108 ++++++++
.../src/MapLibre.tsx | 33 ++-
.../test/MapLibre.test.tsx | 69 ++++-
.../src/CategoricalDeckGLContainer.test.tsx | 207 +++++++++++++-
.../src/CategoricalDeckGLContainer.tsx | 73 ++++-
.../preset-chart-deckgl/src/Multi/Multi.tsx | 25 +-
.../preset-chart-deckgl/src/Multi/MultiV1.test.tsx | 66 ++++-
.../plugins/preset-chart-deckgl/src/Multi/index.ts | 2 +-
.../src/Multi/transformProps.test.ts | 43 +++
.../src/Multi/transformProps.ts | 32 +++
.../preset-chart-deckgl/src/factory.test.tsx | 117 ++++++++
.../plugins/preset-chart-deckgl/src/factory.tsx | 25 ++
.../src/layers/Polygon/Polygon.test.tsx | 100 +++++++
.../src/layers/Polygon/Polygon.tsx | 22 ++
.../Chart/ChartRenderer.refresh.test.tsx | 302 +++++++++++++++++++++
.../src/components/Chart/ChartRenderer.test.tsx | 19 ++
.../src/components/Chart/ChartRenderer.tsx | 90 ++++--
18 files changed, 1305 insertions(+), 46 deletions(-)
diff --git a/superset-frontend/plugins/plugin-chart-cartodiagram/src/components/OlChartMap.tsx b/superset-frontend/plugins/plugin-chart-cartodiagram/src/components/OlChartMap.tsx
index 8c16e2bd2b9..b8df2935596 100644
--- a/superset-frontend/plugins/plugin-chart-cartodiagram/src/components/OlChartMap.tsx
+++ b/superset-frontend/plugins/plugin-chart-cartodiagram/src/components/OlChartMap.tsx
@@ -16,7 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
-import { useEffect, useState } from 'react';
+import { useEffect, useRef, useState } from 'react';
import { useSelector } from 'react-redux';
import Point from 'ol/geom/Point';
@@ -269,6 +269,22 @@ export const OlChartMap = (props: OlChartMapProps) => {
}
}, [olMap, currentMapView.mode]);
+ /**
+ * Refit the map when new data arrives while the view fits the data.
+ * A dashboard auto-refresh keeps the chart mounted, so the initial
+ * extent effect above doesn't run again for the new rows.
+ */
+ const fittedChartConfigs = useRef(currentChartConfigs);
+ useEffect(() => {
+ if (currentChartConfigs === fittedChartConfigs.current) {
+ return;
+ }
+ fittedChartConfigs.current = currentChartConfigs;
+ if (currentMapView.mode === 'FIT_DATA') {
+ fitMapToCharts(olMap, currentChartConfigs);
+ }
+ }, [olMap, currentChartConfigs, currentMapView.mode]);
+
/**
* Send updated zoom to chart config control.
*/
diff --git a/superset-frontend/plugins/plugin-chart-cartodiagram/test/components/OlChartMap.test.tsx b/superset-frontend/plugins/plugin-chart-cartodiagram/test/components/OlChartMap.test.tsx
new file mode 100644
index 00000000000..b5602c7d367
--- /dev/null
+++ b/superset-frontend/plugins/plugin-chart-cartodiagram/test/components/OlChartMap.test.tsx
@@ -0,0 +1,108 @@
+/**
+ * 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 { render } from '@testing-library/react';
+import Map from 'ol/Map.js';
+import View from 'ol/View.js';
+import { toLonLat } from 'ol/proj';
+import { supersetTheme } from '@apache-superset/core/theme';
+import OlChartMap from '../../src/components/OlChartMap';
+import { ChartConfig, MapViewConfigs, OlChartMapProps } from '../../src/types';
+
+jest.mock('react-redux', () => ({
+ ...jest.requireActual('react-redux'),
+ useSelector: () => 'en',
+}));
+
+const chartConfigsAt = (coordinates: [number, number][]): ChartConfig => ({
+ type: 'FeatureCollection',
+ features: coordinates.map(point => ({
+ type: 'Feature',
+ geometry: { type: 'Point', coordinates: point },
+ properties: {},
+ })),
+});
+
+const SAN_FRANCISCO = chartConfigsAt([
+ [-122.45, 37.75],
+ [-122.4, 37.8],
+]);
+const LONDON = chartConfigsAt([
+ [-0.15, 51.48],
+ [-0.1, 51.52],
+]);
+
+const renderMap = (mapView: Partial<MapViewConfigs>) => {
+ const olMap = new Map({ view: new View({ center: [0, 0], zoom: 2 }) });
+ const props = {
+ mapId: 'ol-map',
+ olMap,
+ width: 400,
+ height: 300,
+ chartConfigs: SAN_FRANCISCO,
+ chartVizType: 'pie',
+ chartSize: {
+ type: 'FIXED',
+ configs: { zoom: 2, width: 20, height: 20 },
+ values: {},
+ },
+ layerConfigs: [],
+ mapView: {
+ mode: 'FIT_DATA',
+ zoom: 2,
+ latitude: 0,
+ longitude: 0,
+ fixedZoom: 2,
+ fixedLatitude: 0,
+ fixedLongitude: 0,
+ ...mapView,
+ },
+ chartBackgroundColor: { r: 255, g: 255, b: 255, a: 0 },
+ chartBackgroundBorderRadius: 0,
+ setControlValue: jest.fn(),
+ theme: supersetTheme,
+ } as unknown as OlChartMapProps;
+ const result = render(<OlChartMap {...props} />);
+ const centerLatitude = () => toLonLat(olMap.getView().getCenter()!)[1];
+ const refresh = (chartConfigs: ChartConfig) =>
+ result.rerender(<OlChartMap {...props} chartConfigs={chartConfigs} />);
+ return { centerLatitude, refresh };
+};
+
+test('refits to the charts of a refreshed response in FIT_DATA mode', () => {
+ const { centerLatitude, refresh } = renderMap({ mode: 'FIT_DATA' });
+ expect(centerLatitude()).toBeCloseTo(37.775, 1);
+
+ // An auto-refresh keeps the chart mounted and passes the new rows in.
+ refresh(LONDON);
+
+ expect(centerLatitude()).toBeCloseTo(51.5, 1);
+});
+
+test('keeps the fixed view of a CUSTOM map view when the data changes', () => {
+ const { centerLatitude, refresh } = renderMap({
+ mode: 'CUSTOM',
+ fixedLatitude: 10,
+ fixedLongitude: 20,
+ });
+ expect(centerLatitude()).toBeCloseTo(10);
+
+ refresh(LONDON);
+
+ expect(centerLatitude()).toBeCloseTo(10);
+});
diff --git a/superset-frontend/plugins/plugin-chart-point-cluster-map/src/MapLibre.tsx b/superset-frontend/plugins/plugin-chart-point-cluster-map/src/MapLibre.tsx
index fd18d3b0b26..aa3bc717a94 100644
--- a/superset-frontend/plugins/plugin-chart-point-cluster-map/src/MapLibre.tsx
+++ b/superset-frontend/plugins/plugin-chart-point-cluster-map/src/MapLibre.tsx
@@ -16,7 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
-import { memo, useCallback, useEffect, useState } from 'react';
+import { memo, useCallback, useEffect, useRef, useState } from 'react';
import { Map as MapLibreMap } from 'react-map-gl/maplibre';
import { Map as MapboxMap } from 'react-map-gl/mapbox';
import * as maplibregl from 'maplibre-gl';
@@ -54,6 +54,17 @@ interface Viewport {
zoom: number;
}
+type Bounds = [[number, number], [number, number]];
+
+const sameBounds = (a?: Bounds, b?: Bounds) =>
+ a === b ||
+ (!!a &&
+ !!b &&
+ a[0][0] === b[0][0] &&
+ a[0][1] === b[0][1] &&
+ a[1][0] === b[1][0] &&
+ a[1][1] === b[1][1]);
+
interface Clusterer {
getClusters(bbox: number[], zoom: number): GeoJSONLocation[];
}
@@ -79,7 +90,7 @@ interface MapLibreProps {
pointRadiusUnit?: string;
renderWhileDragging?: boolean;
rgb?: (string | number)[];
- bounds?: [[number, number], [number, number]]; // May be undefined for empty datasets
+ bounds?: Bounds; // May be undefined for empty datasets
viewportLongitude?: number;
viewportLatitude?: number;
viewportZoom?: number;
@@ -116,8 +127,7 @@ function MapLibre({
};
}
return { latitude: 0, longitude: 0, zoom: 1 };
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, []);
+ }, [bounds, width, height]);
const mergeViewportWithProps = useCallback(
(fitBounds: Viewport, base: Viewport = fitBounds): Viewport => ({
@@ -147,6 +157,21 @@ function MapLibre({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [viewportLongitude, viewportLatitude, viewportZoom]);
+ const fittedBounds = useRef(bounds);
+
+ useEffect(() => {
+ if (sameBounds(bounds, fittedBounds.current)) {
+ return;
+ }
+ fittedBounds.current = bounds;
+ // A dashboard auto-refresh keeps the chart mounted and swaps in new
+ // data, so the map refits to the new rows here. Viewport overrides
+ // still take precedence over the fitted values.
+ setViewport(previous =>
+ mergeViewportWithProps(computeFitBounds(), previous),
+ );
+ }, [bounds, computeFitBounds, mergeViewportWithProps]);
+
const handleMove = useCallback(
(evt: {
viewState: { longitude: number; latitude: number; zoom: number };
diff --git a/superset-frontend/plugins/plugin-chart-point-cluster-map/test/MapLibre.test.tsx b/superset-frontend/plugins/plugin-chart-point-cluster-map/test/MapLibre.test.tsx
index 3ae14624770..eef5d3d9962 100644
--- a/superset-frontend/plugins/plugin-chart-point-cluster-map/test/MapLibre.test.tsx
+++ b/superset-frontend/plugins/plugin-chart-point-cluster-map/test/MapLibre.test.tsx
@@ -18,7 +18,7 @@
*/
import { type ReactNode } from 'react';
-import { render, screen } from '@testing-library/react';
+import { act, render, screen } from '@testing-library/react';
import '@testing-library/jest-dom';
import {
OSM_TILE_ATTRIBUTION,
@@ -389,3 +389,70 @@ test('falls back to default viewport when cleared with undefined bounds', () =>
expect(lastMapProps.latitude).toBe(0);
expect(lastMapProps.zoom).toBe(1);
});
+
+test('refits to the bounds of a refreshed response', () => {
+ const { rerender } = render(<MapLibre {...defaultProps} />);
+ expect(lastMapProps.latitude).toBe(40.75);
+
+ // An auto-refresh keeps the chart mounted and passes the new bounds in.
+ rerender(
+ <MapLibre
+ {...defaultProps}
+ bounds={[
+ [-0.15, 51.45],
+ [-0.05, 51.55],
+ ]}
+ />,
+ );
+
+ expect(lastMapProps.longitude).toBe(-0.1);
+ expect(lastMapProps.latitude).toBe(51.5);
+});
+
+test('keeps the viewport overrides when refreshed bounds move', () => {
+ const overrides = {
+ viewportLongitude: -122.4,
+ viewportLatitude: 37.8,
+ viewportZoom: 5,
+ };
+ const { rerender } = render(<MapLibre {...defaultProps} {...overrides} />);
+
+ rerender(
+ <MapLibre
+ {...defaultProps}
+ {...overrides}
+ bounds={[
+ [-0.15, 51.45],
+ [-0.05, 51.55],
+ ]}
+ />,
+ );
+
+ expect(lastMapProps.longitude).toBe(-122.4);
+ expect(lastMapProps.latitude).toBe(37.8);
+ expect(lastMapProps.zoom).toBe(5);
+});
+
+test('keeps a panned map when refreshed bounds are unchanged', () => {
+ const { rerender } = render(<MapLibre {...defaultProps} />);
+
+ act(() => {
+ (lastMapProps.onMove as (evt: { viewState: object }) => void)({
+ viewState: { longitude: 10, latitude: 20, zoom: 3 },
+ });
+ });
+
+ rerender(
+ <MapLibre
+ {...defaultProps}
+ bounds={[
+ [-74.0, 40.7],
+ [-73.9, 40.8],
+ ]}
+ />,
+ );
+
+ expect(lastMapProps.longitude).toBe(10);
+ expect(lastMapProps.latitude).toBe(20);
+ expect(lastMapProps.zoom).toBe(3);
+});
diff --git a/superset-frontend/plugins/preset-chart-deckgl/src/CategoricalDeckGLContainer.test.tsx b/superset-frontend/plugins/preset-chart-deckgl/src/CategoricalDeckGLContainer.test.tsx
index f27c9106ce7..31e34451754 100644
--- a/superset-frontend/plugins/preset-chart-deckgl/src/CategoricalDeckGLContainer.test.tsx
+++ b/superset-frontend/plugins/preset-chart-deckgl/src/CategoricalDeckGLContainer.test.tsx
@@ -16,8 +16,14 @@
* specific language governing permissions and limitations
* under the License.
*/
-import { QueryFormData } from '@superset-ui/core';
-import { getCategories } from './CategoricalDeckGLContainer';
+import { render } from '@testing-library/react';
+import { ThemeProvider, supersetTheme } from '@apache-superset/core/theme';
+import { JsonObject, QueryFormData } from '@superset-ui/core';
+import CategoricalDeckGLContainer, {
+ CategoricalDeckGLContainerProps,
+ getCategories,
+ reconcileCategories,
+} from './CategoricalDeckGLContainer';
import { addColorToFeatures } from './utils/addColor';
import { COLOR_SCHEME_TYPES } from './utilities/utils';
@@ -27,6 +33,16 @@ jest.mock('maplibre-gl', () => ({ setWorkerUrl: jest.fn() }), {
virtual: true,
});
+const mockViewports: JsonObject[] = [];
+jest.mock('./DeckGLContainer', () => ({
+ DeckGLContainerStyledWrapper: jest
+ .requireActual('react')
+ .forwardRef(({ viewport }: { viewport: JsonObject }) => {
+ mockViewports.push(viewport);
+ return <div data-test="deckgl-container" />;
+ }),
+}));
+
// Record every (label, sliceId) pair the categorical color scale is asked to
// resolve, so we can assert the legend and point-color paths key the scale on
// the same slice id.
@@ -72,3 +88,190 @@ test('legend and point colors resolve from the same slice_id', () => {
expect(categories.B.color).toEqual(features[1].color);
expect(features[0].color).not.toEqual(features[1].color);
});
+
+test('reconcileCategories keeps the previous object when the categories are unchanged', () => {
+ const previous = { A: { color: [1, 0, 0, 255], enabled: false } };
+ const next = { A: { color: [1, 0, 0, 255], enabled: true } };
+
+ expect(reconcileCategories(previous, next)).toBe(previous);
+});
+
+test('reconcileCategories adds new categories and keeps the chosen visibility', () => {
+ const previous = {
+ A: { color: [1, 0, 0, 255], enabled: false },
+ B: { color: [0, 1, 0, 255], enabled: true },
+ };
+ const next = {
+ A: { color: [1, 0, 0, 255], enabled: true },
+ C: { color: [0, 0, 1, 255], enabled: true },
+ };
+
+ expect(reconcileCategories(previous, next)).toEqual({
+ A: { color: [1, 0, 0, 255], enabled: false },
+ C: { color: [0, 0, 1, 255], enabled: true },
+ });
+});
+
+test('reconcileCategories shows every category rather than none', () => {
+ const previous = {
+ A: { color: [1, 0, 0, 255], enabled: false },
+ B: { color: [0, 1, 0, 255], enabled: true },
+ };
+ const next = { A: { color: [1, 0, 0, 255], enabled: true } };
+
+ expect(reconcileCategories(previous, next)).toEqual({
+ A: { color: [1, 0, 0, 255], enabled: true },
+ });
+});
+
+test('features of a category that first appears in a refreshed response are drawn', () => {
+ const fd = {
+ datasource: '1__table',
+ viz_type: 'deck_scatter',
+ color_scheme_type: COLOR_SCHEME_TYPES.categorical_palette,
+ color_scheme: 'supersetColors',
+ dimension: 'category',
+ slice_id: 42,
+ color_picker: { r: 0, g: 0, b: 0, a: 1 },
+ } as unknown as QueryFormData;
+ const getLayer = jest.fn(() => ({}));
+ const drawnCategories = () => {
+ const { payload } = (
+ getLayer.mock.calls.at(-1) as unknown as [JsonObject]
+ )[0];
+ return payload.data.features.map((f: JsonObject) => f.cat_color);
+ };
+ const props = {
+ formData: fd,
+ getLayer,
+ getPoints: () => [],
+ viewport: { longitude: 0, latitude: 0, zoom: 1 },
+ width: 400,
+ height: 300,
+ setControlValue: jest.fn(),
+ // The standalone v1 transforms build the payload from the query
+ // response, which carries no form_data.
+ payload: { data: { features: [{ cat_color: 'A' }] } },
+ } as unknown as CategoricalDeckGLContainerProps;
+
+ const { rerender } = render(
+ <ThemeProvider theme={supersetTheme}>
+ <CategoricalDeckGLContainer {...props} />
+ </ThemeProvider>,
+ );
+ expect(drawnCategories()).toEqual(['A']);
+
+ rerender(
+ <ThemeProvider theme={supersetTheme}>
+ <CategoricalDeckGLContainer
+ {...props}
+ payload={{
+ data: { features: [{ cat_color: 'A' }, { cat_color: 'B' }] },
+ }}
+ />
+ </ThemeProvider>,
+ );
+ expect(drawnCategories()).toEqual(['A', 'B']);
+});
+
+test.each([
+ [true, 51.5],
+ [false, 0],
+])(
+ 'with autozoom %s a refreshed response leaves the map centered at latitude %s',
+ (autozoom, expectedLatitude) => {
+ const fd = {
+ datasource: '1__table',
+ viz_type: 'deck_scatter',
+ autozoom,
+ } as unknown as QueryFormData;
+ const props = {
+ formData: fd,
+ getLayer: jest.fn(() => ({})),
+ getPoints: (features: JsonObject[]) =>
+ features.map(feature => feature.position),
+ viewport: { longitude: 0, latitude: 0, zoom: 1 },
+ width: 400,
+ height: 300,
+ setControlValue: jest.fn(),
+ // The standalone v1 transforms build the payload from the query
+ // response, which carries no form_data.
+ payload: {
+ data: {
+ features: [
+ { position: [-122.45, 37.75] },
+ { position: [-122.4, 37.8] },
+ ],
+ },
+ },
+ } as unknown as CategoricalDeckGLContainerProps;
+
+ const { rerender } = render(
+ <ThemeProvider theme={supersetTheme}>
+ <CategoricalDeckGLContainer {...props} />
+ </ThemeProvider>,
+ );
+ expect(mockViewports.at(-1)?.latitude).toBeCloseTo(autozoom ? 37.775 : 0);
+
+ rerender(
+ <ThemeProvider theme={supersetTheme}>
+ <CategoricalDeckGLContainer
+ {...props}
+ payload={{
+ data: {
+ features: [
+ { position: [-0.15, 51.48] },
+ { position: [-0.1, 51.52] },
+ ],
+ },
+ }}
+ />
+ </ThemeProvider>,
+ );
+ expect(mockViewports.at(-1)?.latitude).toBeCloseTo(expectedLatitude, 1);
+ },
+);
+
+test('with autozoom a tilt written back by Explore keeps the viewer on the same rows', () => {
+ const positions = [
+ [-122.45, 37.75],
+ [-122.4, 37.8],
+ ];
+ const props = {
+ formData: {
+ datasource: '1__table',
+ viz_type: 'deck_scatter',
+ autozoom: true,
+ } as unknown as QueryFormData,
+ getLayer: jest.fn(() => ({})),
+ getPoints: (features: JsonObject[]) =>
+ features.map(feature => feature.position),
+ viewport: { longitude: 0, latitude: 0, zoom: 1 },
+ width: 400,
+ height: 300,
+ setControlValue: jest.fn(),
+ payload: { data: { features: positions.map(position => ({ position })) } },
+ } as unknown as CategoricalDeckGLContainerProps;
+
+ const { rerender } = render(
+ <ThemeProvider theme={supersetTheme}>
+ <CategoricalDeckGLContainer {...props} />
+ </ThemeProvider>,
+ );
+ const fitted = mockViewports.at(-1);
+
+ // Explore saves the viewer's tilt through setControlValue, and the transform
+ // re-runs on the same response, building a new features array.
+ rerender(
+ <ThemeProvider theme={supersetTheme}>
+ <CategoricalDeckGLContainer
+ {...props}
+ viewport={{ longitude: -100, latitude: 20, zoom: 6, pitch: 40 }}
+ payload={{
+ data: { features: positions.map(position => ({ position })) },
+ }}
+ />
+ </ThemeProvider>,
+ );
+ expect(mockViewports.at(-1)).toEqual(fitted);
+});
diff --git a/superset-frontend/plugins/preset-chart-deckgl/src/CategoricalDeckGLContainer.tsx b/superset-frontend/plugins/preset-chart-deckgl/src/CategoricalDeckGLContainer.tsx
index 3168f6a13d6..3bd2e221b3f 100644
--- a/superset-frontend/plugins/preset-chart-deckgl/src/CategoricalDeckGLContainer.tsx
+++ b/superset-frontend/plugins/preset-chart-deckgl/src/CategoricalDeckGLContainer.tsx
@@ -25,6 +25,7 @@
/* eslint no-underscore-dangle: ["error", { "allow": ["", "__timestamp"] }] */
import { memo, useCallback, useEffect, useRef, useState } from 'react';
+import { isEqual } from 'lodash-es';
import {
CategoricalColorNamespace,
Datasource,
@@ -41,6 +42,7 @@ import Legend from './components/Legend';
import { hexToRGB } from './utils/colors';
import { getMapboxApiKey } from './utils/mapbox';
import fitViewport, { Viewport } from './utils/fitViewport';
+import computeBoundsFromPoints from './utils/computeBoundsFromPoints';
import {
DeckGLContainerHandle,
DeckGLContainerStyledWrapper,
@@ -81,6 +83,42 @@ export function getCategories(fd: QueryFormData, data: JsonObject[]) {
return categories;
}
+type Categories = Record<string, { color: JsonValue; enabled: boolean }>;
+
+/**
+ * Rebuilds the legend categories for a new response while keeping the
+ * enabled state the viewer chose for categories that are still present.
+ * Returns `previous` unchanged when the set of categories is the same, so
+ * callers can skip the state update.
+ */
+export function reconcileCategories(
+ previous: Categories,
+ next: Categories,
+): Categories {
+ const previousKeys = Object.keys(previous);
+ const nextKeys = Object.keys(next);
+ if (
+ previousKeys.length === nextKeys.length &&
+ nextKeys.every(key => key in previous)
+ ) {
+ return previous;
+ }
+ const reconciled: Categories = {};
+ nextKeys.forEach(key => {
+ reconciled[key] = {
+ ...next[key],
+ enabled: previous[key]?.enabled ?? true,
+ };
+ });
+ // Same rule as toggling the legend: never leave every category hidden.
+ if (Object.values(reconciled).every(category => !category.enabled)) {
+ Object.values(reconciled).forEach(category => {
+ category.enabled = true;
+ });
+ }
+ return reconciled;
+}
+
export type CategoricalDeckGLContainerProps = {
datasource: Datasource;
formData: QueryFormData;
@@ -124,16 +162,49 @@ const CategoricalDeckGLContainer = (props: CategoricalDeckGLContainerProps) => {
props.payload.form_data,
);
const [viewport, setViewport] = useState(getAdjustedViewport());
+ const featuresRef = useRef(props.payload.data.features);
+ // The area autozoom last fitted. The transform builds a new features array
+ // on every run, including the one Explore triggers when it saves the
+ // viewer's pan, zoom or tilt, so a refit keys on these bounds by value.
+ const autozoomBoundsRef = useRef(
+ props.formData.autozoom
+ ? computeBoundsFromPoints(
+ props.getPoints(props.payload.data.features || []),
+ )
+ : undefined,
+ );
useEffect(() => {
+ const features = props.payload.data.features || [];
+ const autozoomBounds = props.formData.autozoom
+ ? computeBoundsFromPoints(props.getPoints(features))
+ : undefined;
if (props.payload.form_data !== stateFormData) {
- const features = props.payload.data.features || [];
const categories = getCategories(props.formData, features);
setViewport(getAdjustedViewport());
setStateFormData(props.payload.form_data);
setCategories(categories);
+ } else if (props.payload.data.features !== featuresRef.current) {
+ // A dashboard auto-refresh keeps the chart mounted and swaps in new
+ // data without a new form_data, so new categories are merged into the
+ // legend here instead of being filtered out as unknown, and autozoom
+ // refits the map when the new rows cover another area.
+ setCategories(previous =>
+ reconcileCategories(
+ previous as Categories,
+ getCategories(props.formData, features),
+ ),
+ );
+ if (
+ autozoomBounds &&
+ !isEqual(autozoomBounds, autozoomBoundsRef.current)
+ ) {
+ setViewport(getAdjustedViewport());
+ }
}
+ featuresRef.current = props.payload.data.features;
+ autozoomBoundsRef.current = autozoomBounds;
}, [getAdjustedViewport, props, stateFormData]);
const setTooltip = useCallback((tooltip: TooltipProps['tooltip']) => {
diff --git a/superset-frontend/plugins/preset-chart-deckgl/src/Multi/Multi.tsx b/superset-frontend/plugins/preset-chart-deckgl/src/Multi/Multi.tsx
index a9a263ad4cd..4c857d29d1e 100644
--- a/superset-frontend/plugins/preset-chart-deckgl/src/Multi/Multi.tsx
+++ b/superset-frontend/plugins/preset-chart-deckgl/src/Multi/Multi.tsx
@@ -101,6 +101,9 @@ export type DeckMultiProps = {
onSelect: () => void;
filterState?: FilterState;
emitCrossFilters?: boolean;
+ // True while a dashboard auto-refresh is in flight. The chart stays mounted
+ // through it, so the layers are reloaded once it lands.
+ isRefreshing?: boolean;
};
const MultiWrapper = styled.div<{ height: number; width: number }>`
@@ -485,14 +488,19 @@ const DeckMulti = (props: DeckMultiProps) => {
formData: QueryFormData,
slices: ({ slice_id: number } & JsonObject)[],
visibleLayers?: number[],
+ isRefresh = false,
): void => {
loadGenerationRef.current += 1;
const { current: generation } = loadGenerationRef;
- setViewport(getAdjustedViewport());
- setSubSlicesLayers({});
setLayerErrors({});
- // Start a fresh feature accumulation for the incremental autozoom refit.
- layerFeaturesRef.current = {};
+ // A refresh reloads the same layers, so the current ones and their
+ // fitted viewport stay on screen until each replacement arrives.
+ if (!isRefresh) {
+ setViewport(getAdjustedViewport());
+ setSubSlicesLayers({});
+ // Start a fresh feature accumulation for the incremental autozoom refit.
+ layerFeaturesRef.current = {};
+ }
let visibleDeckLayers = visibleLayers;
@@ -536,6 +544,7 @@ const DeckMulti = (props: DeckMultiProps) => {
const prevDeckSlices = usePrevious(props.formData.deck_slices);
const prevVisibleLayersRedux = usePrevious(visibleDeckLayersFromRedux);
+ const prevIsRefreshing = usePrevious(props.isRefreshing);
const toLayerFormData = useCallback(
(
@@ -640,8 +649,11 @@ const DeckMulti = (props: DeckMultiProps) => {
prevVisibleLayersRedux,
visibleDeckLayersFromRedux,
);
+ const refreshLanded = Boolean(prevIsRefreshing) && !props.isRefreshing;
+ const isRefreshOnly =
+ refreshLanded && !deckSlicesChanged && !visibilityFilterChanged;
- if (deckSlicesChanged || visibilityFilterChanged) {
+ if (deckSlicesChanged || visibilityFilterChanged || refreshLanded) {
const sliceIds = ensureIsArray(formData.deck_slices) as number[];
const maxSlices = getDeckMultiMaxSlices();
if (sliceIds.length > maxSlices) {
@@ -672,7 +684,7 @@ const DeckMulti = (props: DeckMultiProps) => {
if (fetchGenerationRef.current !== fetchGeneration) {
return;
}
- loadLayers(formData, slices, visibleDeckLayersFromRedux);
+ loadLayers(formData, slices, visibleDeckLayersFromRedux, isRefreshOnly);
});
}
}, [
@@ -680,6 +692,7 @@ const DeckMulti = (props: DeckMultiProps) => {
fetchSubslices,
prevDeckSlices,
prevVisibleLayersRedux,
+ prevIsRefreshing,
visibleDeckLayersFromRedux,
props,
]);
diff --git a/superset-frontend/plugins/preset-chart-deckgl/src/Multi/MultiV1.test.tsx b/superset-frontend/plugins/preset-chart-deckgl/src/Multi/MultiV1.test.tsx
index 29cf99b9c26..a756268fdd4 100644
--- a/superset-frontend/plugins/preset-chart-deckgl/src/Multi/MultiV1.test.tsx
+++ b/superset-frontend/plugins/preset-chart-deckgl/src/Multi/MultiV1.test.tsx
@@ -29,6 +29,9 @@ jest.mock('../DeckGLContainer', () => ({
data-test="deckgl-container"
data-viewport={JSON.stringify(viewport)}
data-layers-count={layers?.length || 0}
+ data-layers-data={JSON.stringify(
+ layers?.map((layer: any) => layer?.props?.data),
+ )}
>
DeckGL Container Mock
</div>
@@ -53,9 +56,14 @@ getChartBuildQueryRegistry().registerValue('deck_scatter', (fd: any) => ({
queries: [{}],
form_data: fd,
}));
-getChartTransformPropsRegistry().registerValue('deck_scatter', () => ({
- payload: { data: { features: SF_FEATURES } },
-}));
+// Builds the layer from the response, so a test can tell which response a
+// rendered layer came from.
+getChartTransformPropsRegistry().registerValue(
+ 'deck_scatter',
+ (chartProps: any) => ({
+ payload: { data: { features: chartProps.queriesData[0].data } },
+ }),
+);
const store = configureStore({ reducer: { dataMask: () => ({}) } });
@@ -225,3 +233,55 @@ test('surfaces a warning in the chart when a layer fails to load', async () => {
// The map still renders alongside the warning.
expect(screen.getByTestId('deckgl-container')).not.toBeNull();
});
+
+test('reloads its layers when a dashboard auto-refresh lands, keeping the current ones on screen', async () => {
+ // ChartRenderer keeps this chart mounted through an auto-refresh, so the
+ // refresh itself has to trigger the reload that a remount used to.
+ const renderWith = (isRefreshing: boolean) => (
+ <Provider store={store}>
+ <ThemeProvider theme={supersetTheme}>
+ <DeckMulti {...v1Props} isRefreshing={isRefreshing} />
+ </ThemeProvider>
+ </Provider>
+ );
+ const getContainer = () => screen.getByTestId('deckgl-container');
+ const { rerender } = render(renderWith(false));
+ await waitFor(() =>
+ expect(getContainer().getAttribute('data-layers-count')).toBe('1'),
+ );
+ expect(SupersetClient.post).toHaveBeenCalledTimes(1);
+
+ rerender(renderWith(true));
+ expect(SupersetClient.post).toHaveBeenCalledTimes(1);
+
+ let resolveReload: (value: unknown) => void = () => {};
+ (SupersetClient.post as jest.Mock).mockReturnValueOnce(
+ new Promise(resolve => {
+ resolveReload = resolve;
+ }),
+ );
+ rerender(renderWith(false));
+
+ await waitFor(() => expect(SupersetClient.post).toHaveBeenCalledTimes(2));
+ // While the new layer data is in flight, the map keeps the previous layer
+ // and its fitted viewport instead of blanking back to the base viewport.
+ expect(getContainer().getAttribute('data-layers-count')).toBe('1');
+ const viewport = JSON.parse(
+ getContainer().getAttribute('data-viewport') || '{}',
+ );
+ expect(viewport.longitude).toBeLessThan(-100);
+
+ const drawnPositions = () =>
+ JSON.parse(getContainer().getAttribute('data-layers-data') || '[]').map(
+ (data: { position: number[] }[]) => data.map(d => d.position),
+ );
+ expect(drawnPositions()).toEqual([SF_FEATURES.map(f => f.position)]);
+
+ const refreshedFeatures = [{ position: [-118.24, 34.05] }];
+ resolveReload({ json: { result: [{ data: refreshedFeatures }] } });
+ // The layer drawn after the refresh is built from the refreshed response,
+ // not kept from the first load.
+ await waitFor(() =>
+ expect(drawnPositions()).toEqual([[refreshedFeatures[0].position]]),
+ );
+});
diff --git a/superset-frontend/plugins/preset-chart-deckgl/src/Multi/index.ts b/superset-frontend/plugins/preset-chart-deckgl/src/Multi/index.ts
index df4e2fa04a7..cabb578e003 100644
--- a/superset-frontend/plugins/preset-chart-deckgl/src/Multi/index.ts
+++ b/superset-frontend/plugins/preset-chart-deckgl/src/Multi/index.ts
@@ -22,7 +22,7 @@ import thumbnail from './images/thumbnail.png';
import thumbnailDark from './images/thumbnail-dark.png';
import example from './images/example.png';
import exampleDark from './images/example-dark.png';
-import transformProps from '../transformProps';
+import transformProps from './transformProps';
import controlPanel from './controlPanel';
const metadata = new ChartMetadata({
diff --git a/superset-frontend/plugins/preset-chart-deckgl/src/Multi/transformProps.test.ts b/superset-frontend/plugins/preset-chart-deckgl/src/Multi/transformProps.test.ts
new file mode 100644
index 00000000000..4b37ade665a
--- /dev/null
+++ b/superset-frontend/plugins/preset-chart-deckgl/src/Multi/transformProps.test.ts
@@ -0,0 +1,43 @@
+/**
+ * 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 { ChartProps } from '@superset-ui/core';
+import { supersetTheme } from '@apache-superset/core/theme';
+import transformProps from './transformProps';
+
+const buildChartProps = (isRefreshing?: boolean) =>
+ new ChartProps({
+ width: 800,
+ height: 600,
+ formData: { viz_type: 'deck_multi', deck_slices: [1] },
+ queriesData: [],
+ theme: supersetTheme,
+ isRefreshing,
+ });
+
+test('passes isRefreshing through so the chart can reload its layers', () => {
+ expect(transformProps(buildChartProps(true)).isRefreshing).toBe(true);
+ expect(transformProps(buildChartProps(false)).isRefreshing).toBe(false);
+});
+
+test('keeps the shared deck.gl props', () => {
+ const props = transformProps(buildChartProps());
+ expect(props.formData).toEqual({ viz_type: 'deck_multi', deck_slices: [1] });
+ expect(props.payload).toBeUndefined();
+ expect(props.viewport).toEqual({ height: 600, width: 800 });
+});
diff --git a/superset-frontend/plugins/preset-chart-deckgl/src/Multi/transformProps.ts b/superset-frontend/plugins/preset-chart-deckgl/src/Multi/transformProps.ts
new file mode 100644
index 00000000000..4060baa17dd
--- /dev/null
+++ b/superset-frontend/plugins/preset-chart-deckgl/src/Multi/transformProps.ts
@@ -0,0 +1,32 @@
+/**
+ * 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 { ChartProps } from '@superset-ui/core';
+import baseTransformProps from '../transformProps';
+
+/**
+ * The shared deck.gl props plus `isRefreshing`. ChartRenderer keeps this chart
+ * mounted through a dashboard auto-refresh, and since its layers fetch their
+ * own data, the chart needs the signal to reload them.
+ */
+export default function transformProps(chartProps: ChartProps) {
+ return {
+ ...baseTransformProps(chartProps),
+ isRefreshing: chartProps.isRefreshing,
+ };
+}
diff --git a/superset-frontend/plugins/preset-chart-deckgl/src/factory.test.tsx b/superset-frontend/plugins/preset-chart-deckgl/src/factory.test.tsx
new file mode 100644
index 00000000000..16838b922c1
--- /dev/null
+++ b/superset-frontend/plugins/preset-chart-deckgl/src/factory.test.tsx
@@ -0,0 +1,117 @@
+/**
+ * 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 { render } from '@testing-library/react';
+import { ThemeProvider, supersetTheme } from '@apache-superset/core/theme';
+import { JsonObject } from '@superset-ui/core';
+import { createDeckGLComponent } from './factory';
+import { Point } from './types';
+
+const mockViewports: JsonObject[] = [];
+jest.mock('./DeckGLContainer', () => ({
+ DeckGLContainerStyledWrapper: jest
+ .requireActual('react')
+ .forwardRef(({ viewport }: { viewport: JsonObject }) => {
+ mockViewports.push(viewport);
+ return <div data-test="deckgl-container" />;
+ }),
+}));
+
+const DeckGLComponent = createDeckGLComponent(
+ () => ({}),
+ (features: JsonObject[]) => features.map(feature => feature.position),
+);
+
+const payloadAt = (positions: Point[]) => ({
+ data: { features: positions.map(position => ({ position })) },
+});
+
+test.each([
+ [true, 51.5],
+ [false, 0],
+])(
+ 'with autozoom %s a refreshed response leaves the map centered at latitude %s',
+ (autozoom, expectedLatitude) => {
+ const props = {
+ formData: { datasource: '1__table', viz_type: 'deck_grid', autozoom },
+ viewport: { longitude: 0, latitude: 0, zoom: 1 },
+ width: 400,
+ height: 300,
+ setControlValue: jest.fn(),
+ payload: payloadAt([
+ [-122.45, 37.75],
+ [-122.4, 37.8],
+ ]),
+ } as unknown as Parameters<typeof DeckGLComponent>[0];
+
+ const { rerender } = render(
+ <ThemeProvider theme={supersetTheme}>
+ <DeckGLComponent {...props} />
+ </ThemeProvider>,
+ );
+ expect(mockViewports.at(-1)?.latitude).toBeCloseTo(autozoom ? 37.775 : 0);
+
+ rerender(
+ <ThemeProvider theme={supersetTheme}>
+ <DeckGLComponent
+ {...props}
+ payload={payloadAt([
+ [-0.15, 51.48],
+ [-0.1, 51.52],
+ ])}
+ />
+ </ThemeProvider>,
+ );
+ expect(mockViewports.at(-1)?.latitude).toBeCloseTo(expectedLatitude, 1);
+ },
+);
+
+test('with autozoom a tilt written back by Explore keeps the viewer on the same rows', () => {
+ const positions: Point[] = [
+ [-122.45, 37.75],
+ [-122.4, 37.8],
+ ];
+ const props = {
+ formData: { datasource: '1__table', viz_type: 'deck_grid', autozoom: true },
+ viewport: { longitude: 0, latitude: 0, zoom: 1 },
+ width: 400,
+ height: 300,
+ setControlValue: jest.fn(),
+ payload: payloadAt(positions),
+ } as unknown as Parameters<typeof DeckGLComponent>[0];
+
+ const { rerender } = render(
+ <ThemeProvider theme={supersetTheme}>
+ <DeckGLComponent {...props} />
+ </ThemeProvider>,
+ );
+ const fitted = mockViewports.at(-1);
+
+ // Explore saves the viewer's tilt through setControlValue, and the transform
+ // re-runs on the same response, building a new features array.
+ rerender(
+ <ThemeProvider theme={supersetTheme}>
+ <DeckGLComponent
+ {...props}
+ viewport={{ longitude: -100, latitude: 20, zoom: 6, pitch: 40 }}
+ payload={payloadAt(positions)}
+ />
+ </ThemeProvider>,
+ );
+ expect(mockViewports.at(-1)).toEqual(fitted);
+});
diff --git a/superset-frontend/plugins/preset-chart-deckgl/src/factory.tsx b/superset-frontend/plugins/preset-chart-deckgl/src/factory.tsx
index ec38466c079..227af549088 100644
--- a/superset-frontend/plugins/preset-chart-deckgl/src/factory.tsx
+++ b/superset-frontend/plugins/preset-chart-deckgl/src/factory.tsx
@@ -40,6 +40,7 @@ import {
} from './DeckGLContainer';
import CategoricalDeckGLContainer from './CategoricalDeckGLContainer';
import fitViewport, { Viewport } from './utils/fitViewport';
+import computeBoundsFromPoints from './utils/computeBoundsFromPoints';
import { Point } from './types';
import { TooltipProps } from './components/Tooltip';
import { getColorBreakpointsBuckets } from './utils';
@@ -113,6 +114,30 @@ export function createDeckGLComponent(
);
const [viewport, setViewport] = useState(getAdjustedViewport());
+ // The area autozoom last fitted. The transform builds a new features array
+ // on every run, including the one Explore triggers when it saves the
+ // viewer's pan, zoom or tilt, so a refit keys on these bounds by value.
+ const autozoomBoundsRef = useRef(
+ props.formData.autozoom
+ ? computeBoundsFromPoints(getPoints(props.payload.data.features))
+ : undefined,
+ );
+
+ useEffect(() => {
+ // A dashboard auto-refresh keeps the chart mounted and swaps in new
+ // data, so autozoom refits the map here when the new rows cover
+ // another area.
+ const autozoomBounds = props.formData.autozoom
+ ? computeBoundsFromPoints(getPoints(props.payload.data.features))
+ : undefined;
+ if (
+ autozoomBounds &&
+ !isEqual(autozoomBounds, autozoomBoundsRef.current)
+ ) {
+ setViewport(getAdjustedViewport());
+ }
+ autozoomBoundsRef.current = autozoomBounds;
+ }, [getAdjustedViewport, props]);
const setTooltip = useCallback((tooltip: TooltipProps['tooltip']) => {
const { current } = containerRef;
diff --git a/superset-frontend/plugins/preset-chart-deckgl/src/layers/Polygon/Polygon.test.tsx b/superset-frontend/plugins/preset-chart-deckgl/src/layers/Polygon/Polygon.test.tsx
index 1776f2bd98d..89b1eb141f5 100644
--- a/superset-frontend/plugins/preset-chart-deckgl/src/layers/Polygon/Polygon.test.tsx
+++ b/superset-frontend/plugins/preset-chart-deckgl/src/layers/Polygon/Polygon.test.tsx
@@ -474,3 +474,103 @@ describe('getPoints utility', () => {
expect(points[4]).toEqual([2, 2]);
});
});
+
+test('autozoom refits the map when a refresh brings rows in another place', () => {
+ mockDeckGLContainerProps.length = 0;
+ mockGetBuckets.mockReturnValue({});
+ const square = (lng: number, lat: number) => [
+ [lng, lat],
+ [lng + 0.05, lat],
+ [lng + 0.05, lat + 0.05],
+ [lng, lat + 0.05],
+ ];
+ const props = {
+ ...mockProps,
+ formData: { ...mockProps.formData, autozoom: true },
+ payload: {
+ ...mockProps.payload,
+ data: {
+ ...mockProps.payload.data,
+ features: [{ population: 1, polygon: square(-122.45, 37.75) }],
+ },
+ },
+ };
+ const lastLatitude = () =>
+ (
+ mockDeckGLContainerProps.at(-1)?.viewport as
+ | { latitude: number }
+ | undefined
+ )?.latitude;
+
+ const { rerender } = render(
+ <ThemeProvider theme={supersetTheme}>
+ <DeckGLPolygon {...props} />
+ </ThemeProvider>,
+ );
+ expect(lastLatitude()).toBeCloseTo(37.775, 1);
+
+ // Same form_data, new rows: what a dashboard auto-refresh delivers.
+ rerender(
+ <ThemeProvider theme={supersetTheme}>
+ <DeckGLPolygon
+ {...props}
+ payload={{
+ ...props.payload,
+ data: {
+ ...props.payload.data,
+ features: [{ population: 1, polygon: square(-0.15, 51.48) }],
+ },
+ }}
+ />
+ </ThemeProvider>,
+ );
+ expect(lastLatitude()).toBeCloseTo(51.505, 1);
+});
+
+test('autozoom keeps a tilt written back by Explore when the rows are the same', () => {
+ mockDeckGLContainerProps.length = 0;
+ mockGetBuckets.mockReturnValue({});
+ const features = () => [
+ {
+ population: 1,
+ polygon: [
+ [-122.45, 37.75],
+ [-122.4, 37.75],
+ [-122.4, 37.8],
+ [-122.45, 37.8],
+ ],
+ },
+ ];
+ const props = {
+ ...mockProps,
+ formData: { ...mockProps.formData, autozoom: true },
+ payload: {
+ ...mockProps.payload,
+ data: { ...mockProps.payload.data, features: features() },
+ },
+ };
+ const lastViewport = () => mockDeckGLContainerProps.at(-1)?.viewport;
+
+ const { rerender } = render(
+ <ThemeProvider theme={supersetTheme}>
+ <DeckGLPolygon {...props} />
+ </ThemeProvider>,
+ );
+ const fitted = lastViewport();
+
+ // Explore saves the viewer's tilt through setControlValue, and the transform
+ // re-runs on the same response, building a new features array.
+ rerender(
+ <ThemeProvider theme={supersetTheme}>
+ <DeckGLPolygon
+ {...props}
+ viewport={{ longitude: -100, latitude: 20, zoom: 6, pitch: 40 }}
+ payload={{
+ ...props.payload,
+ data: { ...props.payload.data, features: features() },
+ }}
+ />
+ </ThemeProvider>,
+ );
+ expect(lastViewport()).toEqual(fitted);
+});
diff --git a/superset-frontend/plugins/preset-chart-deckgl/src/layers/Polygon/Polygon.tsx b/superset-frontend/plugins/preset-chart-deckgl/src/layers/Polygon/Polygon.tsx
index 96635a158ae..7813faa4913 100644
--- a/superset-frontend/plugins/preset-chart-deckgl/src/layers/Polygon/Polygon.tsx
+++ b/superset-frontend/plugins/preset-chart-deckgl/src/layers/Polygon/Polygon.tsx
@@ -22,6 +22,7 @@
/* eslint no-underscore-dangle: ["error", { "allow": ["", "__timestamp"] }] */
import { memo, useCallback, useEffect, useRef, useState } from 'react';
+import { isEqual } from 'lodash-es';
import { t } from '@apache-superset/core/translation';
import {
ContextMenuFilters,
@@ -50,6 +51,7 @@ import { commonLayerProps, getColorForBreakpoints } from '../common';
import { PRIMARY_COLOR } from '../../utilities/controls';
import getPointsFromPolygon from '../../utils/getPointsFromPolygon';
import fitViewport, { Viewport } from '../../utils/fitViewport';
+import computeBoundsFromPoints from '../../utils/computeBoundsFromPoints';
import {
DeckGLContainerHandle,
DeckGLContainerStyledWrapper,
@@ -279,14 +281,34 @@ const DeckGLPolygon = (props: DeckGLPolygonProps) => {
const [viewport, setViewport] = useState(getAdjustedViewport());
const [stateFormData, setStateFormData] = useState(props.payload.form_data);
+ // The area autozoom last fitted. The transform builds a new features array
+ // on every run, including the one Explore triggers when it saves the
+ // viewer's pan, zoom or tilt, so a refit keys on these bounds by value.
+ const autozoomBoundsRef = useRef(
+ props.formData.autozoom
+ ? computeBoundsFromPoints(getPoints(props.payload.data.features || []))
+ : undefined,
+ );
useEffect(() => {
const { payload } = props;
+ const autozoomBounds = props.formData.autozoom
+ ? computeBoundsFromPoints(getPoints(payload.data.features || []))
+ : undefined;
if (payload.form_data !== stateFormData) {
setViewport(getAdjustedViewport());
setStateFormData(payload.form_data);
+ } else if (
+ autozoomBounds &&
+ !isEqual(autozoomBounds, autozoomBoundsRef.current)
+ ) {
+ // A dashboard auto-refresh keeps the chart mounted and swaps in new
+ // data without a new form_data, so autozoom refits the map here when
+ // the new rows cover another area.
+ setViewport(getAdjustedViewport());
}
+ autozoomBoundsRef.current = autozoomBounds;
}, [getAdjustedViewport, props, stateFormData, viewport]);
const setTooltip = useCallback((tooltip: TooltipProps['tooltip']) => {
diff --git a/superset-frontend/src/components/Chart/ChartRenderer.refresh.test.tsx b/superset-frontend/src/components/Chart/ChartRenderer.refresh.test.tsx
new file mode 100644
index 00000000000..5339546f93f
--- /dev/null
+++ b/superset-frontend/src/components/Chart/ChartRenderer.refresh.test.tsx
@@ -0,0 +1,302 @@
+/**
+ * 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 { useEffect } from 'react';
+import { act, render, screen } from 'spec/helpers/testing-library';
+import { ChartMetadata, ChartPlugin, QueryData } from '@superset-ui/core';
+import ChartRenderer, {
+ ChartRendererProps,
+} from 'src/components/Chart/ChartRenderer';
+import { ChartSource } from 'src/types/ChartSource';
+
+// These tests run the real SuperChart, because the bug they guard against
+// lives in what SuperChart does with the data ChartRenderer hands it.
+jest.mock(
+ 'src/components/Chart/ChartContextMenu/ChartContextMenu',
+ () => () => <div />,
+);
+
+const VIZ_TYPE = 'refresh_test_chart';
+const SELF_FETCHING_VIZ_TYPE = 'refresh_test_self_fetching_chart';
+const NO_RESULTS = 'No results were returned for this query';
+
+interface TestChartProps {
+ queriesData: { data: { value: number }[] }[];
+}
+
+const TestChart = ({ queriesData }: TestChartProps) => (
+ <div data-test="refresh-test-chart">value={queriesData[0].data[0].value}</div>
+);
+
+const selfFetchingChartMounted = jest.fn();
+
+// Stands in for deck.gl Multiple Layers: it issues no query of its own, so
+// its response is an empty array, and it loads its data when it mounts.
+const SelfFetchingTestChart = () => {
+ useEffect(() => {
+ selfFetchingChartMounted();
+ }, []);
+ return <div data-test="self-fetching-test-chart" />;
+};
+
+beforeAll(() => {
+ new ChartPlugin({
+ metadata: new ChartMetadata({ name: 'Refresh test chart', thumbnail: '' }),
+ Chart: TestChart,
+ transformProps: chartProps => ({ queriesData: chartProps.queriesData }),
+ })
+ .configure({ key: VIZ_TYPE })
+ .register();
+ new ChartPlugin({
+ metadata: new ChartMetadata({
+ name: 'Self-fetching refresh test chart',
+ thumbnail: '',
+ enableNoResults: false,
+ }),
+ Chart: SelfFetchingTestChart,
+ })
+ .configure({ key: SELF_FETCHING_VIZ_TYPE })
+ .register();
+});
+
+beforeEach(() => {
+ selfFetchingChartMounted.mockClear();
+});
+
+const queriesResponse = (value: number) =>
+ [{ data: [{ value }] }] as unknown as QueryData[];
+
+// SuperChart loads the chart plugin asynchronously, so a chart that is about
+// to render is not in the DOM right after render(). Tests asserting that a
+// chart stays absent have to let that load settle first.
+const waitForChartLoad = () =>
+ act(async () => {
+ await new Promise(resolve => setTimeout(resolve, 0));
+ });
+
+const props = (overrides: Partial<ChartRendererProps>): ChartRendererProps => ({
+ chartId: 1,
+ datasource: {} as ChartRendererProps['datasource'],
+ formData: { viz_type: VIZ_TYPE } as ChartRendererProps['formData'],
+ vizType: VIZ_TYPE,
+ source: ChartSource.Dashboard,
+ width: 600,
+ height: 400,
+ actions: {
+ chartRenderingSucceeded: jest.fn(),
+ chartRenderingFailed: jest.fn(),
+ logEvent: jest.fn(),
+ } as unknown as ChartRendererProps['actions'],
+ queriesResponse: queriesResponse(1),
+ ...overrides,
+});
+
+test('keeps the chart on screen while an auto-refresh query is in flight', async () => {
+ const { rerender } = render(
+ <ChartRenderer
+ {...props({ chartStatus: 'rendered', suppressLoadingSpinner: true })}
+ />,
+ );
+ expect(await screen.findByTestId('refresh-test-chart')).toHaveTextContent(
+ 'value=1',
+ );
+
+ rerender(
+ <ChartRenderer
+ {...props({ chartStatus: 'loading', suppressLoadingSpinner: true })}
+ />,
+ );
+
+ expect(await screen.findByTestId('refresh-test-chart')).toHaveTextContent(
+ 'value=1',
+ );
+ expect(screen.queryByText(NO_RESULTS)).not.toBeInTheDocument();
+});
+
+test('renders the previous data when mounted in the middle of an auto-refresh', async () => {
+ render(
+ <ChartRenderer
+ {...props({ chartStatus: 'loading', suppressLoadingSpinner: true })}
+ />,
+ );
+
+ expect(await screen.findByTestId('refresh-test-chart')).toHaveTextContent(
+ 'value=1',
+ );
+ expect(screen.queryByText(NO_RESULTS)).not.toBeInTheDocument();
+});
+
+test('shows the new data once the auto-refresh query returns', async () => {
+ const { rerender } = render(
+ <ChartRenderer
+ {...props({ chartStatus: 'rendered', suppressLoadingSpinner: true })}
+ />,
+ );
+ await screen.findByTestId('refresh-test-chart');
+ rerender(
+ <ChartRenderer
+ {...props({ chartStatus: 'loading', suppressLoadingSpinner: true })}
+ />,
+ );
+
+ rerender(
+ <ChartRenderer
+ {...props({
+ chartStatus: 'success',
+ suppressLoadingSpinner: true,
+ queriesResponse: queriesResponse(2),
+ })}
+ />,
+ );
+
+ expect(await screen.findByText('value=2')).toBeInTheDocument();
+});
+
+test('still shows the no-results state when a finished query returns no rows', async () => {
+ render(
+ <ChartRenderer
+ {...props({
+ chartStatus: 'rendered',
+ suppressLoadingSpinner: true,
+ queriesResponse: [{ data: [] }] as unknown as QueryData[],
+ })}
+ />,
+ );
+
+ expect(await screen.findByText(NO_RESULTS)).toBeInTheDocument();
+});
+
+const selfFetchingProps = (
+ overrides: Partial<ChartRendererProps>,
+): ChartRendererProps =>
+ props({
+ formData: {
+ viz_type: SELF_FETCHING_VIZ_TYPE,
+ } as ChartRendererProps['formData'],
+ vizType: SELF_FETCHING_VIZ_TYPE,
+ suppressLoadingSpinner: true,
+ queriesResponse: [],
+ ...overrides,
+ });
+
+test('keeps a self-fetching chart mounted while an auto-refresh query is in flight', async () => {
+ const { rerender } = render(
+ <ChartRenderer {...selfFetchingProps({ chartStatus: 'rendered' })} />,
+ );
+ await screen.findByTestId('self-fetching-test-chart');
+
+ rerender(
+ <ChartRenderer {...selfFetchingProps({ chartStatus: 'loading' })} />,
+ );
+ expect(screen.getByTestId('self-fetching-test-chart')).toBeInTheDocument();
+
+ rerender(
+ <ChartRenderer {...selfFetchingProps({ chartStatus: 'success' })} />,
+ );
+ expect(screen.getByTestId('self-fetching-test-chart')).toBeInTheDocument();
+ // A remount would make the chart load all of its data again.
+ expect(selfFetchingChartMounted).toHaveBeenCalledTimes(1);
+});
+
+test('does not render a self-fetching chart whose first query is still in flight', async () => {
+ render(
+ <ChartRenderer
+ {...selfFetchingProps({ chartStatus: 'loading', queriesResponse: null })}
+ />,
+ );
+ await waitForChartLoad();
+
+ expect(
+ screen.queryByTestId('self-fetching-test-chart'),
+ ).not.toBeInTheDocument();
+ expect(selfFetchingChartMounted).not.toHaveBeenCalled();
+});
+
+test('does not render a chart with an empty response while its query is in flight', async () => {
+ render(
+ <ChartRenderer
+ {...props({
+ chartStatus: 'loading',
+ suppressLoadingSpinner: true,
+ queriesResponse: [],
+ })}
+ />,
+ );
+ await waitForChartLoad();
+
+ expect(screen.queryByTestId('refresh-test-chart')).not.toBeInTheDocument();
+ expect(screen.queryByText(NO_RESULTS)).not.toBeInTheDocument();
+});
+
+test('reports the render when an auto-refresh lands on a chart kept on screen', async () => {
+ const chartProps = props({ suppressLoadingSpinner: true });
+ const { actions } = chartProps;
+ const { rerender } = render(
+ <ChartRenderer {...chartProps} chartStatus="rendered" />,
+ );
+ await screen.findByTestId('refresh-test-chart');
+ rerender(<ChartRenderer {...chartProps} chartStatus="loading" />);
+ await screen.findByTestId('refresh-test-chart');
+ expect(actions.chartRenderingSucceeded).not.toHaveBeenCalled();
+
+ rerender(
+ <ChartRenderer
+ {...chartProps}
+ chartStatus="success"
+ queriesResponse={queriesResponse(2)}
+ />,
+ );
+
+ expect(await screen.findByTestId('refresh-test-chart')).toHaveTextContent(
+ 'value=2',
+ );
+ expect(actions.chartRenderingSucceeded).toHaveBeenCalledTimes(1);
+ expect(actions.chartRenderingSucceeded).toHaveBeenCalledWith(1);
+ expect(actions.logEvent).toHaveBeenCalledTimes(1);
+});
+
+test('reports a refreshed render once when the plugin mounts for the new response', async () => {
+ // The previous response had no rows, so the refresh shows the no-results
+ // state and the plugin mounts, and reports itself, when data lands.
+ const chartProps = props({
+ suppressLoadingSpinner: true,
+ queriesResponse: [{ data: [] }] as unknown as QueryData[],
+ });
+ const { actions } = chartProps;
+ const { rerender } = render(
+ <ChartRenderer {...chartProps} chartStatus="rendered" />,
+ );
+ await screen.findByText(NO_RESULTS);
+ rerender(<ChartRenderer {...chartProps} chartStatus="loading" />);
+ await screen.findByText(NO_RESULTS);
+
+ rerender(
+ <ChartRenderer
+ {...chartProps}
+ chartStatus="success"
+ queriesResponse={queriesResponse(2)}
+ />,
+ );
+
+ expect(await screen.findByTestId('refresh-test-chart')).toHaveTextContent(
+ 'value=2',
+ );
+ await waitForChartLoad();
+ expect(actions.chartRenderingSucceeded).toHaveBeenCalledTimes(1);
+ expect(actions.logEvent).toHaveBeenCalledTimes(1);
+});
diff --git a/superset-frontend/src/components/Chart/ChartRenderer.test.tsx b/superset-frontend/src/components/Chart/ChartRenderer.test.tsx
index 16405b2a37e..49de0aa844d 100644
--- a/superset-frontend/src/components/Chart/ChartRenderer.test.tsx
+++ b/superset-frontend/src/components/Chart/ChartRenderer.test.tsx
@@ -48,6 +48,7 @@ jest.mock('@superset-ui/core', () => ({
<div
data-test="mock-super-chart"
data-is-refreshing={isRefreshing ? 'true' : 'false'}
+ data-queries-data={JSON.stringify(props.queriesData ?? null)}
data-enable-no-results={props.enableNoResults ? 'true' : 'false'}
data-async-mode={String(
(props.hooks as { resolveAsyncMode?: () => boolean } | undefined)?.[
@@ -426,6 +427,24 @@ test('renders chart during loading when suppressLoadingSpinner has valid data',
'data-is-refreshing',
'true',
);
+ // Without the previous data SuperChart falls back to the no-results state.
+ expect(getByTestId('mock-super-chart')).toHaveAttribute(
+ 'data-queries-data',
+ JSON.stringify(props.queriesResponse),
+ );
+});
+
+test('does not render chart during loading when the spinner is not suppressed', () => {
+ const props = {
+ ...requiredProps,
+ chartStatus: 'loading' as const,
+ chartAlert: undefined,
+ suppressLoadingSpinner: false,
+ queriesResponse: [{ data: [{ value: 1 }] }],
+ };
+
+ const { queryByTestId } = render(<ChartRenderer {...props} />);
+ expect(queryByTestId('mock-super-chart')).not.toBeInTheDocument();
});
test('does not mark chart as refreshing when loading is not in progress', () => {
diff --git a/superset-frontend/src/components/Chart/ChartRenderer.tsx b/superset-frontend/src/components/Chart/ChartRenderer.tsx
index c81834d52ae..0a6c9df3609 100644
--- a/superset-frontend/src/components/Chart/ChartRenderer.tsx
+++ b/superset-frontend/src/components/Chart/ChartRenderer.tsx
@@ -272,14 +272,44 @@ function ChartRendererComponent({
prevQueriesResponseRef.current = queriesResponse;
}, [queriesResponse]);
+ const currentFormData =
+ chartIsStale && latestQueryFormData ? latestQueryFormData : formData;
+ const vizType = currentFormData.viz_type || propVizType;
+ // Some charts fetch their own data and issue no top-level query (e.g. deck.gl
+ // Multiple Layers, which renders its sub-layer charts), so an empty response
+ // is expected and shouldn't trigger the no-results state. Honor the chart's
+ // own enableNoResults metadata (defaults to true).
+ const chartEnableNoResults =
+ getChartMetadataRegistry().get(vizType)?.enableNoResults ?? true;
+
+ // A failed load leaves its errored response in the store, and the next
+ // CHART_UPDATE_STARTED clears chartAlert but not queriesResponse. Checking
+ // the response itself keeps that stale error from being drawn as chart data
+ // while the retry is in flight.
+ const hasAnyErrors = queriesResponse?.some(item => item?.error);
+ // The response of a chart that fetches its own data stays empty once it has
+ // loaded, so for those any response that landed counts as previous data.
+ const hasPreviousResponse = chartEnableNoResults
+ ? (queriesResponse?.length ?? 0) > 0
+ : Array.isArray(queriesResponse);
+ const hasValidPreviousData = hasPreviousResponse && !hasAnyErrors;
+
+ // An auto-refresh keeps the chart on screen while its query is in flight.
+ // The store holds the previous response until the new one lands, so that
+ // response is what the chart renders in the meantime.
+ const isRefreshing =
+ Boolean(restProps.suppressLoadingSpinner) && chartStatus === 'loading';
+ const hasRenderableResults =
+ resultsReady || (isRefreshing && hasValidPreviousData);
+
// Clone queriesResponse to protect against plugin mutation of Redux state.
- // Gate on `resultsReady` so the deep clone doesn't run for every
+ // Gate on `hasRenderableResults` so the deep clone doesn't run for every
// queriesResponse identity change during loading/idle (only when results
- // are actually about to render). Matches the pre-refactor gating.
+ // are actually about to render).
// TODO: remove once reducers use Redux Toolkit with Immer.
const mutableQueriesResponse = useMemo(
- () => (resultsReady ? cloneDeep(queriesResponse) : undefined),
- [queriesResponse, resultsReady],
+ () => (hasRenderableResults ? cloneDeep(queriesResponse) : undefined),
+ [queriesResponse, hasRenderableResults],
);
// Handler functions
@@ -290,7 +320,16 @@ function ChartRendererComponent({
[addFilter],
);
+ // The response the last render success was reported for. A refreshed
+ // response can be reported both by the effect below and by a plugin that
+ // mounts for it, and only the first report counts.
+ const reportedResponseRef = useRef<QueryData[] | null | undefined>();
+
const handleRenderSuccess = useCallback((): void => {
+ if (reportedResponseRef.current === queriesResponse) {
+ return;
+ }
+ reportedResponseRef.current = queriesResponse;
if (['loading', 'rendered'].indexOf(chartStatus as string) < 0) {
actions.chartRenderingSucceeded(chartId);
}
@@ -305,7 +344,23 @@ function ChartRendererComponent({
duration: Logger.getTimestamp() - renderStartTimeRef.current,
});
}
- }, [actions, chartId, chartStatus, propVizType]);
+ }, [actions, chartId, chartStatus, propVizType, queriesResponse]);
+
+ // The plugin reports render success once, after it loads. A chart kept on
+ // screen through an auto-refresh stays mounted when the new response lands,
+ // so that render is reported here to move the chart back to `rendered`.
+ const keptOnScreenRef = useRef(false);
+ useEffect(() => {
+ if (chartStatus === 'loading') {
+ keptOnScreenRef.current = hasRenderableResults;
+ return;
+ }
+ const refreshLanded = keptOnScreenRef.current;
+ keptOnScreenRef.current = false;
+ if (refreshLanded && chartStatus === 'success') {
+ handleRenderSuccess();
+ }
+ }, [chartStatus, handleRenderSuccess, hasRenderableResults, queriesResponse]);
const handleRenderFailure = useCallback(
(error: Error, info: { componentStack: string } | null): void => {
@@ -448,26 +503,16 @@ function ChartRendererComponent({
],
);
- const hasAnyErrors = queriesResponse?.some(item => item?.error);
- const hasValidPreviousData =
- (queriesResponse?.length ?? 0) > 0 && !hasAnyErrors;
-
if (!!chartAlert || chartStatus === null) {
return null;
}
- if (chartStatus === 'loading') {
- if (!restProps.suppressLoadingSpinner || !hasValidPreviousData) {
- return null;
- }
+ if (chartStatus === 'loading' && !hasRenderableResults) {
+ return null;
}
renderStartTimeRef.current = Logger.getTimestamp();
- const currentFormData =
- chartIsStale && latestQueryFormData ? latestQueryFormData : formData;
- const vizType = currentFormData.viz_type || propVizType;
-
// It's bad practice to use unprefixed `vizType` as classnames for chart
// container. It may cause css conflicts as in the case of legacy table chart.
// When migrating charts, we should gradually add a `superset-chart-` prefix
@@ -533,12 +578,6 @@ function ChartRendererComponent({
Object.keys(ownState.agGridFilterModel).length > 0;
const currentFormDataExtended = currentFormData as JsonObject;
- // Some charts fetch their own data and issue no top-level query (e.g. deck.gl
- // Multiple Layers, which renders its sub-layer charts), so an empty response
- // is expected and shouldn't trigger the no-results state. Honor the chart's
- // own enableNoResults metadata (defaults to true).
- const chartEnableNoResults =
- getChartMetadataRegistry().get(vizType)?.enableNoResults ?? true;
const bypassNoResult =
chartEnableNoResults &&
!(
@@ -584,10 +623,7 @@ function ChartRendererComponent({
legendState={state.legendState}
enableNoResults={bypassNoResult}
legendIndex={state.legendIndex}
- isRefreshing={
- Boolean(restProps.suppressLoadingSpinner) &&
- chartStatus === 'loading'
- }
+ isRefreshing={isRefreshing}
{...drillToDetailProps}
/>
</div>