Skip to content

Interactive interface for browsing global, full-resolution satellite imagery

WV-3739: Fix CMR calls blocking UI layer rendering, implemented async… (#6560)

vicgonzalez25b1acfd578b3a
diff --git a/web/js/containers/map-interactions/ol-vector-interactions.js b/web/js/containers/map-interactions/ol-vector-interactions.js
index 95e310f34..0a4c76adc 100644
--- a/web/js/containers/map-interactions/ol-vector-interactions.js
+++ b/web/js/containers/map-interactions/ol-vector-interactions.js
@@ -57,6 +57,14 @@ export class VectorInteractions extends React.Component {
events.on(MAP_SINGLE_CLICK, this.singleClick);
}
+ componentDidUpdate(prevProps) {
+ const { granuleFootprints } = this.props;
+ const { granuleDate } = this.state;
+ if (granuleDate && prevProps.granuleFootprints !== granuleFootprints) {
+ this.clearGranuleFootprint();
+ }
+ }
+
componentWillUnmount() {
events.off(MAP_MOVE_END, this.moveEnd);
events.off(MAP_MOUSE_MOVE, this.mouseMove);
diff --git a/web/js/containers/map-interactions/ol-vector-interactions.test.js b/web/js/containers/map-interactions/ol-vector-interactions.test.js
index becc55c55..bcab2c0ee 100644
--- a/web/js/containers/map-interactions/ol-vector-interactions.test.js
+++ b/web/js/containers/map-interactions/ol-vector-interactions.test.js
@@ -3,7 +3,7 @@ import renderer from 'react-test-renderer';
import util from '../../util/util';
import { VectorInteractions } from './ol-vector-interactions';
import { registerProjections } from '../../fixtures';
-import { MAP_MOUSE_MOVE, MAP_SINGLE_CLICK } from '../../util/constants';
+import { MAP_MOUSE_MOVE, MAP_SINGLE_CLICK, GRANULE_HOVERED } from '../../util/constants';
let consoleErrorSpy;
let originalConsoleError;
@@ -97,3 +97,197 @@ test('Check that hover changes', () => {
test('Check that cursor-hover class is not present', () => {
expect(component.toJSON()).toMatchSnapshot();
});
+
+describe('componentDidUpdate - clear orphaned granule footprint', () => {
+ let granuleComponent;
+ let granuleHoveredSpy;
+
+ beforeEach(() => {
+ granuleHoveredSpy = jest.fn();
+ events.on(GRANULE_HOVERED, granuleHoveredSpy);
+ });
+
+ afterEach(() => {
+ events.off(GRANULE_HOVERED, granuleHoveredSpy);
+ if (granuleComponent) {
+ act(() => {
+ granuleComponent.unmount();
+ });
+ }
+ });
+
+ test('clears granule footprint when granuleFootprints prop changes and granuleDate is set', () => {
+ const initialFootprints = { '2024-01-15': [[[0, 0], [1, 0], [1, 1], [0, 1]]] };
+ const updatedFootprints = { '2024-01-16': [[[2, 2], [3, 2], [3, 3], [2, 3]]] };
+
+ act(() => {
+ granuleComponent = renderer.create(
+ <VectorInteractions
+ mouseEvents={events}
+ isShowingClick={false}
+ changeCursor={changeCursor}
+ getDialogObject={getDialogObject}
+ openVectorDialog={openVectorDialog}
+ selectVectorFeatures={selectVectorFeatures}
+ lastSelected={{}}
+ measureIsActive={false}
+ onCloseModal={jest.fn()}
+ modalState={{ id: [], isOpen: false }}
+ isDistractionFreeModeActive={false}
+ isMobile={false}
+ proj={{ id: 'geographic' }}
+ activeLayers={[]}
+ granuleFootprints={initialFootprints}
+ />,
+ );
+ });
+
+ // Simulate having a hovered granule by setting internal state
+ const instance = granuleComponent.getInstance();
+ act(() => {
+ instance.setState({ granuleDate: '2024-01-15', granulePlatform: 'MODIS' });
+ });
+
+ // Update granuleFootprints prop to simulate date change
+ act(() => {
+ granuleComponent.update(
+ <VectorInteractions
+ mouseEvents={events}
+ isShowingClick={false}
+ changeCursor={changeCursor}
+ getDialogObject={getDialogObject}
+ openVectorDialog={openVectorDialog}
+ selectVectorFeatures={selectVectorFeatures}
+ lastSelected={{}}
+ measureIsActive={false}
+ onCloseModal={jest.fn()}
+ modalState={{ id: [], isOpen: false }}
+ isDistractionFreeModeActive={false}
+ isMobile={false}
+ proj={{ id: 'geographic' }}
+ activeLayers={[]}
+ granuleFootprints={updatedFootprints}
+ />,
+ );
+ });
+
+ // Verify state was cleared
+ expect(instance.state.granuleDate).toBeNull();
+ expect(instance.state.granulePlatform).toBeNull();
+ // Verify GRANULE_HOVERED event was triggered with null
+ expect(granuleHoveredSpy).toHaveBeenCalledWith(null);
+ });
+
+ test('does NOT clear granule footprint when granuleDate is null', () => {
+ const initialFootprints = { '2024-01-15': [[[0, 0], [1, 0], [1, 1], [0, 1]]] };
+ const updatedFootprints = { '2024-01-16': [[[2, 2], [3, 2], [3, 3], [2, 3]]] };
+
+ act(() => {
+ granuleComponent = renderer.create(
+ <VectorInteractions
+ mouseEvents={events}
+ isShowingClick={false}
+ changeCursor={changeCursor}
+ getDialogObject={getDialogObject}
+ openVectorDialog={openVectorDialog}
+ selectVectorFeatures={selectVectorFeatures}
+ lastSelected={{}}
+ measureIsActive={false}
+ onCloseModal={jest.fn()}
+ modalState={{ id: [], isOpen: false }}
+ isDistractionFreeModeActive={false}
+ isMobile={false}
+ proj={{ id: 'geographic' }}
+ activeLayers={[]}
+ granuleFootprints={initialFootprints}
+ />,
+ );
+ });
+
+ // granuleDate is null (no hover) — should NOT trigger clear
+ const instance = granuleComponent.getInstance();
+
+ act(() => {
+ granuleComponent.update(
+ <VectorInteractions
+ mouseEvents={events}
+ isShowingClick={false}
+ changeCursor={changeCursor}
+ getDialogObject={getDialogObject}
+ openVectorDialog={openVectorDialog}
+ selectVectorFeatures={selectVectorFeatures}
+ lastSelected={{}}
+ measureIsActive={false}
+ onCloseModal={jest.fn()}
+ modalState={{ id: [], isOpen: false }}
+ isDistractionFreeModeActive={false}
+ isMobile={false}
+ proj={{ id: 'geographic' }}
+ activeLayers={[]}
+ granuleFootprints={updatedFootprints}
+ />,
+ );
+ });
+
+ expect(granuleHoveredSpy).not.toHaveBeenCalled();
+ expect(instance.state.granuleDate).toBeNull();
+ });
+
+ test('does NOT clear granule footprint when granuleFootprints prop is the same reference', () => {
+ const sameFootprints = { '2024-01-15': [[[0, 0], [1, 0], [1, 1], [0, 1]]] };
+
+ act(() => {
+ granuleComponent = renderer.create(
+ <VectorInteractions
+ mouseEvents={events}
+ isShowingClick={false}
+ changeCursor={changeCursor}
+ getDialogObject={getDialogObject}
+ openVectorDialog={openVectorDialog}
+ selectVectorFeatures={selectVectorFeatures}
+ lastSelected={{}}
+ measureIsActive={false}
+ onCloseModal={jest.fn()}
+ modalState={{ id: [], isOpen: false }}
+ isDistractionFreeModeActive={false}
+ isMobile={false}
+ proj={{ id: 'geographic' }}
+ activeLayers={[]}
+ granuleFootprints={sameFootprints}
+ />,
+ );
+ });
+
+ const instance = granuleComponent.getInstance();
+ act(() => {
+ instance.setState({ granuleDate: '2024-01-15', granulePlatform: 'MODIS' });
+ });
+
+ // Re-render with the SAME object reference
+ act(() => {
+ granuleComponent.update(
+ <VectorInteractions
+ mouseEvents={events}
+ isShowingClick={false}
+ changeCursor={changeCursor}
+ getDialogObject={getDialogObject}
+ openVectorDialog={openVectorDialog}
+ selectVectorFeatures={selectVectorFeatures}
+ lastSelected={{}}
+ measureIsActive={false}
+ onCloseModal={jest.fn()}
+ modalState={{ id: [], isOpen: false }}
+ isDistractionFreeModeActive={false}
+ isMobile={false}
+ proj={{ id: 'geographic' }}
+ activeLayers={[]}
+ granuleFootprints={sameFootprints}
+ />,
+ );
+ });
+
+ // Should NOT clear because same reference
+ expect(granuleHoveredSpy).not.toHaveBeenCalled();
+ expect(instance.state.granuleDate).toBe('2024-01-15');
+ });
+});
diff --git a/web/js/map/granule/granule-layer-builder.js b/web/js/map/granule/granule-layer-builder.js
index 394de4c8f..87f25e99d 100644
--- a/web/js/map/granule/granule-layer-builder.js
+++ b/web/js/map/granule/granule-layer-builder.js
@@ -2,8 +2,11 @@ import OlLayerGroup from 'ol/layer/Group';
import { throttle as lodashThrottle } from 'lodash';
import OlCollection from 'ol/Collection';
import { DEFAULT_NUM_GRANULES } from '../../modules/layers/constants';
-import { updateGranuleLayerState } from '../../modules/layers/actions';
+import {
+ updateGranuleLayerState,
+} from '../../modules/layers/actions';
import { getGranuleLayer } from '../../modules/layers/selectors';
+import { fetchGranuleDateRanges } from '../../modules/layers/granule-date-ranges-service';
import {
startLoading,
stopLoading,
@@ -79,11 +82,14 @@ export default function granuleLayerBuilder(cache, store, createLayerWMTS) {
return cmrFetch(requestUrl, CMR_FETCH_OPTIONS);
});
const responses = await Promise.allSettled(promises);
- const fulfilledResponses = responses.filter(({ status }) => status === 'fulfilled').map(({ value }) => value);
- const [response, nrtResponse] = fulfilledResponses;
+ // Use positional access so standard vs NRT responses stay in the
+ // correct slots even when one of the two requests rejects.
+ const response = responses[0]?.status === 'fulfilled' ? responses[0].value : null;
+ const nrtResponse = responses[1]?.status === 'fulfilled' ? responses[1].value : null;
const jsonRequests = [response?.json(), nrtResponse?.json()];
const jsonResponses = await Promise.allSettled(jsonRequests);
- const [responseJson, nrtResponseJson] = jsonResponses.filter(({ status }) => status === 'fulfilled').map(({ value }) => value);
+ const responseJson = jsonResponses[0]?.status === 'fulfilled' ? jsonResponses[0].value : null;
+ const nrtResponseJson = jsonResponses[1]?.status === 'fulfilled' ? jsonResponses[1].value : null;
data = responseJson?.feed?.entry || [];
nrtData = nrtResponseJson?.feed?.entry || [];
} catch (e) {
@@ -95,7 +101,6 @@ export default function granuleLayerBuilder(cache, store, createLayerWMTS) {
const transformedData = [...data, ...nrtData].map((entry) => {
const date = toISOStringSeconds(entry.time_start);
-
return transformGranuleData(entry, date, crs);
});
const dedupedData = transformedData.reduce((acc, granule) => {
@@ -135,9 +140,8 @@ export default function granuleLayerBuilder(cache, store, createLayerWMTS) {
};
tileLayer = createLayerWMTS(def, options, null, store.getState());
- attributes.key = granuleISOKey;
- attributes.date = granuleISODate;
- tileLayer.wv = attributes;
+ // Each tile needs its own wv object with the correct key/date.
+ tileLayer.wv = { ...attributes, key: granuleISOKey, date: granuleISODate };
cache.setItem(granuleISOKey, tileLayer, getCacheOptions(period, granuleISODate));
tileLayer.setVisible(false);
return tileLayer;
@@ -166,23 +170,16 @@ export default function granuleLayerBuilder(cache, store, createLayerWMTS) {
const MAX_TIME = 8.64e15;
const gaps = ranges.reduce((acc, [start, end]) => {
- acc.at(-1)[1] = new Date(start);
+ const prev = acc.at(-1);
+ const updated = [prev[0], new Date(start)];
- return [...acc, [new Date(end), new Date(MAX_TIME)]];
+ return [...acc.slice(0, -1), updated, [new Date(end), new Date(MAX_TIME)]];
}, [[new Date(-MAX_TIME), new Date(MAX_TIME)]]);
return gaps;
};
- /**
- * Get granuleCount number of granules that have visible imagery based on
- * predetermined longitude bounds.
- *
- * @param {Array} availableGranules - available granules to be filtered
- * @param {number} granuleCount - number of granules to filter down to
- * @param {Date} leadingEdgeDate - timeline date
- * @returns {array}
- */
+ // Get visible granules at the selected date, filtered by granuleDateRanges.
const getVisibleGranules = (
availableGranules,
granuleCount,
@@ -195,39 +192,33 @@ export default function granuleLayerBuilder(cache, store, createLayerWMTS) {
const availableCount = availableGranules?.length;
if (!availableCount) return { visibleGranules, invisibleGranules };
const count = granuleCount > availableCount ? availableCount : granuleCount;
- const sortedAvailableGranules = availableGranules
+ const sortedAvailableGranules = [...availableGranules]
.sort((a, b) => new Date(b.date) - new Date(a.date));
- let totalLength = visibleGranules.length + invisibleGranules.length;
+ // Timeline picker can't select seconds, so round up to :59.
+ // Clone to avoid mutating the caller's Date object (e.g. the Redux selected date).
+ const edgeDate = new Date(leadingEdgeDate.getTime());
+ edgeDate.setSeconds(59);
+ const isWithinRange = isWithinRanges(edgeDate, granuleDateRanges);
+ const gaps = identifyGaps(granuleDateRanges);
+ const currentlySelectedGap = !isWithinRange
+ ? gaps.find(([start, end]) => edgeDate >= start && edgeDate <= end)
+ : null;
+ let totalLength = 0;
for (let i = 0; totalLength < count; i += 1) {
const item = sortedAvailableGranules[i];
if (!item) break;
- const { date } = item;
- const dateDate = new Date(date);
- // force currently selected time to be 59 seconds.
- // This is to compensate for the inability to select seconds in the timeline
- leadingEdgeDate.setSeconds(59);
- // check if currently selected time is within a date range
- const isWithinRange = isWithinRanges(leadingEdgeDate, granuleDateRanges);
- // check if the current granule is within a date range, defaults to true
+ const dateDate = new Date(item.date);
const granuleIsWithinRange = isWithinRanges(dateDate, granuleDateRanges) ?? true;
- const gaps = identifyGaps(granuleDateRanges); // identify gaps between date ranges
- // get the gap that the currently selected time is within
- const currentlySelectedGap = !isWithinRange
- ? gaps.find(([start, end]) => leadingEdgeDate >= start && leadingEdgeDate <= end)
- : null;
- // check if the current granule is within the currently selected gap
const granuleIsWithinSelectedGap = currentlySelectedGap
? dateDate >= currentlySelectedGap[0] && dateDate <= currentlySelectedGap[1]
: true;
-
- if (dateDate <= leadingEdgeDate && isWithinRange &&
- granuleIsWithinRange && isWithinBounds(crs, item)) {
+ const beforeOrEqual = dateDate <= edgeDate;
+ const inBounds = isWithinBounds(crs, item);
+ if (beforeOrEqual && isWithinRange && granuleIsWithinRange && inBounds) {
visibleGranules.unshift(item);
- } else if (dateDate <= leadingEdgeDate && !granuleIsWithinRange &&
- isWithinBounds(crs, item) && granuleIsWithinSelectedGap) {
+ } else if (beforeOrEqual && !granuleIsWithinRange && inBounds && granuleIsWithinSelectedGap) {
invisibleGranules.unshift(item);
}
-
totalLength = visibleGranules.length + invisibleGranules.length;
}
@@ -237,22 +228,26 @@ export default function granuleLayerBuilder(cache, store, createLayerWMTS) {
return { visibleGranules, invisibleGranules };
};
- /**
- * @method getGranuleAttributes
- * @param {object} def
- * @param {object} options
- * @returns {object} granuleAttributes
- */
const getGranuleAttributes = async (def, options) => {
const state = store.getState();
const { proj: { selected: { crs } } } = state;
- const { granuleCount, date, group } = options;
+ const { granuleCount, date } = options;
const { count: currentCount } = getGranuleLayer(state, def.id) || {};
const count = currentCount || granuleCount || def.count || DEFAULT_NUM_GRANULES;
- const { granuleDateRanges } = def;
- // get granule dates waiting for CMR query and filtering (if necessary)
- const availableGranules = await getQueriedGranuleDates(def, date, group);
+ // Use cached ranges if they cover the selected date; re-fetch otherwise.
+ let granuleDateRanges = def.granuleDateRanges;
+ const rangesCoverDate = granuleDateRanges?.length &&
+ isWithinRanges(date, granuleDateRanges);
+ if (!rangesCoverDate) {
+ const describeDomainsUrl = state.config?.features?.describeDomains?.url ||
+ 'https://gibs.earthdata.nasa.gov';
+ granuleDateRanges = await fetchGranuleDateRanges(def, {
+ crs, describeDomainsUrl, selectedDate: date,
+ });
+ }
+
+ const availableGranules = await getQueriedGranuleDates(def, date);
const {
visibleGranules,
invisibleGranules,
@@ -316,6 +311,10 @@ export default function granuleLayerBuilder(cache, store, createLayerWMTS) {
...granuleAttributes,
visibleGranules: shiftedVisibleGranules,
invisibleGranules: shiftedInvisibleGranules,
+ // Flags empty layers for rebuild; capped to prevent infinite retries.
+ pendingCmrRebuild: shiftedVisibleGranules.length === 0,
+ cmrRebuildAttempts: (attributes.cmrRebuildAttempts || 0) +
+ (shiftedVisibleGranules.length === 0 ? 1 : 0),
};
// Don't update during animation due to the performance hit
diff --git a/web/js/map/layerbuilder.js b/web/js/map/layerbuilder.js
index ebaf3c864..d460a84a5 100644
--- a/web/js/map/layerbuilder.js
+++ b/web/js/map/layerbuilder.js
@@ -113,7 +113,7 @@ export default function mapLayerBuilder(config, cache, store) {
const worker = new Worker('js/workers/describe-domains.worker.js');
worker.onmessage = (event) => {
if (Array.isArray(event.data)) { // our final format is an array
- worker.terminate(); // terminate the worker
+ worker.terminate();
const newRanges = event.data.map(([startDate, endDate, dateInterval]) => ({
startDate, endDate, dateInterval,
}));
@@ -130,7 +130,10 @@ export default function mapLayerBuilder(config, cache, store) {
}
return worker.postMessage({ operation: 'mergeDomains', args: [domains, 60_000, true] });
};
- worker.onerror = () => worker.terminate();
+ worker.onerror = () => {
+ worker.terminate();
+ callback(def, oldRanges, group);
+ };
let startDate = new Date(def.startDate);
const endDate = def.endDate ? new Date(def.endDate).toISOString() : new Date().toISOString();
// If there are any existing dateRanges, find any after the latest one
@@ -454,6 +457,7 @@ export default function mapLayerBuilder(config, cache, store) {
// force currently selected time to be 59 seconds.
// This is to compensate for the inability to select seconds in the timeline
+ layerDate = new Date(layerDate.getTime());
layerDate.setSeconds(59);
const urlParameters = `?TIME=${util.toISOStringSeconds(layerDate, !isSubdaily)}`;
const sourceURL = def.sourceOverride || configSource.url;
@@ -1356,6 +1360,8 @@ export default function mapLayerBuilder(config, cache, store) {
group: options.group,
nextDate,
previousDate,
+ ...(options.cmrRebuildAttempts != null &&
+ { cmrRebuildAttempts: options.cmrRebuildAttempts }),
};
def = lodashCloneDeep(def);
lodashMerge(def, projections[proj.id]);
diff --git a/web/js/mapUI/combineUI.js b/web/js/mapUI/combineUI.js
index e0f7267d2..37666f67c 100644
--- a/web/js/mapUI/combineUI.js
+++ b/web/js/mapUI/combineUI.js
@@ -52,6 +52,7 @@ function CombineUI(props) {
const cache = new Cache(400);
const layerQueue = new PQueue({ concurrency: 3 });
+ const layerCreationQueue = new PQueue({ concurrency: 6 });
const compareMapUi = mapCompare(store);
const runningdata = new MapRunningData(compareMapUi, store);
const { createLayer, layerKey } = mapLayerBuilder(config, cache, store);
@@ -123,6 +124,7 @@ function CombineUI(props) {
ui={ui}
setUI={setUI}
layerQueue={layerQueue}
+ layerCreationQueue={layerCreationQueue}
/>
);
}
diff --git a/web/js/mapUI/components/layers/addLayer.js b/web/js/mapUI/components/layers/addLayer.js
index 1222738f9..a2f202b85 100644
--- a/web/js/mapUI/components/layers/addLayer.js
+++ b/web/js/mapUI/components/layers/addLayer.js
@@ -2,24 +2,24 @@ import React, { useEffect } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import {
- cloneDeep as lodashCloneDeep,
findIndex as lodashFindIndex,
find as lodashFind,
} from 'lodash';
-import { getActiveLayers } from '../../../modules/layers/selectors';
+import { getLayers } from '../../../modules/layers/selectors';
import * as layerConstants from '../../../modules/layers/constants';
-import { clearPreload } from '../../../modules/date/actions';
+import { clearPreload as clearPreloadAction } from '../../../modules/date/actions';
import { DISPLAY_STATIC_MAP } from '../../../modules/ui/constants';
function AddLayer(props) {
const {
action,
- activeLayersState,
activeString,
+ clearPreload: dispatchClearPreload,
compareDate,
compareMapUi,
mode,
preloadNextTiles,
+ projFilteredLayers,
updateLayerVisibilities,
ui,
} = props;
@@ -30,42 +30,80 @@ function AddLayer(props) {
* @returns {void}
*/
const addLayer = async function(def, layerDate, activeLayersParam) {
- const { createLayer } = ui;
- const date = layerDate || compareDate;
- const activeLayers = activeLayersParam || activeLayersState;
- const reverseLayers = lodashCloneDeep(activeLayers).reverse();
- const index = lodashFindIndex(reverseLayers, { id: def.id });
- const mapLayers = ui.selected.getLayers().getArray();
- const firstLayer = mapLayers[0];
-
- if (firstLayer && firstLayer.get('group') && firstLayer.get('granule') !== true) {
- const activelayer = firstLayer.get('group') === activeString
- ? firstLayer
- : mapLayers[1];
- const options = {
- date,
- group: activeString,
- };
- const newLayer = await createLayer(def, options);
- activelayer.getLayers().insertAt(index, newLayer);
- compareMapUi.create(ui.selected, mode);
- } else {
- const newLayer = await createLayer(def);
- const layers = ui.selected.getLayers();
- if (index <= layers.getLength()) {
- layers.insertAt(index, newLayer);
+ // Immediately update visibility for already-loaded layers before async layer creation
+ updateLayerVisibilities();
+
+ try {
+ const { createLayer } = ui;
+ const date = layerDate || compareDate;
+ const reverseLayers = projFilteredLayers;
+ const index = lodashFindIndex(reverseLayers, { id: def.id });
+ if (index === -1) return;
+ const mapLayers = ui.selected.getLayers().getArray();
+ const firstLayer = mapLayers[0];
+
+ if (firstLayer && firstLayer.get('group') && firstLayer.get('granule') !== true) {
+ const activelayer = firstLayer.get('group') === activeString
+ ? firstLayer
+ : mapLayers[1];
+ const options = {
+ date,
+ group: activeString,
+ };
+ const newLayer = await createLayer(def, options);
+
+ // Check for and remove any existing layer with the same ID to avoid duplicates
+ const groupLayers = activelayer.getLayers();
+ const existingIndex = groupLayers.getArray().findIndex(
+ (l) => l.wv?.id === def.id,
+ );
+ let adjustedIndex = index;
+ if (existingIndex >= 0) {
+ groupLayers.removeAt(existingIndex);
+ if (existingIndex < index) adjustedIndex -= 1;
+ }
+
+ if (adjustedIndex <= groupLayers.getLength()) {
+ groupLayers.insertAt(adjustedIndex, newLayer);
+ } else {
+ groupLayers.push(newLayer);
+ }
+ compareMapUi.create(ui.selected, mode);
} else {
- layers.push(newLayer);
+ const newLayer = await createLayer(def);
+ const layers = ui.selected.getLayers();
+
+ // Check for and remove any existing layer with the same ID to avoid duplicates
+ const existingIndex = layers.getArray().findIndex(
+ (l) => l.wv?.id === def.id,
+ );
+ let adjustedIndex = index;
+ if (existingIndex >= 0) {
+ layers.removeAt(existingIndex);
+ if (existingIndex < index) adjustedIndex -= 1;
+ }
+
+ if (adjustedIndex <= layers.getLength()) {
+ layers.insertAt(adjustedIndex, newLayer);
+ } else {
+ layers.push(newLayer);
+ }
}
+ updateLayerVisibilities();
+ preloadNextTiles();
+ } catch (error) {
+ console.warn(`addLayer failed for ${def?.id}:`, error);
}
- updateLayerVisibilities();
- preloadNextTiles();
};
const granuleLayerAdd = (def) => {
- ui.processingPromise = new Promise((resolve) => {
- resolve(addLayer(def));
- });
+ // Chain onto any in-flight processingPromise so concurrent operations
+ // (e.g. reloadLayers building compare groups) are not clobbered.
+ const previous = ui.processingPromise || Promise.resolve();
+ const layerPromise = previous
+ .catch(() => {})
+ .then(() => addLayer(def));
+ ui.processingPromise = layerPromise;
};
// add static layer for kiosk mode in case of gibs/dns failure
@@ -82,7 +120,7 @@ function AddLayer(props) {
if (def.type === 'granule') {
return granuleLayerAdd(def);
}
- clearPreload();
+ dispatchClearPreload();
addLayer(def);
} else if (action.type === DISPLAY_STATIC_MAP) {
addStaticLayer();
@@ -94,13 +132,14 @@ function AddLayer(props) {
}
const mapStateToProps = (state) => {
- const { compare, date } = state;
+ const { compare, date, layers, proj } = state;
const { activeString, mode } = compare;
const { selected, selectedB } = date;
- const activeLayersState = getActiveLayers(state);
+ const layerState = { layers, compare, proj };
+ const projFilteredLayers = getLayers(layerState, { reverse: true });
const compareDate = compare.active && activeString === 'activeB' ? selectedB : selected;
return {
- activeLayersState,
+ projFilteredLayers,
compareDate,
activeString,
mode,
@@ -109,7 +148,7 @@ const mapStateToProps = (state) => {
const mapDispatchToProps = (dispatch) => ({
clearPreload: () => {
- dispatch(clearPreload());
+ dispatch(clearPreloadAction());
},
});
@@ -121,14 +160,15 @@ export default React.memo(
);
AddLayer.propTypes = {
- activeLayersState: PropTypes.oneOfType([PropTypes.array, PropTypes.oneOf(['null'])]),
activeString: PropTypes.string,
- action: PropTypes.oneOfType([PropTypes.object, PropTypes.oneOf(['null'])]),
+ action: PropTypes.object,
+ clearPreload: PropTypes.func,
compareDate: PropTypes.instanceOf(Date),
- compareMapUi: PropTypes.oneOfType([PropTypes.object, PropTypes.oneOf(['null'])]),
+ compareMapUi: PropTypes.object,
mode: PropTypes.string,
preloadNextTiles: PropTypes.func,
- selected: PropTypes.oneOfType([PropTypes.object, PropTypes.oneOf(['null'])]),
+ projFilteredLayers: PropTypes.array,
+ selected: PropTypes.object,
updateLayerVisibilities: PropTypes.func,
- ui: PropTypes.oneOfType([PropTypes.object, PropTypes.oneOf(['null'])]),
+ ui: PropTypes.object,
};
diff --git a/web/js/mapUI/components/update-date/updateDate.js b/web/js/mapUI/components/update-date/updateDate.js
index 813775f2f..4a9e6f3bf 100644
--- a/web/js/mapUI/components/update-date/updateDate.js
+++ b/web/js/mapUI/components/update-date/updateDate.js
@@ -29,7 +29,7 @@ function UpdateDate(props) {
isCompareActive,
layerState,
preloadNextTiles,
- state,
+ allActiveLayersState,
ui,
updateLayerVisibilities,
vectorStyleState,
@@ -59,25 +59,132 @@ function UpdateDate(props) {
setStyleFunction(def, vectorStyleId, vectorStyles, null, vectorStyleState);
}
- async function updateCompareLayer (def, index, mapLayerCollection) {
+ async function updateCompareLayer(
+ def, index, mapLayerCollection, groupOverride, extraOptions, seq,
+ ) {
const { createLayer } = ui;
+ const group = groupOverride || activeString;
const options = {
- group: activeString,
- date: getSelectedDate(dateCompareState),
- ...getGranuleOptions(granuleState, def, activeString),
+ group,
+ date: getSelectedDate(dateCompareState, group === 'activeB' ? 'selectedB' : 'selected'),
+ ...getGranuleOptions(granuleState, def, group),
+ ...extraOptions,
};
const updatedLayer = await createLayer(def, options);
- mapLayerCollection.setAt(index, updatedLayer);
- compareMapUi.update(activeString);
+ // Re-read current group after await since reloadLayers may have restructured it.
+ let targetCollection = mapLayerCollection;
+ let targetIndex = index;
+ if (isCompareActive && ui.selected) {
+ const allGroups = ui.selected.getLayers().getArray();
+ const currentGroupLayer = allGroups.find((lg) => lg.get('group') === group);
+ if (currentGroupLayer?.getLayers) {
+ const freshCollection = currentGroupLayer.getLayers();
+ // Re-find by id after await since concurrent rebuilds can shift indices.
+ const freshArr = freshCollection.getArray();
+ const freshIndex = lodashFindIndex(
+ freshArr, { wv: { def: { id: def.id } } },
+ );
+ if (freshIndex === -1) return;
+ targetCollection = freshCollection;
+ targetIndex = freshIndex;
+ }
+ }
+ // Skip if a more recent updateDate already rendered a newer frame here.
+ // Allows late-arriving layers to progressively render while preventing
+ // out-of-order overwrites.
+ const existing = targetCollection.getArray()[targetIndex];
+ if (existing?.wv?.appliedSeq > seq) return;
+ updatedLayer.wv = { ...updatedLayer.wv, appliedSeq: seq };
+ targetCollection.setAt(targetIndex, updatedLayer);
+ compareMapUi.update(group);
+ }
+
+ // Rebuild empty granule layers on a specific compare side.
+ const MAX_CMR_REBUILD_ATTEMPTS = 3;
+ async function rebuildEmptyCompareGranules(targetString, isStale) {
+ if (!isCompareActive || !ui.selected) return;
+ if (ui.processingPromise) {
+ await ui.processingPromise;
+ if (isStale()) return;
+ }
+
+ const allGroups = ui.selected.getLayers().getArray();
+ const targetGroup = allGroups.find((g) => g.get('group') === targetString);
+ if (!targetGroup) return;
+
+ const targetCollection = targetGroup.getLayers();
+ const targetLayers = targetCollection.getArray();
+
+ // Use live OL layers, not the Redux snapshot which may be stale.
+ const rebuildCandidates = targetLayers
+ .map((layer, index) => ({ layer, index }))
+ .filter(({ layer }) => {
+ const { wv } = layer;
+ return wv?.def?.type === 'granule' &&
+ wv.pendingCmrRebuild &&
+ (wv.cmrRebuildAttempts || 0) < MAX_CMR_REBUILD_ATTEMPTS;
+ });
+
+ await Promise.allSettled(rebuildCandidates.map(async ({ layer, index }) => {
+ const extra = { cmrRebuildAttempts: layer.wv.cmrRebuildAttempts || 0 };
+ await updateCompareLayer(layer.wv.def, index, targetCollection, targetString, extra);
+ }));
}
- async function updateDate(outOfStepChange, skipTitiler) {
+ // Rebuild empty granule layers on both compare sides.
+ async function rebuildAllEmptyCompareGranules(isStale) {
+ const inactiveString = activeString === 'active' ? 'activeB' : 'active';
+ await Promise.allSettled([
+ rebuildEmptyCompareGranules(activeString, isStale),
+ rebuildEmptyCompareGranules(inactiveString, isStale),
+ ]);
+ }
+
+ // Rebuild empty granule layers in non-compare (flat) mode.
+ async function rebuildEmptyNonCompareGranules(isStale) {
+ if (isCompareActive || !ui.selected) return;
const { createLayer } = ui;
const layerGroup = getActiveLayerGroup(layerState);
const mapLayerCollection = layerGroup.getLayers();
const layers = mapLayerCollection.getArray();
- const activeLayersArray = getAllActiveLayers(state);
+
+ const rebuildCandidates = layers
+ .map((layer, index) => ({ layer, index }))
+ .filter(({ layer }) => {
+ const { wv } = layer;
+ return wv?.def?.type === 'granule' &&
+ wv.pendingCmrRebuild &&
+ (wv.cmrRebuildAttempts || 0) < MAX_CMR_REBUILD_ATTEMPTS;
+ });
+
+ await Promise.allSettled(rebuildCandidates.map(async ({ layer }) => {
+ const def = layer.wv.def;
+ const layerOptions = {
+ granuleCount: getGranuleCount(granuleState, def.id),
+ cmrRebuildAttempts: layer.wv.cmrRebuildAttempts || 0,
+ };
+ const updatedLayer = await createLayer(def, layerOptions);
+ if (isStale()) return;
+ const freshLayers = mapLayerCollection.getArray();
+ const freshIndex = freshLayers.findIndex(({ wv }) => wv?.def?.id === def.id);
+ if (freshIndex === -1) return;
+ mapLayerCollection.setAt(freshIndex, updatedLayer);
+ }));
+ }
+
+ async function updateDate(outOfStepChange) {
+ const { createLayer } = ui;
+
+ // Sequence counter to discard stale results from rapid date changes.
+ ui.dateUpdateSeq = (ui.dateUpdateSeq || 0) + 1;
+ const mySeq = ui.dateUpdateSeq;
+ const isStale = () => ui.dateUpdateSeq !== mySeq;
+
+ const layerGroup = getActiveLayerGroup(layerState);
+ const mapLayerCollection = layerGroup.getLayers();
+ const layers = mapLayerCollection.getArray();
+ const activeLayersArray = getAllActiveLayers(allActiveLayersState);
const visibleLayers = activeLayersArray.filter(({ id, visible }) => layers
.findIndex(({ wv }) => wv?.def?.id === id) !== -1 && visible);
@@ -88,8 +195,11 @@ function UpdateDate(props) {
.includes(def.period);
const index = findLayerIndex(def);
const hasVectorStyles = config.vectorStyles && lodashGet(def, 'vectorStyle.id');
- if (isCompareActive && layers.length) {
- await updateCompareLayer(def, index, mapLayerCollection, layers, skipTitiler);
+ if (isCompareActive && layers.length && (temporalLayer || type === 'granule')) {
+ await updateCompareLayer(
+ def, index, mapLayerCollection,
+ undefined, undefined, mySeq,
+ );
} else if (temporalLayer) {
if (index !== undefined && index !== -1) {
const layerValue = layers[index];
@@ -97,7 +207,12 @@ function UpdateDate(props) {
? { granuleCount: getGranuleCount(granuleState, id) }
: { previousLayer: layerValue ? layerValue.wv : null };
const updatedLayer = await createLayer(def, layerOptions);
- mapLayerCollection.setAt(index, updatedLayer);
+ const freshIndex = findLayerIndex(def);
+ if (freshIndex === undefined || freshIndex === -1) return;
+ const existing = mapLayerCollection.getArray()[freshIndex];
+ if (existing?.wv?.appliedSeq > mySeq) return;
+ updatedLayer.wv = { ...updatedLayer.wv, appliedSeq: mySeq };
+ mapLayerCollection.setAt(freshIndex, updatedLayer);
}
}
if (hasVectorStyles && temporalLayer) {
@@ -105,6 +220,7 @@ function UpdateDate(props) {
}
});
await Promise.allSettled(layerPromises);
+ if (isStale()) return;
updateLayerVisibilities();
if (!outOfStepChange) {
preloadNextTiles();
@@ -113,11 +229,17 @@ function UpdateDate(props) {
const actionSwitch = () => {
if (action.type === dateConstants.SELECT_DATE) {
+ // Show already-loaded layers right away while CMR requests are in flight.
+ updateLayerVisibilities();
+
if (ui.processingPromise) {
+ const waitedPromise = ui.processingPromise;
return new Promise((resolve) => {
- resolve(ui.processingPromise);
+ resolve(waitedPromise);
}).then(() => {
- ui.processingPromise = null;
+ if (ui.processingPromise === waitedPromise) {
+ ui.processingPromise = null;
+ }
return updateDate(action.outOfStep);
});
}
@@ -126,15 +248,29 @@ function UpdateDate(props) {
if (action.type === layerConstants.TOGGLE_LAYER_VISIBILITY ||
action.type === layerConstants.TOGGLE_OVERLAY_GROUP_VISIBILITY) {
const outOfStep = false;
- // if date not changing we do not want to recreate titiler layer
- const skipTitiler = true;
- return updateDate(outOfStep, skipTitiler);
+ return updateDate(outOfStep);
+ }
+ // Rebuild layers when date ranges arrive late (L2/TEMPO, NRT).
+ // Separate counter so SELECT_DATE doesn't stale-abort CMR rebuilds.
+ if (action.type === layerConstants.ADD_GRANULE_DATE_RANGES) {
+ ui.cmrRebuildSeq = (ui.cmrRebuildSeq || 0) + 1;
+ const mySeq = ui.cmrRebuildSeq;
+ const isStale = () => ui.cmrRebuildSeq !== mySeq;
+ updateLayerVisibilities();
+ const rebuildPromise = isCompareActive
+ ? rebuildAllEmptyCompareGranules(isStale)
+ : rebuildEmptyNonCompareGranules(isStale);
+ return rebuildPromise.then(() => {
+ if (!isStale()) updateLayerVisibilities();
+ });
}
return undefined;
};
useEffect(() => {
- actionSwitch();
+ actionSwitch()?.catch((error) => {
+ console.warn('updateDate actionSwitch failed:', error);
+ });
}, [action]);
return null;
@@ -151,15 +287,18 @@ const mapStateToProps = (state) => {
const granuleState = { compare, layers };
const layerState = { compare, map };
const vectorStyleState = { proj, vectorStyles, config };
+ // Minimal slice for getAllActiveLayers — avoids passing entire Redux state
+ // which defeats React-Redux shallow equality checks.
+ const allActiveLayersState = { proj, compare, layers };
return {
activeLayers,
activeString,
+ allActiveLayersState,
dateCompareState,
granuleState,
isCompareActive,
layerState,
- state,
vectorStyleState,
};
};
@@ -169,19 +308,19 @@ export default connect(
)(UpdateDate);
UpdateDate.propTypes = {
- action: PropTypes.oneOfType([PropTypes.object, PropTypes.oneOf(['null'])]),
- activeLayers: PropTypes.oneOfType([PropTypes.array, PropTypes.oneOf(['null'])]),
+ action: PropTypes.object,
+ activeLayers: PropTypes.array,
activeString: PropTypes.string,
- compareMapUi: PropTypes.oneOfType([PropTypes.object, PropTypes.oneOf(['null'])]),
- config: PropTypes.oneOfType([PropTypes.object, PropTypes.oneOf(['null'])]),
- dateCompareState: PropTypes.oneOfType([PropTypes.object, PropTypes.oneOf(['null'])]),
+ compareMapUi: PropTypes.object,
+ config: PropTypes.object,
+ dateCompareState: PropTypes.object,
getGranuleOptions: PropTypes.func,
- granuleState: PropTypes.oneOfType([PropTypes.object, PropTypes.oneOf(['null'])]),
+ granuleState: PropTypes.object,
isCompareActive: PropTypes.bool,
- layerState: PropTypes.oneOfType([PropTypes.object, PropTypes.oneOf(['null'])]),
+ layerState: PropTypes.object,
preloadNextTiles: PropTypes.func,
- state: PropTypes.oneOfType([PropTypes.object, PropTypes.oneOf(['null'])]),
- ui: PropTypes.oneOfType([PropTypes.object, PropTypes.oneOf(['null'])]),
+ allActiveLayersState: PropTypes.object,
+ ui: PropTypes.object,
updateLayerVisibilities: PropTypes.func,
- vectorStyleState: PropTypes.oneOfType([PropTypes.object, PropTypes.oneOf(['null'])]),
+ vectorStyleState: PropTypes.object,
};
diff --git a/web/js/mapUI/components/update-projection/updateProjection.js b/web/js/mapUI/components/update-projection/updateProjection.js
index 7ec13cacb..6400aacbc 100644
--- a/web/js/mapUI/components/update-projection/updateProjection.js
+++ b/web/js/mapUI/components/update-projection/updateProjection.js
@@ -1,4 +1,4 @@
-import { useEffect, useState, useRef } from 'react';
+import { useEffect, useRef } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import OlLayerGroup from 'ol/layer/Group';
@@ -27,6 +27,7 @@ import { SET_SCREEN_INFO } from '../../../modules/screen-size/constants';
import { requestPalette as requestPaletteAction } from '../../../modules/palettes/actions';
import usePrevious from '../../../util/customHooks';
import { addTEMPODateRanges as addTEMPODateRangesAction } from '../../../modules/layers/actions';
+import { loadLayersWithSlots } from '../../util/util';
function UpdateProjection(props) {
const {
@@ -39,6 +40,7 @@ function UpdateProjection(props) {
dateCompareState,
fitToLeadingExtent,
getGranuleOptions,
+ layerCreationQueue,
isKioskModeActive,
isMobile,
layerState,
@@ -141,43 +143,65 @@ function UpdateProjection(props) {
}
clearLayers(saveCache);
const defs = getLayers(layerStateRef.current, { reverse: true });
- const layerPromises = defs.map((def) => {
- const options = getGranuleOptions(
- layerStateRef.current,
- def,
- compare.activeString,
- granuleOptions,
- );
- if (def.id.includes('TEMPO')) {
- options.tempoCallback = addTEMPODateRanges;
- }
- return createLayer(def, options);
+
+ // Async loading — each layer renders as soon as it resolves.
+ await loadLayersWithSlots({
+ defs,
+ createLayer,
+ mapUI,
+ queue: saveCache ? null : layerCreationQueue,
+ skipYield: saveCache,
+ updateLayerVisibilities,
+ getLayerOptions: (def) => {
+ const options = getGranuleOptions(
+ layerStateRef.current,
+ def,
+ compare.activeString,
+ granuleOptions,
+ );
+ if (def.id.includes('TEMPO')) {
+ options.tempoCallback = addTEMPODateRanges;
+ }
+ return options;
+ },
});
- const layerResults = await Promise.allSettled(layerPromises);
- const createdLayers = layerResults.filter(({ status }) => status === 'fulfilled').map(({ value }) => value);
- mapUI?.setLayers(createdLayers);
+ return; // Exit early since we've handled the non-compare case
} else {
const stateArray = [['active', 'selected'], ['activeB', 'selectedB']];
if (compare && !compare.isCompareA && compare.mode === 'spy') {
stateArray.reverse(); // Set Layer order based on active A|B group
}
- clearLayers(saveCache);
const stateArrayGroups = stateArray
.map(async (arr) => getCompareLayerGroup(arr, layerStateRef.current, granuleOptions));
- const compareLayerGroups = await Promise.all(stateArrayGroups);
- mapUI?.setLayers(compareLayerGroups);
- compareMapUi.create(mapUI, compare.mode);
+ // Chain onto any in-flight processingPromise so updateDate
+ // and other async callers wait for this build to finish.
+ const previousPromise = ui.processingPromise || Promise.resolve();
+ const compareLoadPromise = previousPromise
+ .catch(() => {}) // don't let a prior failure block this build
+ .then(() => Promise.all(stateArrayGroups))
+ .then((compareLayerGroups) => {
+ clearLayers(saveCache);
+ mapUI?.setLayers(compareLayerGroups);
+ compareMapUi.create(mapUI, compare.mode);
+ });
+ ui.processingPromise = compareLoadPromise;
+ await compareLoadPromise;
+ // Only clear if we're still the latest — a newer call may have chained on.
+ if (ui.processingPromise === compareLoadPromise) {
+ ui.processingPromise = null;
+ }
}
updateLayerVisibilities();
}
const onStopAnimation = function() {
- const needsRefresh = activeLayers.some(({ type }) => type === 'granule' || type === 'vector');
- if (needsRefresh) {
- // The SELECT_DATE and STOP_ANIMATION actions happen back to back and both
- // try to modify map layers asynchronously so we need to set a timeout to allow
- // the updateDate() function to complete before trying to call reloadLayers() here
- setTimeout(reloadLayers, 100);
+ // Only vector layers need a reload here for style refresh.
+ // Granule layers are already rebuilt by updateDate via SELECT_DATE.
+ const hasVectorLayers = activeLayers.some(({ type }) => type === 'vector');
+ if (hasVectorLayers) {
+ // Wait for any pending updateDate work before rebuilding.
+ const waitFor = ui.processingPromise || Promise.resolve();
+ waitFor.catch(() => {}).then(() => reloadLayers());
}
};
@@ -400,10 +424,13 @@ function UpdateProjection(props) {
.map((layer) => layer.granuleDateRanges);
const prevActiveLayers = usePrevious(activeLayers);
- const [selectedDate, setSelectedDate] = useState(dateCompareState.date.selected);
+ const prevActiveString = usePrevious(compare.activeString);
useEffect(() => {
if (!ui.selected) return;
+ // Skip reload on A↔B tab switch — handled by CHANGE_STATE in actionSwitch.
+ if (compare.active && compare.activeString !== prevActiveString) return;
+
const prevL2Layers = selectL2Layers(prevActiveLayers);
const activeL2Layers = selectL2Layers(activeLayers);
// Check if new date ranges have been added to L2 layers.
@@ -414,10 +441,8 @@ function UpdateProjection(props) {
) && prevL2Layers.includes(undefined);
// Check if new layers have been added
const hasNewLayers = prevActiveLayers.length !== activeLayers.length;
- // Check if the date has changed
- const hasNewDate = selectedDate !== dateCompareState.date.selected;
- const needsReload = hasNewDateRanges || hasNewLayers || hasNewDate;
- setSelectedDate(dateCompareState.date.selected);
+ // Date changes are handled by updateDate, not here.
+ const needsReload = hasNewDateRanges || hasNewLayers;
if (needsReload) {
reloadLayers(null, true);
}
@@ -448,7 +473,6 @@ const mapStateToProps = (state) => {
proj,
map,
renderedPalettes,
- requestPaletteAction,
};
};
@@ -473,28 +497,29 @@ export default connect(
)(UpdateProjection);
UpdateProjection.propTypes = {
- action: PropTypes.oneOfType([PropTypes.object, PropTypes.oneOf(['null'])]),
- activeLayers: PropTypes.oneOfType([PropTypes.array, PropTypes.oneOf(['null'])]),
- compare: PropTypes.oneOfType([PropTypes.object, PropTypes.oneOf(['null'])]),
+ action: PropTypes.object,
+ activeLayers: PropTypes.array,
+ compare: PropTypes.object,
compareMode: PropTypes.string,
- compareMapUi: PropTypes.oneOfType([PropTypes.object, PropTypes.oneOf(['null'])]),
- config: PropTypes.oneOfType([PropTypes.object, PropTypes.oneOf(['null'])]),
- dateCompareState: PropTypes.oneOfType([PropTypes.object, PropTypes.oneOf(['null'])]),
+ compareMapUi: PropTypes.object,
+ config: PropTypes.object,
+ dateCompareState: PropTypes.object,
fitToLeadingExtent: PropTypes.func,
getGranuleOptions: PropTypes.func,
+ layerCreationQueue: PropTypes.object,
isKioskModeActive: PropTypes.bool,
isMobile: PropTypes.bool,
- layerState: PropTypes.oneOfType([PropTypes.object, PropTypes.oneOf(['null'])]),
- map: PropTypes.oneOfType([PropTypes.object, PropTypes.oneOf(['null'])]),
- models: PropTypes.oneOfType([PropTypes.object, PropTypes.oneOf(['null'])]),
+ layerState: PropTypes.object,
+ map: PropTypes.object,
+ models: PropTypes.object,
preloadForCompareMode: PropTypes.func,
- proj: PropTypes.oneOfType([PropTypes.object, PropTypes.oneOf(['null'])]),
+ proj: PropTypes.object,
projectionTrigger: PropTypes.number,
- ui: PropTypes.oneOfType([PropTypes.object, PropTypes.oneOf(['null'])]),
+ ui: PropTypes.object,
updateExtent: PropTypes.func,
updateLayerVisibilities: PropTypes.func,
updateMapUI: PropTypes.func,
- renderedPalettes: PropTypes.oneOfType([PropTypes.object, PropTypes.oneOf(['null'])]),
+ renderedPalettes: PropTypes.object,
requestPalette: PropTypes.func,
addTEMPODateRanges: PropTypes.func,
};
diff --git a/web/js/mapUI/mapUI.js b/web/js/mapUI/mapUI.js
index b4fef7e64..2c6eaaee0 100644
--- a/web/js/mapUI/mapUI.js
+++ b/web/js/mapUI/mapUI.js
@@ -68,6 +68,7 @@ function MapUI(props) {
isStaticMapActive,
isTravelModeActive,
lastArrowDirection,
+ layerCreationQueue,
layerQueue,
lastPreloadDate,
layers,
@@ -138,6 +139,7 @@ function MapUI(props) {
case dateConstants.SELECT_DATE:
case layerConstants.TOGGLE_LAYER_VISIBILITY:
case layerConstants.TOGGLE_OVERLAY_GROUP_VISIBILITY:
+ case layerConstants.ADD_GRANULE_DATE_RANGES:
return setDateAction(action);
case layerConstants.UPDATE_OPACITY:
return setOpacityAction(action);
@@ -187,10 +189,17 @@ function MapUI(props) {
ui.selectedVectors = newSelection;
};
- events.on(REDUX_ACTION_DISPATCHED, subscribeToStore);
- window.addEventListener('orientationchange', () => {
- setTimeout(() => { setProjectionTrigger((projectionTrigger) => projectionTrigger + 1); }, 200);
- });
+ useEffect(() => {
+ const handleOrientation = () => {
+ setTimeout(() => { setProjectionTrigger((prev) => prev + 1); }, 200);
+ };
+ events.on(REDUX_ACTION_DISPATCHED, subscribeToStore);
+ window.addEventListener('orientationchange', handleOrientation);
+ return () => {
+ events.off(REDUX_ACTION_DISPATCHED, subscribeToStore);
+ window.removeEventListener('orientationchange', handleOrientation);
+ };
+ }, []);
const updateExtent = () => {
const map = ui.selected;
@@ -203,11 +212,14 @@ function MapUI(props) {
};
const updateLayerVisibilities = () => {
+ // Guard against early calls before map is ready
+ if (!ui.selected) return;
+
const layerGroup = ui.selected.getLayers();
const setRenderable = (layer, parentCompareGroup) => {
const { id, group } = layer.wv;
- const dateGroup = layer.get('date') || group === 'active' ? 'selected' : 'selectedB';
+ const dateGroup = layer.get('date') || (group === 'active' ? 'selected' : 'selectedB');
const date = getSelectedDate(dateCompareState, dateGroup);
const layers = getActiveLayers(activeLayersState, parentCompareGroup || group);
const renderable = isRenderableLayer(id, layers, date, null, renderableLayersState);
@@ -368,6 +380,7 @@ function MapUI(props) {
compareMapUi={compareMapUi}
config={config}
getGranuleOptions={getGranuleOptions}
+ layerCreationQueue={layerCreationQueue}
models={models}
preloadForCompareMode={preloadForCompareMode}
projectionTrigger={projectionTrigger}
@@ -510,6 +523,7 @@ MapUI.propTypes = {
isStaticMapActive: PropTypes.bool,
isTravelModeActive: PropTypes.bool,
lastArrowDirection: PropTypes.string,
+ layerCreationQueue: PropTypes.object,
layerQueue: PropTypes.oneOfType([PropTypes.object, PropTypes.oneOf(['null'])]),
layers: PropTypes.oneOfType([PropTypes.object, PropTypes.oneOf(['null'])]),
lastPreloadDate: PropTypes.oneOfType([PropTypes.object, PropTypes.oneOf(['null'])]),
diff --git a/web/js/mapUI/util/util.js b/web/js/mapUI/util/util.js
index 718e5a121..9bc48dabc 100644
--- a/web/js/mapUI/util/util.js
+++ b/web/js/mapUI/util/util.js
@@ -238,3 +238,92 @@ export function formatSelectedDate(date) {
const formattedDate = `${year}-${month}-${day}`;
return formattedDate;
}
+
+let loadOperationId = 0;
+
+/**
+ * Load layers asynchronously, inserting each into the map as it resolves.
+ * Maintains correct z-order via slot positioning. Superseded operations
+ * (from rapid reloads) skip insertion so they don't corrupt the map.
+ *
+ * @param {Object} options
+ * @param {Array} options.defs - Layer definitions in desired z-order (bottom to top)
+ * @param {Function} options.createLayer - Creates an OL layer from a definition
+ * @param {Object} options.mapUI - OpenLayers map instance
+ * @param {Function} options.updateLayerVisibilities - Updates layer visibility state
+ * @param {Function} options.getLayerOptions - Returns options for a layer definition
+ * @returns {Promise<{layers: Array, results: Array}>}
+ */
+export async function loadLayersWithSlots({
+ defs,
+ createLayer,
+ mapUI,
+ queue,
+ skipYield,
+ updateLayerVisibilities,
+ getLayerOptions,
+}) {
+ if (!defs?.length) {
+ updateLayerVisibilities?.();
+ return { layers: [], results: [] };
+ }
+
+ loadOperationId += 1;
+ const currentOpId = loadOperationId;
+
+ const layerSlots = new Array(defs.length).fill(null);
+
+ // Insert at the correct z-position based on how many lower layers are already present.
+ const insertLayerAtCorrectPosition = (layer, defIndex) => {
+ if (!mapUI) return;
+
+ const layerCollection = mapUI.getLayers();
+ const existingLayers = layerCollection.getArray();
+
+ const insertIndex = existingLayers.filter((existingLayer) => {
+ const existingId = existingLayer.wv?.id;
+ const existingDefIndex = defs.findIndex((d) => d.id === existingId);
+ return existingDefIndex >= 0 && existingDefIndex < defIndex;
+ }).length;
+
+ layerCollection.insertAt(insertIndex, layer);
+ updateLayerVisibilities?.();
+ };
+
+ // Yield to the browser event loop so the render pipeline can run between layers.
+ const yieldToMain = () => new Promise((resolve) => { setTimeout(resolve, 0); });
+
+ const layerPromises = defs.map((def, index) => {
+ const task = async () => {
+ try {
+ const options = getLayerOptions?.(def) || {};
+ const layer = await createLayer(def, options);
+
+ if (layer) {
+ layerSlots[index] = layer;
+
+ // Skip if a newer operation has superseded this one.
+ if (currentOpId !== loadOperationId) {
+ return { status: 'fulfilled', value: layer, def, skipped: true };
+ }
+
+ insertLayerAtCorrectPosition(layer, index);
+ if (!skipYield) await yieldToMain();
+ }
+
+ return { status: 'fulfilled', value: layer, def };
+ } catch (error) {
+ console.warn(`Layer creation failed for ${def.id}:`, error);
+ return { status: 'rejected', reason: error, def };
+ }
+ };
+ return queue ? queue.add(task) : task();
+ });
+
+ await Promise.allSettled(layerPromises);
+ if (currentOpId === loadOperationId) {
+ updateLayerVisibilities?.();
+ }
+ const completedLayers = layerSlots.filter((layer) => layer !== null);
+ return { layers: completedLayers, results: [] };
+}
diff --git a/web/js/modules/compare/actions.js b/web/js/modules/compare/actions.js
index 0154d630c..8c911fb14 100644
--- a/web/js/modules/compare/actions.js
+++ b/web/js/modules/compare/actions.js
@@ -1,4 +1,4 @@
-import { initSecondLayerGroup } from '../layers/actions';
+import { initSecondLayerGroup, syncSecondLayerGroup } from '../layers/actions';
import { initSecondDate, clearPreload } from '../date/actions';
import {
CHANGE_STATE,
@@ -15,11 +15,26 @@ export function toggleActiveCompareState() {
}
export function toggleCompareOnOff() {
return (dispatch, getState) => {
- if (!getState().compare.bStatesInitiated) {
- dispatch(initSecondLayerGroup());
- dispatch(initSecondDate());
+ const state = getState();
+ const { active, bStatesInitiated, lastExitALayerIds } = state.compare;
+ // Only sync/init layers when entering compare mode, not when exiting.
+ if (!active) {
+ if (!bStatesInitiated) {
+ // First compare entry — full clone of A → B.
+ dispatch(initSecondLayerGroup());
+ dispatch(initSecondDate());
+ } else {
+ // Re-entry — only sync layers added to A since last exit,
+ // not layers the user intentionally removed from B.
+ dispatch(syncSecondLayerGroup(lastExitALayerIds));
+ }
}
- dispatch({ type: TOGGLE_ON_OFF });
+ // When exiting, snapshot A's layer IDs so the next re-entry knows
+ // which layers are truly new vs. already existed at exit time.
+ const exitPayload = active
+ ? { lastExitALayerIds: state.layers.active.layers.map((l) => l.id) }
+ : {};
+ dispatch({ type: TOGGLE_ON_OFF, ...exitPayload });
};
}
export function setValue(num) {
diff --git a/web/js/modules/compare/reducers.js b/web/js/modules/compare/reducers.js
index 75f396055..61576587e 100644
--- a/web/js/modules/compare/reducers.js
+++ b/web/js/modules/compare/reducers.js
@@ -27,6 +27,9 @@ export function compareReducer(state = initialCompareState, action) {
return lodashAssign({}, state, {
active: !state.active,
bStatesInitiated: true,
+ // When exiting compare, snapshot A's layer IDs so re-entry SYNC
+ // can distinguish "removed by user" from "added after exit".
+ ...(state.active && { lastExitALayerIds: action.lastExitALayerIds }),
});
case CHANGE_MODE:
return lodashAssign({}, state, {
diff --git a/web/js/modules/date/util.js b/web/js/modules/date/util.js
index 15609ed2e..823aa036e 100644
--- a/web/js/modules/date/util.js
+++ b/web/js/modules/date/util.js
@@ -564,10 +564,24 @@ export function getNextImageryDelta(layers, date, signConstant) {
let invalidLayerCount = 0;
const dateAObj = new Date(date);
let hasDeltaChanged = false;
- let dateRanges;
for (let i = 0; i < layers.length; i += 1) {
+ let dateRanges;
if (Object.prototype.hasOwnProperty.call(layers[i], 'tempoDateRanges')) {
dateRanges = layers[i].tempoDateRanges;
+ } else if (Object.prototype.hasOwnProperty.call(layers[i], 'granuleDateRanges') &&
+ layers[i].granuleDateRanges?.length) {
+ // granuleDateRanges are stored as [[start, end], ...] arrays from CMR/DD workers;
+ // convert to the {startDate, endDate, dateInterval} format used below.
+ // When dateInterval is absent (CMR), derive it from the range span in minutes.
+ dateRanges = layers[i].granuleDateRanges.map(
+ ([startDate, endDate, dateInterval]) => {
+ const interval = dateInterval ||
+ String(Math.max(1, Math.ceil(
+ ((new Date(endDate) - new Date(startDate)) / 1000) / 60,
+ )));
+ return { startDate, endDate, dateInterval: interval };
+ },
+ );
} else if (Object.prototype.hasOwnProperty.call(layers[i], 'dateRanges')) {
dateRanges = layers[i].dateRanges;
}
diff --git a/web/js/modules/layers/actions.js b/web/js/modules/layers/actions.js
index cfe051b12..0fcfcdc15 100644
--- a/web/js/modules/layers/actions.js
+++ b/web/js/modules/layers/actions.js
@@ -16,6 +16,7 @@ import {
import {
ADD_LAYER,
INIT_SECOND_LAYER_GROUP,
+ SYNC_SECOND_LAYER_GROUP,
REORDER_LAYERS,
REORDER_OVERLAY_GROUPS,
TOGGLE_LAYER_VISIBILITY,
@@ -47,6 +48,13 @@ export function initSecondLayerGroup() {
};
}
+export function syncSecondLayerGroup(lastExitALayerIds) {
+ return {
+ type: SYNC_SECOND_LAYER_GROUP,
+ lastExitALayerIds,
+ };
+}
+
export function activateLayersForEventCategory(category) {
return (dispatch, getState) => {
const state = getState();
@@ -228,15 +236,12 @@ export function toggleGroupVisibility(ids, visible) {
return (dispatch, getState) => {
const { compare } = getState();
const activeLayers = getActiveLayersSelector(getState());
- activeLayers.forEach((layerObj) => {
- const layer = layerObj;
- if (ids.includes(layer.id)) {
- layer.visible = visible;
- }
- });
+ const updatedLayers = activeLayers.map((layer) => (
+ ids.includes(layer.id) ? { ...layer, visible } : layer
+ ));
dispatch({
type: TOGGLE_OVERLAY_GROUP_VISIBILITY,
- layers: activeLayers,
+ layers: updatedLayers,
activeString: compare.activeString,
});
};
@@ -351,18 +356,44 @@ export function updateGranuleLayerState(layer) {
};
}
+const granuleRangesEqual = (a, b) => {
+ if (a === b) return true;
+ if (!a || !b || a.length !== b.length) return false;
+ for (let i = 0; i < a.length; i += 1) {
+ if (a[i][0] !== b[i][0] || a[i][1] !== b[i][1]) return false;
+ }
+ return true;
+};
+
export function addGranuleDateRanges(layer, granuleDateRanges) {
return (dispatch, getState) => {
- const state = getState();
- const { activeString } = state.compare;
+ const { active: compareActive, activeString } = getState().compare;
const { id } = layer;
- dispatch({
- type: ADD_GRANULE_DATE_RANGES,
- activeString,
- id,
- granuleDateRanges,
- });
+ const dispatchForSide = (side) => {
+ // Re-read state so the dedup check sees results of prior dispatches.
+ const freshState = getState();
+ const existingLayer = getActiveLayersSelector(freshState, side).find((l) => l.id === id);
+ if (!existingLayer) return;
+ if (granuleRangesEqual(existingLayer.granuleDateRanges, granuleDateRanges)) {
+ return;
+ }
+ dispatch({
+ type: ADD_GRANULE_DATE_RANGES,
+ activeString: side,
+ id,
+ granuleDateRanges,
+ });
+ };
+
+ dispatchForSide(activeString);
+
+ // In compare mode, sync the same ranges to the other side so the B-side
+ // timeline coverage bar is populated regardless of which side is active.
+ if (compareActive) {
+ const otherSide = activeString === 'active' ? 'activeB' : 'active';
+ dispatchForSide(otherSide);
+ }
};
}
diff --git a/web/js/modules/layers/constants.js b/web/js/modules/layers/constants.js
index 1ee4afc5d..89201fd66 100644
--- a/web/js/modules/layers/constants.js
+++ b/web/js/modules/layers/constants.js
@@ -3,6 +3,7 @@ export const REORDER_LAYERS = 'LAYERS/REORDER_LAYERS';
export const REORDER_OVERLAY_GROUPS = 'LAYERS/REORDER_OVERLAY_GROUPS';
export const TOGGLE_OVERLAY_GROUPS = 'LAYERS/TOGGLE_OVERLAY_GROUPS';
export const INIT_SECOND_LAYER_GROUP = 'LAYERS/INIT_SECOND_COMPARE_GROUP';
+export const SYNC_SECOND_LAYER_GROUP = 'LAYERS/SYNC_SECOND_COMPARE_GROUP';
export const TOGGLE_ACTIVE_STATE = 'LAYERS/TOGGLE_ACTIVE_LAYER_STATE';
export const TOGGLE_LAYER_VISIBILITY = 'LAYERS/TOGGLE_LAYER_VISIBILITY';
export const TOGGLE_OVERLAY_GROUP_VISIBILITY = 'LAYERS/TOGGLE_OVERLAY_GROUP_VISIBILITY';
diff --git a/web/js/modules/layers/granule-date-ranges-service.js b/web/js/modules/layers/granule-date-ranges-service.js
new file mode 100644
index 000000000..18833b17c
--- /dev/null
+++ b/web/js/modules/layers/granule-date-ranges-service.js
@@ -0,0 +1,123 @@
+// Fetches granule date ranges using a web worker (cmr or describe-domains
+// depending on the layer config). Results are cached per layer id. The dd
+// worker needs a two-step exchange since DOMParser doesn't exist in workers.
+// Returns [] on error.
+
+const inFlight = new Map();
+
+const buildCmrPromise = (def) => new Promise((resolve) => {
+ const worker = new Worker('js/workers/cmr.worker.js');
+ worker.onmessage = (event) => {
+ worker.terminate();
+ resolve(event.data || []);
+ };
+ worker.onerror = (e) => {
+ console.warn(`granule-date-ranges-service: cmr worker failed for ${def.id}`, e);
+ worker.terminate();
+ resolve([]);
+ };
+ worker.postMessage({ operation: 'getLayerGranuleRanges', args: [def] });
+});
+
+const buildDdPromise = (def, {
+ crs, describeDomainsUrl, selectedDate,
+}) => new Promise((resolve) => {
+ const worker = new Worker('js/workers/describe-domains.worker.js');
+ worker.onmessage = (event) => {
+ if (Array.isArray(event.data)) {
+ worker.terminate();
+ resolve(event.data);
+ return;
+ }
+ // Worker posted raw XML; parse on main thread and post back for merge.
+ try {
+ const parser = new DOMParser();
+ const xmlDoc = parser.parseFromString(event.data, 'text/xml');
+ const domains = xmlDoc.querySelector('Domain')?.textContent;
+ if (!domains) {
+ worker.terminate();
+ resolve([]);
+ return;
+ }
+ worker.postMessage({ operation: 'mergeDomains', args: [domains, 60_000] });
+ } catch (e) {
+ console.warn(`granule-date-ranges-service: failed to parse describeDomains XML for ${def.id}`, e);
+ worker.terminate();
+ resolve([]);
+ }
+ };
+ worker.onerror = (e) => {
+ console.warn(`granule-date-ranges-service: dd worker failed for ${def.id}`, e);
+ worker.terminate();
+ resolve([]);
+ };
+ // Query ±1 day around the selected date rather than the full layer history.
+ // Fewer domains means better merging and much faster responses.
+ const layerStart = new Date(def.startDate);
+ const layerEnd = def.endDate ? new Date(def.endDate) : new Date();
+ let startDate;
+ let endDate;
+ if (selectedDate) {
+ const sel = new Date(selectedDate);
+ const dayMs = 86_400_000;
+ startDate = new Date(Math.max(sel.getTime() - dayMs, layerStart.getTime())).toISOString();
+ endDate = new Date(Math.min(sel.getTime() + dayMs, layerEnd.getTime())).toISOString();
+ } else {
+ startDate = layerStart.toISOString();
+ endDate = layerEnd.toISOString();
+ }
+ const params = {
+ startDate,
+ endDate,
+ id: def.id,
+ proj: crs,
+ baseUrl: describeDomainsUrl,
+ };
+ worker.postMessage({ operation: 'requestDescribeDomains', args: [params] });
+});
+
+export function fetchGranuleDateRanges(def, opts = {}) {
+ if (!def?.id) return Promise.resolve([]);
+
+ const isCmr = def.cmrAvailability || def.dataAvailability === 'cmr';
+ const isDd = def.dataAvailability === 'dd';
+ if (!isCmr && !isDd) return Promise.resolve([]);
+
+ // dd layers are date-dependent, so include the date in the cache key.
+ const dateKey = isDd && opts.selectedDate
+ ? new Date(opts.selectedDate).toISOString()
+ .slice(0, 10)
+ : '';
+ const cacheKey = `${def.id}:${dateKey}`;
+
+ const cached = inFlight.get(cacheKey);
+ if (cached) return cached;
+
+ const promise = (isCmr
+ ? buildCmrPromise(def)
+ : buildDdPromise(def, opts)
+ ).then((result) => {
+ // Evict empty results so the next call can retry.
+ if (!result || result.length === 0) {
+ inFlight.delete(cacheKey);
+ }
+ return result;
+ });
+
+ inFlight.set(cacheKey, promise);
+ return promise;
+}
+
+// Clear cached results so the next call re-fetches (e.g. NRT rolling window).
+export function invalidateGranuleDateRanges(layerId) {
+ for (const key of inFlight.keys()) {
+ if (key === layerId || key.startsWith(`${layerId}:`)) {
+ inFlight.delete(key);
+ }
+ }
+}
+
+// Test-only.
+export function resetGranuleDateRangesCacheForTest() {
+ inFlight.clear();
+}
diff --git a/web/js/modules/layers/granule-date-ranges-service.test.js b/web/js/modules/layers/granule-date-ranges-service.test.js
new file mode 100644
index 000000000..bb7323242
--- /dev/null
+++ b/web/js/modules/layers/granule-date-ranges-service.test.js
@@ -0,0 +1,267 @@
+import {
+ fetchGranuleDateRanges,
+ invalidateGranuleDateRanges,
+ resetGranuleDateRangesCacheForTest,
+} from './granule-date-ranges-service';
+
+// Override jsdom-worker's global Worker with a stub we can drive from
+// the test, so we don't actually run the real worker source (which would
+// hit the network).
+const makeMockWorker = () => {
+ const instances = [];
+ const Ctor = function MockWorker(scriptUrl) {
+ this.scriptUrl = scriptUrl;
+ this.postMessage = jest.fn();
+ this.terminate = jest.fn();
+ this.onmessage = null;
+ this.onerror = null;
+ this.reply = (data) => this.onmessage && this.onmessage({ data });
+ this.fireError = (err) => this.onerror && this.onerror(err);
+ instances.push(this);
+ };
+ Ctor.instances = instances;
+ return Ctor;
+};
+
+let originalWorker;
+let warnSpy;
+
+beforeEach(() => {
+ originalWorker = global.Worker;
+ global.Worker = makeMockWorker();
+ warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => {});
+ resetGranuleDateRangesCacheForTest();
+});
+
+afterEach(() => {
+ global.Worker = originalWorker;
+ warnSpy.mockRestore();
+});
+
+describe('granuleDateRangesService', () => {
+ describe('layer-type detection', () => {
+ test('resolves [] for layers with no availability config', async () => {
+ const def = { id: 'plain-wmts-layer' };
+ const result = await fetchGranuleDateRanges(def, { crs: 'EPSG:4326' });
+ expect(result).toEqual([]);
+ expect(global.Worker.instances).toHaveLength(0);
+ });
+
+ test('resolves [] for falsy def or missing id', async () => {
+ expect(await fetchGranuleDateRanges(undefined, {})).toEqual([]);
+ expect(await fetchGranuleDateRanges({}, {})).toEqual([]);
+ expect(global.Worker.instances).toHaveLength(0);
+ });
+ });
+
+ describe('cmr worker path', () => {
+ test('spawns cmr.worker.js for cmrAvailability layers', async () => {
+ const def = { id: 'cmr-layer', cmrAvailability: true };
+ const promise = fetchGranuleDateRanges(def, { crs: 'EPSG:4326' });
+
+ expect(global.Worker.instances).toHaveLength(1);
+ const worker = global.Worker.instances[0];
+ expect(worker.scriptUrl).toBe('js/workers/cmr.worker.js');
+ expect(worker.postMessage).toHaveBeenCalledWith({
+ operation: 'getLayerGranuleRanges',
+ args: [def],
+ });
+
+ const ranges = [['2026-01-01T00:00:00Z', '2026-01-02T00:00:00Z']];
+ worker.reply(ranges);
+
+ await expect(promise).resolves.toEqual(ranges);
+ expect(worker.terminate).toHaveBeenCalled();
+ });
+
+ test('spawns cmr.worker.js for dataAvailability:cmr layers', async () => {
+ const def = { id: 'cmr-layer-2', dataAvailability: 'cmr' };
+ const promise = fetchGranuleDateRanges(def, { crs: 'EPSG:4326' });
+
+ expect(global.Worker.instances).toHaveLength(1);
+ expect(global.Worker.instances[0].scriptUrl).toBe('js/workers/cmr.worker.js');
+
+ global.Worker.instances[0].reply([]);
+ await expect(promise).resolves.toEqual([]);
+ });
+
+ test('resolves [] when cmr worker errors', async () => {
+ const def = { id: 'cmr-broken', cmrAvailability: true };
+ const promise = fetchGranuleDateRanges(def, { crs: 'EPSG:4326' });
+
+ const worker = global.Worker.instances[0];
+ worker.fireError(new Error('worker boom'));
+
+ await expect(promise).resolves.toEqual([]);
+ expect(worker.terminate).toHaveBeenCalled();
+ });
+
+ test('resolves [] when cmr worker returns falsy', async () => {
+ const def = { id: 'cmr-empty', cmrAvailability: true };
+ const promise = fetchGranuleDateRanges(def, { crs: 'EPSG:4326' });
+ global.Worker.instances[0].reply(undefined);
+ await expect(promise).resolves.toEqual([]);
+ });
+ });
+
+ describe('describe-domains worker path', () => {
+ const ddOpts = {
+ crs: 'EPSG:4326',
+ describeDomainsUrl: 'https://gibs.test',
+ };
+
+ test('spawns describe-domains.worker.js with correct params', async () => {
+ const def = {
+ id: 'dd-layer',
+ dataAvailability: 'dd',
+ startDate: '2026-01-01T00:00:00Z',
+ endDate: '2026-01-10T00:00:00Z',
+ };
+ const promise = fetchGranuleDateRanges(def, ddOpts);
+
+ expect(global.Worker.instances).toHaveLength(1);
+ const worker = global.Worker.instances[0];
+ expect(worker.scriptUrl).toBe('js/workers/describe-domains.worker.js');
+ expect(worker.postMessage).toHaveBeenCalledWith({
+ operation: 'requestDescribeDomains',
+ args: [{
+ startDate: new Date(def.startDate).toISOString(),
+ endDate: new Date(def.endDate).toISOString(),
+ id: def.id,
+ proj: 'EPSG:4326',
+ baseUrl: 'https://gibs.test',
+ }],
+ });
+
+ const ranges = [['2026-01-01T00:00:00Z', '2026-01-10T00:00:00Z']];
+ worker.reply(ranges);
+ await expect(promise).resolves.toEqual(ranges);
+ expect(worker.terminate).toHaveBeenCalled();
+ });
+
+ test('handles two-step XML parse + merge protocol', async () => {
+ const def = {
+ id: 'dd-two-step',
+ dataAvailability: 'dd',
+ startDate: '2026-01-01T00:00:00Z',
+ };
+ const promise = fetchGranuleDateRanges(def, ddOpts);
+ const worker = global.Worker.instances[0];
+
+ // Step 1: raw XML in.
+ const xml = '<Foo><Domain>2026-01-01T00:00:00Z/2026-01-02T00:00:00Z/PT6M</Domain></Foo>';
+ worker.reply(xml);
+
+ expect(worker.postMessage).toHaveBeenLastCalledWith({
+ operation: 'mergeDomains',
+ args: ['2026-01-01T00:00:00Z/2026-01-02T00:00:00Z/PT6M', 60000],
+ });
+
+ // Step 2: merged ranges back.
+ const ranges = [['2026-01-01T00:00:00Z', '2026-01-02T00:00:00Z']];
+ worker.reply(ranges);
+
+ await expect(promise).resolves.toEqual(ranges);
+ expect(worker.terminate).toHaveBeenCalled();
+ });
+
+ test('resolves [] when XML has no <Domain> element', async () => {
+ const def = { id: 'dd-no-domain', dataAvailability: 'dd', startDate: '2026-01-01T00:00:00Z' };
+ const promise = fetchGranuleDateRanges(def, ddOpts);
+ const worker = global.Worker.instances[0];
+
+ worker.reply('<Foo><Bar/></Foo>');
+
+ await expect(promise).resolves.toEqual([]);
+ expect(worker.terminate).toHaveBeenCalled();
+ });
+
+ test('resolves [] when dd worker errors', async () => {
+ const def = { id: 'dd-broken', dataAvailability: 'dd', startDate: '2026-01-01T00:00:00Z' };
+ const promise = fetchGranuleDateRanges(def, ddOpts);
+ global.Worker.instances[0].fireError(new Error('dd boom'));
+ await expect(promise).resolves.toEqual([]);
+ });
+
+ test('uses now as endDate when def.endDate is missing', async () => {
+ const def = { id: 'dd-rolling', dataAvailability: 'dd', startDate: '2026-01-01T00:00:00Z' };
+ fetchGranuleDateRanges(def, ddOpts);
+
+ const args = global.Worker.instances[0].postMessage.mock.calls[0][0].args[0];
+ expect(args.endDate).toBeDefined();
+ expect(typeof args.endDate).toBe('string');
+ expect(new Date(args.endDate).getTime()).toBeGreaterThan(Date.now() - 5000);
+ });
+ });
+
+ describe('memoization', () => {
+ test('concurrent calls for the same layer share one worker', async () => {
+ const def = { id: 'memo-layer', cmrAvailability: true };
+
+ const p1 = fetchGranuleDateRanges(def, {});
+ const p2 = fetchGranuleDateRanges(def, {});
+ const p3 = fetchGranuleDateRanges(def, {});
+
+ expect(global.Worker.instances).toHaveLength(1);
+ expect(p1).toBe(p2);
+ expect(p2).toBe(p3);
+
+ const ranges = [['2026-01-01T00:00:00Z', '2026-01-02T00:00:00Z']];
+ global.Worker.instances[0].reply(ranges);
+
+ await expect(p1).resolves.toEqual(ranges);
+ await expect(p2).resolves.toEqual(ranges);
+ });
+
+ test('subsequent calls after resolve do not spawn a new worker', async () => {
+ const def = { id: 'memo-layer-2', cmrAvailability: true };
+
+ const p1 = fetchGranuleDateRanges(def, {});
+ const ranges = [['2026-01-01T00:00:00Z', '2026-01-02T00:00:00Z']];
+ global.Worker.instances[0].reply(ranges);
+ await p1;
+
+ const p2 = fetchGranuleDateRanges(def, {});
+ expect(global.Worker.instances).toHaveLength(1);
+ await expect(p2).resolves.toEqual(ranges);
+ });
+
+ test('memoization is keyed per layer id', async () => {
+ const defA = { id: 'layer-a', cmrAvailability: true };
+ const defB = { id: 'layer-b', cmrAvailability: true };
+
+ fetchGranuleDateRanges(defA, {});
+ fetchGranuleDateRanges(defB, {});
+
+ expect(global.Worker.instances).toHaveLength(2);
+ });
+
+ test('error result is evicted so the next call can retry', async () => {
+ const def = { id: 'memo-error', cmrAvailability: true };
+
+ const p1 = fetchGranuleDateRanges(def, {});
+ global.Worker.instances[0].fireError(new Error('boom'));
+ await p1;
+
+ const p2 = fetchGranuleDateRanges(def, {});
+ expect(global.Worker.instances).toHaveLength(2);
+ global.Worker.instances[1].reply([['2026-01-01T00:00:00Z', '2026-01-02T00:00:00Z']]);
+ await expect(p2).resolves.toEqual([['2026-01-01T00:00:00Z', '2026-01-02T00:00:00Z']]);
+ });
+ });
+
+ describe('invalidateGranuleDateRanges', () => {
+ test('drops the cached promise so the next call respawns', async () => {
+ const def = { id: 'invalidatable', cmrAvailability: true };
+
+ const p1 = fetchGranuleDateRanges(def, {});
+ global.Worker.instances[0].reply([['2026-01-01T00:00:00Z', '2026-01-02T00:00:00Z']]);
+ await p1;
+
+ invalidateGranuleDateRanges(def.id);
+
+ fetchGranuleDateRanges(def, {});
+ expect(global.Worker.instances).toHaveLength(2);
+ });
+ });
+});
diff --git a/web/js/modules/layers/reducers.js b/web/js/modules/layers/reducers.js
index fbe7460f0..77551dd19 100644
--- a/web/js/modules/layers/reducers.js
+++ b/web/js/modules/layers/reducers.js
@@ -6,6 +6,7 @@ import update from 'immutability-helper';
import {
ADD_LAYER,
INIT_SECOND_LAYER_GROUP,
+ SYNC_SECOND_LAYER_GROUP,
REORDER_LAYERS,
TOGGLE_LAYER_VISIBILITY,
TOGGLE_COLLAPSE_OVERLAY_GROUP,
@@ -147,16 +148,19 @@ export function layerReducer(state = initialState, action) {
},
});
- case TOGGLE_COLLAPSE_OVERLAY_GROUP:
+ case TOGGLE_COLLAPSE_OVERLAY_GROUP: {
+ const groupIndex = getGroupIndex();
+ if (groupIndex < 0) return state;
return update(state, {
[compareState]: {
overlayGroups: {
- [getGroupIndex()]: {
+ [groupIndex]: {
collapsed: { $set: action.collapsed },
},
},
},
});
+ }
case INIT_SECOND_LAYER_GROUP:
return {
@@ -164,6 +168,27 @@ export function layerReducer(state = initialState, action) {
activeB: lodashCloneDeep(state.active),
};
+ // Add layers that were added to A after compare was last exited.
+ // Layers missing from B because the user removed them are NOT re-added.
+ case SYNC_SECOND_LAYER_GROUP: {
+ const bLayerIds = new Set(state.activeB.layers.map((l) => l.id));
+ const lastExitIds = new Set(action.lastExitALayerIds || []);
+ const newLayers = state.active.layers.filter(
+ (l) => !bLayerIds.has(l.id) && !lastExitIds.has(l.id),
+ );
+ if (!newLayers.length) return state;
+ return {
+ ...state,
+ activeB: {
+ ...state.activeB,
+ layers: [
+ ...state.activeB.layers,
+ ...lodashCloneDeep(newLayers),
+ ],
+ },
+ };
+ }
+
case TOGGLE_LAYER_VISIBILITY:
if (getLayerIndex() === -1) return state;
return update(state, {
@@ -307,6 +332,7 @@ export function layerReducer(state = initialState, action) {
granuleDateRanges,
} = action;
const layerIndex = getLayerIndex();
+ if (layerIndex < 0) return state;
return update(state, {
[compareState]: {
@@ -434,6 +460,7 @@ export function layerReducer(state = initialState, action) {
tempoDateRanges,
} = action;
const layerIndex = getLayerIndex();
+ if (layerIndex < 0) return state;
return update(state, {
[compareState]: {
diff --git a/web/js/modules/palettes/reducers.js b/web/js/modules/palettes/reducers.js
index 1bc7f31ad..49d4a8a58 100644
--- a/web/js/modules/palettes/reducers.js
+++ b/web/js/modules/palettes/reducers.js
@@ -16,7 +16,7 @@ import {
CLEAR_CUSTOM,
SET_DISABLED_CLASSIFICATION,
} from './constants';
-import { INIT_SECOND_LAYER_GROUP } from '../layers/constants';
+import { INIT_SECOND_LAYER_GROUP, SYNC_SECOND_LAYER_GROUP } from '../layers/constants';
export const defaultPaletteState = {
rendered: {},
@@ -66,6 +66,13 @@ export function paletteReducer(state = defaultPaletteState, action) {
return lodashAssign({}, state, {
activeB: lodashCloneDeep(state.active),
});
+ case SYNC_SECOND_LAYER_GROUP:
+ // Merge A's palette entries into B. B entries take precedence (listed
+ // second) so existing B-side customizations are preserved; new layers
+ // synced from A get A's palette settings as defaults.
+ return lodashAssign({}, state, {
+ activeB: lodashAssign({}, lodashCloneDeep(state.active), lodashCloneDeep(state.activeB)),
+ });
case SET_THRESHOLD_RANGE_AND_SQUASH:
case SET_CUSTOM:
case SET_DISABLED_CLASSIFICATION:
diff --git a/web/js/workers/describe-domains.worker.js b/web/js/workers/describe-domains.worker.js
index b57212976..275fd694e 100644
--- a/web/js/workers/describe-domains.worker.js
+++ b/web/js/workers/describe-domains.worker.js
@@ -131,14 +131,22 @@ function mergeDomains(domains, timeBuffer, keepDateIntervals = false) {
}
// discontinuous, add new range
- if (bufferedStartTime > lastRangeEndTime || keepDateIntervals) {
+ if (bufferedStartTime > lastRangeEndTime) {
+ return [...acc, [makeDateString(startTime), makeDateString(endTime),
+ ...formattedPeriod]];
+ }
+
+ // When keepDateIntervals is true, preserve each interval as a separate
+ // range even if it overlaps — but still skip exact duplicates (handled
+ // by the "within current range" check above).
+ if (keepDateIntervals) {
return [...acc, [makeDateString(startTime), makeDateString(endTime),
...formattedPeriod]];
}
// intersects current range, merge
if (bufferedStartTime <= lastRangeEndTime &&
- bufferedEndTime > lastRangeEndTime && !keepDateIntervals) {
+ bufferedEndTime > lastRangeEndTime) {
return acc.with(-1, [acc.at(-1)[0], makeDateString(endTime)]);
}