Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.
fix: preserve WMS panel and raster selection ownership (#3936)
Igor Dykhtaea52359f5377
diff --git a/src/components/src/map-container.spec.tsx b/src/components/src/map-container.spec.tsxnew file mode 100644index 000000000..0629dea2b--- /dev/null+++ b/src/components/src/map-container.spec.tsx@@ -0,0 +1,191 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import React, {createRef, StrictMode} from 'react';+import {act, render} from '@testing-library/react';+import MapContainerFactory from './map-container';+import {layerClickUpdater, wmsFeatureInfoUpdater} from '@kepler.gl/reducers';++jest.mock('styled-components', () => ({+ __esModule: true,+ ...jest.requireActual('styled-components'),+ withTheme: Component => Component+}));++jest.mock('@kepler.gl/utils', () => ({+ ...jest.requireActual('@kepler.gl/utils'),+ patchDeckRendererForPostProcessing: jest.fn()+}));++const Empty = () => null;+const MapContainer = MapContainerFactory(+ Empty as any,+ Empty as any,+ Empty as any,+ Empty as any+) as any;++// The response handler only needs selection state. Keep this test independent+// of a WebGL canvas and network-backed basemaps.+beforeEach(() => {+ jest.spyOn(MapContainer.prototype, '_renderMap').mockReturnValue(null);+});+afterEach(() => jest.restoreAllMocks());++function setup(strictMode = false) {+ const coordinate = [10, 20];+ const layer = {+ id: 'wms',+ config: {isVisible: true, visConfig: {allowHover: true}}+ };+ const props = {+ mapStyle: {styleType: 'dark'},+ visState: {+ layers: [layer],+ layerOrder: ['wms'],+ clicked: {picked: true, coordinate, layer: {props: {idx: 0, id: 'wms-WMSLayer'}}},+ splitMaps: [],+ interactionConfig: {tooltip: {enabled: true}, coordinate: {enabled: false}}+ },+ visStateActions: {wmsFeatureInfo: jest.fn()},+ index: 0+ };+ const ref = createRef<any>();+ const element = (visState = props.visState) => {+ const map = <MapContainer {...props} visState={visState} ref={ref} />;+ return strictMode ? <StrictMode>{map}</StrictMode> : map;+ };+ const view = render(element());+ const response = {featureInfo: [{name: 'VALUE', value: '20'}], coordinate};+ let currentState: any = props.visState;+ const rerender = (visState: any) => {+ currentState = visState;+ view.rerender(element(visState));+ };+ props.visStateActions.wmsFeatureInfo.mockImplementation((origin, featureInfo, coordinate) => {+ rerender(wmsFeatureInfoUpdater(currentState, {layer: origin, featureInfo, coordinate} as any));+ });+ return {props, layer, ref, view, response, rerender, getState: () => currentState};+}++test('publishes a response only for the current selection and originating layer', () => {+ const {props, layer, ref, response} = setup();+ ref.current._onWMSFeatureInfo(layer, response);+ expect(props.visStateActions.wmsFeatureInfo).toHaveBeenCalledWith(+ layer,+ response.featureInfo,+ response.coordinate+ );+});++test.each<[string, (state: any) => any]>([+ ['deselection', state => ({...state, clicked: null})],+ [+ 'a later click at the same coordinates',+ state => ({+ ...state,+ clicked: {...state.clicked, coordinate: [...state.clicked.coordinate]}+ })+ ],+ [+ 'layer removal with another layer in the same slot',+ state => ({+ ...state,+ layers: [{id: 'replacement', config: {isVisible: true}}]+ })+ ]+])('ignores a pending response after %s', (_name, update) => {+ const {props, layer, ref, response, rerender} = setup();+ rerender(update(props.visState));+ ref.current._onWMSFeatureInfo(layer, response);+ ref.current._onWMSFeatureInfo(layer, {...response, featureInfo: null});+ expect(props.visStateActions.wmsFeatureInfo).not.toHaveBeenCalled();+});++test.each([+ ['successful WMS/raster query', true, [{name: 'VALUE', value: 'new'}]],+ ['empty or failed WMS query', true, null],+ ['empty or failed raster query', false, null]+])('keeps the latest selection after a newer %s', async (_name, publish, featureInfo) => {+ const {props, layer, ref, response, rerender, getState} = setup();+ const handleResponse = ref.current._onWMSFeatureInfo;+ let finishOld!: () => void;+ const oldRequest = new Promise<void>(resolve => {+ finishOld = resolve;+ }).then(() => handleResponse(layer, response));++ // Repeated coordinates are a new click and must not reuse ownership of the old one.+ const coordinate = [...response.coordinate];+ rerender(+ layerClickUpdater(getState(), {+ info: {...props.visState.clicked, coordinate}+ } as any)+ );+ await act(async () => {+ if (publish) handleResponse(layer, {featureInfo, coordinate});+ });+ const latestSelection = getState().clicked;+ if (publish) {+ expect(latestSelection?.object.wmsFeatureInfo ?? null).toEqual(featureInfo);+ } else {+ expect(latestSelection.coordinate).toBe(coordinate);+ }++ await act(async () => {+ finishOld();+ await oldRequest;+ // An older failed WMS query must not clear the newer selection either.+ handleResponse(layer, {...response, featureInfo: null});+ });+ expect(getState().clicked).toBe(latestSelection);+ expect(props.visStateActions.wmsFeatureInfo).toHaveBeenCalledTimes(publish ? 1 : 0);+});++test('rejects a response without a click coordinate', () => {+ const {props, layer, ref, response, rerender} = setup();+ rerender({...props.visState, clicked: null});+ ref.current._onWMSFeatureInfo(layer, {...response, coordinate: undefined});+ expect(props.visStateActions.wmsFeatureInfo).not.toHaveBeenCalled();+});++test('ignores responses after the map panel unmounts', () => {+ const {props, layer, ref, response, view} = setup();+ const handleResponse = ref.current._onWMSFeatureInfo;+ view.unmount();+ handleResponse(layer, response);+ expect(props.visStateActions.wmsFeatureInfo).not.toHaveBeenCalled();+});++test('accepts the current response after StrictMode remounts the map', () => {+ const {props, layer, ref, response} = setup(true);+ ref.current._onWMSFeatureInfo(layer, response);+ expect(props.visStateActions.wmsFeatureInfo).toHaveBeenCalledWith(+ layer,+ response.featureInfo,+ response.coordinate+ );+});++test('keeps selection ownership through reducer updates and layer reordering', () => {+ const {props, layer, ref, response, rerender} = setup();+ const picked = layerClickUpdater(props.visState as any, {info: props.visState.clicked} as any);+ const resolved = wmsFeatureInfoUpdater(picked, {layer, ...response} as any);+ const reordered = {...resolved, layers: [{id: 'other'}, layer]};+ rerender(reordered);+ ref.current._onWMSFeatureInfo(layer, response);+ expect(props.visStateActions.wmsFeatureInfo).toHaveBeenCalledWith(+ layer,+ response.featureInfo,+ response.coordinate+ );+ props.visStateActions.wmsFeatureInfo.mockClear();+ const selectedAgain = layerClickUpdater(+ reordered as any,+ {+ info: {...props.visState.clicked, coordinate: [...response.coordinate]}+ } as any+ );+ rerender(selectedAgain);+ ref.current._onWMSFeatureInfo(layer, response);+ expect(props.visStateActions.wmsFeatureInfo).not.toHaveBeenCalled();+});diff --git a/src/components/src/map-container.tsx b/src/components/src/map-container.tsxindex 6c3bbcfb6..4062f4788 100644--- a/src/components/src/map-container.tsx+++ b/src/components/src/map-container.tsx@@ -300,6 +300,7 @@ export default function MapContainerFactory(displayName = 'MapContainer';private anyActiveLayerLoading = false;+ private unmounted = false;static contextType = MapViewStateContext;@@ -333,6 +334,7 @@ export default function MapContainerFactory(_rightPress: {x: number; y: number} | null = null;componentDidMount() {+ this.unmounted = false;if (!this._ref.current) {return;}@@ -340,6 +342,7 @@ export default function MapContainerFactory(}componentWillUnmount() {+ this.unmounted = true;if (this._map) {this._map.off(MAPBOXGL_STYLE_UPDATE, this._onMapboxStyleUpdate);this._map.off(MAPBOXGL_RENDER, this._onMapRender);@@ -688,17 +691,17 @@ export default function MapContainerFactory(};_onWMSFeatureInfo = (- idx: number,+ layer: Layer | undefined,data: {featureInfo: Array<{name: string; value: string}> | string | null;coordinate?: [number, number] | null;}) => {- this.props.visStateActions.wmsFeatureInfo(- this.props.visState.layers[idx],- data.featureInfo,- data.coordinate- );+ const {visState, visStateActions} = this.props;+ if (this.unmounted || !layer || !visState.layers.includes(layer)) return;+ // Each deck pick owns its coordinate array, including repeated clicks at the same location.+ if (!data.coordinate || data.coordinate !== visState.clicked?.coordinate) return;+ visStateActions.wmsFeatureInfo(layer, data.featureInfo, data.coordinate);};_handleMapToggleLayer = layerId => {@@ -1246,7 +1249,9 @@ export default function MapContainerFactory(onLayerHover: this._onLayerHover,onSetLayerDomain: this._onLayerSetDomain,onFilteredItemsChange: this._onLayerFilteredItemsChange,- onWMSFeatureInfo: this._onWMSFeatureInfo,+ // Capture the originating layer: an async result may arrive after+ // removal or reordering has put another layer at the same index.+ onWMSFeatureInfo: (idx, data) => this._onWMSFeatureInfo(visState.layers[idx], data),onRedrawNeeded: this._onRedrawNeeded,onFitBounds: this._onFitBounds,onTilesetLoadError: this._onTilesetLoadErrordiff --git a/src/deckgl-layers/src/wms/wms-layer.ts b/src/deckgl-layers/src/wms/wms-layer.tsindex cc48c39eb..b0a69f923 100644--- a/src/deckgl-layers/src/wms/wms-layer.ts+++ b/src/deckgl-layers/src/wms/wms-layer.ts@@ -26,6 +26,7 @@ export type WMSLayerProps = CompositeLayerProps & _WMSLayerProps;/** Props added by the TileLayer */type _WMSLayerProps = {+ idx?: number;data: string | ImageSource;serviceType?: string | 'auto';layers?: string[];diff --git a/src/layers/src/raster-tile/raster-tile-layer.ts b/src/layers/src/raster-tile/raster-tile-layer.tsindex bfb0de658..c43fbf396 100644--- a/src/layers/src/raster-tile/raster-tile-layer.ts+++ b/src/layers/src/raster-tile/raster-tile-layer.ts@@ -490,7 +490,8 @@ export default class RasterTileLayer extends KeplerLayer {if (rows && rows.length > 0 && layerCallbacks?.onWMSFeatureInfo) {layerCallbacks.onWMSFeatureInfo({featureInfo: rows,- coordinate: [coordinate[0], coordinate[1]]+ // Keep the picking coordinate identity to recognize the current selection.+ coordinate: coordinate as [number, number]});}}diff --git a/src/layers/src/wms-layer/wms-layer.ts b/src/layers/src/wms-layer/wms-layer.tsindex c27b74c95..7e4d35003 100644--- a/src/layers/src/wms-layer/wms-layer.ts+++ b/src/layers/src/wms-layer/wms-layer.ts@@ -2,6 +2,7 @@// Copyright contributors to the kepler.gl projectimport {notNullorUndefined} from '@kepler.gl/common-utils';+import type {BitmapLayerPickingInfo} from '@deck.gl/layers';import {DatasetType, WMSDatasetMetadata, LAYER_TYPES} from '@kepler.gl/constants';import {WMSLayer as DeckWMSLayer} from '@kepler.gl/deckgl-layers';import {KeplerTable as KeplerDataset, buildWmsGetLegendGraphicUrl} from '@kepler.gl/table';@@ -79,9 +80,6 @@ export default class WMSLayer extends AbstractTileLayer<WMSTile, any[]> {declare config: WMSLayerConfig;declare visConfigSettings: WMSLayerVisConfigSettings;- // Store reference to the deck layer for feature info access- private deckLayerRef: DeckWMSLayer | null = null;-// Constructorconstructor(props: ConstructorParameters<typeof AbstractTileLayer>[0] & {@@ -341,23 +339,34 @@ export default class WMSLayer extends AbstractTileLayer<WMSTile, any[]> {visible: defaultLayerProps.visible,pickable,// @ts-ignore- onClick: pickable ? this._onClick.bind(this, layerCallbacks) : null+ onClick: pickable+ ? info => {+ // Let deck propagate the click so the pending selection is recorded.+ void this._onClick(layerCallbacks, info);+ }+ : null});- // Store reference to the deck layer for feature info access- this.deckLayerRef = deckLayer;-return [deckLayer];}- protected async _onClick(layerCallbacks, {bitmap, coordinate}) {+ protected async _onClick(+ layerCallbacks,+ {+ bitmap,+ coordinate,+ layer+ }: Omit<BitmapLayerPickingInfo, 'bitmap'> & {+ bitmap?: BitmapLayerPickingInfo['bitmap'];+ }+ ) {if (!bitmap) return null;const x = bitmap.pixel[0];const y = bitmap.pixel[1];- const featureInfo = await this.getWMSFeatureInfo(x, y);+ // PickingInfo carries the actual composite layer for the clicked panel.+ const featureInfo = await this.getWMSFeatureInfo(x, y, layer as DeckWMSLayer | null);- // Call the callback to update state with coordinateif (layerCallbacks?.onWMSFeatureInfo) {layerCallbacks.onWMSFeatureInfo({featureInfo, coordinate});}@@ -368,11 +377,12 @@ export default class WMSLayer extends AbstractTileLayer<WMSTile, any[]> {// Method to retrieve WMS feature info asynchronouslyprotected async getWMSFeatureInfo(x: number,- y: number+ y: number,+ deckLayer?: DeckWMSLayer | null): Promise<Array<{name: string; value: string}> | null> {try {- if (this.deckLayerRef && typeof this.deckLayerRef.getFeatureInfoText === 'function') {- const featureInfoXml = await this.deckLayerRef.getFeatureInfoText(x, y);+ if (deckLayer && typeof deckLayer.getFeatureInfoText === 'function') {+ const featureInfoXml = await deckLayer.getFeatureInfoText(x, y);if (featureInfoXml) {// Parse the XML response to extract attributesconst parsedAttributes = this.parseWMSFeatureInfo(featureInfoXml);diff --git a/test/browser/layer-tests/raster-tile-layer-specs.js b/test/browser/layer-tests/raster-tile-layer-specs.jsindex 2b921b9ea..3049ce881 100644--- a/test/browser/layer-tests/raster-tile-layer-specs.js+++ b/test/browser/layer-tests/raster-tile-layer-specs.js@@ -1258,6 +1258,18 @@ test('#RasterTileLayer -> replacing a PMTiles URL reloads cached tile content',t.end();});+test('#RasterTileLayer -> identify preserves the picking coordinate for selection ownership', async t => {+ const layer = new RasterTileLayer({id: 'identify-coordinate', dataId: 'raster'});+ const rows = [{name: 'BAND', value: '20'}];+ layer._fetchTitilerPoint = async () => rows;+ const results = [];+ const coordinate = [1, 2];+ await layer._onClickIdentify({onWMSFeatureInfo: result => results.push(result)}, {coordinate});+ t.equal(results[0].coordinate, coordinate, 'keeps the exact picking coordinate identity');+ t.deepEqual(results[0].featureInfo, rows, 'publishes the sampled values');+ t.end();+});+test('#RasterTileLayer -> SAVI uses the soil adjustment multiplier in CPU and shader arithmetic', t => {// Evaluate this scalar GLSL function as JavaScript to check the shipped expression.// This is an arithmetic parity test, not a WebGL rendering test.diff --git a/test/browser/layer-tests/wms-layer-specs.js b/test/browser/layer-tests/wms-layer-specs.jsindex a6edfaa25..34835be8f 100644--- a/test/browser/layer-tests/wms-layer-specs.js+++ b/test/browser/layer-tests/wms-layer-specs.js@@ -482,23 +482,64 @@ test('#WMSLayer -> edge cases and error handling', t => {const hoveredObject = invisibleLayer.hasHoveredObject(mockObjectInfo);t.ok(hoveredObject, 'should return hovered object even when layer is not visible');- // Test getWMSFeatureInfo with no deckLayerRef+ // Test getWMSFeatureInfo with no picked deck layerlayer['getWMSFeatureInfo'](100, 200).then(result => {- t.equal(result, null, 'should return null when no deckLayerRef');+ t.equal(result, null, 'should return null when no picked deck layer');}).catch(_error => {- t.fail('should not throw error when no deckLayerRef');+ t.fail('should not throw error when no picked deck layer');});- // Test deckLayerRef storage- layer.renderLayer(MOCK_RENDER_OPTS);- t.ok(layer['deckLayerRef'], 'should store deckLayerRef after first render');-- const firstRef = layer['deckLayerRef'];- layer.renderLayer(MOCK_RENDER_OPTS);- t.ok(layer['deckLayerRef'], 'should have deckLayerRef after second render');- t.notEqual(layer['deckLayerRef'], firstRef, 'should update deckLayerRef on new render');+ t.end();+});+test('#WMSLayer -> split-map clicks query the picked panel image', async t => {+ const layer = createWMSLayer({visConfig: {allowHover: true}});+ const calls = [];+ const results = [];+ const opts = {+ ...MOCK_RENDER_OPTS,+ visible: true,+ layerCallbacks: {onWMSFeatureInfo: result => results.push(result)}+ };+ const [left] = layer.renderLayer(opts);+ const [right] = layer.renderLayer({...opts, mapState: {longitude: 60, zoom: 5}});+ const configurePanel = (deckLayer, bbox, width, response) => {+ deckLayer.state = {+ lastRequestParameters: {bbox, width, height: 100, layers: ['test_layer']},+ imageSource: {+ getFeatureInfoText: async params => {+ calls.push(params);+ return response;+ }+ }+ };+ };+ configurePanel(left, [-10, -5, 10, 5], 200, 'left');+ configurePanel(right, [55, 20, 65, 30], 400, 'right');+ layer.parseWMSFeatureInfo = value => [{name: 'PANEL', value}];+ const coordinate = [0, 0];+ const clickResult = left.props.onClick({+ layer: left,+ bitmap: {pixel: [17, 23]},+ coordinate+ });+ t.equal(clickResult, undefined, 'click propagates to the normal selection handler');+ await new Promise(resolve => setTimeout(resolve, 0));+ t.deepEqual(calls[0].bbox, [-10, -5, 10, 5], 'uses the left image bounds');+ t.equal(calls[0].width, 200, 'uses the left image resolution');+ t.deepEqual([calls[0].x, calls[0].y], [17, 23], 'uses pixels picked from that image');+ t.deepEqual(results[0].featureInfo, [{name: 'PANEL', value: 'left'}]);+ t.equal(results[0].coordinate, coordinate, 'preserves the selection coordinate identity');++ const [hiddenRight] = layer.renderLayer({...opts, visible: false});+ configurePanel(hiddenRight, [100, 20, 110, 30], 600, 'hidden');+ await layer._onClick(opts.layerCallbacks, {+ layer: left,+ bitmap: {pixel: [4, 5]},+ coordinate: [1, 1]+ });+ t.deepEqual(calls[1].bbox, [-10, -5, 10, 5], 'a hidden panel render cannot replace the source');t.end();});