Skip to content

Interactive interface for browsing global, full-resolution satellite imagery

Convert PaletteThreshold and TimelineRangeSelector from class to functional components (#6847)

vicgonzalez2595aad4fe05f9
diff --git a/web/js/components/layer/settings/palette-threshold.js b/web/js/components/layer/settings/palette-threshold.js
index dc3a115e9..77ea5f079 100644
--- a/web/js/components/layer/settings/palette-threshold.js
+++ b/web/js/components/layer/settings/palette-threshold.js
@@ -1,4 +1,4 @@
-import React from 'react';
+import { useState, useEffect, useRef } from 'react';
import PropTypes from 'prop-types';
import lodashDebounce from 'lodash/debounce';
import Checkbox from '../../util/checkbox';
@@ -8,40 +8,38 @@ import {
const thumbsize = 26;
-class PaletteThreshold extends React.Component {
- constructor(props) {
- super(props);
- const {
- start, end, squashed, noclipped,
- } = props;
- this.state = {
- start,
- end,
- squashed,
- noclipped,
- avg: Math.round((start + end) / 2),
- sliderWidth: 264,
- };
- this.debounceSetRange = lodashDebounce(props.setRange, 300);
- this.updateSquashOrNoClip = this.updateSquashOrNoClip.bind(this);
- this.updateThreshold = this.updateThreshold.bind(this);
- this.slider = React.createRef();
- }
-
- componentDidUpdate() {
- const { sliderWidth } = this.state;
- if (sliderWidth !== this.slider.current.offsetWidth && this.slider.current.offsetWidth > 0) {
- this.setState({ sliderWidth: this.slider.current.offsetWidth });
+const PaletteThreshold = ({
+ start: startProp,
+ end: endProp,
+ squashed: squashedProp,
+ noclipped: noclippedProp,
+ setRange,
+ layerId,
+ index,
+ groupName,
+ palette,
+ legend,
+ min,
+ max,
+ globalTemperatureUnit,
+}) => {
+ const [start, setStart] = useState(startProp);
+ const [end, setEnd] = useState(endProp);
+ const [squashed, setSquashed] = useState(squashedProp);
+ const [noclipped, setNoclipped] = useState(noclippedProp);
+ const [avg, setAvg] = useState(Math.round((startProp + endProp) / 2));
+ const [sliderWidth, setSliderWidth] = useState(264);
+
+ const sliderRef = useRef(null);
+ const debouncedSetRange = useRef(lodashDebounce(setRange, 300)).current;
+
+ useEffect(() => {
+ if (sliderRef.current?.offsetWidth > 0 && sliderRef.current.offsetWidth !== sliderWidth) {
+ setSliderWidth(sliderRef.current.offsetWidth);
}
- }
+ });
- updateSquashOrNoClip(type) {
- const {
- setRange, layerId, index, groupName, palette, legend,
- } = this.props;
- const {
- start, end, squashed, noclipped,
- } = this.state;
+ function updateSquashOrNoClip(type) {
const isSquashed = type === 'squash' ? !squashed : squashed;
const isNoClipped = type === 'noclip' ? !noclipped : noclipped;
const startIndex = legend.refs[start];
@@ -57,58 +55,41 @@ class PaletteThreshold extends React.Component {
groupName,
);
if (type === 'squash') {
- this.setState({ squashed: isSquashed });
+ setSquashed(isSquashed);
} else {
- this.setState({ noclipped: isNoClipped });
+ setNoclipped(isNoClipped);
}
}
- /**
- * Update threshold values
- * @param {Array} thresholdArray | Array of start/end indexes for colormap
- */
- updateThreshold(thresholdArray) {
- const {
- layerId, index, groupName, palette, legend,
- } = this.props;
- const {
- start, end, squashed, noclipped,
- } = this.state;
+ function updateThreshold(thresholdArray) {
const newStart = parseInt(thresholdArray[0], 10);
const newEnd = parseInt(thresholdArray[1], 10);
const startRef = legend.refs[newStart];
const endRef = legend.refs[newEnd];
const newAvg = Math.round((newStart + newEnd) / 2);
- // Update local state on every range-selector change but debounce threshold model update
if (newStart !== start && newEnd !== end) {
- this.setState({
- start: newStart,
- end: newEnd,
- avg: newAvg,
- });
+ setStart(newStart);
+ setEnd(newEnd);
+ setAvg(newAvg);
} else if (newStart !== start) {
- this.setState({
- start: newStart,
- avg: newAvg,
- });
+ setStart(newStart);
+ setAvg(newAvg);
} else if (newEnd !== end) {
- this.setState({
- end: newEnd,
- avg: newAvg,
- });
+ setEnd(newEnd);
+ setAvg(newAvg);
} else {
return;
}
const { entries: { refs } } = palette;
- const min = parseFloat(refs.indexOf(startRef));
- const max = parseFloat(refs.lastIndexOf(endRef));
+ const minVal = parseFloat(refs.indexOf(startRef));
+ const maxVal = parseFloat(refs.lastIndexOf(endRef));
- this.debounceSetRange(
+ debouncedSetRange(
layerId,
- min,
- max,
+ minVal,
+ maxVal,
squashed,
noclipped,
index,
@@ -116,128 +97,117 @@ class PaletteThreshold extends React.Component {
);
}
- updateStartThreshold(value) {
- const { end } = this.state;
+ function updateStartThreshold(value) {
const clampedValue = Math.min(value, end - 1);
- this.updateThreshold([clampedValue, end]);
+ updateThreshold([clampedValue, end]);
}
- updateEndThreshold(value) {
- const { start } = this.state;
+ function updateEndThreshold(value) {
const clampedValue = Math.max(value, start + 1);
- this.updateThreshold([start, clampedValue]);
+ updateThreshold([start, clampedValue]);
}
- render() {
- const {
- start, end, squashed, noclipped, avg, sliderWidth,
- } = this.state;
- const {
- index, min, max, legend, globalTemperatureUnit,
- } = this.props;
-
- const units = legend.units || '';
- const {
- needsConversion,
- legendTempUnit,
- } = checkTemperatureUnitConversion(units, globalTemperatureUnit);
- let startLabel = start === 0 && legend.minLabel
- ? legend.minLabel
- : legend.tooltips[start];
- let endLabel = end === legend.tooltips.length - 1 && legend.maxLabel
- ? legend.maxLabel
- : legend.tooltips[end];
-
- if (needsConversion) {
- const parsedMin = convertPaletteValue(startLabel, legendTempUnit, globalTemperatureUnit);
- const parsedMax = convertPaletteValue(endLabel, legendTempUnit, globalTemperatureUnit);
- startLabel = parsedMin;
- endLabel = parsedMax;
- } else {
- startLabel += ` ${units}`;
- endLabel += ` ${units}`;
- }
-
- const minWidth = thumbsize + ((avg - min) / (max - min)) * (sliderWidth - (2 * thumbsize));
- const maxWidth = thumbsize + ((max - avg) / (max - min)) * (sliderWidth - (2 * thumbsize));
- const minPercent = ((start - min) / (avg - min)) * 100;
- const maxPercent = ((end - avg) / (max - avg)) * 100;
- const styles = {
- min: {
- width: minWidth,
- left: 0,
- '--min-range-percent': `${minPercent}%`,
- },
- max: {
- width: maxWidth,
- left: minWidth,
- '--max-range-percent': `${maxPercent}%`,
- },
- };
+ const units = legend.units || '';
+ const {
+ needsConversion,
+ legendTempUnit,
+ } = checkTemperatureUnitConversion(units, globalTemperatureUnit);
+ let startLabel = start === 0 && legend.minLabel
+ ? legend.minLabel
+ : legend.tooltips[start];
+ let endLabel = end === legend.tooltips.length - 1 && legend.maxLabel
+ ? legend.maxLabel
+ : legend.tooltips[end];
+
+ if (needsConversion) {
+ const parsedMin = convertPaletteValue(startLabel, legendTempUnit, globalTemperatureUnit);
+ const parsedMax = convertPaletteValue(endLabel, legendTempUnit, globalTemperatureUnit);
+ startLabel = parsedMin;
+ endLabel = parsedMax;
+ } else {
+ startLabel += ` ${units}`;
+ endLabel += ` ${units}`;
+ }
- return (
- <div className="layer-threshold-select settings-component">
- <h2 className="wv-header">Thresholds</h2>
- <div id={`wv-palette-squash${index}`} className="wv-palette-squash">
- <Checkbox
- name="Squash Palette"
- color="gray"
- checked={squashed}
- label="Squash Palette"
- classNames="wv-squash-button-check"
- id={`wv-squash-button-check${index}`}
- onCheck={() => this.updateSquashOrNoClip('squash')}
- />
- </div>
- <div id={`wv-palette-clip${index}`} className="wv-palette-clip">
- <Checkbox
- name="Clip Palette"
- color="gray"
- checked={!noclipped}
- label="Clip Palette"
- classNames="wv-clip-button-check"
- id={`wv-clip-button-check${index}`}
- onCheck={() => this.updateSquashOrNoClip('noclip')}
- />
- </div>
- <div
- id={`wv-layer-options-threshold${index}`}
- className="wv-layer-options-threshold"
- ref={this.slider}
- >
- <input
- className="double-range form-range start-range palette-threshold-range"
- style={styles.min}
- name="min"
- type="range"
- min={min}
- max={avg}
- value={start}
- onChange={(e) => this.updateStartThreshold(Math.ceil(parseFloat(e.target.value, 10)))}
- />
- <input
- className="double-range form-range end-range palette-threshold-range"
- style={styles.max}
- name="max"
- type="range"
- min={avg}
- max={max}
- value={end}
- onChange={(e) => this.updateEndThreshold(Math.ceil(parseFloat(e.target.value, 10)))}
- />
- <div className="wv-label mt-3">
- <span className="wv-label-range-min wv-label-range">
- {startLabel}
- </span>
- <span className="wv-label-range-max wv-label-range">
- {endLabel}
- </span>
- </div>
+ const minWidth = thumbsize + ((avg - min) / (max - min)) * (sliderWidth - (2 * thumbsize));
+ const maxWidth = thumbsize + ((max - avg) / (max - min)) * (sliderWidth - (2 * thumbsize));
+ const minPercent = ((start - min) / (avg - min)) * 100;
+ const maxPercent = ((end - avg) / (max - avg)) * 100;
+ const styles = {
+ min: {
+ width: minWidth,
+ left: 0,
+ '--min-range-percent': `${minPercent}%`,
+ },
+ max: {
+ width: maxWidth,
+ left: minWidth,
+ '--max-range-percent': `${maxPercent}%`,
+ },
+ };
+
+ return (
+ <div className="layer-threshold-select settings-component">
+ <h2 className="wv-header">Thresholds</h2>
+ <div id={`wv-palette-squash${index}`} className="wv-palette-squash">
+ <Checkbox
+ name="Squash Palette"
+ color="gray"
+ checked={squashed}
+ label="Squash Palette"
+ classNames="wv-squash-button-check"
+ id={`wv-squash-button-check${index}`}
+ onCheck={() => updateSquashOrNoClip('squash')}
+ />
+ </div>
+ <div id={`wv-palette-clip${index}`} className="wv-palette-clip">
+ <Checkbox
+ name="Clip Palette"
+ color="gray"
+ checked={!noclipped}
+ label="Clip Palette"
+ classNames="wv-clip-button-check"
+ id={`wv-clip-button-check${index}`}
+ onCheck={() => updateSquashOrNoClip('noclip')}
+ />
+ </div>
+ <div
+ id={`wv-layer-options-threshold${index}`}
+ className="wv-layer-options-threshold"
+ ref={sliderRef}
+ >
+ <input
+ className="double-range form-range start-range palette-threshold-range"
+ style={styles.min}
+ name="min"
+ type="range"
+ min={min}
+ max={avg}
+ value={start}
+ onChange={(e) => updateStartThreshold(Math.ceil(parseFloat(e.target.value, 10)))}
+ />
+ <input
+ className="double-range form-range end-range palette-threshold-range"
+ style={styles.max}
+ name="max"
+ type="range"
+ min={avg}
+ max={max}
+ value={end}
+ onChange={(e) => updateEndThreshold(Math.ceil(parseFloat(e.target.value, 10)))}
+ />
+ <div className="wv-label mt-3">
+ <span className="wv-label-range-min wv-label-range">
+ {startLabel}
+ </span>
+ <span className="wv-label-range-max wv-label-range">
+ {endLabel}
+ </span>
</div>
</div>
- );
- }
-}
+ </div>
+ );
+};
PaletteThreshold.propTypes = {
end: PropTypes.number,
groupName: PropTypes.string,
diff --git a/web/js/components/range-selection/range-selection.js b/web/js/components/range-selection/range-selection.js
index 10d899380..119684a64 100644
--- a/web/js/components/range-selection/range-selection.js
+++ b/web/js/components/range-selection/range-selection.js
@@ -1,4 +1,4 @@
-import React from 'react';
+import { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import moment from 'moment';
import Dragger from './dragger';
@@ -12,134 +12,45 @@ import { timeScaleOptions } from '../../modules/date/constants';
*
* @class TimelineRangeSelector
*/
-class TimelineRangeSelector extends React.Component {
- constructor(props) {
- super(props);
- this.state = {
- startLocation: props.startLocation,
- endLocation: props.endLocation,
- deltaStart: 0,
- };
- }
+const TimelineRangeSelector = ({
+ startLocation: startLocationProp,
+ endLocation: endLocationProp,
+ axisWidth,
+ endColor = '#295f92',
+ endLocationDate,
+ endTriangleColor = '#4b7aab',
+ frontDate,
+ max,
+ pinWidth = 5,
+ position,
+ rangeColor = '#45bdff',
+ rangeOpacity = 0.3,
+ startColor = '#40a9db',
+ startLocationDate,
+ startTriangleColor = '#fff',
+ timelineEndDateLimit,
+ timelineStartDateLimit,
+ timeScale,
+ transformX,
+ updateAnimationDateAndLocation,
+}) => {
+ const [startLocation, setStartLocation] = useState(startLocationProp);
+ const [endLocation, setEndLocation] = useState(endLocationProp);
+ const [deltaStart, setDeltaStart] = useState(0);
- componentDidMount() {
- this.updateLocation();
- }
-
- componentDidUpdate() {
- const { startLocation, endLocation } = this.props;
-
- if (startLocation !== this.state.startLocation || endLocation !== this.state.endLocation) {
- this.updateLocation();
- }
- }
-
- /*
- * When a child component is dragged,
- * this function is called to determine
- * the correct location for each of the
- * child elements after the drag
- *
- * @method handleDrag
- *
- * @param {number} deltaX - change in x
- * @param {string} id - Identifier used to
- * distinguish between the child elements
- *
- * @return {void}
- */
- onItemDrag = (deltaX, id) => {
- const { endLocation, startLocation } = this.state;
- const { max, pinWidth } = this.props;
- let startX;
- let endX;
-
- if (id === 'start') {
- startX = deltaX + startLocation;
- endX = endLocation;
- if (startX < 0 || startX > endX) {
- return;
- }
- if (startX + pinWidth >= endX) {
- if (startX + pinWidth >= max.width) {
- return;
- }
- endX = startX + pinWidth;
- }
- } else if (id === 'end') {
- startX = startLocation;
- endX = deltaX + endLocation;
- if (endX > max.width || startX > endX) {
- return;
- }
- if (startX + 2 * pinWidth >= endX) {
- startX = endX - pinWidth;
- }
- } else {
- startX = deltaX + startLocation;
- endX = deltaX + endLocation;
- if (endX >= max.width || startX < 0) {
- return;
- }
- }
- this.setState({
- startLocation: startX,
- endLocation: endX,
- });
- this.animationDraggerPositionUpdate(startX, endX, true);
- };
-
- /*
- * Send callback with new locations on
- * Drag Stop
- *
- * @method onDragStop
- *
- * @return {void}
- */
- onDragStop = () => {
- const { endLocation, startLocation } = this.state;
- this.animationDraggerPositionUpdate(startLocation, endLocation, false);
- };
-
- /*
- * Update state based on distance range was dragged
- *
- * @method onRangeDrag
- *
- * @param {number} d - change in x
- * @param {number} deltaStart - delta start to track changes
- *
- * @return {void}
- */
- onRangeDrag = (d, deltaStart) => {
- this.setState((prevState) => {
- const startLocation = prevState.startLocation + d;
- const endLocation = prevState.endLocation + d;
- this.animationDraggerPositionUpdate(startLocation, endLocation, true);
- return {
- startLocation: prevState.startLocation + d,
- endLocation: prevState.endLocation + d,
- deltaStart,
- };
- });
- };
+ useEffect(() => {
+ setStartLocation(startLocationProp);
+ setEndLocation(endLocationProp);
+ }, [startLocationProp, endLocationProp]);
// update animation dragger helper function
- getAnimationLocateDateUpdate = (
+ const getAnimationLocateDateUpdate = (
animLocationDate,
animDraggerLocation,
deltaX,
{ diffZeroValues, diffFactor },
) => {
if (!diffZeroValues) { // month or year
- const {
- timeScale,
- position,
- transformX,
- frontDate,
- } = this.props;
-
const options = timeScaleOptions[timeScale].timeAxis;
const { gridWidth } = options;
@@ -166,21 +77,7 @@ class TimelineRangeSelector extends React.Component {
};
// handle animation dragger drag change
- animationDraggerPositionUpdate = (draggerStartLocation, draggerEndLocation, isDragging) => {
- const {
- timelineStartDateLimit,
- timelineEndDateLimit,
- startLocationDate,
- endLocationDate,
- timeScale,
- updateAnimationDateAndLocation,
- } = this.props;
-
- const {
- startLocation,
- endLocation,
- } = this.state;
-
+ const animationDraggerPositionUpdate = (draggerStartLocation, draggerEndLocation, isDragging) => {
// calculate new start and end positions
const deltaXStart = draggerStartLocation - startLocation;
let animationStartLocationDate = startLocationDate;
@@ -204,7 +101,7 @@ class TimelineRangeSelector extends React.Component {
};
if (deltaXStart !== 0) { // update new start date
- animationStartLocationDate = this.getAnimationLocateDateUpdate(
+ animationStartLocationDate = getAnimationLocateDateUpdate(
animationStartLocationDate,
startLocation,
deltaXStart,
@@ -212,7 +109,7 @@ class TimelineRangeSelector extends React.Component {
);
}
if (deltaXEnd !== 0) { // update new end date
- animationEndLocationDate = this.getAnimationLocateDateUpdate(
+ animationEndLocationDate = getAnimationLocateDateUpdate(
animationEndLocationDate,
endLocation,
deltaXEnd,
@@ -255,100 +152,142 @@ class TimelineRangeSelector extends React.Component {
);
};
- updateLocation = () => {
- const { startLocation, endLocation } = this.props;
- this.setState({
- startLocation,
- endLocation,
- });
+ /*
+ * When a child component is dragged,
+ * this function is called to determine
+ * the correct location for each of the
+ * child elements after the drag
+ *
+ * @method handleDrag
+ *
+ * @param {number} deltaX - change in x
+ * @param {string} id - Identifier used to
+ * distinguish between the child elements
+ *
+ * @return {void}
+ */
+ const onItemDrag = (deltaX, id) => {
+ let startX;
+ let endX;
+
+ if (id === 'start') {
+ startX = deltaX + startLocation;
+ endX = endLocation;
+ if (startX < 0 || startX > endX) {
+ return;
+ }
+ if (startX + pinWidth >= endX) {
+ if (startX + pinWidth >= max.width) {
+ return;
+ }
+ endX = startX + pinWidth;
+ }
+ } else if (id === 'end') {
+ startX = startLocation;
+ endX = deltaX + endLocation;
+ if (endX > max.width || startX > endX) {
+ return;
+ }
+ if (startX + 2 * pinWidth >= endX) {
+ startX = endX - pinWidth;
+ }
+ } else {
+ startX = deltaX + startLocation;
+ endX = deltaX + endLocation;
+ if (endX >= max.width || startX < 0) {
+ return;
+ }
+ }
+ setStartLocation(startX);
+ setEndLocation(endX);
+ animationDraggerPositionUpdate(startX, endX, true);
+ };
+
+ /*
+ * Send callback with new locations on
+ * Drag Stop
+ *
+ * @method onDragStop
+ *
+ * @return {void}
+ */
+ const onDragStop = () => {
+ animationDraggerPositionUpdate(startLocation, endLocation, false);
};
/*
- * @method render
+ * Update state based on distance range was dragged
+ *
+ * @method onRangeDrag
+ *
+ * @param {number} d - change in x
+ * @param {number} newDeltaStart - delta start to track changes
+ *
+ * @return {void}
*/
- render() {
- const { endLocation, deltaStart, startLocation } = this.state;
- const {
- axisWidth,
- endColor,
- endLocationDate,
- endTriangleColor,
- max,
- pinWidth,
- rangeColor,
- rangeOpacity,
- startColor,
- startLocationDate,
- startTriangleColor,
- timelineEndDateLimit,
- timelineStartDateLimit,
- timeScale,
- } = this.props;
- return (
- <svg
- id="wv-timeline-range-selector"
- className="wv-timeline-range-selector"
- width={axisWidth}
- height={75}
- >
- <DraggerRange
- opacity={rangeOpacity}
- startLocation={startLocation}
- endLocation={endLocation}
- startLocationDate={startLocationDate}
- endLocationDate={endLocationDate}
- timelineStartDateLimit={timelineStartDateLimit}
- timelineEndDateLimit={timelineEndDateLimit}
- timeScale={timeScale}
- deltaStart={deltaStart}
- max={max}
- height={64}
- width={pinWidth}
- color={rangeColor}
- draggerID="range-selector-range"
- onDrag={this.onRangeDrag}
- onStop={this.onDragStop}
- id="range"
- />
- <Dragger
- position={startLocation}
- color={startColor}
- width={pinWidth}
- height={45}
- onDrag={this.onItemDrag}
- onStop={this.onDragStop}
- max={max.width}
- draggerID="range-selector-dragger-1"
- backgroundColor={startTriangleColor}
- first
- id="start"
- />
- <Dragger
- max={max.width}
- position={endLocation}
- color={endColor}
- width={pinWidth}
- height={45}
- first={false}
- draggerID="range-selector-dragger-2"
- onDrag={this.onItemDrag}
- onStop={this.onDragStop}
- backgroundColor={endTriangleColor}
- id="end"
- />
- </svg>
- );
- }
-}
+ const onRangeDrag = (d, newDeltaStart) => {
+ const newStartLocation = startLocation + d;
+ const newEndLocation = endLocation + d;
+ setStartLocation((prev) => prev + d);
+ setEndLocation((prev) => prev + d);
+ setDeltaStart(newDeltaStart);
+ animationDraggerPositionUpdate(newStartLocation, newEndLocation, true);
+ };
-TimelineRangeSelector.defaultProps = {
- pinWidth: 5,
- rangeOpacity: 0.3,
- rangeColor: '#45bdff',
- startColor: '#40a9db',
- startTriangleColor: '#fff',
- endColor: '#295f92',
- endTriangleColor: '#4b7aab',
+ return (
+ <svg
+ id="wv-timeline-range-selector"
+ className="wv-timeline-range-selector"
+ width={axisWidth}
+ height={75}
+ >
+ <DraggerRange
+ opacity={rangeOpacity}
+ startLocation={startLocation}
+ endLocation={endLocation}
+ startLocationDate={startLocationDate}
+ endLocationDate={endLocationDate}
+ timelineStartDateLimit={timelineStartDateLimit}
+ timelineEndDateLimit={timelineEndDateLimit}
+ timeScale={timeScale}
+ deltaStart={deltaStart}
+ max={max}
+ height={64}
+ width={pinWidth}
+ color={rangeColor}
+ draggerID="range-selector-range"
+ onDrag={onRangeDrag}
+ onStop={onDragStop}
+ id="range"
+ />
+ <Dragger
+ position={startLocation}
+ color={startColor}
+ width={pinWidth}
+ height={45}
+ onDrag={onItemDrag}
+ onStop={onDragStop}
+ max={max.width}
+ draggerID="range-selector-dragger-1"
+ backgroundColor={startTriangleColor}
+ first
+ id="start"
+ />
+ <Dragger
+ max={max.width}
+ position={endLocation}
+ color={endColor}
+ width={pinWidth}
+ height={45}
+ first={false}
+ draggerID="range-selector-dragger-2"
+ onDrag={onItemDrag}
+ onStop={onDragStop}
+ backgroundColor={endTriangleColor}
+ id="end"
+ />
+ </svg>
+ );
};
TimelineRangeSelector.propTypes = {