Interactive interface for browsing global, full-resolution satellite imagery
PaletteLegend functional component (#6612)
christof-wittreichceb0ebd3fab0
diff --git a/web/js/components/sidebar/paletteLegend.js b/web/js/components/sidebar/paletteLegend.jsindex 9adb1d3b9..3204c724c 100644--- a/web/js/components/sidebar/paletteLegend.js+++ b/web/js/components/sidebar/paletteLegend.js@@ -1,10 +1,11 @@-import React from 'react';+import { useState, useEffect, useRef, Fragment } from 'react';import PropTypes from 'prop-types';import lodashIsNumber from 'lodash/isNumber';import lodashIsEqual from 'lodash/isEqual';import { Tooltip } from 'reactstrap';import VisibilitySensor from '../util/visibility-sensor';import { connect } from 'react-redux';+import usePrevious from '../../util/customHooks';import { getOrbitTrackTitle } from '../../modules/layers/util';import {drawSidebarPaletteOnCanvas,@@ -36,26 +37,45 @@ const getRunningLabelStyle = (xOffset, textWidth, width) => {return { transform: `translateX(${Math.floor(xOffset - halfTextWidth)}px)` };};-// `translateX(${isHoveringLegend ? 0 : xOffset > 0 ? xOffset + 0.5 : 0}px)`,--class PaletteLegend extends React.Component {- constructor(props) {- super(props);- this.state = {- isRunningData: props.isRunningData,- colorHex: props.colorHex,- width: props.width,- scrollContainerEl: null,- };- this.onMouseEnter = this.onMouseEnter.bind(this);- this.hideValue = this.hideValue.bind(this);- this.onMove = this.onMove.bind(this);- }-- componentDidMount() {- const {- getPalette, layer, compareState, toggleAllClassifications,- } = this.props;+function PaletteLegend(props) {+ const {+ isRunningData,+ colorHex,+ width,+ height,+ getPalette,+ layer,+ parentLayer,+ compareState,+ toggleAllClassifications,+ isDistractionFreeModeActive,+ paletteLegends,+ globalTemperatureUnit,+ isEmbedModeActive,+ isMobile,+ palettes,+ paletteId,+ isCustomPalette,+ showingVectorHand,+ showingChartingIcon,+ } = props;++ const [isRunningDataState, setIsRunningDataState] = useState(isRunningData);+ const [colorHexState, setColorHexState] = useState(colorHex);+ const [widthState, setWidthState] = useState(width);+ const [scrollContainerEl, setScrollContainerEl] = useState(null);+ const [isHoveringLegend, setIsHoveringLegend] = useState(false);++ const prevColorHex = usePrevious(colorHex);+ const prevIsRunningData = usePrevious(isRunningData);+ const prevLayer = usePrevious(layer);+ const prevPaletteLegends = usePrevious(paletteLegends);+ const prevWidth = usePrevious(widthState);+ const prevDistractionFree = usePrevious(isDistractionFreeModeActive);++ const palettesArrayRef = useRef([]);++ useEffect(() => {if (layer.disabled === undefined) {// There is not a previous instance, so check the palette defaultsconst palette = getPalette();@@ -65,138 +85,118 @@ class PaletteLegend extends React.Component {}}- this.updateCanvas();- this.setState(() => ({- scrollContainerEl: document.querySelector('#layers-scroll-container'),- }));- }+ updateCanvas();+ setScrollContainerEl(document.querySelector('#layers-scroll-container'));+ }, []);- componentDidUpdate(prevProps) {- const {- isDistractionFreeModeActive,- layer,- width,- paletteLegends,- colorHex,- isRunningData,- } = this.props;-- // Keep state in sync with prop changes, without clobbering hover-driven state.- if (prevProps.colorHex !== colorHex || prevProps.isRunningData !== isRunningData) {- this.setState({- colorHex,- isRunningData,- });- return;+ useEffect(() => {+ if (prevColorHex !== colorHex) {+ setColorHexState(colorHex);+ }+ }, [colorHex]);++ useEffect(() => {+ if (prevIsRunningData !== isRunningData) {+ setIsRunningDataState(isRunningData);}+ }, [isRunningData]);+ useEffect(() => {// Updates when layer options/settings changed, if ZOT changes the width of the palette,// or distraction free mode exit- const layerChange = !lodashIsEqual(layer, prevProps.layer);- const paletteLegendsChange = !lodashIsEqual(paletteLegends, prevProps.paletteLegends);- const widthChange = prevProps.width !== width;- const distractionFreeChange = prevProps.isDistractionFreeModeActive &&- !isDistractionFreeModeActive;+ const layerChange = !lodashIsEqual(layer, prevLayer);+ const paletteLegendsChange = !lodashIsEqual(paletteLegends, prevPaletteLegends);+ const widthChange = prevWidth !== widthState;+ const distractionFreeChange = prevDistractionFree && !isDistractionFreeModeActive;if (layerChange || widthChange || distractionFreeChange || paletteLegendsChange) {- this.updateCanvas();+ updateCanvas();}- }+ }, [layer, paletteLegends, widthState, isDistractionFreeModeActive]);/*** Get percent of selected point position in parent*/- getPercent(len, index) {+ const getPercent = (len, index) => {let segmentWidth;let location;- const { width } = this.state;if (len < 250) {- segmentWidth = width / len;+ segmentWidth = widthState / len;location = segmentWidth * index + 0.5 * segmentWidth;- return lodashIsNumber(location / width) ? location / width : 0;+ return lodashIsNumber(location / widthState) ? location / widthState : 0;}return lodashIsNumber(index / len) ? index / len : 0;- }+ };/*** OnMouseMove get correct canvas Data* @param {Object} canvas | Element* @param {Object} e | Event Object*/- onHoverColorbar(canvas, e) {+ const onHoverColorbar = (canvas, e) => {e.preventDefault();e.stopPropagation();const boundingRec = e.target.getBoundingClientRect();const x = e.clientX - boundingRec.left;const y = e.clientY - boundingRec.top;- const rgba = canvas.current.getContext('2d').getImageData(x, y, 1, 1).data;+ const rgba = canvas.getContext('2d').getImageData(x, y, 1, 1).data;const hex = util.rgbaToHex(rgba[0], rgba[1], rgba[2]);- this.setState({- colorHex: hex,- });- }+ setColorHexState(hex);+ };/*** On Mouse Enter update State* @param {*} e*/- onMouseEnter(e) {+ const onMouseEnter = (e) => {e.preventDefault();e.stopPropagation();- this.setState({- isRunningData: true,- isHoveringLegend: true,- });- }+ setIsRunningDataState(true);+ setIsHoveringLegend(true);+ };/*** Update state on MouseOut*/- hideValue(e) {+ const hideValue = (e) => {e.preventDefault();e.stopPropagation();- this.setState({- isRunningData: false,- isHoveringLegend: false,- });- }+ setIsRunningDataState(false);+ setIsHoveringLegend(false);+ };/*** Style Canvas bases on updates to legend or canvas-width*/- updateCanvas() {- const {- height, width, paletteLegends,- } = this.props;-+ const updateCanvas = () => {paletteLegends.forEach((colorMap, index) => {if (colorMap.type === 'continuous' || colorMap.type === 'discrete') {const ctxStr = `canvas_${index}`;- if (this[ctxStr]) {- const newWidth = this[ctxStr].current.getBoundingClientRect().width;+ if (palettesArrayRef.current[ctxStr]) {+ const newWidth = palettesArrayRef.current[ctxStr].getBoundingClientRect().width;- if (newWidth && newWidth !== this.state.width) {+ if (newWidth && newWidth !== widthState) {// If scrollbar appears canvas width changes.// This value is needed for calculating running data offsets- this.setState({ width: newWidth });+ setWidthState(newWidth);}- const ctx = this[ctxStr].current.getContext('2d');+ const ctx = palettesArrayRef.current[ctxStr].getContext('2d');drawSidebarPaletteOnCanvas(ctx,colorMap.colors,- width,+ widthState,height,);drawTicksOnCanvas(ctx,colorMap,- width,+ widthState,height,);}}});- }+ };/*** Finds the legend object that corresponds to a given hex color.@@ -212,8 +212,7 @@ class PaletteLegend extends React.Component {* @returns {Object|null} The matched legend object or null if no match is found.**/- getLegendObject(legend, hex, acceptableDifference) {- const { globalTemperatureUnit } = this.props;+ const getLegendObject = (legend, hex, acceptableDifference) => {const units = legend.units || '';const { needsConversion, legendTempUnit } = checkTemperatureUnitConversion(@@ -238,7 +237,7 @@ class PaletteLegend extends React.Component {}}return null;- }+ };/*** Render scale-type paletteLegends@@ -246,13 +245,7 @@ class PaletteLegend extends React.Component {* @param {Number} index* @param {Boolean} isMoreThanOneColorBar*/- renderScale(legend, index, isMoreThanOneColorBar) {- const {- layer, width, getPalette, isEmbedModeActive, isMobile, globalTemperatureUnit,- } = this.props;- const {- isRunningData, colorHex, isHoveringLegend,- } = this.state;+ const renderScale = (legend, index, isMoreThanOneColorBar) => {const palette = getPalette(layer.id, index);let percent;let textWidth;@@ -260,15 +253,15 @@ class PaletteLegend extends React.Component {let legendObj;const toolTipLength = legend.tooltips.length;- if (isRunningData && colorHex && this.state.width > 0) {+ if (isRunningDataState && colorHexState && widthState > 0) {const isContinuousVectorLayer = layer.colormapType === 'continuous' && layer.type === 'vector';const acceptableDifference = isContinuousVectorLayer ? 1 : 3;- legendObj = this.getLegendObject(legend, colorHex, acceptableDifference); // {label,len,index}+ legendObj = getLegendObject(legend, colorHexState, acceptableDifference); // {label,len,index}if (legendObj) {- percent = this.getPercent(legendObj.len, legendObj.index);+ percent = getPercent(legendObj.len, legendObj.index);textWidth = util.getTextWidth(legendObj.label, '10px Open Sans');- xOffset = Math.floor(this.state.width * percent);+ xOffset = Math.floor(widthState * percent);if (isEmbedModeActive) {// adjust xOffset per css scale transformxOffset = Math.floor(xOffset / 0.75);@@ -325,14 +318,14 @@ class PaletteLegend extends React.Component {className="wv-palettes-colorbar"id={`${util.encodeId(layer.id)}-${util.encodeId(legend.id)}${index}colorbar`}style={mobileColorbarStyle}- width={width}+ width={widthState}height={24}- ref={this[`canvas_${index}`]}- onMouseEnter={!isMobile ? this.onMouseEnter : null}- onMouseLeave={!isMobile ? this.hideValue : null}+ ref={el => { palettesArrayRef.current[`canvas_${index}`] = el; }}+ onMouseEnter={!isMobile ? onMouseEnter : null}+ onMouseLeave={!isMobile ? hideValue : null}onMouseMove={!isMobile- ? (event) => this.onHoverColorbar(this[`canvas_${index}`], event)+ ? (event) => onHoverColorbar(palettesArrayRef.current[`canvas_${index}`], event): null}/>@@ -353,8 +346,8 @@ class PaletteLegend extends React.Component {<spanclassName="wv-running-label"style={- isRunningData- ? getRunningLabelStyle(xOffset, textWidth, width)+ isRunningDataState+ ? getRunningLabelStyle(xOffset, textWidth, widthState): { display: 'none' }}>@@ -362,30 +355,27 @@ class PaletteLegend extends React.Component {</span></div>);- }+ };/*** Update label & Location on Mousemove* @param {String} color | Hex* @param {Object} e | Event Object*/- onMove(color, e) {+ const onMove = (color, e) => {e.preventDefault();e.stopPropagation();- this.setState({ colorHex: color });- }+ setColorHexState(color);+ };/*** Render a legend of class type* @param {Object} legend | Legend Object* @param {Number} index | Legend Index*/- renderClasses(legend, legendIndex) {- const { isRunningData, colorHex, scrollContainerEl } = this.state;- const {- layer, parentLayer, compareState, getPalette, palettes,- } = this.props;- const activeKeyObj = isRunningData && colorHex && this.getLegendObject(legend, colorHex, 5);+ const renderClasses = (legend, legendIndex) => {+ const activeKeyObj = isRunningDataState && colorHexState &&+ getLegendObject(legend, colorHexState, 5);const legendClass = activeKeyObj? 'wv-running wv-palettes-legend wv-palettes-classes': 'wv-palettes-legend wv-palettes-classes';@@ -422,14 +412,14 @@ class PaletteLegend extends React.Component {}return (- <React.Fragment key={keyId}>+ <Fragment key={keyId}><spanid={keyId}className={inActive ? `${palletteClass} disabled-classification` : palletteClass}style={isInvisible ? null : { backgroundColor: util.hexToRGBA(legendColor) }}- onMouseMove={(event) => this.onMove(legendColor, event)}- onMouseEnter={this.onMouseEnter}- onMouseLeave={this.hideValue}+ onMouseMove={(event) => onMove(legendColor, event)}+ onMouseEnter={onMouseEnter}+ onMouseLeave={hideValue}dangerouslySetInnerHTML={{ __html: ' ' }}/>@@ -452,41 +442,35 @@ class PaletteLegend extends React.Component {{tooltipText}</Tooltip>)}- </React.Fragment>+ </Fragment>);})}</div>)}</VisibilitySensor>);- }+ };/*** Loop through colormaps and render correct legend type*/- renderPaletteLegends() {- const { paletteLegends } = this.props;-+ const renderPaletteLegends = () => {return paletteLegends.map((colorMap, index) => {if (colorMap.type === 'continuous' || colorMap.type === 'discrete') {- this[`canvas_${index}`] = React.createRef();- return this.renderScale(colorMap, index, paletteLegends.length > 1);+ return renderScale(colorMap, index, paletteLegends.length > 1);} if (colorMap.type === 'classification') {- return this.renderClasses(colorMap, index);+ return renderClasses(colorMap, index);}return undefined;});- }+ };- render() {- const {- paletteId, layer, isCustomPalette, showingVectorHand, showingChartingIcon,- } = this.props;- const { isHoveringLegend } = this.state;- const customPaletteClassName = isCustomPalette ? ' is_custom' : '';- const customClass = (showingVectorHand && layer.id.includes('AERONET')) || showingChartingIcon ? ' bottomspace-palette' : customPaletteClassName;- if (!layer.palette) return undefined;- return (+ const customPaletteClassName = isCustomPalette ? ' is_custom' : '';+ const customClass = (showingVectorHand && layer.id.includes('AERONET')) || showingChartingIcon ? ' bottomspace-palette' : customPaletteClassName;++ return !layer.palette+ ? undefined+ : (<divclassName={isHoveringLegend@@ -495,10 +479,9 @@ class PaletteLegend extends React.Component {}id={`${paletteId}_panel`}>- {this.renderPaletteLegends()}+ {renderPaletteLegends()}</div>);- }}PaletteLegend.defaultProps = {isRunningData: false,diff --git a/web/scss/features/sidebar-panel.scss b/web/scss/features/sidebar-panel.scssindex ae31c0a0d..2ca98fa8b 100644--- a/web/scss/features/sidebar-panel.scss+++ b/web/scss/features/sidebar-panel.scss@@ -555,6 +555,10 @@ li.item.productsitem.inmotion,line-height: 16px;}}++ .tooltip-arrow {+ pointer-events: none;+ }}.productsitem button.wv-layers-close {