Skip to content

Interactive interface for browsing global, full-resolution satellite imagery

16.0 KB
Raw Blame
import { useState, useEffect, useRef } from 'react';
import PropTypes from 'prop-types';
import { each as lodashEach, get as lodashGet } from 'lodash';
import {
  TabContent, TabPane, Nav, NavItem, NavLink,
} from 'reactstrap';
import { connect } from 'react-redux';

import Opacity from './opacity';
import Palette from './palette';
import BandSelection from './band-selection/band-selection-parent-info-menu';
import AssociatedLayers from './associated-layers-toggle';
import PaletteThreshold from './palette-threshold';
import GranuleLayerDateList from './granule-date-list';
import GranuleCountSlider from './granule-count-slider';
import DayRangeSlider from './day-range-slider';
import safeLocalStorage from '../../../util/local-storage';
import ImagerySearch from './imagery-search';

import {
  palettesTranslate as palettesTranslateUtil,
} from '../../../modules/palettes/util';
import {
  getDefaultLegend as getDefaultLegendSelector,
  getCustomPalette as getCustomPaletteSelector,
  getPaletteLegends as getPaletteLegendsSelector,
  getPalette as getPaletteSelector,
  getPaletteLegend as getPaletteLegendSelector,
  isPaletteAllowed,
} from '../../../modules/palettes/selectors';
import {
  getGranuleLayer,
  getGranulePlatform,
  getMaxDayRange,
  getLayerDayCount,
} from '../../../modules/layers/selectors';
import {
  setThresholdRangeSquashAndNoClip,
  setCustomPalette as setCustomPaletteAction,
  clearCustomPalette as clearCustomPaletteAction,
  setToggledClassification,
  refreshDisabledClassification,
} from '../../../modules/palettes/actions';
import {
  setFilterRange,
  setStyle,
  clearStyle,
} from '../../../modules/vector-styles/actions';

import {
  getVectorStyle,
} from '../../../modules/vector-styles/selectors';
import {
  updateGranuleLayerOptions as updateGranuleLayerOptionsAction,
  resetGranuleLayerDates as resetGranuleLayerDatesAction,
  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) {
  const {
    clearCustomPalette,
    getPalette,
    paletteOrder,
    getDefaultLegend,
    getCustomPalette,
    globalTemperatureUnit,
    setCustomPalette,
    palettesTranslate,
    groupName,
    setThresholdRange,
    layer,
    toggleClassification,
    toggleAllClassifications,
    screenHeight,
    getPaletteLegends,
    getPaletteLegend,
    granuleOptions,
    resetGranuleLayerDates,
    updateGranuleLayerOptions,
    setOpacity,
    customPalettesIsActive,
    palettedAllowed,
    zot,
    maxDayRange,
    dayCount,
    updateDayCount,
    isMobile,
  } = props;

  const [activeIndex, setActiveIndex] = useState(0);
  const [allowGranuleReorder, setAllowGranuleReorder] = useState(false);

  const canvasRef = useRef(document.createElement('canvas'));

  useEffect(() => {
    canvasRef.current.width = 120;
    canvasRef.current.height = 10;
    const { ALLOW_GRANULE_REORDER } = safeLocalStorage.keys;
    const allowGranuleReorderStored = safeLocalStorage.getItem(ALLOW_GRANULE_REORDER);
    setAllowGranuleReorder(allowGranuleReorderStored);
  }, []);

  /**
   * Render multicolormap layers inside a tab pane
   * @param {object} paletteLegends | legend object
   */
  function renderMultiColormapCustoms(paletteLegends) {
    const navElements = [];
    const paneElements = [];
    lodashEach(paletteLegends, (legend, i) => {
      const activeClass = activeIndex === i ? 'active' : '';
      const dualStr = paletteLegends.length === 2 ? ' dual' : '';
      const navItemEl = (
        <NavItem
          key={`${legend.id}nav`}
          className={`settings-customs-title ${activeClass}${dualStr}`}
        >
          <NavLink onClick={() => setActiveIndex(i)}>
            {legend.title}
          </NavLink>
        </NavItem>
      );
      const palette = getPalette(layer.id, i);
      const max = legend.colors.length - 1;
      const start = palette.min ? legend.refs.indexOf(palette.entries.refs[palette.min]) : 0;
      const end = palette.max ? legend.refs.indexOf(palette.entries.refs[palette.max]) : max;
      let paneItemEl;

      if (legend.type === 'classification' && (legend.colors.length > 1 || layer.id.includes('AERONET'))) {
        paneItemEl = (
          <TabPane key={`${legend.id}pane`} tabId={i}>
            <ClassificationToggle
              height={Math.ceil(screenHeight / 3)}
              palette={palette}
              toggle={(classIndex) => toggleClassification(layer.id, classIndex, i, groupName)}
              legend={legend}
              toggleAll={(disabledArray) => {
                toggleAllClassifications(layer.id, disabledArray, i, groupName);
              }}
            />
          </TabPane>
        );
      } else if (
        legend.type !== 'continuous' &&
        legend.type !== 'discrete' &&
        legend.colors.length > 1
      ) {
        paneItemEl = (
          <TabPane key={`${legend.id}pane`} tabId={i}>
            No customizations available for this palette.
          </TabPane>
        );
      } else {
        paneItemEl = (
          <TabPane key={`${legend.id}pane`} tabId={i}>
            {legend.type !== 'classification'
              ? (
                <PaletteThreshold
                  key={`${layer.id + i}_threshold`}
                  legend={legend}
                  setRange={setThresholdRange}
                  globalTemperatureUnit={globalTemperatureUnit}
                  min={0}
                  max={max}
                  start={start}
                  groupName={groupName}
                  end={end}
                  layerId={layer.id}
                  squashed={!!palette.squash}
                  noclipped={!!palette.noclip}
                  index={i}
                  palette={palette}
                />
              )
              : null}

            <Palette
              setCustomPalette={setCustomPalette}
              groupName={groupName}
              clearCustomPalette={clearCustomPalette}
              getDefaultLegend={getDefaultLegend}
              getCustomPalette={getCustomPalette}
              palettesTranslate={palettesTranslate}
              activePalette={palette.custom || '__default'}
              layer={layer}
              canvas={canvasRef.current}
              index={i}
              paletteOrder={paletteOrder}
            />
          </TabPane>
        );
      }

      paneElements.push(paneItemEl);
      navElements.push(navItemEl);
    });
    return (
      <div className="double-palette">
        <Nav tabs>{navElements}</Nav>
        <TabContent activeTab={activeIndex}>{paneElements}</TabContent>
      </div>
    );
  }

  /**
   * Render Opacity, threshold, and custom palette options
   */
  function renderCustomPalettes() {
    const paletteLegends = getPaletteLegends(layer.id);
    if (!paletteLegends) return '';
    const len = paletteLegends.length;
    const palette = getPalette(layer.id, 0);
    const legend = getPaletteLegend(layer.id, 0);
    const max = palette.legend.colors.length - 1;
    const start = palette.min ? legend.refs.indexOf(palette.entries.refs[palette.min]) : 0;
    const end = palette.max ? legend.refs.indexOf(palette.entries.refs[palette.max]) : max;
    if (len > 1) {
      return renderMultiColormapCustoms(paletteLegends);
    } if (legend.type === 'classification' && legend.colors.length > 1) {
      return (
        <ClassificationToggle
          height={Math.ceil(screenHeight / 2)}
          palette={palette}
          toggle={(classIndex) => toggleClassification(layer.id, classIndex, 0, groupName)}
          legend={legend}
          toggleAll={(disabledArray) => {
            toggleAllClassifications(layer.id, disabledArray, 0, groupName);
          }}
        />
      );
    }
    return (
      <>
        {legend.type !== 'classification' &&
          (
            <PaletteThreshold
              key={`${layer.id}0_threshold`}
              legend={legend}
              globalTemperatureUnit={globalTemperatureUnit}
              setRange={setThresholdRange}
              min={0}
              max={max}
              start={start}
              layerId={layer.id}
              end={end}
              squashed={!!palette.squash}
              noclipped={!!palette.noclip}
              groupName={groupName}
              index={0}
              palette={palette}
            />
          )}
        <Palette
          setCustomPalette={setCustomPalette}
          clearCustomPalette={clearCustomPalette}
          getDefaultLegend={getDefaultLegend}
          getCustomPalette={getCustomPalette}
          palettesTranslate={palettesTranslate}
          activePalette={palette.custom || '__default'}
          layer={layer}
          canvas={canvasRef.current}
          groupName={groupName}
          index={0}
          paletteOrder={paletteOrder}
        />
      </>
    );
  }

  /**
   * Render Granule count slider and granule date list settings (if granule layer)
   */
  const renderGranuleSettings = () => {
    const { count, dates, granulePlatform } = granuleOptions;
    return count
      ? (
        <>
          <GranuleCountSlider
            def={layer}
            count={count}
            granuleDates={dates}
            isMobile={isMobile}
            updateGranuleLayerOptions={updateGranuleLayerOptions}
          />
          {allowGranuleReorder && dates && (
            <GranuleLayerDateList
              def={layer}
              screenHeight={screenHeight}
              granuleDates={dates}
              granuleCount={count}
              updateGranuleLayerOptions={updateGranuleLayerOptions}
              resetGranuleLayerDates={resetGranuleLayerDates}
              granulePlatform={granulePlatform}
            />
          )}
        </>
      )
      : null;
  };

  let renderCustomizations;
  const hasAssociatedLayers = layer.associatedLayers && layer.associatedLayers.length;
  const hasTracks = layer.orbitTracks && layer.orbitTracks.length;
  const titilerLayer = layer.id === 'HLS_Customizable_Sentinel' || layer.id === 'HLS_Customizable_Landsat';
  const granuleMetadata = layer?.enableCMRDataFinder && !(zot?.underZoomValue > 0);
  const layerGroup = layer.layergroup;

  if (layer.type !== 'vector') {
    renderCustomizations = customPalettesIsActive && palettedAllowed && layer.palette
      ? renderCustomPalettes()
      : '';
  } else if (!layer.disableCustomPalettes && layerGroup !== 'Orbital Track' && layerGroup !== 'Reference') {
    // Orbital Tracks palette swap looks bad at WMS zoom levels (white text stamps)
    // Reference (MGRS/HLS Grid) has no need for palettes
    renderCustomizations = renderCustomPalettes();
  }

  if (!layer.id) return '';
  return (
    <>
      <Opacity
        start={Math.ceil(layer.opacity * 100)}
        setOpacity={setOpacity}
        layer={layer}
      />
      {!!maxDayRange && (
        <DayRangeSlider
          layer={layer}
          dayCount={dayCount}
          maxDayRange={maxDayRange}
          isMobile={isMobile}
          updateDayCount={updateDayCount}
        />
      )}
      {renderGranuleSettings()}
      {renderCustomizations}
      {titilerLayer && <BandSelection layer={layer} />}
      {granuleMetadata && <ImagerySearch layer={layer} /> }
      {(hasAssociatedLayers || hasTracks) && <AssociatedLayers layer={layer} />}
    </>
  );
}

function mapStateToProps(state, ownProps) {
  const {
    config, palettes, compare, screenSize, settings,
  } = state;
  const { custom } = palettes;
  const groupName = compare.activeString;
  const globalTemperatureUnit = lodashGet(ownProps, 'layer.disableUnitConversion') ? '' : settings.globalTemperatureUnit;

  const granuleOptions = {};
  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);
  }

  const maxDayRange = getMaxDayRange(ownProps.layer);
  const dayCount = maxDayRange ? getLayerDayCount(state, ownProps.layer.id) : undefined;

  return {
    paletteOrder: config.paletteOrder,
    granuleOptions,
    groupName,
    maxDayRange,
    dayCount,
    isMobile: screenSize.isMobileDevice,
    screenHeight: screenSize.screenHeight,
    customPalettesIsActive: !!config.features.customPalettes,
    globalTemperatureUnit,
    palettedAllowed: isPaletteAllowed(ownProps.layer.id, config),
    palettesTranslate: palettesTranslateUtil,
    getDefaultLegend: (layerId, index) => getDefaultLegendSelector(layerId, index, state),
    getCustomPalette: (id) => getCustomPaletteSelector(id, custom),
    getPaletteLegend: (layerId, index) => getPaletteLegendSelector(
      layerId,
      index,
      groupName,
      state,
    ),
    getPaletteLegends: (layerId) => getPaletteLegendsSelector(layerId, groupName, state),
    getPalette: (layerId, index) => getPaletteSelector(layerId, index, groupName, state),
    getVectorStyle: (layerId, index) => getVectorStyle(layerId, index, groupName, state),
    vectorStyles: config.vectorStyles,
  };
}
const mapDispatchToProps = (dispatch) => ({
  toggleClassification: (layerId, classIndex, index, groupName) => {
    dispatch(
      setToggledClassification(layerId, classIndex, index, groupName),
    );
  },
  toggleAllClassifications: (layerId, disabledArray, index, groupName) => {
    dispatch(
      refreshDisabledClassification(layerId, disabledArray, index, groupName),
    );
  },
  setThresholdRange: (layerId, min, max, squash, noclip, index, groupName) => {
    const props = {
      min, max, squash, noclip,
    };
    dispatch(
      setThresholdRangeSquashAndNoClip(layerId, props, index, groupName),
    );
  },
  setFilterRange: (layerId, min, max, index, groupName) => {
    dispatch(
      setFilterRange(layerId, { min, max }, index, groupName),
    );
  },
  setCustomPalette: (layerId, paletteId, index, groupName) => {
    dispatch(setCustomPaletteAction(layerId, paletteId, index, groupName));
  },
  clearCustomPalette: (layerId, index, groupName) => {
    dispatch(clearCustomPaletteAction(layerId, index, groupName));
  },
  setStyle: (layer, vectorStyleId, groupName) => {
    dispatch(setStyle(layer, vectorStyleId, groupName));
  },
  clearStyle: (layer, vectorStyleId, groupName) => {
    dispatch(clearStyle(layer, vectorStyleId, groupName));
  },
  setOpacity: (id, opacity) => {
    dispatch(setOpacityAction(id, opacity));
  },
  updateGranuleLayerOptions: (dates, def, count) => {
    dispatch(updateGranuleLayerOptionsAction(dates, def, count));
  },
  resetGranuleLayerDates: (id) => {
    dispatch(resetGranuleLayerDatesAction(id));
  },
  updateDayCount: (id, dayCount) => {
    dispatch(updateDayCountAction(id, dayCount));
  },
});

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(LayerSettings);

LayerSettings.defaultProps = {
  layer: { id: null, name: null },
  palettedAllowed: false,
};
LayerSettings.propTypes = {
  clearCustomPalette: PropTypes.func,
  customPalettesIsActive: PropTypes.bool,
  getCustomPalette: PropTypes.func,
  getDefaultLegend: PropTypes.func,
  getPalette: PropTypes.func,
  getPaletteLegend: PropTypes.func,
  getPaletteLegends: PropTypes.func,
  granuleOptions: PropTypes.oneOfType([PropTypes.object, PropTypes.oneOf(['null'])]),
  globalTemperatureUnit: PropTypes.string,
  groupName: PropTypes.string,
  layer: PropTypes.oneOfType([PropTypes.object, PropTypes.oneOf(['null'])]),
  maxDayRange: PropTypes.number,
  dayCount: PropTypes.number,
  isMobile: PropTypes.bool,
  updateDayCount: PropTypes.func,
  palettedAllowed: PropTypes.bool,
  paletteOrder: PropTypes.oneOfType([PropTypes.array, PropTypes.oneOf(['null'])]),
  palettesTranslate: PropTypes.func,
  resetGranuleLayerDates: PropTypes.func,
  screenHeight: PropTypes.number,
  setCustomPalette: PropTypes.func,
  setOpacity: PropTypes.func,
  setThresholdRange: PropTypes.func,
  toggleClassification: PropTypes.func,
  updateGranuleLayerOptions: PropTypes.func,
  toggleAllClassifications: PropTypes.func,
  zot: PropTypes.oneOfType([PropTypes.object, PropTypes.oneOf(['null'])]),
};