Skip to content

Interactive interface for browsing global, full-resolution satellite imagery

WV-4158 Finish implementation of Granules count slider

Victor Gonzalez Leonaa4ddd28bfa6
diff --git a/web/js/components/layer/settings/granule-count-slider.js b/web/js/components/layer/settings/granule-count-slider.js
index 5c7d384cb..3ddc7d6f4 100644
--- a/web/js/components/layer/settings/granule-count-slider.js
+++ b/web/js/components/layer/settings/granule-count-slider.js
@@ -1,8 +1,8 @@
-import { useState } from 'react';
import PropTypes from 'prop-types';
-import { connect } from 'react-redux';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
-import { UncontrolledTooltip } from 'reactstrap';
+import HoverTooltip from '../../util/hover-tooltip';
+import useDebouncedSliderValue from '../../util/use-debounced-slider-value';
+import util from '../../../util/util';
import { DEFAULT_NUM_GRANULES, MIN_GRANULES, MAX_GRANULES } from '../../../modules/layers/constants';
function GranuleCountSlider(props) {
@@ -10,49 +10,43 @@ function GranuleCountSlider(props) {
count,
def,
granuleDates,
- granulePlatform,
+ isMobile,
updateGranuleLayerOptions,
} = props;
- const [granuleCount, setGranuleCount] = useState(count);
-
- const onChange = (val) => {
- updateGranuleLayerOptions(granuleDates, def, val);
- };
+ const [value, onSlide] = useDebouncedSliderValue(
+ count,
+ (val) => updateGranuleLayerOptions(granuleDates, def, val),
+ );
- const satelliteInfo = `Updating granule count for all granules layers associated with the ${granulePlatform} satellite.`;
+ const infoId = `granule-count-info-${util.encodeId(def.id)}`;
return (
<div className="layer-granule-count-select settings-component">
<div className="d-flex">
<h2 className="wv-header">Granule Count</h2>
- <FontAwesomeIcon id="bbox-limit-info" icon="info-circle" className="ms-2" widthAuto />
- <UncontrolledTooltip
- id="center-align-tooltip"
+ <FontAwesomeIcon id={infoId} icon="info-circle" className="ms-2" widthAuto />
+ <HoverTooltip
+ target={infoId}
placement="right"
- target="bbox-limit-info"
- >
- {satelliteInfo}
- </UncontrolledTooltip>
+ isMobile={isMobile}
+ labelText="Number of most recent granules composited together, ending at the selected time."
+ />
</div>
<input
type="range"
className="form-range"
min={MIN_GRANULES}
max={MAX_GRANULES}
- defaultValue={count}
- onChange={(e) => {
- const val = parseInt(e.target.value, 10);
- setGranuleCount(val);
- onChange(val);
- }}
+ step={1}
+ value={value}
+ onChange={(e) => onSlide(parseInt(e.target.value, 10))}
style={{
- '--value-percent': `${((granuleCount - MIN_GRANULES) / (MAX_GRANULES - MIN_GRANULES)) * 100}%`,
+ '--value-percent': `${((value - MIN_GRANULES) / (MAX_GRANULES - MIN_GRANULES)) * 100}%`,
}}
-
/>
<div className="wv-label wv-label-granule-count mt-1">
- {granuleCount}
+ {value === 1 ? '1 granule' : `${value} granules`}
</div>
</div>
);
@@ -65,19 +59,8 @@ GranuleCountSlider.propTypes = {
granuleDates: PropTypes.oneOfType([PropTypes.array, PropTypes.oneOf(['null'])]),
def: PropTypes.oneOfType([PropTypes.object, PropTypes.oneOf(['null'])]),
count: PropTypes.number,
- granulePlatform: PropTypes.string,
+ isMobile: PropTypes.bool,
updateGranuleLayerOptions: PropTypes.func,
};
-const mapStateToProps = (state) => {
- const { layers } = state;
- const { granulePlatform } = layers.active;
-
- return {
- granulePlatform,
- };
-};
-
-export default connect(
- mapStateToProps,
-)(GranuleCountSlider);
+export default GranuleCountSlider;
diff --git a/web/js/components/layer/settings/granule-count-slider.test.js b/web/js/components/layer/settings/granule-count-slider.test.js
index 16bece16b..ed8945bcf 100644
--- a/web/js/components/layer/settings/granule-count-slider.test.js
+++ b/web/js/components/layer/settings/granule-count-slider.test.js
@@ -1,7 +1,8 @@
-import { render, screen, fireEvent } from '@testing-library/react';
+/* eslint-disable react/jsx-props-no-spreading */
+import {
+ render, screen, fireEvent, act,
+} from '@testing-library/react';
import '@testing-library/jest-dom';
-import { Provider } from 'react-redux';
-import configureStore from 'redux-mock-store';
jest.mock('../../../modules/layers/constants', () => ({
DEFAULT_NUM_GRANULES: 10,
@@ -11,108 +12,54 @@ jest.mock('../../../modules/layers/constants', () => ({
jest.mock('@fortawesome/react-fontawesome', () => ({
FontAwesomeIcon: () => <span data-testid="fa-icon" />,
}));
-jest.mock('reactstrap', () => {
- const actual = jest.requireActual('reactstrap');
- return { ...actual, UncontrolledTooltip: () => null };
-});
+jest.mock('../../util/hover-tooltip', () => function MockHoverTooltip() { return null; });
import GranuleCountSlider from './granule-count-slider';
-const mockStore = configureStore([]);
-const store = mockStore({ layers: { active: { granulePlatform: 'Terra' } } });
-
const defaultProps = {
count: 10,
- def: { id: 'MODIS_Terra_CorrRefl_TrueColor' },
+ def: { id: 'VIIRS_NOAA20_CorrectedReflectance_TrueColor_Granule' },
granuleDates: ['2023-01-01', '2023-01-02'],
+ isMobile: false,
updateGranuleLayerOptions: jest.fn(),
};
const renderSlider = (overrides = {}) => {
const props = { ...defaultProps, ...overrides };
- return render(
- <Provider store={store}>
- <GranuleCountSlider
- count={props.count}
- def={props.def}
- granuleDates={props.granuleDates}
- updateGranuleLayerOptions={props.updateGranuleLayerOptions}
- />
- </Provider>,
- );
+ return render(<GranuleCountSlider {...props} />);
};
beforeEach(() => {
jest.clearAllMocks();
+ jest.useFakeTimers();
});
-describe('GranuleCountSlider', () => {
- describe('layout', () => {
- it('renders the Granule Count heading', () => {
- renderSlider();
- expect(screen.getByText('Granule Count')).toBeInTheDocument();
- });
-
- it('renders the info icon', () => {
- renderSlider();
- expect(screen.getByTestId('fa-icon')).toBeInTheDocument();
- });
-
- it('renders the range input', () => {
- renderSlider();
- expect(screen.getByRole('slider')).toBeInTheDocument();
- });
-
- it('displays the current count as the label', () => {
- renderSlider({ count: 15 });
- expect(screen.getByText('15')).toBeInTheDocument();
- });
- });
-
- describe('range input attributes', () => {
- it('sets min to MIN_GRANULES (1)', () => {
- renderSlider();
- expect(screen.getByRole('slider')).toHaveAttribute('min', '1');
- });
-
- it('sets max to MAX_GRANULES (30)', () => {
- renderSlider();
- expect(screen.getByRole('slider')).toHaveAttribute('max', '30');
- });
+afterEach(() => {
+ jest.runOnlyPendingTimers();
+ jest.useRealTimers();
+});
- it('sets defaultValue to the count prop', () => {
- renderSlider({ count: 7 });
- expect(screen.getByRole('slider')).toHaveAttribute('value', '7');
- });
+describe('GranuleCountSlider', () => {
+ it('follows external count updates (e.g. from the sidebar row slider)', () => {
+ const { rerender } = renderSlider({ count: 7 });
+ rerender(<GranuleCountSlider {...defaultProps} count={12} />);
+ expect(screen.getByRole('slider')).toHaveAttribute('value', '12');
});
- describe('onChange', () => {
- it('updates the displayed count label when slider changes', () => {
- renderSlider({ count: 10 });
- fireEvent.change(screen.getByRole('slider'), { target: { value: '20' } });
- expect(screen.getByText('20')).toBeInTheDocument();
- });
-
- it('calls updateGranuleLayerOptions with new value on change', () => {
- const updateGranuleLayerOptions = jest.fn();
- renderSlider({ updateGranuleLayerOptions });
- fireEvent.change(screen.getByRole('slider'), { target: { value: '18' } });
- expect(updateGranuleLayerOptions).toHaveBeenCalledWith(
- defaultProps.granuleDates,
- defaultProps.def,
- 18,
- );
- });
-
- it('calls updateGranuleLayerOptions with parsed integer value', () => {
- const updateGranuleLayerOptions = jest.fn();
- renderSlider({ updateGranuleLayerOptions });
- fireEvent.change(screen.getByRole('slider'), { target: { value: '5' } });
- expect(updateGranuleLayerOptions).toHaveBeenCalledWith(
- expect.anything(),
- expect.anything(),
- 5,
- );
+ it('debounces the call to updateGranuleLayerOptions', () => {
+ const updateGranuleLayerOptions = jest.fn();
+ renderSlider({ updateGranuleLayerOptions });
+ fireEvent.change(screen.getByRole('slider'), { target: { value: '5' } });
+ fireEvent.change(screen.getByRole('slider'), { target: { value: '18' } });
+ expect(updateGranuleLayerOptions).not.toHaveBeenCalled();
+ act(() => {
+ jest.runAllTimers();
});
+ expect(updateGranuleLayerOptions).toHaveBeenCalledTimes(1);
+ expect(updateGranuleLayerOptions).toHaveBeenCalledWith(
+ defaultProps.granuleDates,
+ defaultProps.def,
+ 18,
+ );
});
});
diff --git a/web/js/components/layer/settings/layer-settings.js b/web/js/components/layer/settings/layer-settings.js
index 03c2ad19c..88080e52a 100644
--- a/web/js/components/layer/settings/layer-settings.js
+++ b/web/js/components/layer/settings/layer-settings.js
@@ -56,6 +56,7 @@ import {
setOpacity as setOpacityAction,
updateDayCount as updateDayCountAction,
} from '../../../modules/layers/actions';
+import { DEFAULT_NUM_GRANULES } from '../../../modules/layers/constants';
import ClassificationToggle from './classification-toggle';
function LayerSettings(props) {
@@ -274,16 +275,17 @@ function LayerSettings(props) {
*/
const renderGranuleSettings = () => {
const { count, dates, granulePlatform } = granuleOptions;
- return dates
+ return count
? (
<>
<GranuleCountSlider
def={layer}
count={count}
granuleDates={dates}
+ isMobile={isMobile}
updateGranuleLayerOptions={updateGranuleLayerOptions}
/>
- {allowGranuleReorder && (
+ {allowGranuleReorder && dates && (
<GranuleLayerDateList
def={layer}
screenHeight={screenHeight}
@@ -350,12 +352,11 @@ function mapStateToProps(state, ownProps) {
const groupName = compare.activeString;
const globalTemperatureUnit = lodashGet(ownProps, 'layer.disableUnitConversion') ? '' : settings.globalTemperatureUnit;
- const granuleState = getGranuleLayer(state, ownProps.layer.id);
const granuleOptions = {};
- if (granuleState) {
- const { dates, count } = granuleState;
- granuleOptions.dates = dates;
- granuleOptions.count = count || 20;
+ if (ownProps.layer.type === 'granule') {
+ const granuleState = getGranuleLayer(state, ownProps.layer.id) || {};
+ granuleOptions.dates = granuleState.dates;
+ granuleOptions.count = granuleState.count || ownProps.layer.count || DEFAULT_NUM_GRANULES;
granuleOptions.granulePlatform = getGranulePlatform(state);
}
diff --git a/web/js/components/layer/settings/layer-settings.test.js b/web/js/components/layer/settings/layer-settings.test.js
index be6221542..67a1a460a 100644
--- a/web/js/components/layer/settings/layer-settings.test.js
+++ b/web/js/components/layer/settings/layer-settings.test.js
@@ -261,23 +261,25 @@ describe('LayerSettings', () => {
});
describe('granule settings', () => {
- it('renders GranuleCountSlider when granuleOptions has dates', () => {
+ const granuleLayer = { ...standardLayer, type: 'granule' };
+
+ it('renders GranuleCountSlider for a granule layer with granule state', () => {
const { getGranuleLayer } = require('../../../modules/layers/selectors');
getGranuleLayer.mockReturnValue({ dates: ['2023-01-01'], count: 5 });
- renderSettings(standardLayer);
+ renderSettings(granuleLayer);
expect(screen.getByTestId('granule-count-slider')).toBeInTheDocument();
});
- it('does not render GranuleCountSlider when getGranuleLayer returns null', () => {
+ it('renders GranuleCountSlider before the granule layer has been built', () => {
const { getGranuleLayer } = require('../../../modules/layers/selectors');
getGranuleLayer.mockReturnValue(null);
- renderSettings();
- expect(screen.queryByTestId('granule-count-slider')).not.toBeInTheDocument();
+ renderSettings(granuleLayer);
+ expect(screen.getByTestId('granule-count-slider')).toBeInTheDocument();
});
- it('does not render GranuleCountSlider when granule dates are null', () => {
+ it('does not render GranuleCountSlider for non-granule layers', () => {
const { getGranuleLayer } = require('../../../modules/layers/selectors');
- getGranuleLayer.mockReturnValue({ dates: null, count: 5 });
+ getGranuleLayer.mockReturnValue({ dates: ['2023-01-01'], count: 5 });
renderSettings(standardLayer);
expect(screen.queryByTestId('granule-count-slider')).not.toBeInTheDocument();
});
@@ -287,9 +289,18 @@ describe('LayerSettings', () => {
getItem.mockReturnValue('true');
const { getGranuleLayer } = require('../../../modules/layers/selectors');
getGranuleLayer.mockReturnValue({ dates: ['2023-01-01'], count: 5 });
- renderSettings(standardLayer);
+ renderSettings(granuleLayer);
expect(screen.getByTestId('granule-date-list')).toBeInTheDocument();
});
+
+ it('does not render GranuleDateList until granule dates are available', () => {
+ const { getItem } = require('../../../util/local-storage');
+ getItem.mockReturnValue('true');
+ const { getGranuleLayer } = require('../../../modules/layers/selectors');
+ getGranuleLayer.mockReturnValue(null);
+ renderSettings(granuleLayer);
+ expect(screen.queryByTestId('granule-date-list')).not.toBeInTheDocument();
+ });
});
describe('renderCustomPalettes — single palette', () => {
diff --git a/web/js/containers/sidebar/layer-row.js b/web/js/containers/sidebar/layer-row.js
index 70851a9cb..bd725a2c4 100644
--- a/web/js/containers/sidebar/layer-row.js
+++ b/web/js/containers/sidebar/layer-row.js
@@ -37,7 +37,7 @@ import {
getActiveLayers, makeGetDescription, getCollections,
getMaxDayRange, getLayerDayCount, getGranuleLayer,
} from '../../modules/layers/selectors';
-import { MAX_GRANULES, DEFAULT_DAY_COUNT } from '../../modules/layers/constants';
+import { MAX_GRANULES, DEFAULT_NUM_GRANULES, DEFAULT_DAY_COUNT } from '../../modules/layers/constants';
import { formatDailyDate, formatSubdailyDate } from '../../mapUI/components/kiosk/tile-measurement/utils/date-util';
import { coverageDateFormatter } from '../../modules/date/util';
import { SIDEBAR_LAYER_HOVER, MAP_RUNNING_DATA } from '../../util/constants';
@@ -864,7 +864,9 @@ const makeMapStateToProps = () => {
cmrBaseUrl,
maxDayRange,
dayCount,
- granuleCount: granuleState ? granuleState.count : null,
+ granuleCount: layer.type === 'granule'
+ ? (granuleState?.count || layer.count || DEFAULT_NUM_GRANULES)
+ : null,
granuleDates: granuleState ? granuleState.dates : null,
};
};
diff --git a/web/js/containers/sidebar/layer-row.test.js b/web/js/containers/sidebar/layer-row.test.js
index a3c97159e..81398bcc7 100644
--- a/web/js/containers/sidebar/layer-row.test.js
+++ b/web/js/containers/sidebar/layer-row.test.js
@@ -966,6 +966,17 @@ describe('mapStateToProps', () => {
expect(msp(makeState({ screenSize: { isMobileDevice: true } }), ownProps).isMobile).toBe(true);
});
+ describe('granuleCount', () => {
+ const { getGranuleLayer } = jest.requireMock('../../modules/layers/selectors');
+ const granuleOwnProps = (layer) => ({ ...ownProps, layer: { ...ownProps.layer, type: 'granule', ...layer } });
+
+ it('defaults to DEFAULT_NUM_GRANULES before the granule layer is built', () => {
+ getGranuleLayer.mockReturnValueOnce(null);
+ const msp = capturedMakeMapStateToProps();
+ expect(msp(makeState(), granuleOwnProps()).granuleCount).toBe(10);
+ });
+ });
+
it('maps isEmbedModeActive from embed', () => {
const msp = capturedMakeMapStateToProps();
expect(msp(makeState({
diff --git a/web/js/map/granule/granule-layer-builder.js b/web/js/map/granule/granule-layer-builder.js
index 87f25e99d..4ac04fbea 100644
--- a/web/js/map/granule/granule-layer-builder.js
+++ b/web/js/map/granule/granule-layer-builder.js
@@ -228,11 +228,12 @@ export default function granuleLayerBuilder(cache, store, createLayerWMTS) {
return { visibleGranules, invisibleGranules };
};
- const getGranuleAttributes = async (def, options) => {
+ const getGranuleAttributes = async (def, options, group) => {
const state = store.getState();
const { proj: { selected: { crs } } } = state;
const { granuleCount, date } = options;
- const { count: currentCount } = getGranuleLayer(state, def.id) || {};
+ // Read the count for the compare side being built, not the side being edited
+ const { count: currentCount } = getGranuleLayer(state, def.id, group) || {};
const count = currentCount || granuleCount || def.count || DEFAULT_NUM_GRANULES;
// Use cached ranges if they cover the selected date; re-fetch otherwise.
@@ -288,7 +289,7 @@ export default function granuleLayerBuilder(cache, store, createLayerWMTS) {
return granuleLayer;
}
- const granuleAttributes = await getGranuleAttributes(def, options);
+ const granuleAttributes = await getGranuleAttributes(def, options, group);
const { visibleGranules, invisibleGranules } = granuleAttributes;
const shouldShift = def.shiftadjacentdays ?? true; // defaults to true
const shiftedVisibleGranules = shouldShift
diff --git a/web/js/map/granule/granule-layer-builder.test.js b/web/js/map/granule/granule-layer-builder.test.js
index 3b20e38ef..b9a247bc9 100644
--- a/web/js/map/granule/granule-layer-builder.test.js
+++ b/web/js/map/granule/granule-layer-builder.test.js
@@ -106,6 +106,29 @@ describe('granule layer builder', () => {
expect(granuleLayer.get('layerId')).toBe(`${granuleLayerDef.id}-${options.group}`);
});
+ it('uses the granule count of the compare side being built', async () => {
+ const state = fixtures.getState();
+ const sideWithCount = (count) => ({
+ granuleLayers: { [granuleLayerDef.id]: { count } },
+ });
+ store = mockStore({
+ ...state,
+ compare: { ...state.compare, activeString: 'active' },
+ layers: {
+ ...state.layers,
+ active: { ...state.layers.active, ...sideWithCount(7) },
+ activeB: { ...state.layers.activeB, ...sideWithCount(3) },
+ },
+ });
+ const { createLayerWMTS } = layerbuilder(config, cache, store);
+ const builder = granuleLayerBuilder(cache, store, createLayerWMTS);
+ const { options, attributes } = buildOptionsAndAttributes(IN_RANGE_DATE, { group: 'activeB' });
+
+ const granuleLayer = await builder.getGranuleLayer(granuleLayerDef, attributes, options);
+
+ expect(granuleLayer.wv.count).toBe(3);
+ });
+
it('attaches wv.visibleGranules and wv.invisibleGranules arrays to the layer', async () => {
const { options, attributes } = buildOptionsAndAttributes(IN_RANGE_DATE);
diff --git a/web/js/modules/layers/actions.js b/web/js/modules/layers/actions.js
index 5d6e9f4d7..015ff1d83 100644
--- a/web/js/modules/layers/actions.js
+++ b/web/js/modules/layers/actions.js
@@ -10,7 +10,6 @@ import {
activateLayersForEventCategory as activateLayersForEventCategorySelector,
findEventLayers,
getGranuleLayer,
- getGranuleLayersOfActivePlatform,
getActiveGranuleLayers,
} from './selectors';
import {
@@ -308,7 +307,8 @@ export function showLayers(layers) {
function updateGranuleLayerGeometry(layer, dates, granuleGeometry) {
return (dispatch, getState) => {
const { compare, layers } = getState();
- const { activeString } = compare;
+ // Write to the compare side the layer was built for
+ const activeString = layer.wv.group || compare.activeString;
const { id, count } = layer.wv;
const layerDef = layers.layerConfig[id];
const granulePlatform = `${layerDef.subtitle}`;
@@ -334,7 +334,9 @@ function updateGranuleLayerGeometry(layer, dates, granuleGeometry) {
function addGranuleLayerDates(layer, granuleFootprints, granulePlatform) {
return (dispatch, getState) => {
- const { compare: { activeString } } = getState();
+ const { compare } = getState();
+ // Write to the compare side the layer was built for
+ const activeString = layer.wv.group || compare.activeString;
const { id, granuleDates, count } = layer.wv;
dispatch({
@@ -360,7 +362,7 @@ export function updateGranuleLayerState(layer) {
const isMostRecentDateOutOfRange = new Date(mostRecentGranuleDate) > new Date(endDate);
const updatedDates = isMostRecentDateOutOfRange ? [] : reorderedGranules || granuleDates;
const granuleFootprints = getGranuleFootprints(layer);
- const existingLayer = getGranuleLayer(state, id);
+ const existingLayer = getGranuleLayer(state, id, layer.wv.group);
if (existingLayer) {
dispatch(updateGranuleLayerGeometry(layer, updatedDates, granuleFootprints));
@@ -412,21 +414,13 @@ export function addGranuleDateRanges(layer, granuleDateRanges) {
export function updateGranuleLayerOptions(dates, def, count) {
return (dispatch, getState) => {
- const state = getState();
- const { activeString } = state.compare;
-
- const granulePlatform = def.subtitle;
- const activeGranuleLayers = getActiveGranuleLayers(state);
- const platformLayers = getGranuleLayersOfActivePlatform(granulePlatform, activeGranuleLayers);
-
- platformLayers.forEach((layer) => {
- dispatch({
- type: UPDATE_GRANULE_LAYER_OPTIONS,
- id: layer,
- activeKey: activeString,
- dates,
- count,
- });
+ const { activeString } = getState().compare;
+ dispatch({
+ type: UPDATE_GRANULE_LAYER_OPTIONS,
+ id: def.id,
+ activeKey: activeString,
+ dates,
+ count,
});
};
}
diff --git a/web/js/modules/layers/actions.test.js b/web/js/modules/layers/actions.test.js
index 4e425feef..d322c5f23 100644
--- a/web/js/modules/layers/actions.test.js
+++ b/web/js/modules/layers/actions.test.js
@@ -575,9 +575,9 @@ describe('Layer actions', () => {
});
});
- test('UPDATE_GRANULE_LAYER_OPTIONS dispatches for each matching platform layer [layers-action-update-granule-layer-options]', () => {
+ test('UPDATE_GRANULE_LAYER_OPTIONS dispatches only for the given layer [layers-action-update-granule-layer-options]', () => {
const dates = ['2021-01-01', '2021-01-02'];
- const def = { subtitle: 'Aqua / MODIS' };
+ const def = { id: 'aqua-aod', subtitle: 'Aqua / MODIS' };
const count = 20;
const granuleState = {
...getState(layers),
@@ -585,24 +585,26 @@ describe('Layer actions', () => {
...getState(layers).layers,
active: {
...getState(layers).layers.active,
- granuleLayers: { 'aqua-aod': { count, dates, granulePlatform: 'Aqua / MODIS' } },
+ granuleLayers: {
+ 'aqua-aod': { count, dates, granulePlatform: 'Aqua / MODIS' },
+ 'aqua-cr': { count, dates, granulePlatform: 'Aqua / MODIS' },
+ },
granulePlatform: 'Aqua / MODIS',
},
},
};
const granuleStore = mockStore(granuleState);
granuleStore.dispatch(updateGranuleLayerOptions(dates, def, count));
- const actions = granuleStore.getActions();
- expect(actions.length).toBeGreaterThanOrEqual(1);
- actions.forEach((action) => {
- expect(action.type).toBe(LAYER_CONSTANTS.UPDATE_GRANULE_LAYER_OPTIONS);
- expect(action.dates).toEqual(dates);
- expect(action.count).toBe(count);
- expect(action.activeKey).toBe('active');
- });
+ expect(granuleStore.getActions()).toEqual([{
+ type: LAYER_CONSTANTS.UPDATE_GRANULE_LAYER_OPTIONS,
+ id: 'aqua-aod',
+ activeKey: 'active',
+ dates,
+ count,
+ }]);
});
- test('UPDATE_GRANULE_LAYER_OPTIONS dispatches no actions when no matching platform layers [layers-action-update-granule-layer-options-no-match]', () => {
+ test('UPDATE_GRANULE_LAYER_OPTIONS dispatches before the layer has granule state [layers-action-update-granule-layer-options-no-state]', () => {
const granuleState = {
...getState(layers),
layers: {
@@ -610,13 +612,15 @@ describe('Layer actions', () => {
active: {
...getState(layers).layers.active,
granuleLayers: {},
- granulePlatform: 'Aqua / MODIS',
},
},
};
const granuleStore = mockStore(granuleState);
- granuleStore.dispatch(updateGranuleLayerOptions(['2021-01-01'], { subtitle: 'Terra / MODIS' }, 10));
- expect(granuleStore.getActions()).toHaveLength(0);
+ granuleStore.dispatch(updateGranuleLayerOptions(null, { id: 'terra-cr', subtitle: 'Terra / MODIS' }, 12));
+ const actions = granuleStore.getActions();
+ expect(actions).toHaveLength(1);
+ expect(actions[0].id).toBe('terra-cr');
+ expect(actions[0].count).toBe(12);
});
test('updateGranuleLayerState dispatches only ADD_GRANULE_LAYER_DATES when no existing layer [layers-action-update-granule-layer-state-new]', () => {
@@ -647,6 +651,24 @@ describe('Layer actions', () => {
});
});
+ test('updateGranuleLayerState writes to the compare side the layer was built for [layers-action-update-granule-layer-state-group]', () => {
+ const mockLayer = {
+ wv: {
+ id: 'aqua-aod',
+ group: 'activeB',
+ count: 3,
+ granuleDates: ['2021-01-03T00:00:00Z'],
+ reorderedGranules: null,
+ def: { endDate: '2030-01-01T00:00:00Z', subtitle: 'Aqua / MODIS' },
+ },
+ };
+ getGranuleFootprints.mockReturnValue({});
+ getGranuleLayer.mockReturnValue(null);
+ store.dispatch(updateGranuleLayerState(mockLayer));
+ expect(getGranuleLayer).toHaveBeenCalledWith(expect.anything(), 'aqua-aod', 'activeB');
+ expect(store.getActions()[0].activeKey).toBe('activeB');
+ });
+
test('updateGranuleLayerState dispatches UPDATE_GRANULE_LAYER_GEOMETRY and ADD_GRANULE_LAYER_DATES when layer exists [layers-action-update-granule-layer-state-existing]', () => {
const granuleDates = ['2021-01-03T00:00:00Z'];
const mockFootprints = { type: 'FeatureCollection', features: [] };
diff --git a/web/js/modules/layers/reducers.js b/web/js/modules/layers/reducers.js
index 66788150c..961f4aed5 100644
--- a/web/js/modules/layers/reducers.js
+++ b/web/js/modules/layers/reducers.js
@@ -1,6 +1,7 @@
import {
cloneDeep as lodashCloneDeep,
findIndex as lodashFindIndex,
+ omitBy as lodashOmitBy,
} from 'lodash';
import update from 'immutability-helper';
import {
@@ -169,23 +170,30 @@ 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.
+ // Apply changes made to A while compare was off: add layers added to A,
+ // and remove layers removed from A. Layers the user removed from or
+ // added to B during compare are left alone.
case SYNC_SECOND_LAYER_GROUP: {
+ const aLayerIds = new Set(state.active.layers.map((l) => l.id));
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;
+ const isRemovedFromA = (id) => lastExitIds.has(id) && !aLayerIds.has(id);
+ const keptLayers = state.activeB.layers.filter((l) => !isRemovedFromA(l.id));
+ if (!newLayers.length && keptLayers.length === state.activeB.layers.length) return state;
+ const layers = [...keptLayers, ...lodashCloneDeep(newLayers)];
return {
...state,
activeB: {
...state.activeB,
- layers: [
- ...state.activeB.layers,
- ...lodashCloneDeep(newLayers),
- ],
+ layers,
+ overlayGroups: getOverlayGroups(layers, state.activeB.overlayGroups),
+ granuleLayers: lodashOmitBy(
+ state.activeB.granuleLayers,
+ (_granuleLayer, id) => isRemovedFromA(id),
+ ),
},
};
}
@@ -365,11 +373,16 @@ export function layerReducer(state = initialState, action) {
id, activeKey, count, dates,
} = action;
+ // The entry may not exist yet if the map hasn't built this layer
return update(state, {
[activeKey]: {
granuleLayers: {
[id]: {
- $merge: { count, dates },
+ $apply: (granuleLayer = {}) => ({
+ ...granuleLayer,
+ count,
+ dates: dates || granuleLayer.dates,
+ }),
},
},
},
diff --git a/web/js/modules/layers/reducers.test.js b/web/js/modules/layers/reducers.test.js
index 1295f1a01..0ea26e8eb 100644
--- a/web/js/modules/layers/reducers.test.js
+++ b/web/js/modules/layers/reducers.test.js
@@ -364,6 +364,41 @@ describe('layer Reducer tests', () => {
expect(bIds).toContain('terra-cr');
});
+ test('SYNC_SECOND_LAYER_GROUP removes layers that were removed from A while compare was off [layers-reducer-sync-second-layer-group-removes-layers]', () => {
+ const removedLayer = { id: 'granule-cr', group: 'overlays', layergroup: 'Granules' };
+ const stateWithB = {
+ ...initialState,
+ activeB: {
+ ...initialState.activeB,
+ layers: [removedLayer, ...initialLayers],
+ granuleLayers: { 'granule-cr': { count: 10 } },
+ },
+ };
+ const response = layerReducer(stateWithB, {
+ type: SYNC_SECOND_LAYER_GROUP,
+ lastExitALayerIds: ['granule-cr', 'aqua-cr', 'terra-cr'],
+ });
+ expect(response.activeB.layers.map((l) => l.id)).not.toContain('granule-cr');
+ expect(response.activeB.granuleLayers).toEqual({});
+ expect(response.activeB.overlayGroups.map((g) => g.groupName)).not.toContain('Granules');
+ });
+
+ test('SYNC_SECOND_LAYER_GROUP keeps layers added to B during compare [layers-reducer-sync-second-layer-group-keeps-b-layers]', () => {
+ const bOnlyLayer = { id: 'b-only', group: 'overlays', layergroup: 'Other' };
+ const stateWithB = {
+ ...initialState,
+ activeB: {
+ ...initialState.activeB,
+ layers: [bOnlyLayer, ...initialLayers],
+ },
+ };
+ const response = layerReducer(stateWithB, {
+ type: SYNC_SECOND_LAYER_GROUP,
+ lastExitALayerIds: ['aqua-cr', 'terra-cr'],
+ });
+ expect(response.activeB.layers.map((l) => l.id)).toContain('b-only');
+ });
+
test('ADD_LAYERS_FOR_EVENT sets eventLayers when provided [layers-reducer-add-layer-for-event-with-event-layers]', () => {
const mockEventLayers = ['layer-event-1'];
const response = layerReducer(initialState, {
@@ -493,6 +528,36 @@ describe('layer Reducer tests', () => {
expect(response.active.granuleLayers['terra-cr'].dates).toEqual(newDates);
});
+ test('UPDATE_GRANULE_LAYER_OPTIONS creates the granule layer entry when missing [layers-reducer-update-granule-layer-options-missing]', () => {
+ const response = layerReducer(initialState, {
+ type: UPDATE_GRANULE_LAYER_OPTIONS,
+ id: 'terra-cr',
+ activeKey: 'active',
+ count: 12,
+ dates: null,
+ });
+ expect(response.active.granuleLayers['terra-cr'].count).toEqual(12);
+ });
+
+ test('UPDATE_GRANULE_LAYER_OPTIONS keeps existing dates when none are passed [layers-reducer-update-granule-layer-options-keep-dates]', () => {
+ const dates = ['2022-05-01'];
+ const initialWithGranule = update(initialState, {
+ active: {
+ granuleLayers: {
+ $merge: { 'terra-cr': { dates, count: 10 } },
+ },
+ },
+ });
+ const response = layerReducer(initialWithGranule, {
+ type: UPDATE_GRANULE_LAYER_OPTIONS,
+ id: 'terra-cr',
+ activeKey: 'active',
+ count: 3,
+ dates: null,
+ });
+ expect(response.active.granuleLayers['terra-cr']).toEqual({ dates, count: 3 });
+ });
+
test('UPDATE_GRANULE_LAYER_GEOMETRY updates geometry and footprints for granule layer [layers-reducer-update-granule-layer-geometry]', () => {
const initialWithGranule = update(initialState, {
active: {
diff --git a/web/js/modules/layers/selectors.js b/web/js/modules/layers/selectors.js
index cc4c80b25..e4c3b451d 100644
--- a/web/js/modules/layers/selectors.js
+++ b/web/js/modules/layers/selectors.js
@@ -242,17 +242,6 @@ export const getActiveGranuleFootPrints = (state) => {
return isActiveGranuleVisible.length && granuleLayers ? granuleFootprints : {};
};
-export const getGranuleLayersOfActivePlatform = (platform, activeLayers) => {
- const activeLayersArray = Object.entries(activeLayers);
- const platformLayers = [];
- activeLayersArray.forEach(([key, value]) => {
- if (value.granulePlatform === platform) {
- platformLayers.push(key);
- }
- });
- return platformLayers;
-};
-
/**
* Return a map of active layers where key is layer id
*/
diff --git a/web/js/modules/layers/util.js b/web/js/modules/layers/util.js
index 8318a4b28..4079ba14e 100644
--- a/web/js/modules/layers/util.js
+++ b/web/js/modules/layers/util.js
@@ -24,7 +24,7 @@ import { getPaletteAttributeArray } from '../palettes/util';
import { getVectorStyleAttributeArray } from '../vector-styles/util';
import util from '../../util/util';
import { parseDate } from '../date/util';
-import { DEFAULT_DAY_COUNT, MIN_DAY_COUNT, MAX_DAY_COUNT } from './constants';
+import { DEFAULT_DAY_COUNT, MIN_DAY_COUNT, MAX_DAY_COUNT, DEFAULT_NUM_GRANULES } from './constants';
/**
* Given a layer definition, returns formatted string
@@ -912,6 +912,15 @@ export function serializeLayers(layers, state, groupName) {
value: def.dayCount,
});
}
+ if (def.type === 'granule') {
+ const { count } = getGranuleLayer(state, def.id, groupName) || {};
+ if (count && count !== DEFAULT_NUM_GRANULES) {
+ item.attributes.push({
+ id: 'count',
+ value: count,
+ });
+ }
+ }
if (def.palette &&
(def.custom || def.min || def.max || def.squash || def.noclip || def.disabled ||
(palettes[def.id] && palettes[def.id].maps && palettes[def.id].maps.length > 1))) {
@@ -931,14 +940,6 @@ export function serializeLayers(layers, state, groupName) {
item.attributes = vectorStyleAttributeArray.length
? item.attributes.concat(vectorStyleAttributeArray)
: item.attributes;
- } else if (def.type === 'granule') {
- const granuleLayer = getGranuleLayer(state, def.id);
- if (granuleLayer) {
- const { count } = granuleLayer;
- item.attributes = count !== 20
- ? item.attributes.concat({ id: 'count', value: count })
- : item.attributes;
- }
}
return util.appendAttributesForURL(item);
diff --git a/web/js/modules/layers/util.test.js b/web/js/modules/layers/util.test.js
index 62fbb89d4..b235be438 100644
--- a/web/js/modules/layers/util.test.js
+++ b/web/js/modules/layers/util.test.js
@@ -159,6 +159,31 @@ describe('multi-day aggregation permalink', () => {
});
});
+describe('granule count permalink', () => {
+ const getGranuleState = (granuleLayers) => ({
+ palettes: {
+ active: {},
+ rendered: config.palettes.rendered,
+ custom: config.palettes.custom,
+ },
+ config,
+ layers: { active: { granuleLayers } },
+ });
+ const layer = {
+ id: 'terra-aod', type: 'granule', visible: true, opacity: 1,
+ };
+
+ test('serializes count when it differs from the default', () => {
+ const state = getGranuleState({ 'terra-aod': { count: 12 } });
+ expect(serializeLayers([layer], state, 'active')[0]).toBe('terra-aod(count=12)');
+ });
+
+ test('omits count at the default value of 10', () => {
+ const state = getGranuleState({ 'terra-aod': { count: 10 } });
+ expect(serializeLayers([layer], state, 'active')[0]).toBe('terra-aod');
+ });
+});
+
// Permalink 1.0
describe('permalink 1.0', () => {
beforeEach(() => {