Skip to content

Interactive interface for browsing global, full-resolution satellite imagery

More linting rules

Jason Kent3e598d2dfc02
diff --git a/.eslintrc b/.eslintrc
index d36c0eec3..544481f7b 100644
--- a/.eslintrc
+++ b/.eslintrc
@@ -75,22 +75,28 @@
*/
// Base rule overrides
- "default-case": "warn",
- "no-nested-ternary": "warn",
- "no-shadow": "warn",
- "prefer-const": "warn",
- "class-methods-use-this": "warn",
- "no-plusplus": "warn",
+ "no-nested-ternary": "warn", // 58 errors
+ "no-shadow": "warn", // 136 errors
"max-len": "off",
-
- "consistent-return": "off",
+ "consistent-return": "off", // 73 erorrs
"no-underscore-dangle": "off",
"func-names": "off",
- "no-param-reassign": "warn",
- "no-use-before-define": "off",
+ "no-param-reassign": [ // 329 errors
+ "warn",
+ {
+ "props": false
+ }
+ ],
+ "no-use-before-define": [
+ "error",
+ {
+ "functions": false,
+ "classes": true,
+ "variables": false
+ }
+ ],
// Import rules overrides
- "import/prefer-default-export": "off",
"import/no-cycle": "warn",
// Accesibility rules overrides
@@ -107,13 +113,48 @@
"jsx-a11y/click-events-have-key-events": "off",
// React rules overrides
- "react/destructuring-assignment": "warn", // 464 errors
- "react/no-unused-state": "warn", // 38 errors
- "react/jsx-props-no-spreading": "warn",
+ "react/jsx-props-no-spreading": "warn", // 17 errors
"react/jsx-filename-extension": "off",
- "react/sort-comp": "off",
-
- "react/no-unused-prop-types": "warn", // 66 errors
+ "react/sort-comp": [
+ "error",
+ {
+ "order": [
+ "static-methods",
+ "lifecycle",
+ "everything-else",
+ "render"
+ ],
+ "groups": {
+ "lifecycle": [
+ "displayName",
+ "propTypes",
+ "contextTypes",
+ "childContextTypes",
+ "mixins",
+ "statics",
+ "defaultProps",
+ "constructor",
+ "getDefaultProps",
+ "state",
+ "getInitialState",
+ "getChildContext",
+ "getDerivedStateFromProps",
+ "componentWillMount",
+ "UNSAFE_componentWillMount",
+ "componentDidMount",
+ "componentWillReceiveProps",
+ "UNSAFE_componentWillReceiveProps",
+ "shouldComponentUpdate",
+ "componentWillUpdate",
+ "UNSAFE_componentWillUpdate",
+ "getSnapshotBeforeUpdate",
+ "componentDidUpdate",
+ "componentDidCatch",
+ "componentWillUnmount"
+ ]
+ }
+ }
+ ],
"react/forbid-prop-types": "off", // 216 errors
"react/require-default-props": "off" // 965 errors
}
diff --git a/e2e/features/data-download/data-download-test.js b/e2e/features/data-download/data-download-test.js
index 68dd45cd1..530542ccd 100644
--- a/e2e/features/data-download/data-download-test.js
+++ b/e2e/features/data-download/data-download-test.js
@@ -50,7 +50,7 @@ module.exports = {
// On Valid Data Select, 'No Data Available' indicator disappears and data layer is in sidebar
// Click from year 2022 down to 2013
- for (let i = 0; i <= 8; i++) {
+ for (let i = 0; i <= 8; i += 1) {
client.click(downYearInputButton);
}
client.expect
@@ -62,7 +62,7 @@ module.exports = {
// On Valid Data Select, 'No Data Available' indicator appears
// Click from year 2013 up to 2022
- for (let i = 0; i <= 8; i++) {
+ for (let i = 0; i <= 8; i += 1) {
client.click(upYearInputButton);
}
client.expect.element('#indicator').to.be.present;
diff --git a/e2e/features/image-download/resolutions3413-test.js b/e2e/features/image-download/resolutions3413-test.js
index 1c588a0ea..ea0890d4c 100644
--- a/e2e/features/image-download/resolutions3413-test.js
+++ b/e2e/features/image-download/resolutions3413-test.js
@@ -66,7 +66,7 @@ module.exports = {
'Last zoom level is 250m': function(c) {
// mash the zoom button a bunch of times and see if it changes
- for (let i = 0; i < 5; i++) {
+ for (let i = 0; i < 5; i += 1) {
zoomIn(c, 'arctic');
}
openImageDownloadPanel(c);
diff --git a/e2e/features/image-download/resolutions4326-test.js b/e2e/features/image-download/resolutions4326-test.js
index 1e9851355..462a247ba 100644
--- a/e2e/features/image-download/resolutions4326-test.js
+++ b/e2e/features/image-download/resolutions4326-test.js
@@ -94,7 +94,7 @@ module.exports = {
'Last zoom level is 30m': function(c) {
// mash the zoom button a bunch of times and see if it changes
- for (let i = 0; i < 5; i++) {
+ for (let i = 0; i < 5; i += 1) {
zoomIn(c, 'geographic');
}
openImageDownloadPanel(c);
diff --git a/e2e/features/tour/tour-test.js b/e2e/features/tour/tour-test.js
index af3be368a..8126cdd12 100644
--- a/e2e/features/tour/tour-test.js
+++ b/e2e/features/tour/tour-test.js
@@ -15,7 +15,7 @@ module.exports = {
client.waitForElementVisible('.tour-in-progress .step-total', 2000, () => {
client.getText('.tour-in-progress .step-total', (result) => { totalSteps = parseInt(result.value, 10); })
.perform(() => {
- for (let i = 0; i < totalSteps; i++) {
+ for (let i = 0; i < totalSteps; i += 1) {
client.pause(500);
client.click('.step-container .step-next');
}
diff --git a/tasks/link-check/html-url-extract.js b/tasks/link-check/html-url-extract.js
index f4f4c087b..ab8377b77 100644
--- a/tasks/link-check/html-url-extract.js
+++ b/tasks/link-check/html-url-extract.js
@@ -28,7 +28,7 @@ const getUrls = (htmlArray) => {
const trackDoubles = {};
const scrapedHTML = [];
- for (let i = 0; i < htmlArray.length; i++) {
+ for (let i = 0; i < htmlArray.length; i += 1) {
const $ = cheerio.load(fs.readFileSync(htmlArray[i]));
const links = $('a');
diff --git a/tasks/link-check/natural-event-url-extract.js b/tasks/link-check/natural-event-url-extract.js
index c91d289db..fd6bed64a 100644
--- a/tasks/link-check/natural-event-url-extract.js
+++ b/tasks/link-check/natural-event-url-extract.js
@@ -35,14 +35,14 @@ const scrapeLinks = async(htmlLinks) => {
const trackDoubles = {};
const addedUrls = [];
- for (let i = 0; i < htmlLinks.length; i++) {
+ for (let i = 0; i < htmlLinks.length; i += 1) {
const htmlLink = htmlLinks[i];
// eslint-disable-next-line no-await-in-loop
await fetch(htmlLink)
.then(async(res) => {
const status = await res.json();
const urls = await findProp(status, ['url', 'link', 'source']);
- for (let j = 0; j < urls.length; j++) {
+ for (let j = 0; j < urls.length; j += 1) {
const url = urls[j];
const linkRel = Object.keys(url)[0];
const linkHref = Object.values(url)[0];
diff --git a/tasks/link-check/url-check.js b/tasks/link-check/url-check.js
index 478fb676e..d82a01ef1 100644
--- a/tasks/link-check/url-check.js
+++ b/tasks/link-check/url-check.js
@@ -10,7 +10,7 @@ const requestCheck = async(urls) => {
ERROR: [],
STATUSCODE: {},
};
- for (let i = 0; i < urls.length; i++) {
+ for (let i = 0; i < urls.length; i += 1) {
const linkName = Object.keys(urls[i])[0];
const url = Object.values(urls[i])[0];
diff --git a/web/js/app.js b/web/js/app.js
index 2f2e6573a..212944f34 100644
--- a/web/js/app.js
+++ b/web/js/app.js
@@ -81,7 +81,7 @@ import '../css/vectorMeta.css';
import '../css/geostationary-modal.css';
import '../css/orbitTracks.css';
import '../pages/css/document.css';
-import { keyPress } from './modules/key-press/actions';
+import keyPress from './modules/key-press/actions';
class App extends React.Component {
constructor(props) {
@@ -90,11 +90,6 @@ class App extends React.Component {
this.handleKeyPress = this.handleKeyPress.bind(this);
}
- handleKeyPress(event) {
- const ctrlOrCmdKey = event.ctrlKey || event.metaKey;
- this.props.keyPressAction(event.keyCode, event.shiftKey, ctrlOrCmdKey);
- }
-
componentDidMount() {
document.addEventListener('keydown', this.handleKeyPress);
}
@@ -103,45 +98,16 @@ class App extends React.Component {
document.removeEventListener('keydown', this.handleKeyPress);
}
- render() {
- const {
- isAnimationWidgetActive, isTourActive, locationKey, modalId, mapMouseEvents,
- } = this.props;
-
- return (
- <div className="wv-content" id="wv-content" data-role="content">
- <Toolbar />
- <MapInteractions mouseEvents={mapMouseEvents} />
- <div id="wv-alert-container" className="wv-alert-container">
- <FeatureAlert />
- </div>
- <Sidebar />
- {isTourActive ? <Tour /> : null}
- <div id="layer-modal" className="layer-modal" />
- <div id="layer-settings-modal" />
- <div id="eventsHolder" />
- <div id="imagedownload" />
- <div id="dlMap" />
- <Timeline key={locationKey || '1'} />
- <div id="wv-animation-widet-case">
- {isAnimationWidgetActive ? <AnimationWidget key={locationKey || '2'} /> : null}
- </div>
- <MeasureButton />
-
- <Modal key={modalId} />
- <ErrorBoundary>
- <Debug parameters={this.props.parameters} />
- </ErrorBoundary>
- </div>
- );
+ handleKeyPress(event) {
+ const { keyPressAction } = this.props;
+ const ctrlOrCmdKey = event.ctrlKey || event.metaKey;
+ keyPressAction(event.keyCode, event.shiftKey, ctrlOrCmdKey);
}
onload() {
const self = this;
- let config;
const state = self.props.parameters;
-
- config = self.props.config;
+ const { config } = self.props;
config.parameters = state;
// get user IP address for GTM/GA using https://www.ipify.org/ API
@@ -190,7 +156,41 @@ class App extends React.Component {
};
util.wrap(main)();
}
+
+ render() {
+ const {
+ isAnimationWidgetActive, isTourActive, locationKey, modalId, mapMouseEvents, parameters,
+ } = this.props;
+
+ return (
+ <div className="wv-content" id="wv-content" data-role="content">
+ <Toolbar />
+ <MapInteractions mouseEvents={mapMouseEvents} />
+ <div id="wv-alert-container" className="wv-alert-container">
+ <FeatureAlert />
+ </div>
+ <Sidebar />
+ {isTourActive ? <Tour /> : null}
+ <div id="layer-modal" className="layer-modal" />
+ <div id="layer-settings-modal" />
+ <div id="eventsHolder" />
+ <div id="imagedownload" />
+ <div id="dlMap" />
+ <Timeline key={locationKey || '1'} />
+ <div id="wv-animation-widet-case">
+ {isAnimationWidgetActive ? <AnimationWidget key={locationKey || '2'} /> : null}
+ </div>
+ <MeasureButton />
+
+ <Modal key={modalId} />
+ <ErrorBoundary>
+ <Debug parameters={parameters} />
+ </ErrorBoundary>
+ </div>
+ );
+ }
}
+
function mapStateToProps(state, ownProps) {
return {
state,
@@ -226,5 +226,4 @@ App.propTypes = {
mapMouseEvents: PropTypes.object,
modalId: PropTypes.string,
parameters: PropTypes.object,
- state: PropTypes.object,
};
diff --git a/web/js/combine-middleware.js b/web/js/combine-middleware.js
index df67515d9..e647d4f04 100644
--- a/web/js/combine-middleware.js
+++ b/web/js/combine-middleware.js
@@ -8,7 +8,7 @@ const loggerMiddleware = createLogger({ collapsed: true });
* @param {Boolean} isDebugMode | Server is in debug mode
* @param {Object} locationMiddleware | redux-location-state middleware
*/
-export function getMiddleware(isDebugMode, locationMiddleware) {
+export default function getMiddleware(isDebugMode, locationMiddleware) {
return isDebugMode
? compact([thunkMiddleware, locationMiddleware, loggerMiddleware])
: compact([thunkMiddleware, locationMiddleware]);
diff --git a/web/js/combine-models.js b/web/js/combine-models.js
index ae8bdfaf8..1348be115 100644
--- a/web/js/combine-models.js
+++ b/web/js/combine-models.js
@@ -1,11 +1,11 @@
import util from './util/util';
-import { mapModel } from './map/model';
+import mapModel from './map/model';
/**
* Return initiated legacy models Object
* @param {Object} config
*/
-export function combineModels(config) {
+export default function combineModels(config) {
const models = {
wv: {
events: util.events(),
diff --git a/web/js/combine-ui.js b/web/js/combine-ui.js
index 079ad8b26..08bc6f7f8 100644
--- a/web/js/combine-ui.js
+++ b/web/js/combine-ui.js
@@ -1,7 +1,7 @@
import util from './util/util';
-import { mapui } from './map/ui';
-import { mapAnimate } from './map/animate';
-import { dataUi } from './map/data/ui';
+import mapui from './map/ui';
+import mapAnimate from './map/animate';
+import dataUi from './map/data/ui';
import naturalEventsUI from './map/natural-events/ui';
/**
@@ -10,7 +10,7 @@ import naturalEventsUI from './map/natural-events/ui';
* @param {Object} config
* @param {Object} MapMouseEvents | Map events object that is registered here and used in react to render coords
*/
-export function combineUi(models, config, MapMouseEvents, store) {
+export default function combineUi(models, config, MapMouseEvents, store) {
const ui = {};
ui.events = util.events();
const subscribeToStore = function() {
@@ -52,6 +52,7 @@ export function combineUi(models, config, MapMouseEvents, store) {
return ui;
}
+
function registerMapMouseHandlers(maps, events) {
Object.values(maps).forEach((map) => {
const element = map.getTargetElement();
diff --git a/web/js/components/animation-widget/gif-panel-grid.js b/web/js/components/animation-widget/gif-panel-grid.js
index e9f3a9896..bf53ad191 100644
--- a/web/js/components/animation-widget/gif-panel-grid.js
+++ b/web/js/components/animation-widget/gif-panel-grid.js
@@ -11,22 +11,22 @@ import { faTimes } from '@fortawesome/free-solid-svg-icons';
* @class ResolutionTable
* @extends React.Component
*/
-export class GifPanelGrid extends React.Component {
+export default class GifPanelGrid extends React.Component {
renderImageSize() {
- const { requestSize } = this.props;
+ const { valid, maxGifSize, requestSize } = this.props;
const roundedSize = requestSize.toFixed(2);
- if (!this.props.valid) {
+ if (!valid) {
return (
<div id="gif-size" className="gif-size gif-size-invalid grid-child">
<FontAwesomeIcon icon={faTimes} fixedWidth />
- <span>{`${this.props.maxGifSize} MB ~${roundedSize} MB`}</span>
+ <span>{`${maxGifSize} MB ~${roundedSize} MB`}</span>
</div>
);
}
return (
<div id="gif-size" className="gif-size grid-child">
<span>
- {`${this.props.maxGifSize} MB / ~${roundedSize} MB`}
+ {`${maxGifSize} MB / ~${roundedSize} MB`}
{' '}
</span>
</div>
@@ -34,6 +34,9 @@ export class GifPanelGrid extends React.Component {
}
render() {
+ const {
+ startDate, endDate, speed, increment, valid, height, width, maxImageDimensionSize,
+ } = this.props;
const imageSize = this.renderImageSize();
return (
<div className="gif-download-grid">
@@ -42,7 +45,7 @@ export class GifPanelGrid extends React.Component {
</div>
<div className="grid-child">
<span>
- {this.props.startDate}
+ {startDate}
{' '}
</span>
</div>
@@ -50,19 +53,19 @@ export class GifPanelGrid extends React.Component {
<span>End Date: </span>
</div>
<div className="grid-child">
- <span>{this.props.endDate}</span>
+ <span>{endDate}</span>
</div>
<div className="grid-child label">
<span>Speed: </span>
</div>
<div className="grid-child">
- <span>{`${this.props.speed} Frames Per Second`}</span>
+ <span>{`${speed} Frames Per Second`}</span>
</div>
<div className="grid-child label">
<span>Increment:</span>
</div>
<div className="grid-child">
- <span>{this.props.increment}</span>
+ <span>{increment}</span>
</div>
<div className="grid-child label">
<span>Max / Raw Size:</span>
@@ -73,18 +76,18 @@ export class GifPanelGrid extends React.Component {
</div>
<div
className={
- this.props.valid
+ valid
? 'grid-child gif-max-size'
: 'grid-child gif-max-size gif-size-invalid'
}
>
- <span>{`${this.props.maxImageDimensionSize}px`}</span>
+ <span>{`${maxImageDimensionSize}px`}</span>
</div>
<div className="grid-child label">
<span>Image Dimensions:</span>
</div>
<div className="grid-child" id="wv-image-width">
- <span>{`${this.props.width}px x ${this.props.height}px`}</span>
+ <span>{`${width}px x ${height}px`}</span>
</div>
</div>
);
diff --git a/web/js/components/animation-widget/gif-panel.js b/web/js/components/animation-widget/gif-panel.js
index d89832712..db76f391d 100644
--- a/web/js/components/animation-widget/gif-panel.js
+++ b/web/js/components/animation-widget/gif-panel.js
@@ -1,9 +1,9 @@
import React from 'react';
import PropTypes from 'prop-types';
import SelectionList from '../util/selector';
-import { GifPanelGrid } from './gif-panel-grid';
+import GifPanelGrid from './gif-panel-grid';
import Button from '../util/button';
-import { Checkbox } from '../util/checkbox';
+import Checkbox from '../util/checkbox';
import { getDimensions } from '../../modules/image-download/util';
const MAX_GIF_SIZE = 250;
@@ -20,13 +20,9 @@ export default class GifPanel extends React.Component {
constructor(props) {
super(props);
this.state = {
- imgHeight: props.imgHeight,
- imgWidth: props.imgWidth,
speed: props.speed,
resolutions: props.resolutions,
resolution: props.resolution,
- valid: props.valid,
- showDates: props.showDates,
increment: props.increment,
};
this.handleChange = this.handleChange.bind(this);
@@ -47,8 +43,13 @@ export default class GifPanel extends React.Component {
onCheck,
showDates,
numberOfFrames,
+ firstLabel,
+ onClick,
+ onDownloadClick,
} = this.props;
- const { resolution } = this.state;
+ const {
+ resolution, resolutions, speed, increment,
+ } = this.state;
const dimensions = getDimensions(projId, lonlats, resolution);
const { height } = dimensions;
const { width } = dimensions;
@@ -58,11 +59,11 @@ export default class GifPanel extends React.Component {
<div className="gif-dialog">
<div className="animation-gif-dialog-wrapper">
<div className="gif-selector-case">
- {this.props.firstLabel}
+ {firstLabel}
<SelectionList
id="gif-resolution"
- optionArray={this.state.resolutions}
- value={this.state.resolution}
+ optionArray={resolutions}
+ value={resolution}
optionName="resolution"
onChange={this.handleChange}
/>
@@ -74,14 +75,14 @@ export default class GifPanel extends React.Component {
maxGifSize={MAX_GIF_SIZE}
maxImageDimensionSize={MAX_IMAGE_DIMENSION_SIZE}
valid={valid}
- onClick={this.props.onDownloadClick}
+ onClick={onDownloadClick}
startDate={startDate}
endDate={endDate}
- speed={this.state.speed}
- increment={this.state.increment}
+ speed={speed}
+ increment={increment}
/>
<Button
- onClick={() => this.props.onClick(width, height)}
+ onClick={() => onClick(width, height)}
text="Create GIF"
valid={valid}
/>
@@ -101,33 +102,23 @@ export default class GifPanel extends React.Component {
GifPanel.defaultProps = {
firstLabel: 'Resolution (per pixel):',
- maxGifSize: 20,
- secondLabel: 'Format',
showDates: true,
};
GifPanel.propTypes = {
- checked: PropTypes.bool,
endDate: PropTypes.string,
firstLabel: PropTypes.string,
- imgHeight: PropTypes.number,
- imgWidth: PropTypes.number,
increment: PropTypes.string,
lonlats: PropTypes.array,
- maxGifSize: PropTypes.number,
- maxImageDimensionSize: PropTypes.number,
numberOfFrames: PropTypes.number,
onCheck: PropTypes.func,
onClick: PropTypes.func,
onDownloadClick: PropTypes.func,
projId: PropTypes.string,
- requestSize: PropTypes.string,
resolution: PropTypes.string,
resolutions: PropTypes.object,
- secondLabel: PropTypes.string,
showDates: PropTypes.bool,
speed: PropTypes.number,
startDate: PropTypes.string,
- valid: PropTypes.bool,
};
const isFileSizeValid = function(requestSize, imgHeight, imgWidth) {
return (
diff --git a/web/js/components/animation-widget/gif-post-creation.js b/web/js/components/animation-widget/gif-post-creation.js
index 3733f6b0a..b8297a8da 100644
--- a/web/js/components/animation-widget/gif-post-creation.js
+++ b/web/js/components/animation-widget/gif-post-creation.js
@@ -8,7 +8,7 @@ import { Modal, ModalBody, ModalHeader } from 'reactstrap';
import util from '../../util/util';
import Button from '../util/button';
-export class GifResults extends Component {
+export default class GifResults extends Component {
getStyle(imgElWidth, imgElHeight) {
const { screenHeight, screenWidth } = this.props;
const width = imgElWidth + 204;
diff --git a/web/js/components/animation-widget/loop-button.js b/web/js/components/animation-widget/loop-button.js
index 2288ea770..c3171d230 100644
--- a/web/js/components/animation-widget/loop-button.js
+++ b/web/js/components/animation-widget/loop-button.js
@@ -1,3 +1,4 @@
+/* eslint-disable react/destructuring-assignment */
import React from 'react';
import PropTypes from 'prop-types';
diff --git a/web/js/components/animation-widget/play-queue.js b/web/js/components/animation-widget/play-queue.js
index d212c7a26..99e59110c 100644
--- a/web/js/components/animation-widget/play-queue.js
+++ b/web/js/components/animation-widget/play-queue.js
@@ -82,7 +82,7 @@ class PlayAnimation extends React.Component {
} else {
day = this.nextDate(day);
}
- i++;
+ i += 1;
}
return util.toISOStringSeconds(day);
};
@@ -104,7 +104,7 @@ class PlayAnimation extends React.Component {
togglePlaying();
return;
}
- for (let i = 0; i < queueLength; i++) {
+ for (let i = 0; i < queueLength; i += 1) {
this.addDate(day);
day = this.getNextBufferDate(day, startDate, endDate);
if (util.toISOStringSeconds(day) === lastToQueue) {
@@ -120,10 +120,11 @@ class PlayAnimation extends React.Component {
*/
checkShouldPlay = function(isLoopStart) {
const { startDate, endDate, hasCustomPalettes } = this.props;
+ const { isPlaying } = this.state;
const currentDate = util.parseDateUTC(this.currentPlayingDate);
const lastToQueue = this.getLastBufferDateStr(currentDate, startDate, endDate);
- if (this.state.isPlaying && !isLoopStart) {
+ if (isPlaying && !isLoopStart) {
return false;
}
if (this.preloadObject[lastToQueue]) {
@@ -227,16 +228,16 @@ class PlayAnimation extends React.Component {
* @param endDate {object} JS date
*/
customQueuer(currentDate, startDate, endDate) {
- let nextDateStr;
+ const { isPlaying } = this.state;
let nextDate = this.nextDate(currentDate);
if (nextDate > endDate) {
nextDate = startDate;
}
- nextDateStr = util.toISOStringSeconds(nextDate);
+ const nextDateStr = util.toISOStringSeconds(nextDate);
if (
!this.preloadObject[nextDateStr]
&& !this.inQueueObject[nextDateStr]
- && !this.state.isPlaying
+ && !isPlaying
) {
this.clearCache();
this.checkQueue();
@@ -334,7 +335,7 @@ class PlayAnimation extends React.Component {
if (day.valueOf() === jsTestDate.valueOf()) {
return true;
}
- i++;
+ i += 1;
}
return false;
}
@@ -375,7 +376,8 @@ class PlayAnimation extends React.Component {
*/
play(dateStr) {
const { togglePlaying } = this.props;
- if (!this.state.isPlaying) this.setState({ isPlaying: true });
+ const { isPlaying } = this.state;
+ if (!isPlaying) this.setState({ isPlaying: true });
this.animate(dateStr);
if (document.hidden) {
diff --git a/web/js/components/compare/alert.js b/web/js/components/compare/alert.js
index 47e838972..cbb82b630 100644
--- a/web/js/components/compare/alert.js
+++ b/web/js/components/compare/alert.js
@@ -1,6 +1,6 @@
import React from 'react';
-export const CompareAlertModalBody = () => (
+const CompareAlertModalBody = () => (
<div className="compare-dialog">
<p>How to get started?</p>
<ul>
@@ -29,3 +29,5 @@ export const CompareAlertModalBody = () => (
</ul>
</div>
);
+
+export default CompareAlertModalBody;
diff --git a/web/js/components/compare/opacity-slider.js b/web/js/components/compare/opacity-slider.js
index 74e8d33cb..a689d9c0a 100644
--- a/web/js/components/compare/opacity-slider.js
+++ b/web/js/components/compare/opacity-slider.js
@@ -35,10 +35,12 @@ class OpacitySlider extends React.Component {
* @return {void}
*/
onSlide(value) {
- this.props.onSlide(value);
+ const { onSlide } = this.props;
+ onSlide(value);
}
render() {
+ const { value } = this.state;
return (
<div id="ab-slider-case" className="ab-slider-case">
<label className="wv-slider-label left">
@@ -46,7 +48,7 @@ class OpacitySlider extends React.Component {
</label>
<div className="input-range ">
<SliderWithTooltip
- defaultValue={this.state.value}
+ defaultValue={value}
tipFormatter={percentFormatter}
onChange={this.debounceOpacityUpdate}
onAfterChange={this.onSlide}
diff --git a/web/js/components/compare/pick.js b/web/js/components/compare/pick.js
index 35e41b66e..c6b31f419 100644
--- a/web/js/components/compare/pick.js
+++ b/web/js/components/compare/pick.js
@@ -7,8 +7,6 @@ class Pick extends React.Component {
super(props);
this.state = {
position: props.position,
- visibility: props.visibility,
- color: props.color,
max: props.max,
};
}
@@ -17,8 +15,9 @@ class Pick extends React.Component {
* Return visibility style string
*/
getVisibility() {
+ const { position, max } = this.state;
let visibility = 'visible';
- if (this.state.position < 0 || this.state.position > this.state.max) {
+ if (position < 0 || position > max) {
visibility = 'hidden';
}
return visibility;
@@ -30,7 +29,9 @@ class Pick extends React.Component {
* @param {number} y | y offset
*/
getText(x, y, visibility) {
- if (this.props.text) {
+ const { text } = this.props;
+ const { textColor } = this.state;
+ if (text) {
return (
<text
x={x}
@@ -38,11 +39,11 @@ class Pick extends React.Component {
alignmentBaseline="middle"
textAnchor="middle"
style={{
- fill: this.state.textColor ? this.state.textColor : null,
+ fill: textColor || null,
visibility: visibility || null,
}}
>
- {this.props.text}
+ {text}
</text>
);
}
@@ -51,7 +52,7 @@ class Pick extends React.Component {
render() {
const visibility = this.getVisibility();
const {
- yOffset, path, width, height,
+ yOffset, path, width, height, color,
} = this.props;
const { position } = this.state;
const translate = `translate(${position},${yOffset})`;
@@ -59,7 +60,7 @@ class Pick extends React.Component {
<g transform={translate}>
<path
style={{
- fill: this.props.color ? this.props.color : null,
+ fill: color || null,
visibility,
}}
d={path}
@@ -78,7 +79,6 @@ Pick.propTypes = {
path: PropTypes.string,
position: PropTypes.number,
text: PropTypes.string,
- visibility: PropTypes.string,
width: PropTypes.number,
yOffset: PropTypes.number,
};
diff --git a/web/js/components/date-selector/date-selector.js b/web/js/components/date-selector/date-selector.js
index 5d27e35e7..123b98098 100644
--- a/web/js/components/date-selector/date-selector.js
+++ b/web/js/components/date-selector/date-selector.js
@@ -28,6 +28,73 @@ class DateSelector extends Component {
};
}
+ shouldComponentUpdate(nextProps, nextState) {
+ const {
+ date,
+ subDailyMode,
+ maxDate,
+ minDate,
+ } = this.props;
+ const {
+ year,
+ month,
+ day,
+ hour,
+ minute,
+ yearValid,
+ monthValid,
+ dayValid,
+ hourValid,
+ minuteValid,
+ tab,
+ } = this.state;
+
+ const updateCheck = year === nextState.year
+ && month === nextState.month
+ && day === nextState.day
+ && hour === nextState.hour
+ && minute === nextState.minute
+ && yearValid === nextState.yearValid
+ && monthValid === nextState.monthValid
+ && dayValid === nextState.dayValid
+ && hourValid === nextState.hourValid
+ && minuteValid === nextState.minuteValid
+ && tab === nextState.tab
+ && date.getTime() === nextProps.date.getTime()
+ && subDailyMode === nextProps.subDailyMode
+ && maxDate.getTime() === nextProps.maxDate.getTime()
+ && minDate.getTime() === nextProps.minDate.getTime();
+ return !updateCheck;
+ }
+
+ componentDidUpdate(prevProps) {
+ const {
+ date,
+ id,
+ minDate,
+ maxDate,
+ } = this.props;
+ const {
+ year,
+ month,
+ day,
+ hour,
+ minute,
+ } = this.state;
+
+ // parent arrow clicks should override any temporary values within date selector
+ if (prevProps.date.getTime() !== date.getTime()) {
+ this.clearTimeValuesAndValidation();
+ }
+ // handle animation start/end date limit changes and pending invalid -> valid dates
+ const minDateChangeEndUpdate = id === 'end' && prevProps.minDate.getTime() !== minDate.getTime();
+ const maxDateChangeStartUpdate = id === 'start' && prevProps.maxDate.getTime() !== maxDate.getTime();
+ const anyPendingTimeUnits = year || month || day || hour || minute;
+ if ((minDateChangeEndUpdate || maxDateChangeStartUpdate) && anyPendingTimeUnits) {
+ this.updateDate();
+ }
+ }
+
/**
* @desc add individual timeunit input
*
@@ -48,10 +115,11 @@ class DateSelector extends Component {
* @param {Number} previousTab - input
* @returns {void}
*/
- setFocusedTab = (tab, previousTab = this.state.previousTab) => {
+ setFocusedTab = (tab, previousTabParam) => {
+ const { previousTab } = this.state;
this.setState({
tab,
- previousTab,
+ previousTab: previousTabParam || previousTab,
});
}
@@ -241,6 +309,7 @@ class DateSelector extends Component {
const dateWithinRange = dateTime >= minDateTime && dateTime <= maxDateTime;
// updateDate at this stage can still be invalid with pending timeunit changes
+ // eslint-disable-next-line react/destructuring-assignment
const updatedDate = date.getTime() !== this.props.date.getTime();
const newDateWithinRange = dateWithinRange && updatedDate;
if (validDate && (isRollDate || newDateWithinRange)) {
@@ -274,6 +343,7 @@ class DateSelector extends Component {
* @param {Boolean} isRollDate
* @returns {void}
*/
+ // eslint-disable-next-line react/destructuring-assignment
updateDate = (date = this.props.date, isRollDate = false) => {
const { id, onDateChange } = this.props;
const newDate = this.updateDateCheck(date, isRollDate);
@@ -305,73 +375,6 @@ class DateSelector extends Component {
});
}
- shouldComponentUpdate(nextProps, nextState) {
- const {
- date,
- subDailyMode,
- maxDate,
- minDate,
- } = this.props;
- const {
- year,
- month,
- day,
- hour,
- minute,
- yearValid,
- monthValid,
- dayValid,
- hourValid,
- minuteValid,
- tab,
- } = this.state;
-
- const updateCheck = year === nextState.year
- && month === nextState.month
- && day === nextState.day
- && hour === nextState.hour
- && minute === nextState.minute
- && yearValid === nextState.yearValid
- && monthValid === nextState.monthValid
- && dayValid === nextState.dayValid
- && hourValid === nextState.hourValid
- && minuteValid === nextState.minuteValid
- && tab === nextState.tab
- && date.getTime() === nextProps.date.getTime()
- && subDailyMode === nextProps.subDailyMode
- && maxDate.getTime() === nextProps.maxDate.getTime()
- && minDate.getTime() === nextProps.minDate.getTime();
- return !updateCheck;
- }
-
- componentDidUpdate(prevProps) {
- const {
- date,
- id,
- minDate,
- maxDate,
- } = this.props;
- const {
- year,
- month,
- day,
- hour,
- minute,
- } = this.state;
-
- // parent arrow clicks should override any temporary values within date selector
- if (prevProps.date.getTime() !== date.getTime()) {
- this.clearTimeValuesAndValidation();
- }
- // handle animation start/end date limit changes and pending invalid -> valid dates
- const minDateChangeEndUpdate = id === 'end' && prevProps.minDate.getTime() !== minDate.getTime();
- const maxDateChangeStartUpdate = id === 'start' && prevProps.maxDate.getTime() !== maxDate.getTime();
- const anyPendingTimeUnits = year || month || day || hour || minute;
- if ((minDateChangeEndUpdate || maxDateChangeStartUpdate) && anyPendingTimeUnits) {
- this.updateDate();
- }
- }
-
render() {
const {
date,
diff --git a/web/js/components/date-selector/input.js b/web/js/components/date-selector/input.js
index 3b008c0bc..e1aae257b 100644
--- a/web/js/components/date-selector/input.js
+++ b/web/js/components/date-selector/input.js
@@ -20,6 +20,11 @@ class DateInputColumn extends Component {
this.inputs = [];
}
+ componentDidMount() {
+ this.updateValue();
+ this.setTextSize();
+ }
+
componentDidUpdate(prevProps) {
const { focused, tabIndex, value } = this.props;
if (focused) {
@@ -30,11 +35,6 @@ class DateInputColumn extends Component {
}
}
- componentDidMount() {
- this.updateValue();
- this.setTextSize();
- }
-
setTextSize = () => {
const { type } = this.props;
let size;
@@ -156,7 +156,8 @@ class DateInputColumn extends Component {
}
yearValidation = (input) => {
- const date = new Date(this.props.date);
+ let { date } = this.props;
+ date = new Date(date);
if (input > 1000 && input < 9999) {
const newDate = new Date(date.setUTCFullYear(input));
return this.validateDate(newDate);
@@ -165,7 +166,8 @@ class DateInputColumn extends Component {
}
monthValidation = (input) => {
- const date = new Date(this.props.date);
+ let { date } = this.props;
+ date = new Date(date);
let newDate;
// eslint-disable-next-line no-restricted-globals
if (!isNaN(input) && input < 13 && input > 0) {
@@ -195,7 +197,8 @@ class DateInputColumn extends Component {
}
dayValidation = (input) => {
- const date = new Date(this.props.date);
+ let { date } = this.props;
+ date = new Date(date);
const standardMaxDateForMonth = 31;
if (input > 0 && input <= standardMaxDateForMonth) {
@@ -215,7 +218,8 @@ class DateInputColumn extends Component {
}
hourValidation = (input) => {
- const date = new Date(this.props.date);
+ let { date } = this.props;
+ date = new Date(date);
if (input >= 0 && input <= 23) {
const newDate = new Date(date.setUTCHours(input));
return this.validateDate(newDate);
@@ -224,7 +228,8 @@ class DateInputColumn extends Component {
}
minuteValidation = (input) => {
- const date = new Date(this.props.date);
+ let { date } = this.props;
+ date = new Date(date);
if (input >= 0 && input <= 59) {
const newDate = new Date(date.setUTCMinutes(input));
return this.validateDate(newDate);
@@ -259,23 +264,25 @@ class DateInputColumn extends Component {
}
blur = (e) => {
- const { setFocusedTab, tabIndex, type } = this.props;
+ const {
+ setFocusedTab, tabIndex, type, value,
+ } = this.props;
// check for valid date on blur
const inputValue = e.target.value;
const newDate = this.validateBasedOnType(inputValue);
- let value = newDate === null
- ? this.props.value
+ let newValue = newDate === null
+ ? value
: inputValue;
// eslint-disable-next-line no-restricted-globals
- if (type === 'month' && !isNaN(value)) {
- value = util.monthStringArray[value - 1];
- } else if (value.length === 1) {
- value = `0${value}`;
+ if (type === 'month' && !isNaN(newValue)) {
+ newValue = util.monthStringArray[newValue - 1];
+ } else if (newValue.length === 1) {
+ newValue = `0${newValue}`;
}
this.setState({
- value,
+ value: newValue,
selected: false,
});
diff --git a/web/js/components/dateline/dateline.js b/web/js/components/dateline/dateline.js
index 50fd6e076..feb4a701e 100644
--- a/web/js/components/dateline/dateline.js
+++ b/web/js/components/dateline/dateline.js
@@ -52,11 +52,14 @@ class Line extends React.Component {
* return {Void}
*/
mouseOverHidden(e) {
- this.props.lineOver(
+ const {
+ lineOver, overlay, lineX, tooltip,
+ } = this.props;
+ lineOver(
[e.clientX, e.clientY],
- this.props.overlay,
- this.props.lineX,
- this.props.tooltip,
+ overlay,
+ lineX,
+ tooltip,
);
}
@@ -68,33 +71,46 @@ class Line extends React.Component {
* return {Void}
*/
mouseOutHidden() {
- this.props.lineOut(this.props.tooltip);
+ const { lineOut, tooltip } = this.props;
+ lineOut(tooltip);
}
render() {
+ const {
+ id,
+ svgStyle,
+ width,
+ style,
+ classes,
+ color,
+ strokeWidth,
+ opacity,
+ dashArray,
+ } = this.props;
+ const { height, active, hovered } = this.state;
return (
<svg
onMouseOver={this.mouseOver.bind(this)}
onMouseOut={this.mouseOut.bind(this)}
- style={this.props.svgStyle}
- width={this.props.width}
- id={this.props.id}
- height={this.state.height}
- className={this.props.classes}
+ style={svgStyle}
+ width={width}
+ id={id}
+ height={height}
+ className={classes}
>
<line
- strokeWidth={this.props.strokeWidth}
- stroke={this.props.color}
+ strokeWidth={strokeWidth}
+ stroke={color}
opacity={
- (this.state.hovered && this.state.active)
- || (this.state.active && util.browser.mobileAndTabletDevice)
- ? this.props.opacity
+ (hovered && active)
+ || (active && util.browser.mobileAndTabletDevice)
+ ? opacity
: '0'
}
- x1={this.props.strokeWidth / 2}
- x2={this.props.strokeWidth / 2}
- strokeDasharray={this.props.dashArray}
- y2={this.state.height}
+ x1={strokeWidth / 2}
+ x2={strokeWidth / 2}
+ strokeDasharray={dashArray}
+ y2={height}
y1="0"
/>
<line
@@ -102,14 +118,14 @@ class Line extends React.Component {
onMouseOver={this.mouseOverHidden.bind(this)}
onMouseMove={this.mouseOverHidden.bind(this)}
onMouseOut={this.mouseOutHidden.bind(this)}
- style={this.props.style}
+ style={style}
opacity="0"
- x1={this.props.strokeWidth / 2}
- x2={this.props.strokeWidth / 2}
- strokeWidth={this.props.strokeWidth}
- stroke={this.props.color}
+ x1={strokeWidth / 2}
+ x2={strokeWidth / 2}
+ strokeWidth={strokeWidth}
+ stroke={color}
y1="0"
- y2={this.state.height}
+ y2={height}
/>
</svg>
);
diff --git a/web/js/components/dateline/text.js b/web/js/components/dateline/text.js
index 6a24f3636..ebe3d9966 100644
--- a/web/js/components/dateline/text.js
+++ b/web/js/components/dateline/text.js
@@ -22,65 +22,53 @@ class LineText extends React.Component {
}
render() {
+ const { dateLeft, dateRight, active } = this.state;
+ const {
+ textWidth, recRadius, fill, textY, color, width, textOpacity, textHeight, rectOpacity,
+ } = this.props;
const leftTextWidth = Math.round(
- util.getTextWidth(this.state.dateLeft, '13px Open Sans') * 100,
- ) / 100 || this.props.textWidth;
+ util.getTextWidth(dateLeft, '13px Open Sans') * 100,
+ ) / 100 || textWidth;
const rightTextWidth = Math.round(
- util.getTextWidth(this.state.dateRight, '13px Open Sans') * 100,
- ) / 100 || this.props.textWidth;
+ util.getTextWidth(dateRight, '13px Open Sans') * 100,
+ ) / 100 || textWidth;
const svgStyle = {
transform: `translateX(${-(leftTextWidth + 20)}px)`,
};
return (
<svg className="dateline-text" style={svgStyle}>
<rect
- fill={this.props.fill}
+ fill={fill}
width={leftTextWidth + 12}
- height={this.props.textHeight}
+ height={textHeight}
x={0}
- rx={this.props.recRadius}
- opacity={
- this.state.active && this.state.dateLeft
- ? this.props.rectOpacity
- : '0'
- }
+ rx={recRadius}
+ opacity={active && dateLeft ? rectOpacity : '0'}
/>
<text
- y={this.props.textY}
+ y={textY}
x={6}
- fill={this.props.color}
- width={this.props.width}
- opacity={
- this.state.active && this.state.dateLeft
- ? this.props.textOpacity
- : '0'
- }
+ fill={color}
+ width={width}
+ opacity={active && dateLeft ? textOpacity : '0'}
>
- {this.state.dateLeft}
+ {dateLeft}
</text>
<rect
- fill={this.props.fill}
+ fill={fill}
width={rightTextWidth + 12}
- height={this.props.textHeight}
+ height={textHeight}
x={leftTextWidth + 40}
- rx={this.props.recRadius}
- opacity={
- this.state.active && this.state.dateRight
- ? this.props.rectOpacity
- : '0'
- }
+ rx={recRadius}
+ opacity={active && dateRight ? rectOpacity : '0'}
/>
<text
- y={this.props.textY}
+ y={textY}
x={leftTextWidth + 46}
- fill={this.props.color}
- opacity={
- this.state.active && this.state.dateRight
- ? this.props.textOpacity
- : '0'
- }
+ fill={color}
+ opacity={active && dateRight ? textOpacity : '0'}
>
- {this.state.dateRight}
+ {dateRight}
</text>
</svg>
);
@@ -105,7 +93,6 @@ LineText.propTypes = {
fill: PropTypes.string,
recRadius: PropTypes.number,
rectOpacity: PropTypes.number,
- svgStyle: PropTypes.object,
textHeight: PropTypes.number,
textOpacity: PropTypes.number,
textWidth: PropTypes.number,
diff --git a/web/js/components/events/alert-body.js b/web/js/components/events/alert-body.js
index 69ed28f36..118b18584 100644
--- a/web/js/components/events/alert-body.js
+++ b/web/js/components/events/alert-body.js
@@ -1,6 +1,6 @@
import React from 'react';
-export const EventsAlertModalBody = () => (
+const EventsAlertModalBody = () => (
<div className="event-alert-modal-body">
<h3 className="wv-data-unavailable-header">
Why can’t I see an event?
@@ -45,3 +45,5 @@ export const EventsAlertModalBody = () => (
</p>
</div>
);
+
+export default EventsAlertModalBody;
diff --git a/web/js/components/feature-alert/alert.js b/web/js/components/feature-alert/alert.js
index 8015235fb..d81e5b210 100644
--- a/web/js/components/feature-alert/alert.js
+++ b/web/js/components/feature-alert/alert.js
@@ -1,6 +1,6 @@
+/* eslint-disable react/no-unused-state */
import React from 'react';
import { connect } from 'react-redux';
-import PropTypes from 'prop-types';
import { openCustomContent } from '../../modules/modal/actions';
import util from '../../util/util';
@@ -53,10 +53,6 @@ const mapDispatchToProps = (dispatch) => ({
},
});
-FeaturedAlert.propTypes = {
- showModal: PropTypes.func,
-};
-
export default connect(
null,
mapDispatchToProps,
diff --git a/web/js/components/feature-alert/geostationary-modal.js b/web/js/components/feature-alert/geostationary-modal.js
index 7c22a2376..738fb3187 100644
--- a/web/js/components/feature-alert/geostationary-modal.js
+++ b/web/js/components/feature-alert/geostationary-modal.js
@@ -7,7 +7,7 @@ import {
Row,
Col,
} from 'reactstrap';
-import { history } from '../../main';
+import history from '../../main';
class GeostationaryModalBody extends React.Component {
constructor(props) {
diff --git a/web/js/components/image-download/grid.js b/web/js/components/image-download/grid.js
index e716e2ab7..89d1087fe 100644
--- a/web/js/components/image-download/grid.js
+++ b/web/js/components/image-download/grid.js
@@ -14,22 +14,22 @@ import Button from '../util/button';
*/
export default class ResolutionTable extends React.Component {
renderImageSize() {
- const size = this.props.fileSize;
- if (!this.props.validSize) {
+ const { fileSize, validSize } = this.props;
+ if (!validSize) {
return (
<div
id="wv-image-size"
className="wv-image-size wv-image-size-invalid grid-child"
>
<FontAwesomeIcon icon={faTimes} fixedWidth />
- <span>{`~${size}MB`}</span>
+ <span>{`~${fileSize}MB`}</span>
</div>
);
}
return (
<div id="wv-image-size" className="wv-image-size grid-child">
<span>
- {`~${size} MB`}
+ {`~${fileSize} MB`}
{' '}
</span>
</div>
diff --git a/web/js/components/image-download/notify.js b/web/js/components/image-download/notify.js
index ff94d2ed4..251c70c73 100644
--- a/web/js/components/image-download/notify.js
+++ b/web/js/components/image-download/notify.js
@@ -3,7 +3,7 @@ import PropTypes from 'prop-types';
import { ModalFooter } from 'reactstrap';
import Button from '../util/button';
-export const Notify = (props) => {
+const Notify = (props) => {
const { bodyText, cancel, accept } = props;
return (
<>
@@ -23,3 +23,5 @@ Notify.propTypes = {
bodyText: PropTypes.string,
cancel: PropTypes.func,
};
+
+export default Notify;
diff --git a/web/js/components/image-download/panel.js b/web/js/components/image-download/panel.js
index fd1f06e49..0c696890f 100644
--- a/web/js/components/image-download/panel.js
+++ b/web/js/components/image-download/panel.js
@@ -35,10 +35,8 @@ export default class ImageResSelection extends React.Component {
this.state = {
fileType: props.fileType,
- fileSize: props.fileSize,
isWorldfile: props.isWorldfile,
resolution: props.resolution,
- valid: props.valid,
debugUrl: '',
};
this.handleChange = this.handleChange.bind(this);
@@ -103,28 +101,32 @@ export default class ImageResSelection extends React.Component {
}
_renderFileTypeSelect() {
- if (this.props.fileTypeOptions) {
+ const { fileTypeOptions, fileTypes, secondLabel } = this.props;
+ const { fileType } = this.state;
+ if (fileTypeOptions) {
return (
<div className="wv-image-header">
<SelectionList
id="wv-image-format"
optionName="filetype"
- value={this.state.fileType}
- optionArray={this.props.fileTypes}
+ value={fileType}
+ optionArray={fileTypes}
onChange={this.handleChange}
/>
- {this.props.secondLabel}
+ {secondLabel}
</div>
);
}
}
_renderWorldfileSelect() {
- if (this.props.worldFileOptions) {
- const value = this.state.isWorldfile ? 1 : 0;
+ const { worldFileOptions } = this.props;
+ const { isWorldfile, fileType } = this.state;
+ if (worldFileOptions) {
+ const value = isWorldfile ? 1 : 0;
return (
<div className="wv-image-header">
- {this.state.fileType === 'application/vnd.google-earth.kmz' ? (
+ {fileType === 'application/vnd.google-earth.kmz' ? (
<select disabled>
<option value={0}>No</option>
</select>
@@ -146,7 +148,7 @@ export default class ImageResSelection extends React.Component {
render() {
const {
- getLayers, projection, lonlats, resolutions, maxImageSize,
+ getLayers, projection, lonlats, resolutions, maxImageSize, firstLabel,
} = this.props;
const { resolution, debugUrl } = this.state;
const dimensions = getDimensions(projection.id, lonlats, resolution);
@@ -170,7 +172,7 @@ export default class ImageResSelection extends React.Component {
optionName="resolution"
onChange={this.handleChange}
/>
- {this.props.firstLabel}
+ {firstLabel}
</div>
{filetypeSelect}
{worldfileSelect}
@@ -199,15 +201,12 @@ ImageResSelection.defaultProps = {
worldFileOptions: true,
};
ImageResSelection.propTypes = {
- crs: PropTypes.string,
date: PropTypes.object,
- fileSize: PropTypes.string,
fileType: PropTypes.string,
fileTypeOptions: PropTypes.bool,
fileTypes: PropTypes.object,
firstLabel: PropTypes.string,
getLayers: PropTypes.func,
- hasSubdailyLayers: PropTypes.bool,
isWorldfile: PropTypes.bool,
lonlats: PropTypes.array,
maxImageSize: PropTypes.string,
@@ -217,6 +216,5 @@ ImageResSelection.propTypes = {
resolutions: PropTypes.object,
secondLabel: PropTypes.string,
url: PropTypes.string,
- valid: PropTypes.bool,
worldFileOptions: PropTypes.bool,
};
diff --git a/web/js/components/layer/info/date-ranges.js b/web/js/components/layer/info/date-ranges.js
index 03732ac3a..a0c8f888b 100644
--- a/web/js/components/layer/info/date-ranges.js
+++ b/web/js/components/layer/info/date-ranges.js
@@ -5,7 +5,7 @@ import util from '../../../util/util';
import Scrollbar from '../../util/scrollbar';
import { dateOverlap } from '../../../modules/layers/util';
-export class DateRanges extends React.Component {
+export default class DateRanges extends React.Component {
constructor(props) {
super(props);
this.state = {
@@ -13,35 +13,29 @@ export class DateRanges extends React.Component {
};
}
- renderListItem(layer) {
- return layer.dateRanges
- .slice(0)
- .reverse()
- .map((l) => {
- let listItemStartDate;
- let listItemEndDate;
-
- if (l.startDate) {
- listItemStartDate = util.coverageDateFormatter('START-DATE', l.startDate, layer.period);
- }
-
- if (l.endDate) {
- listItemEndDate = util.coverageDateFormatter('END-DATE', l.endDate, layer.period);
- }
-
- return (
- <ListGroupItem key={`${l.startDate} - ${l.endDate}`}>
- {`${listItemStartDate} - ${listItemEndDate}`}
- </ListGroupItem>
- );
- });
- }
+ renderListItem = (layer) => layer.dateRanges
+ .slice(0)
+ .reverse()
+ .map((l) => {
+ let listItemStartDate;
+ let listItemEndDate;
+ if (l.startDate) {
+ listItemStartDate = util.coverageDateFormatter('START-DATE', l.startDate, layer.period);
+ }
+ if (l.endDate) {
+ listItemEndDate = util.coverageDateFormatter('END-DATE', l.endDate, layer.period);
+ }
+ return (
+ <ListGroupItem key={`${l.startDate} - ${l.endDate}`}>
+ {`${listItemStartDate} - ${listItemEndDate}`}
+ </ListGroupItem>
+ );
+ })
render() {
const { layer, screenHeight } = this.props;
const { showRanges } = this.state;
const style = showRanges ? { display: 'block' } : { display: 'none' };
-
let listItems;
if (layer.dateRanges && layer.dateRanges.length > 1) {
diff --git a/web/js/components/layer/info/info.js b/web/js/components/layer/info/info.js
index 8c9164725..c70d422aa 100644
--- a/web/js/components/layer/info/info.js
+++ b/web/js/components/layer/info/info.js
@@ -1,10 +1,14 @@
import React from 'react';
import PropTypes from 'prop-types';
import { dateOverlap } from '../../../modules/layers/util';
-import { DateRanges } from './date-ranges';
+import DateRanges from './date-ranges';
import util from '../../../util/util';
import Scrollbars from '../../util/scrollbar';
+function configureTemporalDate(dateType, date, period) {
+ return util.coverageDateFormatter(dateType, date, period);
+}
+
class LayerInfo extends React.Component {
constructor(props) {
super(props);
@@ -33,9 +37,6 @@ class LayerInfo extends React.Component {
}
}
- configureTemporalDate(dateType, date, period) {
- return util.coverageDateFormatter(dateType, date, period);
- }
render() {
const { layer, screenHeight } = this.props;
@@ -52,13 +53,13 @@ class LayerInfo extends React.Component {
<span id={`${layerId}-startDate`} className="layer-date-start">
{layer.startDate
? `Temporal coverage: ${
- this.configureTemporalDate('START-DATE', layer.startDate, layer.period)}`
+ configureTemporalDate('START-DATE', layer.startDate, layer.period)}`
: ''}
</span>
<span id={`${layerId}-endDate`} className="layer-date-end">
{layer.startDate && layer.endDate
? ` - ${
- this.configureTemporalDate('END-DATE', layer.endDate, layer.period)}`
+ configureTemporalDate('END-DATE', layer.endDate, layer.period)}`
: layer.startDate
? ' - Present'
: ''}
diff --git a/web/js/components/layer/product-picker/category-layer-row.js b/web/js/components/layer/product-picker/category-layer-row.js
index 0f6c05d01..aa2028f40 100644
--- a/web/js/components/layer/product-picker/category-layer-row.js
+++ b/web/js/components/layer/product-picker/category-layer-row.js
@@ -25,7 +25,6 @@ class CategoryLayerRow extends React.Component {
constructor(props) {
super(props);
this.state = {
- isSelected: props.isSelected,
projection: props.projection,
};
}
@@ -248,8 +247,6 @@ CategoryLayerRow.propTypes = {
activeLayers: PropTypes.array,
addLayer: PropTypes.func,
category: PropTypes.object,
- checked: PropTypes.bool,
- getSourceMetadata: PropTypes.func,
hasMeasurementSetting: PropTypes.func,
id: PropTypes.string,
isMobile: PropTypes.bool,
@@ -261,7 +258,6 @@ CategoryLayerRow.propTypes = {
selectedDate: PropTypes.object,
selectedMeasurementSourceIndex: PropTypes.number,
setSourceIndex: PropTypes.func,
- sourceMetadata: PropTypes.object,
updateSelectedMeasurement: PropTypes.func,
};
diff --git a/web/js/components/layer/product-picker/header.js b/web/js/components/layer/product-picker/header.js
index f34d150ac..41dfb94e1 100644
--- a/web/js/components/layer/product-picker/header.js
+++ b/web/js/components/layer/product-picker/header.js
@@ -32,8 +32,9 @@ class ProductPickerHeader extends React.Component {
}
componentDidMount() {
+ const { isMobile } = this.props;
setTimeout(() => {
- if (this._input && !this.props.isMobile) this._input.focus();
+ if (this._input && !isMobile) this._input.focus();
}, 500);
}
@@ -42,18 +43,21 @@ class ProductPickerHeader extends React.Component {
* @method revertToInitialScreen
*/
revertToInitialScreen(e) {
+ const { updateListState } = this.props;
e.preventDefault();
- this.props.updateListState();
+ updateListState();
this.setState({ inputValue: '' });
}
handleChange(e) {
- this.props.runSearch(e.target.value);
+ const { runSearch } = this.props;
+ runSearch(e.target.value);
this.setState({ inputValue: e.target.value });
}
render() {
const isAutoFocus = !util.browser.touchDevice;
+ const { inputValue } = this.state;
const {
selectedProjection,
selectedDate,
@@ -63,6 +67,7 @@ class ProductPickerHeader extends React.Component {
toggleFilterByAvailable,
filterByAvailable,
isMobile,
+ children,
} = this.props;
const isSearching = listType === 'search';
const categoryId = category && category.id;
@@ -122,7 +127,7 @@ class ProductPickerHeader extends React.Component {
<Input
onChange={this.handleChange}
id="layers-search-input"
- value={this.state.inputValue}
+ value={inputValue}
placeholder="Search"
// eslint-disable-next-line no-return-assign
innerRef={(c) => (this._input = c)}
@@ -130,7 +135,7 @@ class ProductPickerHeader extends React.Component {
autoFocus={isAutoFocus}
/>
</InputGroup>
- {this.props.children}
+ {children}
</>
);
}
@@ -143,7 +148,6 @@ ProductPickerHeader.propTypes = {
inputValue: PropTypes.string,
isMobile: PropTypes.bool,
listType: PropTypes.string,
- modalView: PropTypes.string,
runSearch: PropTypes.func,
selectedDate: PropTypes.object,
selectedProjection: PropTypes.string,
diff --git a/web/js/components/layer/product-picker/layer-filters.js b/web/js/components/layer/product-picker/layer-filters.js
index dab578165..3e9ac5bfd 100644
--- a/web/js/components/layer/product-picker/layer-filters.js
+++ b/web/js/components/layer/product-picker/layer-filters.js
@@ -30,7 +30,6 @@ const LayerFilters = (props) => {
LayerFilters.propTypes = {
filterByAvailable: PropTypes.bool,
- numResults: PropTypes.number,
selectedDate: PropTypes.object,
toggleFilterByAvailable: PropTypes.func,
};
diff --git a/web/js/components/layer/product-picker/layer-list.js b/web/js/components/layer/product-picker/layer-list.js
index 0c95f5029..84e51b570 100644
--- a/web/js/components/layer/product-picker/layer-list.js
+++ b/web/js/components/layer/product-picker/layer-list.js
@@ -13,21 +13,21 @@ class LayerList extends React.Component {
/**
* Handle selecting/showing metadata when there is only a single search result
*/
- componentDidUpdate(prevProps, prevState, snapshot) {
+ componentDidMount() {
const { selectedLayer } = this.props;
- if (prevProps.selectedLayer !== selectedLayer) {
- const id = selectedLayer ? selectedLayer.id : null;
- this.showLayerMetadata(id);
+ if (selectedLayer && selectedLayer.id) {
+ this.showLayerMetadata(selectedLayer.id);
}
}
/**
* Handle selecting/showing metadata when there is only a single search result
*/
- componentDidMount() {
+ componentDidUpdate(prevProps, prevState, snapshot) {
const { selectedLayer } = this.props;
- if (selectedLayer && selectedLayer.id) {
- this.showLayerMetadata(selectedLayer.id);
+ if (prevProps.selectedLayer !== selectedLayer) {
+ const id = selectedLayer ? selectedLayer.id : null;
+ this.showLayerMetadata(id);
}
}
diff --git a/web/js/components/layer/product-picker/layer-metadata-detail.js b/web/js/components/layer/product-picker/layer-metadata-detail.js
index 6bea3e080..252f9c8f9 100644
--- a/web/js/components/layer/product-picker/layer-metadata-detail.js
+++ b/web/js/components/layer/product-picker/layer-metadata-detail.js
@@ -37,35 +37,77 @@ class LayerMetadataDetail extends React.Component {
this.setState((prevState) => ({ isDateRangesExpanded: !prevState.isDateRangesExpanded }));
}
- getListItems(layer) {
- return layer.dateRanges
- .slice(0)
- .reverse()
- .map((l) => {
- let listItemStartDate;
- let listItemEndDate;
+ getListItems = (layer) => layer.dateRanges
+ .slice(0)
+ .reverse()
+ .map((l) => {
+ let listItemStartDate;
+ let listItemEndDate;
+ if (l.startDate) {
+ listItemStartDate = util.coverageDateFormatter('START-DATE', l.startDate, layer.period);
+ }
+ if (l.endDate) {
+ listItemEndDate = util.coverageDateFormatter('END-DATE', l.endDate, layer.period);
+ }
- if (l.startDate) {
- listItemStartDate = util.coverageDateFormatter('START-DATE', l.startDate, layer.period);
- }
+ return (
+ <ListGroupItem key={`${l.startDate} - ${l.endDate}`}>
+ {`${listItemStartDate} - ${listItemEndDate}`}
+ </ListGroupItem>
+ );
+ })
- if (l.endDate) {
- listItemEndDate = util.coverageDateFormatter('END-DATE', l.endDate, layer.period);
- }
+ renderSplitTitle = (title) => {
+ const splitIdx = title.indexOf('(');
+ const attrs = title.slice(splitIdx);
+ const titleName = title.slice(0, splitIdx - 1);
+ return splitIdx < 0
+ ? (<h3>{title}</h3>)
+ : (
+ <>
+ <h3>{titleName}</h3>
+ <h4>{attrs}</h4>
+ </>
+ );
+ }
- return (
- <ListGroupItem key={`${l.startDate} - ${l.endDate}`}>
- {`${listItemStartDate} - ${listItemEndDate}`}
- </ListGroupItem>
- );
- });
+ /**
+ * Return text with the temporal range based on layer start
+ * and end dates
+ * @param {object} layer the layer object
+ * @return {string} Return a string with temporal range information
+ */
+ dateRangeText = (layer) => {
+ let startDate;
+ let startDateId;
+ let endDate;
+ let endDateId;
+
+ if (layer.startDate) {
+ startDateId = `${layer.id}-startDate`;
+ startDate = util.coverageDateFormatter('START-DATE', layer.startDate, layer.period);
+ }
+ if (layer.endDate) {
+ endDateId = `${layer.id}-endDate`;
+ endDate = util.parseDate(layer.endDate);
+ if (endDate <= util.today() && !layer.inactive) {
+ endDate = 'Present';
+ } else {
+ endDate = util.coverageDateFormatter('END-DATE', layer.endDate, layer.period);
+ }
+ } else {
+ endDate = 'Present';
+ }
+ return `Temporal coverage:
+ <span class="layer-date-start" id='${startDateId}'> ${startDate} </span> -
+ <span class="layer-end-date" id='${endDateId}'> ${endDate} </span>`;
}
renderLayerDates() {
const { layer } = this.props;
const { isDateRangesExpanded } = this.state;
- let listItems; let
- dateRanges;
+ let listItems;
+ let dateRanges;
if (layer.dateRanges && layer.dateRanges.length > 1) {
dateRanges = dateOverlap(layer.period, layer.dateRanges);
@@ -79,7 +121,7 @@ class LayerMetadataDetail extends React.Component {
{layer.startDate && (
<p className="layer-date-range">
<span
- dangerouslySetInnerHTML={{ __html: dateRangeText(layer) }}
+ dangerouslySetInnerHTML={{ __html: this.dateRangeText(layer) }}
/>
{layer.dateRanges
&& layer.dateRanges.length > 1
@@ -106,36 +148,11 @@ class LayerMetadataDetail extends React.Component {
);
}
- renderSplitTitle(title) {
- const splitIdx = title.indexOf('(');
- const attrs = title.slice(splitIdx);
- const titleName = title.slice(0, splitIdx - 1);
- return splitIdx < 0
- ? (
- <h3>
- {' '}
- {title}
- {' '}
- </h3>
- )
- : (
- <>
- <h3>
- {' '}
- {titleName}
- {' '}
- </h3>
- <h4>
- {' '}
- {attrs}
- {' '}
- </h4>
- </>
- );
- }
-
render() {
- if (!this.props.layer) {
+ const {
+ layer, selectedProjection, isActive, showPreviewImage,
+ } = this.props;
+ if (!layer) {
return (
<div className="no-results">
<FontAwesomeIcon icon={faGlobeAmericas} />
@@ -144,9 +161,6 @@ class LayerMetadataDetail extends React.Component {
</div>
);
}
- const {
- layer, selectedProjection, isActive, showPreviewImage,
- } = this.props;
const {
title, subtitle, track, metadata,
} = layer;
@@ -195,47 +209,7 @@ LayerMetadataDetail.propTypes = {
layer: PropTypes.object,
removeLayer: PropTypes.func,
selectedProjection: PropTypes.string,
- showMetadataForLayer: PropTypes.func,
showPreviewImage: PropTypes.bool,
};
export default LayerMetadataDetail;
-
-/**
- * dateRangeText - Return text with the temporal range based on layer start
- * and end dates
- *
- * @method toggleMetadataButtons
- * @param {object} layer the layer object
- * @return {string} Return a string with temporal range information
- */
-const dateRangeText = (layer) => {
- let startDate; let startDateId; let endDate; let
- endDateId;
-
- if (layer.startDate) {
- startDateId = `${layer.id}-startDate`;
- startDate = util.coverageDateFormatter('START-DATE', layer.startDate, layer.period);
- }
-
- if (layer.endDate) {
- endDateId = `${layer.id}-endDate`;
- endDate = util.parseDate(layer.endDate);
-
- if (endDate <= util.today() && !layer.inactive) {
- endDate = 'Present';
- } else {
- endDate = util.coverageDateFormatter('END-DATE', layer.endDate, layer.period);
- }
- } else {
- endDate = 'Present';
- }
-
- const dateRange = `
- Temporal coverage:
- <span class="layer-date-start" id='${startDateId}'> ${startDate} </span> -
- <span class="layer-end-date" id='${endDateId}'> ${endDate} </span>
- `;
-
- return dateRange;
-};
diff --git a/web/js/components/layer/product-picker/measurement-layer-row.js b/web/js/components/layer/product-picker/measurement-layer-row.js
index ac6cdd3c8..153a3c5ef 100644
--- a/web/js/components/layer/product-picker/measurement-layer-row.js
+++ b/web/js/components/layer/product-picker/measurement-layer-row.js
@@ -6,7 +6,7 @@ import moment from 'moment';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faBan } from '@fortawesome/free-solid-svg-icons';
import { availableAtDate } from '../../../modules/layers/util';
-import { Checkbox } from '../../util/checkbox';
+import Checkbox from '../../util/checkbox';
/*
* A scrollable list of layers
* @class LayerList
@@ -25,11 +25,12 @@ class MeasurementLayerRow extends React.Component {
onClick() {
const { removeLayer, addLayer, layer } = this.props;
- const checked = !this.state.checked;
+ const { checked } = this.state;
+ const newChecked = !checked;
this.setState((prevState) => ({
checked: !prevState.checked,
}));
- if (!checked) {
+ if (!newChecked) {
removeLayer(layer.id);
} else {
addLayer(layer.id);
@@ -102,7 +103,6 @@ MeasurementLayerRow.propTypes = {
checked: PropTypes.bool,
layer: PropTypes.object,
measurementId: PropTypes.string,
- onClick: PropTypes.func,
removeLayer: PropTypes.func,
selectedDate: PropTypes.object,
title: PropTypes.string,
diff --git a/web/js/components/layer/product-picker/product-picker.js b/web/js/components/layer/product-picker/product-picker.js
index 4e11a1f59..173eef6a5 100644
--- a/web/js/components/layer/product-picker/product-picker.js
+++ b/web/js/components/layer/product-picker/product-picker.js
@@ -53,7 +53,6 @@ class ProductPicker extends React.Component {
this.state = {
modalElement: undefined,
headerElement: undefined,
- listScrollTop: props.listScrollTop || 0,
};
this.runSearch = lodashDebounce(this.runSearch.bind(this), 300);
@@ -178,8 +177,8 @@ class ProductPicker extends React.Component {
* @param {String} id | Measurement ID
*/
updateSelectedMeasurement(id) {
- const { update } = this.props;
- if (this.props.selectedMeasurement !== id) {
+ const { update, selectedMeasurement } = this.props;
+ if (selectedMeasurement !== id) {
update({
selectedMeasurement: id,
selectedMeasurementSourceIndex: 0,
@@ -204,8 +203,12 @@ class ProductPicker extends React.Component {
}
getSelectedMeasurementSource() {
- const { selectedMeasurement, selectedMeasurementSourceIndex } = this.props;
- const measurements = Object.values(this.props.measurementConfig);
+ const {
+ selectedMeasurement,
+ selectedMeasurementSourceIndex,
+ measurementConfig,
+ } = this.props;
+ const measurements = Object.values(measurementConfig);
const currentMeasurement = measurements.find((measure) => measure.id === selectedMeasurement);
if (currentMeasurement) {
const sources = Object.values(currentMeasurement.sources)
@@ -238,10 +241,11 @@ class ProductPicker extends React.Component {
* @param {String} key | categoryType identifier
*/
sort(key) {
+ const { update } = this.props;
if (key === 'featured') {
this.toggleFeatureTab();
} else {
- this.props.update({
+ update({
categoryType: key,
listType: 'category',
selectedMeasurement: null,
@@ -266,7 +270,8 @@ class ProductPicker extends React.Component {
* When using "back" button or clearing search field, unset selections
*/
revertSearchState() {
- this.props.update({
+ const { update } = this.props;
+ update({
listType: 'category',
inputValue: '',
selectedLayer: null,
@@ -281,7 +286,8 @@ class ProductPicker extends React.Component {
* @param {*} selectedLayer - the layer for which to show metadata
*/
showMetadataForLayer(selectedLayer) {
- this.props.update({ selectedLayer });
+ const { update } = this.props;
+ update({ selectedLayer });
}
renderLayerList() {
@@ -575,11 +581,9 @@ ProductPicker.propTypes = {
activeLayers: PropTypes.array,
addLayer: PropTypes.func,
allLayers: PropTypes.array,
- categories: PropTypes.array,
category: PropTypes.object,
categoryConfig: PropTypes.object,
categoryType: PropTypes.string,
- drawMeasurements: PropTypes.func,
filterByAvailable: PropTypes.bool,
filteredRows: PropTypes.array,
filterProjections: PropTypes.func,
@@ -598,11 +602,9 @@ ProductPicker.propTypes = {
onToggle: PropTypes.func,
removeLayer: PropTypes.func,
screenHeight: PropTypes.number,
- searchResultRows: PropTypes.array,
selectedDate: PropTypes.object,
selectedLayer: PropTypes.object,
selectedMeasurement: PropTypes.string,
- selectedMeasurementSource: PropTypes.object,
selectedMeasurementSourceIndex: PropTypes.number,
selectedProjection: PropTypes.string,
showPreviewImage: PropTypes.bool,
diff --git a/web/js/components/layer/product-picker/search-layer-row.js b/web/js/components/layer/product-picker/search-layer-row.js
index 816692860..b6d20c376 100644
--- a/web/js/components/layer/product-picker/search-layer-row.js
+++ b/web/js/components/layer/product-picker/search-layer-row.js
@@ -20,6 +20,12 @@ class LayerRow extends React.Component {
this.toggleShowMetadata = this.toggleShowMetadata.bind(this);
}
+ UNSAFE_componentWillReceiveProps(nextProps) {
+ this.setState({
+ checked: nextProps.isEnabled,
+ });
+ }
+
/**
* Toggle layer checked state
* @method toggleCheck
@@ -60,40 +66,20 @@ class LayerRow extends React.Component {
*
* @param {*} title - the full layer title
*/
- renderSplitTitle(title) {
+ renderSplitTitle = (title) => {
const splitIdx = title.indexOf('(');
const attrs = title.slice(splitIdx);
const titleName = title.slice(0, splitIdx - 1);
return splitIdx < 0
- ? (
- <h3>
- {' '}
- {title}
- {' '}
- </h3>
- )
+ ? (<h3>{title}</h3>)
: (
<>
- <h3>
- {' '}
- {titleName}
- {' '}
- </h3>
- <h4>
- {' '}
- {attrs}
- {' '}
- </h4>
+ <h3>{titleName}</h3>
+ <h4>{attrs}</h4>
</>
);
}
- UNSAFE_componentWillReceiveProps(nextProps) {
- this.setState({
- checked: nextProps.isEnabled,
- });
- }
-
render() {
const { checked } = this.state;
const { layer, isMetadataShowing } = this.props;
@@ -137,7 +123,6 @@ LayerRow.propTypes = {
offState: PropTypes.func,
onState: PropTypes.func,
showLayerMetadata: PropTypes.func,
- toggleDateRangesExpansion: PropTypes.func,
};
export default LayerRow;
diff --git a/web/js/components/layer/settings/classification-toggle.js b/web/js/components/layer/settings/classification-toggle.js
index 364d5dd34..e2849ce07 100644
--- a/web/js/components/layer/settings/classification-toggle.js
+++ b/web/js/components/layer/settings/classification-toggle.js
@@ -3,55 +3,38 @@ import PropTypes from 'prop-types';
import Switch from '../../util/switch';
import Scrollbar from '../../util/scrollbar';
-class ClassificationToggle extends React.Component {
- constructor(props) {
- super(props);
- this.state = {
- active: props.active,
- };
- }
-
- render() {
- const {
- legend, toggle, palette, height,
- } = this.props;
- const { tooltips } = legend;
- return (
- <div className="layer-classification-toggle settings-component">
- <h2 className="wv-header">Disable/Enable</h2>
- <Scrollbar style={{ maxHeight: `${height}px` }}>
- {legend.colors.map((color, index) => {
- const id = legend.id + index;
- const tooltip = tooltips[index];
- const inActive = palette.disabled && palette.disabled.includes(index);
- return (
- <Switch
- id={id}
- key={id}
- color={color.substring(0, 6)}
- label={tooltip}
- active={!inActive}
- toggle={() => toggle(index)}
- />
- );
- })}
- </Scrollbar>
- </div>
- );
- }
+export default function ClassificationToggle (props) {
+ const {
+ legend, toggle, palette, height,
+ } = props;
+ const { tooltips } = legend;
+ return (
+ <div className="layer-classification-toggle settings-component">
+ <h2 className="wv-header">Disable/Enable</h2>
+ <Scrollbar style={{ maxHeight: `${height}px` }}>
+ {legend.colors.map((color, index) => {
+ const id = legend.id + index;
+ const tooltip = tooltips[index];
+ const inActive = palette.disabled && palette.disabled.includes(index);
+ return (
+ <Switch
+ id={id}
+ key={id}
+ color={color.substring(0, 6)}
+ label={tooltip}
+ active={!inActive}
+ toggle={() => toggle(index)}
+ />
+ );
+ })}
+ </Scrollbar>
+ </div>
+ );
}
-ClassificationToggle.defaultProps = {
- start: 100,
-};
+
ClassificationToggle.propTypes = {
- active: PropTypes.bool,
height: PropTypes.number,
- layer: PropTypes.object,
legend: PropTypes.object,
palette: PropTypes.object,
- setOpacity: PropTypes.func,
- start: PropTypes.number,
toggle: PropTypes.func,
};
-
-export default ClassificationToggle;
diff --git a/web/js/components/layer/settings/opacity.js b/web/js/components/layer/settings/opacity.js
index 1f001030f..e467eaa72 100644
--- a/web/js/components/layer/settings/opacity.js
+++ b/web/js/components/layer/settings/opacity.js
@@ -12,6 +12,7 @@ class OpacitySelect extends React.Component {
render() {
const { layer, setOpacity, start } = this.props;
+ const { value } = this.state;
return (
<div className="layer-opacity-select settings-component">
<h2 className="wv-header">Opacity</h2>
@@ -23,7 +24,7 @@ class OpacitySelect extends React.Component {
}}
/>
<div className="wv-label wv-label-opacity">
- {`${this.state.value}%`}
+ {`${value}%`}
</div>
</div>
);
diff --git a/web/js/components/layer/settings/orbit-tracks-toggle.js b/web/js/components/layer/settings/orbit-tracks-toggle.js
index fbc2849f3..56cebfd47 100644
--- a/web/js/components/layer/settings/orbit-tracks-toggle.js
+++ b/web/js/components/layer/settings/orbit-tracks-toggle.js
@@ -1,7 +1,7 @@
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
-import { Checkbox } from '../../util/checkbox';
+import Checkbox from '../../util/checkbox';
import { addLayer, removeLayer } from '../../../modules/layers/actions';
import { getOrbitTrackTitle } from '../../../modules/layers/util';
diff --git a/web/js/components/layer/settings/palette-threshold.js b/web/js/components/layer/settings/palette-threshold.js
index 1e4d93a93..c38181ba7 100644
--- a/web/js/components/layer/settings/palette-threshold.js
+++ b/web/js/components/layer/settings/palette-threshold.js
@@ -2,7 +2,7 @@ import React from 'react';
import PropTypes from 'prop-types';
import lodashDebounce from 'lodash/debounce';
import { Range as RangeInput } from 'rc-slider';
-import { Checkbox } from '../../util/checkbox';
+import Checkbox from '../../util/checkbox';
class ThresholdSelect extends React.Component {
constructor(props) {
@@ -12,7 +12,6 @@ class ThresholdSelect extends React.Component {
start,
end,
squashed,
- activeDragger: 'start',
};
this.debounceSetRange = lodashDebounce(props.setRange, 300);
this.updateSquash = this.updateSquash.bind(this);
@@ -51,7 +50,7 @@ class ThresholdSelect extends React.Component {
const {
layerId, index, groupName, palette, legend,
} = this.props;
- const { start, end } = this.state;
+ const { start, end, squashed } = this.state;
const newStart = Math.ceil(Number(thresholdArray[0]));
const newEnd = Math.ceil(Number(thresholdArray[1]));
const startRef = legend.refs[newStart];
@@ -78,7 +77,7 @@ class ThresholdSelect extends React.Component {
layerId,
parseFloat(palette.entries.refs.indexOf(startRef)),
parseFloat(palette.entries.refs.indexOf(endRef)),
- this.state.squashed,
+ squashed,
index,
groupName,
);
diff --git a/web/js/components/layer/settings/palette.js b/web/js/components/layer/settings/palette.js
index 0dfb2f01f..62c81efef 100644
--- a/web/js/components/layer/settings/palette.js
+++ b/web/js/components/layer/settings/palette.js
@@ -123,7 +123,7 @@ class PaletteSelect extends React.Component {
onClick={() => this.onChangePalette(id)}
/>
<label htmlFor={`wv-palette-radio-${id}`}>
- <img src={this.props.canvas.toDataURL('image/png')} />
+ <img src={canvas.toDataURL('image/png')} />
<span className="wv-palette-label">{legend.name || 'Default'}</span>
</label>
</div>
diff --git a/web/js/components/layer/settings/settings.js b/web/js/components/layer/settings/settings.js
index f24afe9be..5b4eac0b9 100644
--- a/web/js/components/layer/settings/settings.js
+++ b/web/js/components/layer/settings/settings.js
@@ -353,13 +353,10 @@ export default connect(
)(LayerSettings);
LayerSettings.defaultProps = {
- isOpen: false,
layer: { id: null, name: null },
palettedAllowed: false,
- title: null,
};
LayerSettings.propTypes = {
- canvas: PropTypes.object,
clearCustomPalette: PropTypes.func,
clearStyle: PropTypes.func,
customPalettesIsActive: PropTypes.bool,
@@ -368,21 +365,16 @@ LayerSettings.propTypes = {
getPalette: PropTypes.func,
getPaletteLegend: PropTypes.func,
getPaletteLegends: PropTypes.func,
- getVectorStyle: PropTypes.func,
groupName: PropTypes.string,
- index: PropTypes.number,
- isOpen: PropTypes.bool,
layer: PropTypes.object,
palettedAllowed: PropTypes.bool,
paletteOrder: PropTypes.array,
palettesTranslate: PropTypes.func,
screenHeight: PropTypes.number,
setCustomPalette: PropTypes.func,
- setFilterRange: PropTypes.func,
setOpacity: PropTypes.func,
setStyle: PropTypes.func,
setThresholdRange: PropTypes.func,
- title: PropTypes.string,
toggleClassification: PropTypes.func,
vectorStyles: PropTypes.object,
};
diff --git a/web/js/components/layer/settings/vector-filter.js b/web/js/components/layer/settings/vector-filter.js
index be8035f43..7ee70125e 100644
--- a/web/js/components/layer/settings/vector-filter.js
+++ b/web/js/components/layer/settings/vector-filter.js
@@ -9,7 +9,6 @@ class VectorFilter extends React.Component {
this.state = {
start: props.start,
end: props.end,
- activeDragger: 'start',
};
this.debounceSetRange = lodashDebounce(props.setFilterRange, 300);
this.updateFilter = this.updateFilter.bind(this);
diff --git a/web/js/components/map/coordinates.js b/web/js/components/map/coordinates.js
index 9e3acae54..c645c5465 100644
--- a/web/js/components/map/coordinates.js
+++ b/web/js/components/map/coordinates.js
@@ -9,29 +9,32 @@ const formatOrder = {
'latlon-dms': 'latlon-dd',
};
-export class Coordinates extends React.Component {
+export default class Coordinates extends React.Component {
constructor(props) {
super(props);
this.changeFormat = this.changeFormat.bind(this);
}
changeFormat() {
- const thisFormat = this.props.format;
- const nextFormat = formatOrder[thisFormat];
- this.props.onFormatChange(nextFormat);
+ const { format, onFormatChange } = this.props;
+ const nextFormat = formatOrder[format];
+ onFormatChange(nextFormat);
}
render() {
- if (this.props.latitude === null) {
+ const {
+ latitude, longitude, format, crs,
+ } = this.props;
+ if (latitude === null) {
return null;
}
- if (this.props.longitude === null) {
+ if (longitude === null) {
return null;
}
const coords = util.formatCoordinate(
- [this.props.longitude, this.props.latitude],
- this.props.format,
+ [longitude, latitude],
+ format,
);
return (
@@ -42,7 +45,7 @@ export class Coordinates extends React.Component {
<span className="map-coord">
{coords}
{' '}
- {this.props.crs}
+ {crs}
</span>
<div className="coord-btn">
<i className="coord-switch" />
diff --git a/web/js/components/map/coordinates.test.js b/web/js/components/map/coordinates.test.js
index 82414728a..b71c7b176 100644
--- a/web/js/components/map/coordinates.test.js
+++ b/web/js/components/map/coordinates.test.js
@@ -1,7 +1,7 @@
/* eslint-disable no-restricted-syntax */
import React from 'react';
import renderer from 'react-test-renderer';
-import { Coordinates } from './coordinates';
+import Coordinates from './coordinates';
describe('formats', () => {
const formats = ['latlon-dd', 'latlon-dm', 'latlon-dms'];
diff --git a/web/js/components/map/ol-coordinates.js b/web/js/components/map/ol-coordinates.js
index 68cd20b21..5bef0d107 100644
--- a/web/js/components/map/ol-coordinates.js
+++ b/web/js/components/map/ol-coordinates.js
@@ -1,10 +1,10 @@
import React from 'react';
import PropTypes from 'prop-types';
import { transform } from 'ol/proj';
-import { Coordinates } from './coordinates';
+import Coordinates from './coordinates';
import util from '../../util/util';
-export class OlCoordinates extends React.Component {
+export default class OlCoordinates extends React.Component {
constructor(props) {
super(props);
this.state = {
@@ -20,14 +20,16 @@ export class OlCoordinates extends React.Component {
this.registerMouseListeners();
}
- registerMouseListeners() {
- this.props.mouseEvents.on('mousemove', this.mouseMove);
- this.props.mouseEvents.on('mouseout', this.mouseOut);
+ componentWillUnmount() {
+ const { mouseEvents } = this.props;
+ mouseEvents.off('mousemove', this.mouseMove);
+ mouseEvents.off('mouseout', this.mouseOut);
}
- componentWillUnmount() {
- this.props.mouseEvents.off('mousemove', this.mouseMove);
- this.props.mouseEvents.off('mouseout', this.mouseOut);
+ registerMouseListeners() {
+ const { mouseEvents } = this.props;
+ mouseEvents.on('mousemove', this.mouseMove);
+ mouseEvents.on('mouseout', this.mouseOut);
}
mouseMove(event, map, crs) {
@@ -38,6 +40,7 @@ export class OlCoordinates extends React.Component {
return;
}
let pcoord = transform(coord, crs, 'EPSG:4326');
+ // eslint-disable-next-line prefer-const
let [lon, lat] = pcoord;
if (Math.abs(lat) > 90) {
this.clearCoord();
@@ -83,18 +86,21 @@ export class OlCoordinates extends React.Component {
}
render() {
+ const {
+ hasMouse, format, latitude, longitude, crs,
+ } = this.state;
// Don't render until a mouse is being used
- if (!this.state.hasMouse) {
+ if (!hasMouse) {
return null;
}
return (
<div id="ol-coords-case">
<Coordinates
- format={this.state.format}
- latitude={this.state.latitude}
- longitude={this.state.longitude}
- crs={this.state.crs}
+ format={format}
+ latitude={latitude}
+ longitude={longitude}
+ crs={crs}
onFormatChange={this.changeFormat}
/>
</div>
diff --git a/web/js/components/map/ol-coordinates.test.js b/web/js/components/map/ol-coordinates.test.js
index 55f05b2cc..580b5db03 100644
--- a/web/js/components/map/ol-coordinates.test.js
+++ b/web/js/components/map/ol-coordinates.test.js
@@ -1,7 +1,7 @@
import React from 'react';
import renderer from 'react-test-renderer';
import util from '../../util/util';
-import { OlCoordinates } from './ol-coordinates';
+import OlCoordinates from './ol-coordinates';
import { registerProjections } from '../../fixtures';
let events;
diff --git a/web/js/components/measure-tool/measure-menu.js b/web/js/components/measure-tool/measure-menu.js
index 0f926b8f9..caeb332e1 100644
--- a/web/js/components/measure-tool/measure-menu.js
+++ b/web/js/components/measure-tool/measure-menu.js
@@ -48,9 +48,10 @@ class MeasureMenu extends Component {
}
unitToggle(evt) {
+ const { onToggleUnits } = this.props;
const { checked } = evt.target;
const units = checked ? 'mi' : 'km';
- this.props.onToggleUnits(units);
+ onToggleUnits(units);
}
tooltipToggle() {
@@ -60,7 +61,7 @@ class MeasureMenu extends Component {
}
render() {
- const { isTouchDevice } = this.props;
+ const { isTouchDevice, units } = this.props;
const listSize = isTouchDevice ? 'medium' : 'small';
return (
<>
@@ -71,10 +72,10 @@ class MeasureMenu extends Component {
className="custom-control-input"
type="checkbox"
onChange={this.unitToggle}
- defaultChecked={this.props.units === 'mi'}
+ defaultChecked={units === 'mi'}
/>
<label className="custom-control-label" htmlFor="unit-toggle">
- {this.props.units}
+ {units}
</label>
</div>
</Form>
diff --git a/web/js/components/projection/util.js b/web/js/components/projection/util.js
index 97d537837..266811a8a 100644
--- a/web/js/components/projection/util.js
+++ b/web/js/components/projection/util.js
@@ -1,4 +1,4 @@
-export function parse(state, errors, config) {
+export default function parse(state, errors, config) {
// Permalink version 1.0 - 1.1
if (state.switch) {
state.p = state.switch;
diff --git a/web/js/components/range-selection/dragger-range.js b/web/js/components/range-selection/dragger-range.js
index 492cf424b..e637ebcd7 100644
--- a/web/js/components/range-selection/dragger-range.js
+++ b/web/js/components/range-selection/dragger-range.js
@@ -9,22 +9,35 @@ import { timeScaleOptions } from '../../modules/date/constants';
* @class TimelineDraggerRange
*/
class TimelineDraggerRange extends PureComponent {
- /*
- * @constructor
- */
constructor(props) {
super(props);
+ const { startLocation } = props;
this.state = {
width: 0,
- startLocation: this.props.startLocation,
- endLocation: this.props.endLocation,
- previousStartLocation: this.props.startLocation,
+ startLocation,
+ previousStartLocation: startLocation,
};
this.handleDrag = this.handleDrag.bind(this);
this.handleDraggerClick = this.handleDraggerClick.bind(this);
}
+ componentDidMount() {
+ this.checkWidth();
+ }
+
+ componentDidUpdate(prevProps) {
+ // update state and checkWidth only on startLocation and/or endLocation changes
+ const { startLocation, endLocation } = this.props;
+ if (
+ prevProps.startLocation !== startLocation
+ || prevProps.endLocation !== endLocation
+ ) {
+ this.updateExtent(this.props);
+ this.checkWidth();
+ }
+ }
+
/*
* Resize timeline dragger width
*
@@ -33,16 +46,17 @@ class TimelineDraggerRange extends PureComponent {
* @return {void}
*/
checkWidth() {
- let start = this.props.startLocation;
- let end = this.props.endLocation;
- const max = this.props.max.width;
+ const { startLocation, endLocation, max } = this.props;
+ let start = startLocation;
+ let end = endLocation;
+ const maxWidth = max.width;
let width;
if (start < 0) {
start = 0;
}
- if (end > max) {
- end = max;
+ if (end > maxWidth) {
+ end = maxWidth;
}
width = end - start;
if (width < 0) {
@@ -76,6 +90,7 @@ class TimelineDraggerRange extends PureComponent {
startLocation,
timelineEndDateLimit,
timeScale,
+ onDrag,
} = this.props;
let { endLocationDate } = this.props;
let timelineEndDate = new Date(timelineEndDateLimit);
@@ -138,7 +153,7 @@ class TimelineDraggerRange extends PureComponent {
}
}
- this.props.onDrag(deltaX, deltaStart);
+ onDrag(deltaX, deltaStart);
}
/*
@@ -150,11 +165,12 @@ class TimelineDraggerRange extends PureComponent {
* @return {number}
*/
handleStartPositionRestriction() {
+ const { startLocation, deltaStart } = this.props;
// if startLocation is in the past prior to min past of current viewable timeline
- if (this.props.startLocation <= 0) {
- return -this.props.deltaStart;
+ if (startLocation <= 0) {
+ return -deltaStart;
}
- return this.props.startLocation - this.props.deltaStart;
+ return startLocation - deltaStart;
}
/*
@@ -166,11 +182,12 @@ class TimelineDraggerRange extends PureComponent {
* @return {void}
*/
handleDraggerClick(e) {
+ const { startLocation, previousStartLocation } = this.state;
e.preventDefault();
// compare start locations to check if range has been dragged vs. clicked
if (
- this.state.startLocation.toFixed(3)
- !== this.state.previousStartLocation.toFixed(3)
+ startLocation.toFixed(3)
+ !== previousStartLocation.toFixed(3)
) {
this.setState((prevState) => ({
previousStartLocation: prevState.startLocation,
@@ -178,53 +195,41 @@ class TimelineDraggerRange extends PureComponent {
}
}
- componentDidMount() {
- this.checkWidth();
- }
-
// update state - used in componentDidUpdate
updateExtent(nextProps) {
this.setState({
startLocation: nextProps.startLocation,
- endLocation: nextProps.endLocation,
});
}
- componentDidUpdate(prevProps) {
- // update state and checkWidth only on startLocation and/or endLocation changes
- if (
- prevProps.startLocation !== this.props.startLocation
- || prevProps.endLocation !== this.props.endLocation
- ) {
- this.updateExtent(this.props);
- this.checkWidth();
- }
- }
-
/*
* @method render
*/
render() {
+ const {
+ onStop, height, color, opacity, draggerID,
+ } = this.props;
+ const { width } = this.state;
return (
<Draggable
handle=".dragger-range"
axis="x"
position={null}
defaultPosition={{ x: 0, y: 11 }}
- onStop={this.props.onStop}
+ onStop={onStop}
onDrag={this.handleDrag}
>
<rect
x={this.handleStartPositionRestriction()}
- fill={this.props.color}
- width={this.state.width}
+ fill={color}
+ width={width}
style={{
- fillOpacity: this.props.opacity,
+ fillOpacity: opacity,
cursor: 'pointer',
}}
- height={this.props.height}
+ height={height}
className="dragger-range"
- id={this.props.draggerID}
+ id={draggerID}
onClick={this.handleDraggerClick}
/>
</Draggable>
@@ -239,13 +244,11 @@ TimelineDraggerRange.propTypes = {
endLocation: PropTypes.number,
endLocationDate: PropTypes.object,
height: PropTypes.number,
- id: PropTypes.string,
max: PropTypes.object,
onDrag: PropTypes.func,
onStop: PropTypes.func,
opacity: PropTypes.number,
startLocation: PropTypes.number,
- startLocationDate: PropTypes.object,
timelineEndDateLimit: PropTypes.string,
timeScale: PropTypes.string,
width: PropTypes.number,
diff --git a/web/js/components/range-selection/dragger.js b/web/js/components/range-selection/dragger.js
index a7bfa84a4..dd6d25171 100644
--- a/web/js/components/range-selection/dragger.js
+++ b/web/js/components/range-selection/dragger.js
@@ -41,13 +41,17 @@ class TimelineDragger extends PureComponent {
}
getDefaultDragger(visibility) {
+ const {
+ draggerID, width, color, height,
+ } = this.props;
+ const { backgroundColor } = this.state;
return (
<>
<rect
- width={this.props.width}
+ width={width}
height={52}
style={{
- fill: this.props.color,
+ fill: color,
visibility,
}}
/>
@@ -57,24 +61,11 @@ class TimelineDragger extends PureComponent {
* rectangle element
*/}
<polygon
- points={
- `0,0,${
- this.props.height / 1.5
- },0 ${
- this.props.height / 3
- }, ${
- this.props.height / 1.5}`
- }
- transform={
- `translate(${
- -this.props.width * 2.45
- }, ${
- -this.props.height / 2
- })`
- }
- id={this.props.draggerID}
+ points={`0,0,${height / 1.5},0 ${height / 3}, ${height / 1.5}`}
+ transform={`translate(${-width * 2.45}, ${-height / 2})`}
+ id={draggerID}
style={{
- fill: this.state.backgroundColor,
+ fill: backgroundColor,
visibility,
stroke: '#000',
cursor: 'pointer',
@@ -92,23 +83,20 @@ class TimelineDragger extends PureComponent {
* @returns JSX element
*/
getCustomDragger(visibility) {
+ const {
+ color, height, width, path,
+ } = this.props;
return (
<>
<path
style={{
- fill: this.props.color ? this.props.color : null,
+ fill: color || null,
visibility,
}}
- d={this.props.path}
- transform={
- `translate(${
- -this.props.width / 2
- }, ${
- -this.props.height / 4
- })`
- }
+ d={path}
+ transform={`translate(${-width / 2}, ${-height / 4})`}
/>
- {this.getText(-5, lodashRound(this.props.height / 6, 4))}
+ {this.getText(-5, lodashRound(height / 6, 4))}
</>
);
}
@@ -117,8 +105,9 @@ class TimelineDragger extends PureComponent {
* Return visibility style string
*/
getVisibility() {
+ const { position, max } = this.state;
let visibility = 'visible';
- if (this.state.position < 0 || this.state.position > this.state.max) {
+ if (position < 0 || position > max) {
visibility = 'hidden';
}
return visibility;
@@ -130,8 +119,10 @@ class TimelineDragger extends PureComponent {
* @param {number} y | y offset
*/
getText(x, y) {
+ const { text } = this.props;
+ const { textColor } = this.state;
const visibility = this.getVisibility();
- if (this.props.text) {
+ if (text) {
return (
<text
x={x}
@@ -139,11 +130,11 @@ class TimelineDragger extends PureComponent {
alignmentBaseline="middle"
textAnchor="middle"
style={{
- fill: this.state.textColor ? this.state.textColor : null,
+ fill: textColor || null,
visibility: visibility || null,
}}
>
- {this.props.text}
+ {text}
</text>
);
}
@@ -160,10 +151,11 @@ class TimelineDragger extends PureComponent {
* @return {void}
*/
handleDrag(e, d) {
+ const { onDrag, id } = this.props;
e.stopPropagation();
e.preventDefault();
const deltaX = e.movementX || d.deltaX;
- this.props.onDrag(d.deltaX, this.props.id, d.x);
+ onDrag(d.deltaX, id, d.x);
this.setState((prevState) => ({
position: prevState.position + deltaX,
}));
@@ -174,17 +166,21 @@ class TimelineDragger extends PureComponent {
*/
render() {
const visibility = this.getVisibility();
+ const {
+ id, path, onStop, yOffset,
+ } = this.props;
+ const { position } = this.state;
return (
<Draggable
onDrag={this.handleDrag}
- position={{ x: this.state.position, y: this.props.yOffset }}
+ position={{ x: position, y: yOffset }}
onStop={() => {
- this.props.onStop(this.props.id, this.state.position);
+ onStop(id, position);
}}
axis="x"
>
<g>
- {!this.props.path
+ {!path
? this.getDefaultDragger(visibility)
: this.getCustomDragger(visibility)}
</g>
diff --git a/web/js/components/range-selection/range-selection.js b/web/js/components/range-selection/range-selection.js
index 89517e7b4..26a1be94c 100644
--- a/web/js/components/range-selection/range-selection.js
+++ b/web/js/components/range-selection/range-selection.js
@@ -22,6 +22,18 @@ class TimelineRangeSelector extends React.Component {
};
}
+ componentDidMount() {
+ this.updateLocation();
+ }
+
+ componentDidUpdate() {
+ const { startLocation, endLocation } = this.props;
+ // eslint-disable-next-line react/destructuring-assignment
+ if (startLocation !== this.state.startLocation || endLocation !== this.state.endLocation) {
+ this.updateLocation();
+ }
+ }
+
/*
* When a child component is dragged,
* this function is called to determine
@@ -120,6 +132,7 @@ class TimelineRangeSelector extends React.Component {
timeScale,
position,
transformX,
+ frontDate,
} = this.props;
const options = timeScaleOptions[timeScale].timeAxis;
@@ -127,7 +140,7 @@ class TimelineRangeSelector extends React.Component {
const startDraggerPositionRelativeToFrontDate = animDraggerLocation - position - transformX + deltaX;
const gridWidthCoef = startDraggerPositionRelativeToFrontDate / gridWidth;
- const draggerDateAdded = moment.utc(this.props.frontDate).add(Math.floor(gridWidthCoef), timeScale);
+ const draggerDateAdded = moment.utc(frontDate).add(Math.floor(gridWidthCoef), timeScale);
const draggerDateAddedValue = draggerDateAdded.valueOf();
let daysCount;
if (timeScale === 'year') {
@@ -154,6 +167,7 @@ class TimelineRangeSelector extends React.Component {
startLocationDate,
endLocationDate,
timeScale,
+ updateAnimationDateAndLocation,
} = this.props;
const {
@@ -223,7 +237,7 @@ class TimelineRangeSelector extends React.Component {
draggerStartLocation = startLocation;
animationStartLocationDate = endDateLimit;
}
- this.props.updateAnimationDateAndLocation(
+ updateAnimationDateAndLocation(
animationStartLocationDate,
animationEndLocationDate,
draggerStartLocation,
@@ -232,24 +246,14 @@ class TimelineRangeSelector extends React.Component {
);
}
- componentDidMount() {
- this.updateLocation();
- }
-
updateLocation = () => {
+ const { startLocation, endLocation } = this.props;
this.setState({
- startLocation: this.props.startLocation,
- endLocation: this.props.endLocation,
+ startLocation,
+ endLocation,
});
}
- componentDidUpdate() {
- const { startLocation, endLocation } = this.props;
- if (startLocation !== this.state.startLocation || endLocation !== this.state.endLocation) {
- this.updateLocation();
- }
- }
-
/*
* @method render
*/
@@ -346,8 +350,6 @@ TimelineRangeSelector.propTypes = {
endTriangleColor: PropTypes.string,
frontDate: PropTypes.string,
max: PropTypes.object,
- onDrag: PropTypes.func,
- parentOffset: PropTypes.number,
pinWidth: PropTypes.number,
position: PropTypes.number,
rangeColor: PropTypes.string,
diff --git a/web/js/components/sidebar/mode-selection.js b/web/js/components/sidebar/mode-selection.js
index c5d799efc..d67a4f9d1 100644
--- a/web/js/components/sidebar/mode-selection.js
+++ b/web/js/components/sidebar/mode-selection.js
@@ -7,12 +7,12 @@ class ModeSelection extends React.Component {
super(props);
this.state = {
selected: props.selected,
- loaded: false,
};
}
UNSAFE_componentWillReceiveProps(newProp) {
- if (this.state.selected !== newProp.selected) {
+ const { selected } = this.state;
+ if (selected !== newProp.selected) {
this.setState({ selected: newProp.selected });
}
}
diff --git a/web/js/components/sidebar/paletteLegend.js b/web/js/components/sidebar/paletteLegend.js
index c8da4d5d2..78e6dfc67 100644
--- a/web/js/components/sidebar/paletteLegend.js
+++ b/web/js/components/sidebar/paletteLegend.js
@@ -8,24 +8,87 @@ import { getOrbitTrackTitle } from '../../modules/layers/util';
import { drawSidebarPaletteOnCanvas, drawTicksOnCanvas } from '../../modules/palettes/util';
import util from '../../util/util';
+/**
+ * @param {Number} index | Selected label Index
+ * @param {Number} boxWidth | Width of Each label box
+ * @param {Number} textWidth | Label width
+ * @param {Number} width | Case width
+ */
+// const getClassLabelStyle = (index, boxWidth, textWidth, width, rowEndIndex) => {
+// const halfTextWidth = textWidth / 2 || 0;
+// const xOffset = boxWidth * (index - rowEndIndex) + boxWidth / 2 || 0;
+
+// if (halfTextWidth > xOffset) {
+// return { textAlign: 'left', visibility: 'visible' };
+// } if (xOffset + halfTextWidth > width) {
+// return { textAlign: 'right', visibility: 'visible' };
+// }
+// return {
+// marginLeft: `${xOffset - halfTextWidth}px`,
+// visibility: 'visible',
+// textAlign: 'left',
+// };
+// };
+
+/**
+ * Find wanted legend object from Hex
+ * @param {Object} legend
+ * @param {String} hex
+ * @param {Number} acceptableDifference
+ */
+const getLegendObject = (legend, hex, acceptableDifference) => {
+ const units = legend.units || '';
+ for (let i = 0, len = legend.colors.length; i < len; i += 1) {
+ if (util.hexColorDelta(legend.colors[i], hex) < acceptableDifference) {
+ // If the two colors are close
+ return {
+ label: units ? `${legend.tooltips[i]} ${units}` : legend.tooltips[i],
+ len,
+ index: i,
+ };
+ }
+ }
+ return null;
+};
+
+/**
+ * @param {Number} xOffset | X px Location of running-data
+ * @param {Number} textWidth | px width of text calculated with canvas
+ * @param {Number} width | Case width
+ */
+const getRunningLabelStyle = (xOffset, textWidth, width) => {
+ if (!xOffset || !textWidth || !width) return { left: '0' };
+ const halfTextWidth = textWidth / 2 || 0;
+ if (halfTextWidth > xOffset) {
+ return { left: '0' };
+ } if (xOffset + halfTextWidth > width) {
+ return { right: '0' };
+ }
+ return { left: `${Math.floor(xOffset - halfTextWidth)}px` };
+};
+
class PaletteLegend extends React.Component {
constructor(props) {
super(props);
this.state = {
isRunningData: props.isRunningData,
colorHex: props.colorHex,
- isHoveringCanvas: props.isHoveringCanvas,
- width: this.props.width,
+ width: props.width,
scrollContainerEl: null,
};
}
+ componentDidMount() {
+ this.updateCanvas();
+ this.setState(() => ({
+ scrollContainerEl: document.querySelector('#productsHolder .simplebar-wrapper'),
+ }));
+ }
+
UNSAFE_componentWillReceiveProps(props) {
- if (
- props.colorHex !== this.state.colorHex
- || props.isRunningData !== this.state.isRunningData
- ) {
+ const { colorHex, isRunningData } = this.state;
+ if (props.colorHex !== colorHex || props.isRunningData !== isRunningData) {
this.setState({
isRunningData: props.isRunningData,
colorHex: props.colorHex,
@@ -33,16 +96,10 @@ class PaletteLegend extends React.Component {
}
}
- componentDidMount() {
- this.updateCanvas();
- this.setState(() => ({
- scrollContainerEl: document.querySelector('#productsHolder .simplebar-wrapper'),
- }));
- }
-
componentDidUpdate(prevProps) {
+ const { layer, width } = this.props;
// Only updates when layer options/settings have changed or if ZOT changes the width of the palette
- if (!lodashIsEqual(this.props.layer, prevProps.layer) || (prevProps.width !== this.props.width)) {
+ if (!lodashIsEqual(layer, prevProps.layer) || (prevProps.width !== width)) {
this.updateCanvas();
}
}
@@ -94,27 +151,6 @@ class PaletteLegend extends React.Component {
});
}
- /**
- * Find wanted legend object from Hex
- * @param {Object} legend
- * @param {String} hex
- * @param {Number} acceptableDifference
- */
- getLegendObject(legend, hex, acceptableDifference) {
- const units = legend.units || '';
- for (let i = 0, len = legend.colors.length; i < len; i++) {
- if (util.hexColorDelta(legend.colors[i], hex) < acceptableDifference) {
- // If the two colors are close
- return {
- label: units ? `${legend.tooltips[i]} ${units}` : legend.tooltips[i],
- len,
- index: i,
- };
- }
- }
- return null;
- }
-
/**
* Update state on MouseOut
*/
@@ -140,6 +176,7 @@ class PaletteLegend extends React.Component {
const ctxStr = `canvas_${index}`;
if (this[ctxStr]) {
const newWidth = this[ctxStr].current.getBoundingClientRect().width;
+ // eslint-disable-next-line react/destructuring-assignment
if (newWidth !== this.state.width) {
// If scrollbar appears canvas width changes.
// This value is needed for calculating running data offsets
@@ -186,44 +223,6 @@ class PaletteLegend extends React.Component {
}
}
- /**
- * @param {Number} index | Selected label Index
- * @param {Number} boxWidth | Width of Each label box
- * @param {Number} textWidth | Label width
- * @param {Number} width | Case width
- */
- getClassLabelStyle(index, boxWidth, textWidth, width, rowEndIndex) {
- const halfTextWidth = textWidth / 2 || 0;
- const xOffset = boxWidth * (index - rowEndIndex) + boxWidth / 2 || 0;
-
- if (halfTextWidth > xOffset) {
- return { textAlign: 'left', visibility: 'visible' };
- } if (xOffset + halfTextWidth > width) {
- return { textAlign: 'right', visibility: 'visible' };
- }
- return {
- marginLeft: `${xOffset - halfTextWidth}px`,
- visibility: 'visible',
- textAlign: 'left',
- };
- }
-
- /**
- * @param {Number} xOffset | X px Location of running-data
- * @param {Number} textWidth | px width of text calculated with canvas
- * @param {Number} width | Case width
- */
- getRunningLabelStyle(xOffset, textWidth, width) {
- if (!xOffset || !textWidth || !width) return { left: '0' };
- const halfTextWidth = textWidth / 2 || 0;
- if (halfTextWidth > xOffset) {
- return { left: '0' };
- } if (xOffset + halfTextWidth > width) {
- return { right: '0' };
- }
- return { left: `${Math.floor(xOffset - halfTextWidth)}px` };
- }
-
/**
* Render scale-type paletteLegends
* @param {Object} legend
@@ -236,14 +235,18 @@ class PaletteLegend extends React.Component {
} = this.props;
const { isRunningData, colorHex, isHoveringLegend } = this.state;
const palette = getPalette(layer.id, index);
- let percent; let textWidth; let xOffset; let
- legendObj;
+ let percent;
+ let textWidth;
+ let xOffset;
+ let legendObj;
const toolTipLength = legend.tooltips.length;
+ // eslint-disable-next-line react/destructuring-assignment
if (isRunningData && colorHex && this.state.width > 0) {
- legendObj = this.getLegendObject(legend, colorHex, 5); // {label,len,index}
+ legendObj = getLegendObject(legend, colorHex, 5); // {label,len,index}
if (legendObj) {
percent = this.getPercent(legendObj.len, legendObj.index);
textWidth = util.getTextWidth(legendObj.label, '10px Open Sans');
+ // eslint-disable-next-line react/destructuring-assignment
xOffset = Math.floor(this.state.width * percent);
}
}
@@ -300,7 +303,7 @@ class PaletteLegend extends React.Component {
className="wv-running-label"
style={
isRunningData
- ? this.getRunningLabelStyle(xOffset, textWidth, this.state.width)
+ ? getRunningLabelStyle(xOffset, textWidth, width)
: { display: 'none' }
}
>
@@ -331,7 +334,7 @@ class PaletteLegend extends React.Component {
const {
layer, parentLayer, layerGroupName, getPalette,
} = this.props;
- const activeKeyObj = isRunningData && colorHex && this.getLegendObject(legend, colorHex, 5);
+ const activeKeyObj = isRunningData && colorHex && getLegendObject(legend, colorHex, 5);
const legendClass = activeKeyObj
? 'wv-running wv-palettes-legend wv-palettes-classes'
: 'wv-palettes-legend wv-palettes-classes';
@@ -439,8 +442,6 @@ class PaletteLegend extends React.Component {
}
PaletteLegend.defaultProps = {
isRunningData: false,
- isHoveringLegend: false,
- isRunningDataEnabled: true,
width: 231,
height: 12,
};
@@ -450,12 +451,8 @@ PaletteLegend.propTypes = {
getPalette: PropTypes.func,
height: PropTypes.number,
isCustomPalette: PropTypes.bool,
- isHoveringCanvas: PropTypes.bool,
- isHoveringLegend: PropTypes.bool,
isMobile: PropTypes.bool,
isRunningData: PropTypes.bool,
- isRunningDataEnabled: PropTypes.bool,
- isSubLayer: PropTypes.bool,
layer: PropTypes.object,
layerGroupName: PropTypes.string,
paletteId: PropTypes.string,
diff --git a/web/js/components/sidebar/product.js b/web/js/components/sidebar/product.js
index aa9c26d6c..e7c003e8c 100644
--- a/web/js/components/sidebar/product.js
+++ b/web/js/components/sidebar/product.js
@@ -86,11 +86,8 @@ class Data extends React.Component {
);
}
}
-Data.defaultProps = {
- count: 0,
-};
+
Data.propTypes = {
- count: PropTypes.number,
countsObject: PropTypes.object,
id: PropTypes.string,
isSelected: PropTypes.bool,
diff --git a/web/js/components/timeline/custom-interval-selector/delta-input.js b/web/js/components/timeline/custom-interval-selector/delta-input.js
index c7d9cf903..faf67852f 100644
--- a/web/js/components/timeline/custom-interval-selector/delta-input.js
+++ b/web/js/components/timeline/custom-interval-selector/delta-input.js
@@ -18,6 +18,11 @@ class DeltaInput extends PureComponent {
};
}
+ componentDidMount() {
+ const { deltaValue } = this.props;
+ this.setValue(deltaValue);
+ }
+
onKeyInput = (e) => {
let { value } = e.target;
if (value === '' || regex.test(value)) {
@@ -51,11 +56,12 @@ class DeltaInput extends PureComponent {
}
handleBlur = () => {
+ const { changeDelta } = this.props;
const { value } = this.state;
if (value >= 1 && value < 1000) {
this.setState({
valid: true,
- }, this.props.changeDelta(value));
+ }, changeDelta(value));
} else {
this.setState({
valid: false,
@@ -69,10 +75,6 @@ class DeltaInput extends PureComponent {
});
}
- componentDidMount() {
- this.setValue(this.props.deltaValue);
- }
-
render() {
const {
value,
diff --git a/web/js/components/timeline/custom-interval-selector/interval-select.js b/web/js/components/timeline/custom-interval-selector/interval-select.js
index ce0c97531..ab118462b 100644
--- a/web/js/components/timeline/custom-interval-selector/interval-select.js
+++ b/web/js/components/timeline/custom-interval-selector/interval-select.js
@@ -9,8 +9,9 @@ import PropTypes from 'prop-types';
*/
class TimeScaleSelect extends PureComponent {
handleChangeZoomLevel = (e) => {
+ const { changeZoomLevel } = this.props;
const zoomLevel = e.target.value;
- this.props.changeZoomLevel(zoomLevel);
+ changeZoomLevel(zoomLevel);
}
handleSubmit = (e) => {
diff --git a/web/js/components/timeline/custom-interval-selector/interval-selector-widget.js b/web/js/components/timeline/custom-interval-selector/interval-selector-widget.js
index 99ab4c912..4bdac30e8 100644
--- a/web/js/components/timeline/custom-interval-selector/interval-selector-widget.js
+++ b/web/js/components/timeline/custom-interval-selector/interval-selector-widget.js
@@ -19,26 +19,32 @@ import { toggleCustomModal } from '../../../modules/date/actions';
* @class CustomIntervalSelectorWidget
*/
class CustomIntervalSelectorWidget extends PureComponent {
+ componentDidUpdate(prevProps) {
+ const { customIntervalModalOpen } = this.props;
+ // handle focus widget on opening
+ if (customIntervalModalOpen && !prevProps.customIntervalModalOpen) {
+ this.customIntervalWidget.focus();
+ }
+ }
+
changeDelta = (value) => {
+ const {
+ changeCustomInterval, customIntervalZoomLevel,
+ } = this.props;
if (value >= 0 && value <= 1000) {
- this.props.changeCustomInterval(value, this.props.customIntervalZoomLevel);
+ changeCustomInterval(value, customIntervalZoomLevel);
}
}
changeZoomLevel = (zoomLevel) => {
- this.props.changeCustomInterval(this.props.customDelta, timeScaleToNumberKey[zoomLevel]);
+ const { changeCustomInterval, customDelta } = this.props;
+ changeCustomInterval(customDelta, timeScaleToNumberKey[zoomLevel]);
}
handleKeyPress= (e) => {
+ const { closeModal } = this.props;
if (e.key === 'Escape') {
- this.props.closeModal();
- }
- }
-
- componentDidUpdate(prevProps) {
- // handle focus widget on opening
- if (this.props.customIntervalModalOpen && !prevProps.customIntervalModalOpen) {
- this.customIntervalWidget.focus();
+ closeModal();
}
}
@@ -93,5 +99,4 @@ CustomIntervalSelectorWidget.propTypes = {
customIntervalModalOpen: PropTypes.bool,
customIntervalZoomLevel: PropTypes.number,
hasSubdailyLayers: PropTypes.bool,
- toggleCustomIntervalModal: PropTypes.func,
};
diff --git a/web/js/components/timeline/date-util.js b/web/js/components/timeline/date-util.js
index 5f825caa9..3534e7a0f 100644
--- a/web/js/components/timeline/date-util.js
+++ b/web/js/components/timeline/date-util.js
@@ -19,14 +19,14 @@ export const getISODateFormatted = (date) => `${new Date(date).toISOString().spl
// timeRange extension to pop NUM times
export const removeBackMultipleInPlace = (timeRange, num) => {
- for (let i = 0; i < num; i++) {
+ for (let i = 0; i < num; i += 1) {
timeRange.pop();
}
};
// timeRange extension to shift NUM times
export const removeFrontMultipleInPlace = (timeRange, num) => {
- for (let i = 0; i < num; i++) {
+ for (let i = 0; i < num; i += 1) {
timeRange.shift();
}
};
diff --git a/web/js/components/timeline/distraction-free-time.js b/web/js/components/timeline/distraction-free-time.js
index 587023839..1b80195b6 100644
--- a/web/js/components/timeline/distraction-free-time.js
+++ b/web/js/components/timeline/distraction-free-time.js
@@ -4,7 +4,8 @@ import util from '../../util/util';
class DistractionFreeTimeUI extends PureComponent {
handleMouseOver = () => {
- this.props.hoverOverDistractionFreeTimeUI(true);
+ const { hoverOverDistractionFreeTimeUI } = this.props;
+ hoverOverDistractionFreeTimeUI(true);
}
render() {
diff --git a/web/js/components/timeline/mobile-date-picker.js b/web/js/components/timeline/mobile-date-picker.js
index 0c1c86351..d1ba31edd 100644
--- a/web/js/components/timeline/mobile-date-picker.js
+++ b/web/js/components/timeline/mobile-date-picker.js
@@ -63,6 +63,18 @@ class MobileDatePicker extends Component {
};
}
+ componentDidMount() {
+ this.setInitDates();
+ }
+
+ componentDidUpdate(prevProps) {
+ const { date, endDateLimit } = this.props;
+ // update on new endDateLimit or changed date
+ if (prevProps.endDateLimit !== endDateLimit || prevProps.date !== date) {
+ this.setInitDates();
+ }
+ }
+
handleClickDateButton = () => {
this.setState({
isOpen: true,
@@ -76,13 +88,14 @@ class MobileDatePicker extends Component {
}
handleSelect = (time) => {
+ const { onDateChange } = this.props;
this.setState({
time,
isOpen: false,
});
// convert date back to local time
const date = this.convertToLocalDateObject(time);
- this.props.onDateChange(getISODateFormatted(date));
+ onDateChange(getISODateFormatted(date));
}
// used for init mount
@@ -112,18 +125,6 @@ class MobileDatePicker extends Component {
return dateLocal;
}
- componentDidMount() {
- this.setInitDates();
- }
-
- componentDidUpdate(prevProps) {
- const { date, endDateLimit } = this.props;
- // update on new endDateLimit or changed date
- if (prevProps.endDateLimit !== endDateLimit || prevProps.date !== date) {
- this.setInitDates();
- }
- }
-
render() {
const {
time,
diff --git a/web/js/components/timeline/timeline-axis/date-calc.js b/web/js/components/timeline/timeline-axis/date-calc.js
index 465e67abb..544e680c7 100644
--- a/web/js/components/timeline/timeline-axis/date-calc.js
+++ b/web/js/components/timeline/timeline-axis/date-calc.js
@@ -16,7 +16,7 @@ const limitCache = {};
* @param {endDateLimit} endDateLimit - max date within timeline range
* @returns {Array} timeRange - consecutive time units based on range
*/
-export function getTimeRange(startDate, endDate, timeScale, startDateLimit, endDateLimit) {
+export default function getTimeRange(startDate, endDate, timeScale, startDateLimit, endDateLimit) {
const timeRange = [];
const { format } = timeScaleOptions[timeScale].timeAxis;
diff --git a/web/js/components/timeline/timeline-axis/grid-range/tile-rect.js b/web/js/components/timeline/timeline-axis/grid-range/tile-rect.js
index 4f7ba3360..1fbce9683 100644
--- a/web/js/components/timeline/timeline-axis/grid-range/tile-rect.js
+++ b/web/js/components/timeline/timeline-axis/grid-range/tile-rect.js
@@ -73,8 +73,8 @@ class TileRect extends PureComponent {
* @returns {void}
*/
showHover = (e) => {
- const { item, index } = this.props;
- this.props.showHover(e, item.rawDate, item.rawNextDate, index);
+ const { item, index, showHover } = this.props;
+ showHover(e, item.rawDate, item.rawNextDate, index);
}
render() {
diff --git a/web/js/components/timeline/timeline-axis/timeline-axis.js b/web/js/components/timeline/timeline-axis/timeline-axis.js
index d0b65225f..0bdff4a5b 100644
--- a/web/js/components/timeline/timeline-axis/timeline-axis.js
+++ b/web/js/components/timeline/timeline-axis/timeline-axis.js
@@ -9,7 +9,7 @@ import {
} from 'lodash';
import GridRange from './grid-range/grid-range';
-import { getTimeRange } from './date-calc';
+import getTimeRange from './date-calc';
import {
timeScaleOptions,
timeScaleToNumberKey,
@@ -48,6 +48,162 @@ class TimelineAxis extends Component {
this.wheelTimeout = 0;
}
+ componentDidMount() {
+ const {
+ draggerSelected,
+ draggerTimeState,
+ draggerTimeStateB,
+ timeScale,
+ } = this.props;
+ const time = draggerSelected === 'selected' ? draggerTimeState : draggerTimeStateB;
+ this.updateScale(time, timeScale, 0.5);
+ }
+
+ shouldComponentUpdate(nextProps, nextState) {
+ const { init } = this.state;
+ if (init === true) {
+ return true;
+ }
+ const {
+ axisWidth,
+ draggerSelected,
+ timeScale,
+ isCompareModeActive,
+ hasSubdailyLayers,
+ matchingTimelineCoverage,
+ timelineEndDateLimit,
+ transformX,
+ frontDate,
+ backDate,
+ position,
+ dateA,
+ dateB,
+ } = this.props;
+
+ const checkForPropsUpdates = nextProps.axisWidth === axisWidth
+ && nextProps.position === position
+ && nextProps.dateA === dateA
+ && nextProps.dateB === dateB
+ && nextProps.draggerSelected === draggerSelected
+ && nextProps.timeScale === timeScale
+ && nextProps.isCompareModeActive === isCompareModeActive
+ && nextProps.hasSubdailyLayers === hasSubdailyLayers
+ && nextProps.timelineEndDateLimit === timelineEndDateLimit
+ && nextProps.transformX === transformX
+ && nextProps.frontDate === frontDate
+ && nextProps.backDate === backDate
+ && lodashIsEqual(nextProps.matchingTimelineCoverage, matchingTimelineCoverage);
+
+ const {
+ dragSentinelChangeNumber,
+ dragSentinelCount,
+ gridNumber,
+ gridWidth,
+ leftBound,
+ midPoint,
+ numberOfVisibleTiles,
+ rightBound,
+ wheelZoom,
+ } = this.state;
+
+ const checkForStateUpdates = dragSentinelChangeNumber === nextState.dragSentinelChangeNumber
+ && dragSentinelCount === nextState.dragSentinelCount
+ && gridNumber === nextState.gridNumber
+ && gridWidth === nextState.gridWidth
+ && leftBound === nextState.leftBound
+ && midPoint === nextState.midPoint
+ && numberOfVisibleTiles === nextState.numberOfVisibleTiles
+ && rightBound === nextState.rightBound
+ && wheelZoom === nextState.wheelZoom;
+ if (checkForPropsUpdates && checkForStateUpdates) {
+ return false;
+ }
+ return true;
+ }
+
+ componentDidUpdate(prevProps) {
+ const {
+ dateA,
+ dateB,
+ hoverTime,
+ draggerSelected,
+ isDraggerDragging,
+ timeScale,
+ axisWidth,
+ isAnimationPlaying,
+ isCompareModeActive,
+ isTimelineDragging,
+ draggerTimeState,
+ draggerTimeStateB,
+ timelineEndDateLimit,
+ } = this.props;
+ const { wheelZoom } = this.state;
+
+ let draggerDate = draggerSelected === 'selected' ? draggerTimeState : draggerTimeStateB;
+
+ // update timescale axis focus
+ if (timeScale !== prevProps.timeScale) {
+ let leftOffset;
+ if (wheelZoom === true) {
+ draggerDate = hoverTime;
+ } else {
+ leftOffset = 0.8;
+ }
+ // add updateTimeScale flag to indicate showHover should not fire immediately
+ // eslint-disable-next-line react/no-did-update-set-state
+ this.setState({
+ updatedTimeScale: true,
+ });
+ this.updateScale(draggerDate, timeScale, leftOffset, true, prevProps.timeScale);
+ }
+
+ // update axis on browser width change
+ if (axisWidth !== prevProps.axisWidth) {
+ this.updateScale(draggerDate, timeScale, 0.5);
+ }
+
+ // update scale if end time limit has changed (e.g. time has elapsed since the app was started)
+ if (timelineEndDateLimit !== prevProps.timelineEndDateLimit && !isAnimationPlaying && !isDraggerDragging && !isTimelineDragging) {
+ this.updateScale(draggerDate, timeScale, 0.5);
+ }
+
+ // handle switching A/B dragger axis focus if switched from A/B sidebar tabs
+ if (isCompareModeActive && (draggerSelected !== prevProps.draggerSelected)) {
+ if (draggerSelected === 'selected') {
+ const draggerCheck = this.checkDraggerMoveOrUpdateScale(prevProps.dateA);
+ if (!draggerCheck.withinRange) {
+ this.updateScaleWithOffset(dateA, timeScale, draggerCheck);
+ }
+ } else {
+ const draggerCheck = this.checkDraggerMoveOrUpdateScale(prevProps.dateB, true);
+ if (!draggerCheck.withinRange) {
+ this.updateScaleWithOffset(dateB, timeScale, draggerCheck);
+ }
+ }
+ }
+
+ const animationTurnOn = !prevProps.isAnimationPlaying && isAnimationPlaying;
+ const animationTurnOff = prevProps.isAnimationPlaying && !isAnimationPlaying;
+ // handle date axis focus when animation runs and animation range is not visible
+ if (animationTurnOn || animationTurnOff) {
+ const selectedDate = draggerSelected === 'selected' ? dateA : dateB;
+ const draggerCheck = this.checkDraggerMoveOrUpdateScale(selectedDate);
+ if (!draggerCheck.withinRange) {
+ this.updateScale(selectedDate, timeScale, 0.5);
+ }
+ // handle dragger and potential axis updates
+ } else if (!isDraggerDragging) {
+ // handle A dragger change
+ if (draggerSelected === 'selected' || isCompareModeActive) {
+ this.handleDraggerUpdateCheck(dateA, prevProps.dateA, draggerTimeState, false);
+ }
+ // handle B dragger change
+ if (draggerSelected === 'selectedB' || isCompareModeActive) {
+ this.handleDraggerUpdateCheck(dateB, prevProps.dateB, draggerTimeStateB, true);
+ }
+ }
+ }
+
/**
* @desc main function to update axis scale, time range, grids tiles/text, dragger A/B positions, animation start/end draggers
* @param {String} inputDate
@@ -72,7 +228,9 @@ class TimelineAxis extends Component {
animEndLocationDate,
timelineStartDateLimit,
timelineEndDateLimit,
+ updatePositioning,
} = this.props;
+ const { draggerWidth } = this.state;
const options = timeScaleOptions[timeScale].timeAxis;
const { gridWidth } = options;
const timelineAxisWidth = axisWidth;
@@ -104,7 +262,7 @@ class TimelineAxis extends Component {
const midPoint = numberOfVisibleTiles / 2 * gridWidth - gridWidth * gridNumber / 2;
// horizontal scroll will disable this, so use frontDate in that case
- let hoverTimeString = hoverTime || this.props.draggerTimeState;
+ let hoverTimeString = hoverTime || draggerTimeState;
// handle timeline axis start/end limits
const isBeforeStart = new Date(hoverTimeString) <= new Date(timelineStartDateLimit);
@@ -259,8 +417,8 @@ class TimelineAxis extends Component {
const transformX = boundsDiff - pixelsToAdd - 2;
const animationStartLocation = animationStartDraggerLocation + position + transformX;
const animationEndLocation = animationEndDraggerLocation + position + transformX;
- draggerPosition = draggerPosition - pixelsToAdd + position - this.state.draggerWidth + boundsDiff;
- draggerPositionB = draggerPositionB - pixelsToAdd + position - this.state.draggerWidth + boundsDiff;
+ draggerPosition = draggerPosition - pixelsToAdd + position - draggerWidth + boundsDiff;
+ draggerPositionB = draggerPositionB - pixelsToAdd + position - draggerWidth + boundsDiff;
const updatePositioningArguments = {
hasMoved: false,
isTimelineDragging: false,
@@ -290,7 +448,7 @@ class TimelineAxis extends Component {
wheelZoom: false,
hitLeftBound: false,
hitRightBound: false,
- }, this.props.updatePositioning(updatePositioningArguments, isYearOrMonth ? hoverTime : hoverTimeString));
+ }, updatePositioning(updatePositioningArguments, isYearOrMonth ? hoverTime : hoverTimeString));
}
/**
@@ -485,99 +643,6 @@ class TimelineAxis extends Component {
};
}
- componentDidMount() {
- const {
- draggerSelected,
- draggerTimeState,
- draggerTimeStateB,
- timeScale,
- } = this.props;
- const time = draggerSelected === 'selected' ? draggerTimeState : draggerTimeStateB;
- this.updateScale(time, timeScale, 0.5);
- }
-
- componentDidUpdate(prevProps) {
- const {
- dateA,
- dateB,
- hoverTime,
- draggerSelected,
- isDraggerDragging,
- timeScale,
- axisWidth,
- isAnimationPlaying,
- isCompareModeActive,
- isTimelineDragging,
- draggerTimeState,
- draggerTimeStateB,
- timelineEndDateLimit,
- } = this.props;
- const { wheelZoom } = this.state;
-
- let draggerDate = draggerSelected === 'selected' ? draggerTimeState : draggerTimeStateB;
-
- // update timescale axis focus
- if (timeScale !== prevProps.timeScale) {
- let leftOffset;
- if (wheelZoom === true) {
- draggerDate = hoverTime;
- } else {
- leftOffset = 0.8;
- }
- // add updateTimeScale flag to indicate showHover should not fire immediately
- // eslint-disable-next-line react/no-did-update-set-state
- this.setState({
- updatedTimeScale: true,
- });
- this.updateScale(draggerDate, timeScale, leftOffset, true, prevProps.timeScale);
- }
-
- // update axis on browser width change
- if (axisWidth !== prevProps.axisWidth) {
- this.updateScale(draggerDate, timeScale, 0.5);
- }
-
- // update scale if end time limit has changed (e.g. time has elapsed since the app was started)
- if (timelineEndDateLimit !== prevProps.timelineEndDateLimit && !isAnimationPlaying && !isDraggerDragging && !isTimelineDragging) {
- this.updateScale(draggerDate, timeScale, 0.5);
- }
-
- // handle switching A/B dragger axis focus if switched from A/B sidebar tabs
- if (isCompareModeActive && (draggerSelected !== prevProps.draggerSelected)) {
- if (draggerSelected === 'selected') {
- const draggerCheck = this.checkDraggerMoveOrUpdateScale(prevProps.dateA);
- if (!draggerCheck.withinRange) {
- this.updateScaleWithOffset(dateA, timeScale, draggerCheck);
- }
- } else {
- const draggerCheck = this.checkDraggerMoveOrUpdateScale(prevProps.dateB, true);
- if (!draggerCheck.withinRange) {
- this.updateScaleWithOffset(dateB, timeScale, draggerCheck);
- }
- }
- }
-
- const animationTurnOn = !prevProps.isAnimationPlaying && isAnimationPlaying;
- const animationTurnOff = prevProps.isAnimationPlaying && !isAnimationPlaying;
- // handle date axis focus when animation runs and animation range is not visible
- if (animationTurnOn || animationTurnOff) {
- const selectedDate = draggerSelected === 'selected' ? dateA : dateB;
- const draggerCheck = this.checkDraggerMoveOrUpdateScale(selectedDate);
- if (!draggerCheck.withinRange) {
- this.updateScale(selectedDate, timeScale, 0.5);
- }
- // handle dragger and potential axis updates
- } else if (!isDraggerDragging) {
- // handle A dragger change
- if (draggerSelected === 'selected' || isCompareModeActive) {
- this.handleDraggerUpdateCheck(dateA, prevProps.dateA, draggerTimeState, false);
- }
- // handle B dragger change
- if (draggerSelected === 'selectedB' || isCompareModeActive) {
- this.handleDraggerUpdateCheck(dateB, prevProps.dateB, draggerTimeStateB, true);
- }
- }
- }
/**
* @desc check if dragger within axis range or need scale update
@@ -978,7 +1043,10 @@ class TimelineAxis extends Component {
dragSentinelCount,
} = this.state;
const {
+ draggerVisible,
+ draggerVisibleB,
timeScale,
+ transformX,
updatePositioning,
updatePositioningOnSimpleDrag,
} = this.props;
@@ -1004,13 +1072,13 @@ class TimelineAxis extends Component {
hasMoved: true,
isTimelineDragging: true,
position,
- transformX: this.props.transformX,
+ transformX,
frontDate,
backDate,
draggerPosition,
draggerPositionB,
- draggerVisible: this.props.draggerVisible,
- draggerVisibleB: this.props.draggerVisibleB,
+ draggerVisible,
+ draggerVisibleB,
animationStartLocation,
animationEndLocation,
};
@@ -1341,68 +1409,6 @@ class TimelineAxis extends Component {
</g>
)
- shouldComponentUpdate(nextProps, nextState) {
- const { init } = this.state;
- if (init === true) {
- return true;
- }
- const {
- axisWidth,
- draggerSelected,
- timeScale,
- isCompareModeActive,
- hasSubdailyLayers,
- matchingTimelineCoverage,
- timelineEndDateLimit,
- transformX,
- frontDate,
- backDate,
- position,
- dateA,
- dateB,
- } = this.props;
-
- const checkForPropsUpdates = nextProps.axisWidth === axisWidth
- && nextProps.position === position
- && nextProps.dateA === dateA
- && nextProps.dateB === dateB
- && nextProps.draggerSelected === draggerSelected
- && nextProps.timeScale === timeScale
- && nextProps.isCompareModeActive === isCompareModeActive
- && nextProps.hasSubdailyLayers === hasSubdailyLayers
- && nextProps.timelineEndDateLimit === timelineEndDateLimit
- && nextProps.transformX === transformX
- && nextProps.frontDate === frontDate
- && nextProps.backDate === backDate
- && lodashIsEqual(nextProps.matchingTimelineCoverage, matchingTimelineCoverage);
-
- const {
- dragSentinelChangeNumber,
- dragSentinelCount,
- gridNumber,
- gridWidth,
- leftBound,
- midPoint,
- numberOfVisibleTiles,
- rightBound,
- wheelZoom,
- } = this.state;
-
- const checkForStateUpdates = dragSentinelChangeNumber === nextState.dragSentinelChangeNumber
- && dragSentinelCount === nextState.dragSentinelCount
- && gridNumber === nextState.gridNumber
- && gridWidth === nextState.gridWidth
- && leftBound === nextState.leftBound
- && midPoint === nextState.midPoint
- && numberOfVisibleTiles === nextState.numberOfVisibleTiles
- && rightBound === nextState.rightBound
- && wheelZoom === nextState.wheelZoom;
- if (checkForPropsUpdates && checkForStateUpdates) {
- return false;
- }
- return true;
- }
-
render() {
const {
axisWidth,
@@ -1525,7 +1531,6 @@ TimelineAxis.propTypes = {
showHover: PropTypes.func,
showHoverOff: PropTypes.func,
showHoverOn: PropTypes.func,
- startDate: PropTypes.string,
timelineEndDateLimit: PropTypes.string,
timelineStartDateLimit: PropTypes.string,
timeScale: PropTypes.string,
diff --git a/web/js/components/timeline/timeline-controls/animation-button.js b/web/js/components/timeline/timeline-controls/animation-button.js
index 66b80394c..2d3c4a2b6 100644
--- a/web/js/components/timeline/timeline-controls/animation-button.js
+++ b/web/js/components/timeline/timeline-controls/animation-button.js
@@ -7,14 +7,13 @@ import { faVideo } from '@fortawesome/free-solid-svg-icons';
class AnimationButton extends PureComponent {
render() {
const className = 'button-action-group animate-button';
+ const { disabled, title, clickAnimationButton } = this.props;
return (
<div
- className={
- this.props.disabled ? `wv-disabled-button ${className}` : className
- }
- title={this.props.title ? this.props.title : 'Set up animation'}
+ className={disabled ? `wv-disabled-button ${className}` : className}
+ title={title || 'Set up animation'}
>
- <div id="animate-button" onClick={this.props.clickAnimationButton}>
+ <div id="animate-button" onClick={clickAnimationButton}>
<FontAwesomeIcon icon={faVideo} className="wv-animate" size="3x" />
</div>
</div>
diff --git a/web/js/components/timeline/timeline-controls/axis-timescale-change-controls.js b/web/js/components/timeline/timeline-controls/axis-timescale-change-controls.js
index 7fe61902c..373af95cd 100644
--- a/web/js/components/timeline/timeline-controls/axis-timescale-change-controls.js
+++ b/web/js/components/timeline/timeline-controls/axis-timescale-change-controls.js
@@ -11,11 +11,13 @@ import Arrow from '../../util/arrow';
*/
class AxisTimeScaleChangeControls extends PureComponent {
onClickUp = () => {
- this.props.decrementTimeScale();
+ const { decrementTimeScale } = this.props;
+ decrementTimeScale();
}
onClickDown = () => {
- this.props.incrementTimeScale();
+ const { incrementTimeScale } = this.props;
+ incrementTimeScale();
}
render() {
diff --git a/web/js/components/timeline/timeline-controls/axis-timescale-change-tooltip.js b/web/js/components/timeline/timeline-controls/axis-timescale-change-tooltip.js
index f977b35e7..9a38084ca 100644
--- a/web/js/components/timeline/timeline-controls/axis-timescale-change-tooltip.js
+++ b/web/js/components/timeline/timeline-controls/axis-timescale-change-tooltip.js
@@ -10,6 +10,7 @@ import PropTypes from 'prop-types';
class AxisTimeScaleChangeTooltip extends PureComponent {
// Handle change axis timescale
changeTimeScale = (timeScale) => {
+ // eslint-disable-next-line react/destructuring-assignment
this.props.changeTimeScale(timeScale);
};
diff --git a/web/js/components/timeline/timeline-controls/axis-timescale-change.js b/web/js/components/timeline/timeline-controls/axis-timescale-change.js
index fa2040165..50af687ce 100644
--- a/web/js/components/timeline/timeline-controls/axis-timescale-change.js
+++ b/web/js/components/timeline/timeline-controls/axis-timescale-change.js
@@ -96,6 +96,7 @@ class AxisTimeScaleChange extends PureComponent {
hasSubdailyLayers,
changeTimeScale,
} = this.props;
+ const { toolTipHovered } = this.state;
return (
<div
className="zoom-level-change"
@@ -112,7 +113,7 @@ class AxisTimeScaleChange extends PureComponent {
<AxisTimeScaleChangeControls
timeScale={timeScale}
hasSubdailyLayers={hasSubdailyLayers}
- toolTipHovered={this.state.toolTipHovered}
+ toolTipHovered={toolTipHovered}
changeTimeScale={changeTimeScale}
incrementTimeScale={this.incrementTimeScale}
decrementTimeScale={this.decrementTimeScale}
diff --git a/web/js/components/timeline/timeline-controls/date-change-arrows.js b/web/js/components/timeline/timeline-controls/date-change-arrows.js
index 1c9804702..418b129fc 100644
--- a/web/js/components/timeline/timeline-controls/date-change-arrows.js
+++ b/web/js/components/timeline/timeline-controls/date-change-arrows.js
@@ -11,18 +11,25 @@ const intervals = {
left: 0,
right: 0,
};
+
class DateChangeArrows extends PureComponent {
+ componentWillUnmount() {
+ clearInterval(intervals.left);
+ clearInterval(intervals.right);
+ }
+
/**
* @desc repeatedly call while mouse down - decrement date
* @returns {void}
*/
leftArrowDown = () => {
- this.props.leftArrowDown();
+ const { leftArrowDown } = this.props;
+ leftArrowDown();
mouseHoldCheckTimer = setTimeout(() => {
mouseHoldCheckTimer = null;
isMouseHolding = true;
// set interval for holding arrow down
- intervals.left = setInterval(this.props.leftArrowDown, ANIMATION_DELAY);
+ intervals.left = setInterval(leftArrowDown, ANIMATION_DELAY);
}, CLICK_TIMEOUT_DELAY);
}
@@ -31,12 +38,13 @@ class DateChangeArrows extends PureComponent {
* @returns {void}
*/
rightArrowDown = () => {
- this.props.rightArrowDown();
+ const { rightArrowDown } = this.props;
+ rightArrowDown();
mouseHoldCheckTimer = setTimeout(() => {
mouseHoldCheckTimer = null;
isMouseHolding = true;
// set interval for holding arrow down
- intervals.right = setInterval(this.props.rightArrowDown, ANIMATION_DELAY);
+ intervals.right = setInterval(rightArrowDown, ANIMATION_DELAY);
}, CLICK_TIMEOUT_DELAY);
}
@@ -45,13 +53,14 @@ class DateChangeArrows extends PureComponent {
* @returns {void}
*/
leftArrowUp = () => {
+ const { leftArrowUp } = this.props;
if (mouseHoldCheckTimer) {
clearTimeout(mouseHoldCheckTimer);
} else if (isMouseHolding) {
isMouseHolding = false;
}
clearInterval(intervals.left);
- this.props.leftArrowUp();
+ leftArrowUp();
}
/**
@@ -59,18 +68,14 @@ class DateChangeArrows extends PureComponent {
* @returns {void}
*/
rightArrowUp = () => {
+ const { rightArrowUp } = this.props;
if (mouseHoldCheckTimer) {
clearTimeout(mouseHoldCheckTimer);
} else if (isMouseHolding) {
isMouseHolding = false;
}
clearInterval(intervals.right);
- this.props.rightArrowUp();
- }
-
- componentWillUnmount() {
- clearInterval(intervals.left);
- clearInterval(intervals.right);
+ rightArrowUp();
}
render() {
diff --git a/web/js/components/timeline/timeline-controls/interval-timescale-change.js b/web/js/components/timeline/timeline-controls/interval-timescale-change.js
index 7ec343eb0..037096497 100644
--- a/web/js/components/timeline/timeline-controls/interval-timescale-change.js
+++ b/web/js/components/timeline/timeline-controls/interval-timescale-change.js
@@ -18,6 +18,28 @@ class TimeScaleIntervalChange extends PureComponent {
};
}
+ componentDidMount() {
+ const { customDelta, customIntervalZoomLevel } = this.props;
+ if (customDelta !== 1 && customIntervalZoomLevel) {
+ this.setCustomIntervalText();
+ }
+ }
+
+ componentDidUpdate(prevProps) {
+ const {
+ customDelta,
+ timeScaleChangeUnit,
+ customSelected,
+ } = this.props;
+ if (customSelected && customDelta && timeScaleChangeUnit) {
+ const didCustomDeltaChange = customDelta !== prevProps.customDelta;
+ const didTimeScaleChangeUnitChange = timeScaleChangeUnit !== prevProps.timeScaleChangeUnit;
+ if (didCustomDeltaChange || didTimeScaleChangeUnitChange) {
+ this.setCustomIntervalText();
+ }
+ }
+ }
+
// Interval select tooltip on
toolTipHoverOn = () => {
this.setState({
@@ -34,10 +56,11 @@ class TimeScaleIntervalChange extends PureComponent {
// handle click of timescale intervals
handleClickInterval = (timescale, openModal = false) => {
+ const { setTimeScaleIntervalChangeUnit } = this.props;
// send props function to change timescale interval throughout app
this.setState({
toolTipHovered: false,
- }, this.props.setTimeScaleIntervalChangeUnit(timescale, openModal));
+ }, setTimeScaleIntervalChangeUnit(timescale, openModal));
}
// individual linking timescale handlers
@@ -71,32 +94,12 @@ class TimeScaleIntervalChange extends PureComponent {
// set custom text for custom interval
setCustomIntervalText = () => {
+ const { customDelta, customIntervalZoomLevel } = this.props;
this.setState({
- customIntervalText: `${this.props.customDelta} ${this.props.customIntervalZoomLevel}`,
+ customIntervalText: `${customDelta} ${customIntervalZoomLevel}`,
});
}
- componentDidMount() {
- if (this.props.customDelta !== 1 && this.props.customIntervalZoomLevel) {
- this.setCustomIntervalText();
- }
- }
-
- componentDidUpdate(prevProps) {
- const {
- customDelta,
- timeScaleChangeUnit,
- customSelected,
- } = this.props;
- if (customSelected && customDelta && timeScaleChangeUnit) {
- const didCustomDeltaChange = customDelta !== prevProps.customDelta;
- const didTimeScaleChangeUnitChange = timeScaleChangeUnit !== prevProps.timeScaleChangeUnit;
- if (didCustomDeltaChange || didTimeScaleChangeUnitChange) {
- this.setCustomIntervalText();
- }
- }
- }
-
render() {
const {
customIntervalText,
diff --git a/web/js/components/timeline/timeline-data/timeline-data.js b/web/js/components/timeline/timeline-data/timeline-data.js
index 273797aff..296a6d421 100644
--- a/web/js/components/timeline/timeline-data/timeline-data.js
+++ b/web/js/components/timeline/timeline-data/timeline-data.js
@@ -198,6 +198,7 @@ class TimelineData extends Component {
* @param {Array} layers
* @returns {Object} startDate, endDate
*/
+ // eslint-disable-next-line react/destructuring-assignment
addMatchingCoverageToTimeline = (isChecked, layerCollection = this.state.activeLayers) => {
const { setMatchingTimelineCoverage } = this.props;
const layers = this.getActiveLayers(layerCollection);
diff --git a/web/js/components/timeline/timeline-draggers/dragger-container.js b/web/js/components/timeline/timeline-draggers/dragger-container.js
index ca78bb68e..0594092fe 100644
--- a/web/js/components/timeline/timeline-draggers/dragger-container.js
+++ b/web/js/components/timeline/timeline-draggers/dragger-container.js
@@ -22,6 +22,44 @@ class DraggerContainer extends PureComponent {
};
}
+ componentDidUpdate(prevProps) {
+ const {
+ draggerTimeState,
+ draggerTimeStateB,
+ isDraggerDragging,
+ draggerSelected,
+ isCompareModeActive,
+ setDraggerVisibility,
+ } = this.props;
+
+ // handle dragger visibility update on compare mode activate/deactivate
+ const hasCompareModeChanged = isCompareModeActive !== prevProps.isCompareModeActive;
+ if (hasCompareModeChanged) {
+ // turn on compare mode
+ if (isCompareModeActive) {
+ setDraggerVisibility(true, true);
+ } else if (draggerSelected === 'selected') {
+ // turn off compare mode
+ setDraggerVisibility(true, false);
+ } else {
+ setDraggerVisibility(false, true);
+ }
+ }
+
+ if (!isDraggerDragging) {
+ // handle A dragger change
+ const propsTimeStateChanged = draggerTimeState !== prevProps.draggerTimeState;
+ if (propsTimeStateChanged && (isCompareModeActive || draggerSelected === 'selected')) {
+ this.setDraggerPosition(draggerTimeState, false);
+ }
+ // handle B dragger change
+ const propsTimeStateBChanged = draggerTimeStateB !== prevProps.draggerTimeStateB;
+ if (propsTimeStateBChanged && (isCompareModeActive || draggerSelected === 'selectedB')) {
+ this.setDraggerPosition(draggerTimeStateB, true);
+ }
+ }
+ }
+
/**
* @desc select dragger 'selected' or 'selectedB'
* @param {String} draggerName
@@ -29,12 +67,13 @@ class DraggerContainer extends PureComponent {
* @returns {void}
*/
selectDragger = (draggerName, e) => {
+ const { draggerSelected, onChangeSelectedDragger } = this.props;
if (e) {
e.stopPropagation();
e.preventDefault();
}
- if (draggerName !== this.props.draggerSelected) {
- this.props.onChangeSelectedDragger(draggerName);
+ if (draggerName !== draggerSelected) {
+ onChangeSelectedDragger(draggerName);
}
}
@@ -56,6 +95,7 @@ class DraggerContainer extends PureComponent {
timelineEndDateLimit,
updateDraggerDatePosition,
} = this.props;
+ const { draggerWidth } = this.state;
const isBetween = getIsBetween(inputTime, frontDate, backDate);
let draggerVisible = false;
@@ -78,11 +118,11 @@ class DraggerContainer extends PureComponent {
const { gridWidth } = options;
const frontDateObj = moment.utc(frontDate);
const pixelsToAddToDraggerNew = Math.abs(frontDateObj.diff(inputTime, timeScale, true) * gridWidth);
- newDraggerPosition = pixelsToAddToDraggerNew + position - this.state.draggerWidth + transformX + 2;
+ newDraggerPosition = pixelsToAddToDraggerNew + position - draggerWidth + transformX + 2;
// determine max timelineEndDate position for dragger
const endDateLimitPositionFromFront = Math.abs(frontDateObj.diff(timelineEndDateLimit, timeScale, true) * gridWidth);
- const endDatePosition = endDateLimitPositionFromFront + position - this.state.draggerWidth + transformX + 2;
+ const endDatePosition = endDateLimitPositionFromFront + position - draggerWidth + transformX + 2;
// checks to prevent positioning outside of valid timeline range
const isBeforeFrontDate = new Date(inputTime) < new Date(frontDate);
@@ -127,6 +167,7 @@ class DraggerContainer extends PureComponent {
timelineEndDateLimit,
updateDraggerDatePosition,
} = this.props;
+ const { draggerWidth } = this.state;
// get timescale specific options for scaleMs and gridWidth
const options = timeScaleOptions[timeScale].timeAxis;
@@ -150,7 +191,7 @@ class DraggerContainer extends PureComponent {
const diffZeroValues = options.scaleMs;
if (!diffZeroValues) {
// calculate based on frontDate due to varying number of days per month and per year (leapyears)
- const draggerPositionRelativeToFrontDate = this.state.draggerWidth - 2 + newDraggerPosition - position - transformX;
+ const draggerPositionRelativeToFrontDate = draggerWidth - 2 + newDraggerPosition - position - transformX;
const gridWidthCoef = draggerPositionRelativeToFrontDate / gridWidth;
const draggerDateAdded = moment.utc(frontDate).add(Math.floor(gridWidthCoef), timeScale);
@@ -181,44 +222,6 @@ class DraggerContainer extends PureComponent {
});
}
- componentDidUpdate(prevProps) {
- const {
- draggerTimeState,
- draggerTimeStateB,
- isDraggerDragging,
- draggerSelected,
- isCompareModeActive,
- setDraggerVisibility,
- } = this.props;
-
- // handle dragger visibility update on compare mode activate/deactivate
- const hasCompareModeChanged = isCompareModeActive !== prevProps.isCompareModeActive;
- if (hasCompareModeChanged) {
- // turn on compare mode
- if (isCompareModeActive) {
- setDraggerVisibility(true, true);
- } else if (draggerSelected === 'selected') {
- // turn off compare mode
- setDraggerVisibility(true, false);
- } else {
- setDraggerVisibility(false, true);
- }
- }
-
- if (!isDraggerDragging) {
- // handle A dragger change
- const propsTimeStateChanged = draggerTimeState !== prevProps.draggerTimeState;
- if (propsTimeStateChanged && (isCompareModeActive || draggerSelected === 'selected')) {
- this.setDraggerPosition(draggerTimeState, false);
- }
- // handle B dragger change
- const propsTimeStateBChanged = draggerTimeStateB !== prevProps.draggerTimeStateB;
- if (propsTimeStateBChanged && (isCompareModeActive || draggerSelected === 'selectedB')) {
- this.setDraggerPosition(draggerTimeStateB, true);
- }
- }
- }
-
render() {
const {
draggerSelected,
diff --git a/web/js/components/toolbar/share/links.js b/web/js/components/toolbar/share/links.js
index cf3cf3b24..68661f68a 100644
--- a/web/js/components/toolbar/share/links.js
+++ b/web/js/components/toolbar/share/links.js
@@ -7,8 +7,9 @@ import { faFacebookF, faTwitter, faRedditAlien } from '@fortawesome/free-brands-
class ShareLinks extends React.Component {
onClick(event, type) {
+ const { onClick } = this.props;
event.preventDefault();
- this.props.onClick(type);
+ onClick(type);
}
render() {
diff --git a/web/js/components/toolbar/share/share.js b/web/js/components/toolbar/share/share.js
index 816d1e1af..e64574ee4 100644
--- a/web/js/components/toolbar/share/share.js
+++ b/web/js/components/toolbar/share/share.js
@@ -14,14 +14,18 @@ class Share extends React.Component {
}
render() {
+ const {
+ fbLink, twLink, rdLink, emailLink,
+ } = this.state;
+ const { clickFunction } = this.props;
return (
<div>
<ShareLinks
- fbLink={this.state.fbLink}
- twLink={this.state.twLink}
- rdLink={this.state.rdLink}
- emailLink={this.state.emailLink}
- onClick={this.props.clickFunction}
+ fbLink={fbLink}
+ twLink={twLink}
+ rdLink={rdLink}
+ emailLink={emailLink}
+ onClick={clickFunction}
/>
</div>
);
diff --git a/web/js/components/tooltip/tooltip.js b/web/js/components/tooltip/tooltip.js
index 57a70de11..4457e0ff6 100644
--- a/web/js/components/tooltip/tooltip.js
+++ b/web/js/components/tooltip/tooltip.js
@@ -23,23 +23,26 @@ class Tooltip extends React.Component {
}
onClick(str) {
- this.props.onClick(str);
+ const { onClick } = this.props;
+ onClick(str);
}
render() {
+ const { text, dataArray } = this.props;
+ const { hovered } = this.state;
return (
<div
onMouseEnter={this.mouseOver.bind(this)}
onMouseLeave={this.mouseOut.bind(this)}
className="wv-tooltip-case"
>
- <span>{this.props.text}</span>
+ <span>{text}</span>
<div
className="wv-tooltip"
- style={this.state.hovered ? { visibility: 'visible' } : {}}
+ style={hovered ? { visibility: 'visible' } : {}}
>
<ul>
- {this.props.dataArray.map((dataEl, i) => (
+ {dataArray.map((dataEl, i) => (
<li
/* eslint react/no-array-index-key: 1 */
key={`tooltip-${dataEl}-${i}`}
diff --git a/web/js/components/tour/content-intro.js b/web/js/components/tour/content-intro.js
index a32944fef..178924914 100644
--- a/web/js/components/tour/content-intro.js
+++ b/web/js/components/tour/content-intro.js
@@ -1,3 +1,4 @@
+/* eslint-disable react/destructuring-assignment */
import React from 'react';
import PropTypes from 'prop-types';
diff --git a/web/js/components/tour/modal-tour-complete.js b/web/js/components/tour/modal-tour-complete.js
index 26f424581..ad19c2e1f 100644
--- a/web/js/components/tour/modal-tour-complete.js
+++ b/web/js/components/tour/modal-tour-complete.js
@@ -78,7 +78,6 @@ ModalComplete.propTypes = {
endTour: PropTypes.func.isRequired,
modalComplete: PropTypes.bool.isRequired,
resetTour: PropTypes.func.isRequired,
- className: PropTypes.string,
};
export default ModalComplete;
diff --git a/web/js/components/tour/modal-tour-in-progress.js b/web/js/components/tour/modal-tour-in-progress.js
index 73d6eefac..16ed26e60 100644
--- a/web/js/components/tour/modal-tour-in-progress.js
+++ b/web/js/components/tour/modal-tour-in-progress.js
@@ -12,23 +12,34 @@ class ModalInProgress extends React.Component {
}
render() {
- const { description } = this.props;
+ const {
+ className,
+ currentStory,
+ description,
+ modalInProgress,
+ endTour,
+ showTourAlert,
+ currentStep,
+ totalSteps,
+ decreaseStep,
+ incrementStep,
+ } = this.props;
return (
<div>
<Modal
- isOpen={this.props.modalInProgress}
- toggle={this.props.endTour}
- onClosed={this.props.showTourAlert}
+ isOpen={modalInProgress}
+ toggle={endTour}
+ onClosed={showTourAlert}
wrapClassName="tour tour-in-progress"
className={
- `${this.props.className} ${this.props.currentStory.type}`
+ `${className} ${currentStory.type}`
}
backdrop={false}
keyboard={false}
>
- <ModalHeader toggle={this.props.endTour} charCode="">
- {this.props.currentStory.title}
+ <ModalHeader toggle={endTour} charCode="">
+ {currentStory.title}
<i className="modal-icon" aria-hidden="true" />
</ModalHeader>
<ModalBody>
@@ -41,10 +52,10 @@ class ModalInProgress extends React.Component {
</ModalBody>
<ModalFooter>
<Steps
- currentStep={this.props.currentStep}
- totalSteps={this.props.totalSteps}
- decreaseStep={this.props.decreaseStep}
- incrementStep={this.props.incrementStep}
+ currentStep={currentStep}
+ totalSteps={totalSteps}
+ decreaseStep={decreaseStep}
+ incrementStep={incrementStep}
/>
</ModalFooter>
</Modal>
diff --git a/web/js/components/tour/modal-tour-start.js b/web/js/components/tour/modal-tour-start.js
index 29e8edd87..61768bd5a 100644
--- a/web/js/components/tour/modal-tour-start.js
+++ b/web/js/components/tour/modal-tour-start.js
@@ -18,7 +18,7 @@ class ModalStart extends React.Component {
constructor(props) {
super(props);
this.state = {
- checked: this.props.checked,
+ checked: props.checked,
};
this.setWrapperRef = this.setWrapperRef.bind(this);
@@ -42,48 +42,55 @@ class ModalStart extends React.Component {
// Use custom clickOutside function since we contained the clickable area with
// CSS to have a cleaner looking scrollbar
handleClickOutside(e) {
+ const { toggleModalStart } = this.props;
if (this.wrapperRef && !this.wrapperRef.contains(e.target)) {
- this.props.toggleModalStart(e);
+ toggleModalStart(e);
}
}
// Handle the show/hide checkbox state
handleCheck() {
+ const { hideTour, showTour } = this.props;
+ const { checked } = this.state;
this.setState((prevState) => ({
checked: !prevState.checked,
}));
- if (!this.state.checked) {
- this.props.hideTour();
+ if (!checked) {
+ hideTour();
} else {
- this.props.showTour();
+ showTour();
}
}
render() {
+ const {
+ modalStart, endTour, showTourAlert, toggleModalStart, className, height, stories, storyOrder, selectTour,
+ } = this.props;
+ const { checked } = this.state;
return (
<Modal
- isOpen={this.props.modalStart}
- toggle={this.props.endTour}
- onClosed={this.props.showTourAlert}
+ isOpen={modalStart}
+ toggle={endTour}
+ onClosed={showTourAlert}
wrapClassName="tour tour-start"
- className={this.props.className}
+ className={className}
backdrop
fade={false}
keyboard={false}
innerRef={this.setWrapperRef}
>
- <ModalHeader toggle={this.props.endTour} charCode="">
+ <ModalHeader toggle={endTour} charCode="">
Welcome to Worldview!
</ModalHeader>
- <Scrollbars style={{ maxHeight: `${this.props.height - 200}px` }}>
+ <Scrollbars style={{ maxHeight: `${height - 200}px` }}>
<ModalBody>
- <TourIntro toggleModalStart={this.props.toggleModalStart} />
+ <TourIntro toggleModalStart={toggleModalStart} />
<TourBoxes
- stories={this.props.stories}
- storyOrder={this.props.storyOrder}
- selectTour={this.props.selectTour}
+ stories={stories}
+ storyOrder={storyOrder}
+ selectTour={selectTour}
/>
</ModalBody>
@@ -96,7 +103,7 @@ class ModalStart extends React.Component {
addon
type="checkbox"
className="float-right m-0"
- defaultChecked={this.state.checked}
+ defaultChecked={checked}
onChange={this.handleCheck}
aria-label="Hide this box until a new story has been added."
/>
diff --git a/web/js/components/tour/tour-box.js b/web/js/components/tour/tour-box.js
index 019c6a89c..d71662fa9 100644
--- a/web/js/components/tour/tour-box.js
+++ b/web/js/components/tour/tour-box.js
@@ -13,45 +13,65 @@ class TourBox extends React.Component {
}
UNSAFE_componentWillMount() {
- if (this.props.backgroundImage) {
+ const { backgroundImage, storyId } = this.props;
+ if (backgroundImage) {
this.setState({
- styles: { backgroundImage: `url(config/metadata/stories/${this.props.storyId}/${this.props.backgroundImage})` },
+ styles: {
+ backgroundImage: `url(config/metadata/stories/${storyId}/${backgroundImage})`,
+ },
});
}
}
onMouseOver(e) {
+ const { backgroundImageHover, storyId } = this.props;
e.preventDefault();
- if (this.props.backgroundImageHover) {
+ if (backgroundImageHover) {
this.setState({
- styles: { backgroundImage: `url(config/metadata/stories/${this.props.storyId}/${this.props.backgroundImageHover})` },
+ styles: {
+ backgroundImage: `url(config/metadata/stories/${storyId}/${backgroundImageHover})`,
+ },
});
}
}
onMouseOut(e) {
+ const { backgroundImage, storyId } = this.props;
e.preventDefault();
- if (this.props.backgroundImage) {
+ if (backgroundImage) {
this.setState({
- styles: { backgroundImage: `url(config/metadata/stories/${this.props.storyId}/${this.props.backgroundImage})` },
+ styles: {
+ backgroundImage: `url(config/metadata/stories/${storyId}/${backgroundImage})`,
+ },
});
}
}
render() {
+ const {
+ index, story, storyId, storyOrder, className, title, description, selectTour,
+ } = this.props;
+ const { styles } = this.state;
let floatBox = '';
- if (this.props.storyOrder.length - (this.props.index + 1) === 0
- || this.props.storyOrder.length - (this.props.index + 2) === 0) {
+ if (storyOrder.length - (index + 1) === 0
+ || storyOrder.length - (index + 2) === 0) {
floatBox = ' tour-box-float';
}
return (
- <a href="#" style={this.state.styles} onMouseOver={(e) => this.onMouseOver(e)} onMouseOut={(e) => this.onMouseOut(e)} className={this.props.className + floatBox} onClick={(e) => this.props.selectTour(e, this.props.story, this.props.index, this.props.storyId)}>
+ <a
+ href="#"
+ style={styles}
+ onMouseOver={(e) => this.onMouseOver(e)}
+ onMouseOut={(e) => this.onMouseOut(e)}
+ className={className + floatBox}
+ onClick={(e) => selectTour(e, story, index, storyId)}
+ >
<div className="tour-box-content">
<div className="tour-box-header">
- <h3 className="tour-box-title">{this.props.title}</h3>
+ <h3 className="tour-box-title">{title}</h3>
</div>
<div className="tour-box-description">
- <p>{this.props.description}</p>
+ <p>{description}</p>
</div>
</div>
</a>
diff --git a/web/js/components/util/alert.js b/web/js/components/util/alert.js
index 2240c689d..fa54ed260 100644
--- a/web/js/components/util/alert.js
+++ b/web/js/components/util/alert.js
@@ -43,6 +43,7 @@ export default class AlertComponent extends React.Component {
renderAlert() {
const {
+ id,
title,
message,
iconClassName,
@@ -55,7 +56,7 @@ export default class AlertComponent extends React.Component {
: faExclamationTriangle;
return (
<Alert
- id={this.props.id}
+ id={id}
className="wv-alert"
isOpen={isOpen}
>
@@ -70,7 +71,7 @@ export default class AlertComponent extends React.Component {
</div>
</div>
{onDismiss && (
- <div id={`${this.props.id}-close`} className="close-alert" onClick={onDismiss}>
+ <div id={`${id}-close`} className="close-alert" onClick={onDismiss}>
<FontAwesomeIcon icon={faTimes} className="exit" size="1x" />
</div>
)}
@@ -79,7 +80,8 @@ export default class AlertComponent extends React.Component {
}
render() {
- return this.props.noPortal
+ const { noPortal } = this.props;
+ return noPortal
? this.renderAlert()
: (
<Portal node={document && document.getElementById('wv-alert-container')}>
diff --git a/web/js/components/util/checkbox.js b/web/js/components/util/checkbox.js
index e5733fd84..8692ceb36 100644
--- a/web/js/components/util/checkbox.js
+++ b/web/js/components/util/checkbox.js
@@ -6,7 +6,7 @@ import PropTypes from 'prop-types';
* @class Checkbox
* @extends React.Component
*/
-export class Checkbox extends React.Component {
+export default class Checkbox extends React.Component {
constructor(props) {
super(props);
this.state = {
@@ -15,7 +15,8 @@ export class Checkbox extends React.Component {
}
UNSAFE_componentWillReceiveProps(nextProps) {
- if (this.state.checked !== nextProps.checked) {
+ const { checked } = this.state;
+ if (checked !== nextProps.checked) {
this.setState({
checked: nextProps.checked,
});
diff --git a/web/js/components/util/debug.js b/web/js/components/util/debug.js
index 85fd4a47f..f55a0c9a0 100644
--- a/web/js/components/util/debug.js
+++ b/web/js/components/util/debug.js
@@ -1,17 +1,13 @@
-import React from 'react';
import PropTypes from 'prop-types';
/*
* @class Debug
- * @extends React.Component
*/
-export default class Debug extends React.Component {
- render() {
- if (this.props.parameters.showError) {
- throw new Error('this is a test error');
- }
- return '';
+export default function Debug ({ parameters }) {
+ if (parameters.showError) {
+ throw new Error('this is a test error');
}
+ return '';
}
Debug.propTypes = {
diff --git a/web/js/components/util/detect-outer-click.js b/web/js/components/util/detect-outer-click.js
index da0a88135..0b91bd226 100644
--- a/web/js/components/util/detect-outer-click.js
+++ b/web/js/components/util/detect-outer-click.js
@@ -32,17 +32,19 @@ export default class OutsideAlerter extends Component {
* Alert if clicked on outside of element
*/
handleClickOutside(event) {
+ const { onClick, disabled } = this.props;
if (
this.wrapperRef
&& !this.wrapperRef.contains(event.target)
- && !this.props.disabled
+ && !disabled
) {
- this.props.onClick();
+ onClick();
}
}
render() {
- return <div ref={this.setWrapperRef}>{this.props.children}</div>;
+ const { children } = this.props;
+ return <div ref={this.setWrapperRef}>{children}</div>;
}
}
OutsideAlerter.defaultProps = {
diff --git a/web/js/components/util/scrollbar.js b/web/js/components/util/scrollbar.js
index 357c2b1c5..b4b0c757a 100644
--- a/web/js/components/util/scrollbar.js
+++ b/web/js/components/util/scrollbar.js
@@ -9,6 +9,9 @@ import { debounce } from 'lodash';
export default function Scrollbars(props) {
const ref = useRef();
const [scrollTop, updateScrollTop] = useState(0);
+ const {
+ scrollBarVerticalTop, style, className, onScroll, children,
+ } = props;
/**
* Add/remove 'scrollbar-visible' class based on content size
@@ -45,25 +48,24 @@ export default function Scrollbars(props) {
}
function setScrollTop() {
const { contentWrapperEl } = ref.current;
- const { scrollBarVerticalTop } = props;
if (contentWrapperEl) {
updateScrollTop(scrollBarVerticalTop);
contentWrapperEl.scrollTop = scrollBarVerticalTop;
}
}
setTimeout(setScrollTop, 100);
- }, [props.scrollBarVerticalTop]);
+ }, [scrollBarVerticalTop]);
/**
* Handle register/deregister of scroll event listener
*/
useEffect(() => {
- if (!props.onScroll) return;
+ if (!onScroll) return;
const { contentWrapperEl } = ref && ref.current;
function scrollListener() {
// Avoid calling event listener when we are setting scrollTop manually
if (contentWrapperEl.scrollTop !== scrollTop) {
- props.onScroll(contentWrapperEl);
+ onScroll(contentWrapperEl);
}
}
contentWrapperEl.addEventListener('scroll', scrollListener);
@@ -75,11 +77,11 @@ export default function Scrollbars(props) {
return (
<SimpleBarReact
autoHide={false}
- style={props.style}
- className={props.className}
+ style={style}
+ className={className}
ref={ref}
>
- {props.children}
+ {children}
</SimpleBarReact>
);
}
diff --git a/web/js/components/util/selector.js b/web/js/components/util/selector.js
index 625e0c70a..056928b62 100644
--- a/web/js/components/util/selector.js
+++ b/web/js/components/util/selector.js
@@ -6,35 +6,29 @@ import PropTypes from 'prop-types';
* @class Selector
* @extends React.Component
*/
-export default class Selector extends React.Component {
- constructor(props) {
- super(props);
- this.props = props;
- this.state = {
- value: props.value,
- };
- }
+export default function Selector (props) {
+ const {
+ onChange, optionName, optionArray, id, value,
+ } = props;
- handleChange(event) {
- this.props.onChange(this.props.optionName, event.target.value);
- }
+ const handleChange = (event) => {
+ onChange(optionName, event.target.value);
+ };
- render() {
- return (
- <select
- value={this.props.value}
- id={this.props.id}
- onChange={this.handleChange.bind(this)}
- >
- {this.props.optionArray.values.map((dataEl, i) => (
- /* eslint react/no-array-index-key: 1 */
- <option key={`${dataEl.value}-${i}`} value={dataEl.value}>
- {dataEl.text}
- </option>
- ))}
- </select>
- );
- }
+ return (
+ <select
+ value={value}
+ id={id}
+ onChange={handleChange}
+ >
+ {optionArray.values.map((dataEl, i) => (
+ /* eslint react/no-array-index-key: 1 */
+ <option key={`${dataEl.value}-${i}`} value={dataEl.value}>
+ {dataEl.text}
+ </option>
+ ))}
+ </select>
+ );
}
Selector.propTypes = {
diff --git a/web/js/components/util/spinner-modal.js b/web/js/components/util/spinner-modal.js
index 676d3d63c..491c1078c 100644
--- a/web/js/components/util/spinner-modal.js
+++ b/web/js/components/util/spinner-modal.js
@@ -22,7 +22,8 @@ export default class SpinnerModal extends React.Component {
render() {
const { headerText, onClose, delay } = this.props;
- if (delay && !this.state.metDelay) return '';
+ const { metDelay } = this.state;
+ if (delay && !metDelay) return '';
return (
<Modal isOpen toggle={onClose}>
<ModalHeader toggle={onClose}>{headerText}</ModalHeader>
diff --git a/web/js/components/vector-metadata/table.js b/web/js/components/vector-metadata/table.js
index a8f560192..021097d13 100644
--- a/web/js/components/vector-metadata/table.js
+++ b/web/js/components/vector-metadata/table.js
@@ -5,16 +5,9 @@ import VectorMetaTooltip from './tooltip';
import util from '../../util/util';
export default class VectorMetaTable extends React.Component {
- constructor(props) {
- super(props);
- this.state = {
- tooltipOpen: false,
- };
- }
-
shouldComponentUpdate(nextProps) {
const { id, title } = this.props;
- if (id && title && nextProps.id && nextProps.title && this.props.id === nextProps.id && title === nextProps.title) {
+ if (id && title && nextProps.id && nextProps.title && id === nextProps.id && title === nextProps.title) {
return false;
}
return true;
diff --git a/web/js/components/vector-metadata/tooltip.js b/web/js/components/vector-metadata/tooltip.js
index 9d34951d9..6018cd73e 100644
--- a/web/js/components/vector-metadata/tooltip.js
+++ b/web/js/components/vector-metadata/tooltip.js
@@ -39,6 +39,7 @@ export default class VectorMetaTooltip extends React.Component {
render() {
const { id, index, description } = this.props;
const elId = util.cleanId(String(`tooltip${id}${index}`));
+ const { tooltipOpen } = this.state;
return (
<div
@@ -54,7 +55,7 @@ export default class VectorMetaTooltip extends React.Component {
dangerouslySetInnerHTML={{ __html: description }}
boundariesElement="window"
placement="right"
- isOpen={this.state.tooltipOpen}
+ isOpen={tooltipOpen}
target={elId}
fade={false}
/>
diff --git a/web/js/containers/animation-widget.js b/web/js/containers/animation-widget.js
index 5f1600e6c..a250c2b3c 100644
--- a/web/js/containers/animation-widget.js
+++ b/web/js/containers/animation-widget.js
@@ -23,8 +23,8 @@ import PlayButton from '../components/animation-widget/play-button';
import TimeScaleIntervalChange from '../components/timeline/timeline-controls/interval-timescale-change';
import CustomIntervalSelectorWidget from '../components/timeline/custom-interval-selector/interval-selector-widget';
import PlayQueue from '../components/animation-widget/play-queue';
-import { Notify } from '../components/image-download/notify';
-import { promiseImageryForTime } from '../modules/map/selectors';
+import Notify from '../components/image-download/notify';
+import promiseImageryForTime from '../modules/map/selectors';
import GifContainer from './gif';
import {
selectDate,
@@ -107,10 +107,7 @@ class AnimationWidget extends React.Component {
const halfWidgetWidth = (props.subDailyMode ? subdailyWidgetWidth : widgetWidth) / 2;
this.state = {
speed: props.speed,
- isSliding: false,
- isGifActive: false,
hoverGif: false,
- customIntervalModalOpen: false,
widgetPosition: {
x: (props.screenWidth / 2) - halfWidgetWidth,
y: -10,
@@ -162,7 +159,7 @@ class AnimationWidget extends React.Component {
* @param {*} e
* @param {*} data
*/
- handleDragStart(e, data) {
+ handleDragStart = (e, data) => {
const draggableTargets = [
'wv-animation-widget',
'wv-animation-widget-header',
@@ -171,7 +168,7 @@ class AnimationWidget extends React.Component {
];
const { classList } = e.target;
return draggableTargets.some((tClass) => classList.contains(tClass));
- }
+ };
onExpandedDrag(e, position) {
const { x, y } = position;
@@ -263,11 +260,13 @@ class AnimationWidget extends React.Component {
* @return {void}
*/
onLoop() {
+ const { looping } = this.state;
+ const { onPushLoop } = this.props;
let loop = true;
- if (this.state.looping) {
+ if (looping) {
loop = false;
}
- this.props.onPushLoop(loop);
+ onPushLoop(loop);
}
onDateChange(date, id) {
@@ -292,7 +291,7 @@ class AnimationWidget extends React.Component {
*/
onIntervalSelect(timeScale, openModal) {
let delta;
- const { customInterval, customDelta } = this.props;
+ const { onIntervalSelect, customInterval, customDelta } = this.props;
const customSelected = timeScale === 'custom';
if (openModal) {
@@ -307,7 +306,7 @@ class AnimationWidget extends React.Component {
timeScale = Number(timeScaleToNumberKey[timeScale]);
delta = 1;
}
- this.props.onIntervalSelect(delta, timeScale, customSelected);
+ onIntervalSelect(delta, timeScale, customSelected);
}
/**
@@ -341,8 +340,8 @@ class AnimationWidget extends React.Component {
* @param {Object} JS Date - endDate
*/
zeroDates = () => {
+ const { subDailyMode } = this.props;
let {
- subDailyMode,
startDate,
endDate,
} = this.props;
@@ -380,12 +379,13 @@ class AnimationWidget extends React.Component {
* @returns {void}
*/
changeCustomInterval = (delta, timeScale) => {
- this.props.changeCustomInterval(delta, timeScale);
+ const { changeCustomInterval } = this.props;
+ changeCustomInterval(delta, timeScale);
};
toggleHoverGif() {
- const hoverState = this.state.hoverGif;
- this.setState({ hoverGif: !hoverState });
+ const { hoverGif } = this.state;
+ this.setState({ hoverGif: !hoverGif });
}
renderToolTip() {
@@ -409,15 +409,17 @@ class AnimationWidget extends React.Component {
renderCollapsedWidget() {
const {
+ onClose,
isPlaying,
onPushPause,
hasSubdailyLayers,
} = this.props;
+ const { collapsedWidgetPosition } = this.state;
return (
<Draggable
bounds="body"
onStart={this.handleDragStart}
- position={this.state.collapsedWidgetPosition}
+ position={collapsedWidgetPosition}
onDrag={this.onCollapsedDrag}
>
<div
@@ -433,7 +435,7 @@ class AnimationWidget extends React.Component {
pause={onPushPause}
/>
<FontAwesomeIcon icon={faChevronUp} className="wv-expand" onClick={this.toggleCollapse} />
- <FontAwesomeIcon icon={faTimes} className="wv-close" onClick={this.props.onClose} />
+ <FontAwesomeIcon icon={faTimes} className="wv-close" onClick={onClose} />
</div>
</div>
</Draggable>
@@ -446,6 +448,7 @@ class AnimationWidget extends React.Component {
isPlaying,
maxDate,
minDate,
+ onSlide,
sliderLabel,
startDate,
endDate,
@@ -459,12 +462,12 @@ class AnimationWidget extends React.Component {
animationCustomModalOpen,
hasSubdailyLayers,
} = this.props;
- const { speed } = this.state;
+ const { speed, widgetPosition } = this.state;
const gifDisabled = numberOfFrames >= maxFrames;
return (
<Draggable
bounds="body"
- position={this.state.widgetPosition}
+ position={widgetPosition}
onDrag={this.onExpandedDrag}
onStart={this.handleDragStart}
>
@@ -500,14 +503,10 @@ class AnimationWidget extends React.Component {
step={0.5}
max={10}
min={0.5}
- value={this.state.speed}
+ value={speed}
onChange={(num) => this.setState({ speed: num })}
handle={RangeHandle}
- onBeforeChange={() => this.setState({ isSliding: true })}
- onAfterChange={() => {
- this.props.onSlide(speed);
- this.setState({ isSliding: false });
- }}
+ onAfterChange={() => { onSlide(speed); }}
/>
<span className="wv-slider-label">{sliderLabel}</span>
</div>
@@ -548,7 +547,7 @@ class AnimationWidget extends React.Component {
/>
</div>
<FontAwesomeIcon icon={faChevronDown} className="wv-minimize" onClick={this.toggleCollapse} />
- <FontAwesomeIcon icon={faTimes} className="wv-close" onClick={this.props.onClose} />
+ <FontAwesomeIcon icon={faTimes} className="wv-close" onClick={onClose} />
{/* Custom time interval selection */}
<CustomIntervalSelectorWidget
@@ -637,6 +636,7 @@ class AnimationWidget extends React.Component {
);
}
}
+
function mapStateToProps(state) {
const {
layers,
@@ -654,15 +654,17 @@ function mapStateToProps(state) {
const {
startDate, endDate, speed, loop, isPlaying, isActive, gifActive,
} = animation;
- let {
+ const {
customSelected,
- interval,
delta,
- customInterval,
customDelta,
appNow,
animationCustomModalOpen,
} = date;
+ let {
+ interval,
+ customInterval,
+ } = date;
const activeStr = compare.activeString;
const activeDateStr = compare.isCompareA ? 'selected' : 'selectedB';
const hasSubdailyLayers = hasSubDailySelector(layers[activeStr]);
@@ -838,7 +840,6 @@ AnimationWidget.propTypes = {
hasSubdailyLayers: PropTypes.bool,
interval: PropTypes.string,
isActive: PropTypes.bool,
- isCompareActive: PropTypes.bool,
isGifActive: PropTypes.bool,
isPlaying: PropTypes.bool,
isRotated: PropTypes.bool,
@@ -850,7 +851,6 @@ AnimationWidget.propTypes = {
notify: PropTypes.func,
numberOfFrames: PropTypes.number,
onClose: PropTypes.func,
- onDateChange: PropTypes.func,
onIntervalSelect: PropTypes.func,
onPushLoop: PropTypes.func,
onPushPause: PropTypes.func,
@@ -868,7 +868,6 @@ AnimationWidget.propTypes = {
speed: PropTypes.number,
startDate: PropTypes.object,
subDailyMode: PropTypes.bool,
- toggleCollapse: PropTypes.func,
toggleCustomModal: PropTypes.func,
toggleGif: PropTypes.func,
};
diff --git a/web/js/containers/error-boundary.js b/web/js/containers/error-boundary.js
index 3da2e0341..53670add2 100644
--- a/web/js/containers/error-boundary.js
+++ b/web/js/containers/error-boundary.js
@@ -27,18 +27,21 @@ class ErrorBoundary extends React.Component {
}
componentDidCatch(error, info) {
+ const { errorAlert } = this.props;
this.setState({ error: true });
// Display fallback UI
- this.props.errorAlert();
+ errorAlert();
// log the error
console.warn(error, info);
}
render() {
- if (this.state.error) {
+ const { error } = this.state;
+ const { children } = this.props;
+ if (error) {
return '';
}
- return this.props.children;
+ return children;
}
}
const mapDispatchToProps = (dispatch) => ({
diff --git a/web/js/containers/gif.js b/web/js/containers/gif.js
index c3932dc6f..24ebda8e6 100644
--- a/web/js/containers/gif.js
+++ b/web/js/containers/gif.js
@@ -21,8 +21,8 @@ import {
imageUtilGetCoordsFromPixelValues,
} from '../modules/image-download/util';
import { timeScaleFromNumberKey } from '../modules/date/constants';
-import { GifResults } from '../components/animation-widget/gif-post-creation';
-import { getImageArray } from '../modules/animation/selectors';
+import GifResults from '../components/animation-widget/gif-post-creation';
+import getImageArray from '../modules/animation/selectors';
import { getStampProps, svgToPng } from '../modules/animation/util';
import { changeCropBounds } from '../modules/animation/actions';
@@ -66,16 +66,18 @@ class GIF extends Component {
componentWillUnmount() {
this.mounted = false;
- if (this.state.isDownloading) {
+ const { isDownloading } = this.state;
+ if (isDownloading) {
gifStream.cancel();
}
}
- getStyle(state) {
+ getStyle() {
+ const { offsetLeft, offsetRight, offsetTop } = this.state;
return {
- left: state.offsetLeft,
- right: state.offsetRight,
- top: state.offsetTop,
+ left: offsetLeft,
+ right: offsetRight,
+ top: offsetTop,
maxWidth: 342,
};
}
@@ -117,7 +119,7 @@ class GIF extends Component {
isOpen
wrapClassName="clickable-behind-modal toolbar_modal_outer"
className="gif-modal dynamic-modal"
- style={this.getStyle(this.state)}
+ style={this.getStyle()}
toggle={onClose}
>
<ModalHeader toggle={onClose}>Create An Animated GIF</ModalHeader>
@@ -170,8 +172,6 @@ class GIF extends Component {
h: boundaries.x2 - boundaries.x,
};
let stampWidth;
- let stampProps;
- let newImage;
const breakPointOne = 300;
const stampWidthRatio = 4.889;
@@ -212,7 +212,7 @@ class GIF extends Component {
},
);
};
- stampProps = getStampProps(
+ const stampProps = getStampProps(
stampWidthRatio,
breakPointOne,
stampWidth,
@@ -220,7 +220,7 @@ class GIF extends Component {
width,
height,
);
- newImage = svgToPng(
+ const newImage = svgToPng(
'brand/images/wv-logo-w-shadow.svg',
stampProps.stampHeight,
);
@@ -436,7 +436,6 @@ GIF.propTypes = {
endDate: PropTypes.string,
getImageArray: PropTypes.func,
increment: PropTypes.string,
- isActive: PropTypes.bool,
map: PropTypes.object,
numberOfFrames: PropTypes.number,
onBoundaryChange: PropTypes.func,
diff --git a/web/js/containers/image-download.js b/web/js/containers/image-download.js
index 576fd1bc3..ec10cc00b 100644
--- a/web/js/containers/image-download.js
+++ b/web/js/containers/image-download.js
@@ -32,8 +32,7 @@ const DEFAULT_URL = 'http://localhost:3002/api/v1/snapshot';
class ImageDownloadContainer extends Component {
constructor(props) {
super(props);
- const { screenHeight } = props;
- const { screenWidth } = props;
+ const { onBoundaryChange, screenHeight, screenWidth } = props;
this.state = {
fileType: props.fileType,
resolution: props.resolution,
@@ -45,10 +44,7 @@ class ImageDownloadContainer extends Component {
y2: screenHeight / 2 + 100,
},
};
- this.debounceBoundaryUpdate = lodashDebounce(
- this.props.onBoundaryChange,
- 200,
- );
+ this.debounceBoundaryUpdate = lodashDebounce(onBoundaryChange, 200);
this.onBoundaryChange = this.onBoundaryChange.bind(this);
}
@@ -237,5 +233,4 @@ ImageDownloadContainer.propTypes = {
resolution: PropTypes.string,
screenHeight: PropTypes.number,
screenWidth: PropTypes.number,
- worldfile: PropTypes.bool,
};
diff --git a/web/js/containers/info.js b/web/js/containers/info.js
index 827bc383c..81e2ee032 100644
--- a/web/js/containers/info.js
+++ b/web/js/containers/info.js
@@ -8,13 +8,13 @@ import {
renderTemplate,
openCustomContent,
} from '../modules/modal/actions';
-import { toggleDistractionFreeMode } from '../modules/ui/actions';
+import toggleDistractionFreeMode from '../modules/ui/actions';
import { ABOUT_PAGE_REQUEST } from '../modules/modal/constants';
import IconList from '../components/util/list';
-import { onClickFeedback } from '../modules/feedback/util';
+import onClickFeedback from '../modules/feedback/util';
import { addToLocalStorage } from '../modules/notifications/util';
-import { initFeedback } from '../modules/feedback/actions';
+import initFeedback from '../modules/feedback/actions';
import { startTour, endTour } from '../modules/tour/actions';
import { notificationsSeen } from '../modules/notifications/actions';
import util from '../util/util';
@@ -22,7 +22,8 @@ import Notifications from './notifications';
class InfoList extends Component {
getNotificationListItem(obj) {
- const { number, type, object } = this.props.notifications;
+ const { notifications, notificationClick } = this.props;
+ const { number, type, object } = notifications;
return {
text: 'Notifications',
@@ -36,7 +37,7 @@ class InfoList extends Component {
badge: number,
className: type ? `${type}-notification` : '',
onClick: () => {
- this.props.notificationClick(object, number);
+ notificationClick(object, number);
},
};
}
@@ -217,7 +218,6 @@ InfoList.propTypes = {
isDistractionFreeModeActive: PropTypes.bool,
isMobile: PropTypes.bool,
isTourActive: PropTypes.bool,
- models: PropTypes.object,
notificationClick: PropTypes.func,
notifications: PropTypes.object,
sendFeedback: PropTypes.func,
diff --git a/web/js/containers/map-interactions.js b/web/js/containers/map-interactions.js
index 992faaf97..101fe2320 100644
--- a/web/js/containers/map-interactions.js
+++ b/web/js/containers/map-interactions.js
@@ -2,7 +2,7 @@ import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { groupBy as lodashGroupBy, debounce as lodashDebounce, get as lodashGet } from 'lodash';
-import { OlCoordinates } from '../components/map/ol-coordinates';
+import OlCoordinates from '../components/map/ol-coordinates';
import vectorDialog from './vector-dialog';
import { onMapClickGetVectorFeatures } from '../modules/vector-styles/util';
import { openCustomContent, onClose } from '../modules/modal/actions';
@@ -19,8 +19,9 @@ export class MapInteractions extends React.Component {
}
registerMouseListeners() {
- this.props.mouseEvents.on('mousemove', this.mouseMove);
- this.props.mouseEvents.on('singleclick', this.singleClick);
+ const { mouseEvents } = this.props;
+ mouseEvents.on('mousemove', this.mouseMove);
+ mouseEvents.on('singleclick', this.singleClick);
}
singleClick(e, map) {
diff --git a/web/js/containers/modal.js b/web/js/containers/modal.js
index 7906c0bac..23d69d463 100644
--- a/web/js/containers/modal.js
+++ b/web/js/containers/modal.js
@@ -26,7 +26,6 @@ class ModalContainer extends Component {
this.state = {
width: props.customProps.width,
height: props.customProps.height,
- isDraggable: props.isDraggable,
offsetLeft: props.customProps.offsetLeft,
offsetTop: props.customProps.offsetTop,
offsetRight: props.customProps.offsetRight,
@@ -78,6 +77,7 @@ class ModalContainer extends Component {
isMobile,
screenHeight,
} = this.props;
+ const { width, height } = this.state;
// Populate props from custom obj
const newProps = isCustom && id ? update(this.props, { $merge: customProps }) : this.props;
const {
@@ -125,8 +125,8 @@ class ModalContainer extends Component {
<Resizable
className="resize-box"
resizeHandles={['se']}
- width={this.state.width || newProps.width}
- height={this.state.height || newProps.height}
+ width={width || newProps.width}
+ height={height || newProps.height}
minConstraints={[250, 250]}
maxConstraints={[495, screenHeight]}
handleSize={[8, 8]}
@@ -157,8 +157,8 @@ class ModalContainer extends Component {
? (
<CompletelyCustomModal
key={`custom_${lowerCaseId}`}
- modalHeight={this.state.height || newProps.height}
- modalWidth={this.state.width || newProps.width}
+ modalHeight={height || newProps.height}
+ modalWidth={width || newProps.width}
{...customProps}
toggleWithClose={toggleFunction}
/>
diff --git a/web/js/containers/projection.js b/web/js/containers/projection.js
index 001c17f25..205e06c61 100644
--- a/web/js/containers/projection.js
+++ b/web/js/containers/projection.js
@@ -4,7 +4,7 @@ import { connect } from 'react-redux';
import { get as lodashGet } from 'lodash';
// eslint-disable-next-line import/no-unresolved
import googleTagManager from 'googleTagManager';
-import { changeProjection } from '../modules/projection/actions';
+import changeProjection from '../modules/projection/actions';
import { onToggle } from '../modules/modal/actions';
import { resetProductPickerState } from '../modules/product-picker/actions';
import IconList from '../components/util/list';
@@ -98,7 +98,6 @@ export default connect(
ProjectionList.propTypes = {
config: PropTypes.object,
- models: PropTypes.object,
onCloseModal: PropTypes.func,
projection: PropTypes.string,
projectionArray: PropTypes.array,
diff --git a/web/js/containers/share.js b/web/js/containers/share.js
index a3e30ba57..a3d4ed387 100644
--- a/web/js/containers/share.js
+++ b/web/js/containers/share.js
@@ -13,10 +13,9 @@ import {
} from 'reactstrap';
import ShareLinks from '../components/toolbar/share/links';
import { getSharelink, openPromisedSocial } from '../modules/link/util';
-import { Checkbox } from '../components/util/checkbox';
+import Checkbox from '../components/util/checkbox';
import { requestShortLink } from '../modules/link/actions';
-
-import { history } from '../main';
+import history from '../main';
const getShortenRequestString = function(mock, permalink) {
const mockStr = mock || '';
@@ -30,6 +29,7 @@ const getShortenRequestString = function(mock, permalink) {
encodeURIComponent(permalink)}`
);
};
+
class ShareLinkContainer extends Component {
constructor(props) {
super(props);
@@ -43,6 +43,12 @@ class ShareLinkContainer extends Component {
this.onLinkClick = this.onLinkClick.bind(this);
}
+ static getDerivedStateFromProps(nextProps, prevState) {
+ if (nextProps.shortLink.error && prevState.isShort) {
+ return { isShort: false, showErrorTooltip: true };
+ } return null;
+ }
+
componentDidMount() {
this.unlisten = history.listen((location, action) => {
const newString = location.search;
@@ -123,12 +129,6 @@ class ShareLinkContainer extends Component {
}
}
- static getDerivedStateFromProps(nextProps, prevState) {
- if (nextProps.shortLink.error && prevState.isShort) {
- return { isShort: false, showErrorTooltip: true };
- } return null;
- }
-
renderToolTips() {
const { showErrorTooltip, tooltipOpen } = this.state;
if (showErrorTooltip) {
@@ -238,7 +238,6 @@ export default connect(
ShareLinkContainer.propTypes = {
mock: PropTypes.string,
- queryString: PropTypes.string,
requestShortLink: PropTypes.func,
shortLink: PropTypes.object,
};
diff --git a/web/js/containers/sidebar/compare.js b/web/js/containers/sidebar/compare.js
index 436daa97f..6a340abf9 100644
--- a/web/js/containers/sidebar/compare.js
+++ b/web/js/containers/sidebar/compare.js
@@ -9,7 +9,7 @@ import { getLayers } from '../../modules/layers/selectors';
import { toggleActiveCompareState } from '../../modules/compare/actions';
import util from '../../util/util';
import AlertUtil from '../../components/util/alert';
-import { CompareAlertModalBody } from '../../components/compare/alert';
+import CompareAlertModalBody from '../../components/compare/alert';
import { openCustomContent } from '../../modules/modal/actions';
const tabHeight = 32;
@@ -40,12 +40,13 @@ class CompareCase extends React.Component {
openAlertModal,
checkerBoardPattern,
} = this.props;
+ const { showAlert } = this.state;
const outerClass = 'layer-container sidebar-panel';
const tabClasses = 'ab-tab';
return (
<div className={isActive ? '' : 'hidden '}>
- {this.state.showAlert ? (
+ {showAlert ? (
<AlertUtil
isOpen
onClick={openAlertModal}
diff --git a/web/js/containers/sidebar/data.js b/web/js/containers/sidebar/data.js
index 79bd99f6a..925ee3b68 100644
--- a/web/js/containers/sidebar/data.js
+++ b/web/js/containers/sidebar/data.js
@@ -96,12 +96,10 @@ const Data = (props) => {
Data.propTypes = {
activeLayers: PropTypes.array,
counts: PropTypes.object,
- data: PropTypes.object,
findProductToSelect: PropTypes.func,
height: PropTypes.number,
isActive: PropTypes.bool,
products: PropTypes.object,
- selected: PropTypes.string,
selectedProduct: PropTypes.string,
selectProduct: PropTypes.func,
showUnavailableReason: PropTypes.func,
diff --git a/web/js/containers/sidebar/events.js b/web/js/containers/sidebar/events.js
index 8bcca6119..e625ac112 100644
--- a/web/js/containers/sidebar/events.js
+++ b/web/js/containers/sidebar/events.js
@@ -14,7 +14,7 @@ import {
deselectEvent,
} from '../../modules/natural-events/actions';
import util from '../../util/util';
-import { EventsAlertModalBody } from '../../components/events/alert-body';
+import EventsAlertModalBody from '../../components/events/alert-body';
import { getEventsWithinExtent } from '../../modules/natural-events/selectors';
import { collapseSidebar } from '../../modules/sidebar/actions';
import { selectDate } from '../../modules/date/actions';
@@ -107,16 +107,20 @@ class Events extends React.Component {
return (
<>
- {showAlert && this.state.showAlert ? (
- <AlertUtil
- id="event-alert"
- isOpen
- onClick={openAlertModal}
- onDismiss={this.dismissAlert}
- message="Events may not be visible at all times."
- />
- )
- : ''}
+ {
+ // eslint-disable-next-line react/destructuring-assignment
+ showAlert && this.state.showAlert
+ ? (
+ <AlertUtil
+ id="event-alert"
+ isOpen
+ onClick={openAlertModal}
+ onDismiss={this.dismissAlert}
+ message="Events may not be visible at all times."
+ />
+ )
+ : ''
+ }
<Scrollbars
style={{ maxHeight: `${height}px` }}
scrollBarVerticalTop={scrollBarVerticalTop}
@@ -281,14 +285,12 @@ Events.propTypes = {
isMobile: PropTypes.bool,
openAlertModal: PropTypes.func,
requestCategories: PropTypes.func,
- requestedEvents: PropTypes.object,
requestEvents: PropTypes.func,
requestSources: PropTypes.func,
selected: PropTypes.object,
selectedDate: PropTypes.string,
selectEvent: PropTypes.func,
showAlert: PropTypes.bool,
- showAll: PropTypes.bool,
sources: PropTypes.array,
visibleEvents: PropTypes.object,
visibleWithinMapExtent: PropTypes.object,
diff --git a/web/js/containers/sidebar/footer-content.js b/web/js/containers/sidebar/footer-content.js
index c82989fc4..4f18c507c 100644
--- a/web/js/containers/sidebar/footer-content.js
+++ b/web/js/containers/sidebar/footer-content.js
@@ -5,7 +5,7 @@ import googleTagManager from 'googleTagManager';
import { get as lodashGet } from 'lodash';
import { connect } from 'react-redux';
import Button from '../../components/util/button';
-import { Checkbox } from '../../components/util/checkbox';
+import Checkbox from '../../components/util/checkbox';
import ModeSelection from '../../components/sidebar/mode-selection';
import { toggleCompareOnOff, changeMode } from '../../modules/compare/actions';
import {
@@ -207,7 +207,6 @@ FooterContent.propTypes = {
compareMode: PropTypes.string,
counts: PropTypes.object,
dataSelectionSize: PropTypes.number,
- events: PropTypes.array,
isCompareActive: PropTypes.bool,
isMobile: PropTypes.bool,
onGetData: PropTypes.func,
diff --git a/web/js/containers/sidebar/layer-list.js b/web/js/containers/sidebar/layer-list.js
index 1309b9cf7..ab60b1952 100644
--- a/web/js/containers/sidebar/layer-list.js
+++ b/web/js/containers/sidebar/layer-list.js
@@ -24,7 +24,6 @@ class LayerList extends React.Component {
super(props);
this.state = {
palettes: {},
- layers: props.layers,
};
this.promises = {};
this.onDragEnd = this.onDragEnd.bind(this);
diff --git a/web/js/containers/sidebar/layer.js b/web/js/containers/sidebar/layer.js
index 1e05e769f..41863ad26 100644
--- a/web/js/containers/sidebar/layer.js
+++ b/web/js/containers/sidebar/layer.js
@@ -38,14 +38,6 @@ const getItemStyle = (isDragging, draggableStyle) => ({
});
class Layer extends React.Component {
- constructor(props) {
- super(props);
- const { index } = props;
- this.state = {
- index,
- };
- }
-
getPaletteLegend = () => {
const {
compare,
diff --git a/web/js/containers/sidebar/orbit-track.js b/web/js/containers/sidebar/orbit-track.js
index da95ce001..29506c1e3 100644
--- a/web/js/containers/sidebar/orbit-track.js
+++ b/web/js/containers/sidebar/orbit-track.js
@@ -61,7 +61,6 @@ OrbitTrack.propTypes = {
hasPalette: PropTypes.bool,
isLoading: PropTypes.bool,
isMobile: PropTypes.bool,
- palette: PropTypes.object,
paletteLegends: PropTypes.array,
parentLayer: PropTypes.object,
renderedPalette: PropTypes.object,
diff --git a/web/js/containers/sidebar/sidebar.js b/web/js/containers/sidebar/sidebar.js
index fa54bb547..df1a3367b 100644
--- a/web/js/containers/sidebar/sidebar.js
+++ b/web/js/containers/sidebar/sidebar.js
@@ -106,9 +106,11 @@ class Sidebar extends React.Component {
}
selectEvent(id, date) {
- this.state.selectEvent(id, date);
- if (this.props.isMobile) {
- this.props.collapseSidebar();
+ const { selectEvent } = this.state;
+ const { isMobile, collapseSidebar } = this.props;
+ selectEvent(id, date);
+ if (isMobile) {
+ collapseSidebar();
}
}
@@ -134,6 +136,7 @@ class Sidebar extends React.Component {
}
getProductsToRender(activeTab, isCompareMode) {
+ const { activeString } = this.props;
const { subComponentHeight } = this.state;
if (isCompareMode) {
return (
@@ -148,7 +151,7 @@ class Sidebar extends React.Component {
<Layers
height={subComponentHeight}
isActive={activeTab === 'layers'}
- layerGroupName={this.props.activeString}
+ layerGroupName={activeString}
checkerBoardPattern={this.checkerBoardPattern}
/>
);
diff --git a/web/js/containers/timeline/timeline.js b/web/js/containers/timeline/timeline.js
index 5cd62b622..dd144f728 100644
--- a/web/js/containers/timeline/timeline.js
+++ b/web/js/containers/timeline/timeline.js
@@ -90,6 +90,7 @@ class Timeline extends React.Component {
showHoverLine: false,
showDraggerTime: false,
isAnimationDraggerDragging: false,
+ // eslint-disable-next-line react/no-unused-state
isArrowDown: false,
isHoverOverDistractionFreeTimeUI: false,
isDraggerDragging: false,
@@ -146,6 +147,100 @@ class Timeline extends React.Component {
this.appNowUpdateInterval = 0;
}
+ static getDerivedStateFromProps(props, currentState) {
+ // Update animation Date states when animation is initiated
+ if (!currentState.animationEndLocationDate
+ && !currentState.animationStartLocationDate
+ && props.animStartLocationDate
+ && props.animEndLocationDate) {
+ const { position, transformX } = currentState;
+ const { timeScale } = props;
+ const startDate = props.animStartLocationDate;
+ const endDate = props.animEndLocationDate;
+ const options = timeScaleOptions[timeScale].timeAxis;
+ const { gridWidth } = options;
+
+ const frontDate = moment.utc(currentState.frontDate);
+ const startLocation = frontDate.diff(startDate, timeScale, true) * gridWidth;
+ const endLocation = frontDate.diff(endDate, timeScale, true) * gridWidth;
+ return {
+ animationStartLocationDate: props.animStartLocationDate,
+ animationEndLocationDate: props.animEndLocationDate,
+ animationStartLocation: position - startLocation + transformX,
+ animationEndLocation: position - endLocation + transformX,
+ };
+ }
+ return null;
+ }
+
+ componentDidMount() {
+ document.addEventListener('keydown', this.handleKeyDown);
+ document.addEventListener('keyup', this.handleKeyUp);
+ // prevent default react synthetic event passive event listener
+ // that allows browser resize/zoom on certain wheel events
+ document.querySelector('.timeline-container').addEventListener('wheel', preventDefaultFunc, { passive: false });
+
+ this.checkAndUpdateAppNow = this.checkAndUpdateAppNow.bind(this);
+ this.appNowUpdateInterval = setInterval(this.checkAndUpdateAppNow, 60000 * 15);
+ this.setInitialState();
+ }
+
+ componentDidUpdate(prevProps, prevState) {
+ const prevStartLocationDate = prevProps.animStartLocationDate;
+ const prevEndLocationDate = prevProps.animEndLocationDate;
+ const {
+ animStartLocationDate,
+ animEndLocationDate,
+ dateA,
+ dateB,
+ isAnimationPlaying,
+ isAnimationWidgetOpen,
+ isGifActive,
+ hasSubdailyLayers,
+ } = this.props;
+ const { frontDate, draggerTimeState, draggerTimeStateB } = this.state;
+
+ // handle update animation positioning and local state from play button/gif creation
+ const didAnimationTurnOn = !prevProps.isAnimationPlaying && isAnimationPlaying;
+ const didGifTurnOn = !prevProps.isGifActive && isGifActive;
+ if (didAnimationTurnOn || didGifTurnOn) {
+ this.animationDraggerDateUpdateLocal(animStartLocationDate, animEndLocationDate);
+ }
+
+ // handle location update triggered from animation start/end date change from animation widget
+ if (isAnimationWidgetOpen) {
+ if (prevStartLocationDate && prevEndLocationDate) {
+ const animStartDateChanged = prevStartLocationDate.getTime() !== animStartLocationDate.getTime();
+ const animEndDateChanged = prevEndLocationDate.getTime() !== animEndLocationDate.getTime();
+ const frontDateChanged = prevState.frontDate !== frontDate;
+ if (animStartDateChanged || animEndDateChanged || frontDateChanged) {
+ this.animationDraggerDateUpdate(animStartLocationDate, animEndLocationDate);
+ }
+ }
+ }
+
+ // if user adds a subdaily layer (and none were active) adjust the time backwards if needed
+ // and change the time scale to hourly
+ if (hasSubdailyLayers && !prevProps.hasSubdailyLayers) {
+ this.moveSelectedDateBackwards();
+ this.changeTimeScale(4);
+ }
+
+ if (dateA !== prevProps.dateA && dateA !== draggerTimeState) {
+ this.updateDraggerTimeState(dateA, false);
+ }
+ if (dateB !== prevProps.dateB && dateB !== draggerTimeStateB) {
+ this.updateDraggerTimeState(dateB, true);
+ }
+ }
+
+ componentWillUnmount() {
+ if (this.appNowUpdateInterval) clearInterval(this.appNowUpdateInterval);
+ document.removeEventListener('keydown', this.handleKeyDown);
+ document.removeEventListener('keyup', this.handleKeyUp);
+ document.querySelector('.timeline-container').removeEventListener('wheel', preventDefaultFunc);
+ }
+
// chain throttled timescale wheel change call after debounce for smoother UX
throttleChangeTimeScaleWheel = (e) => {
this.throttleChangeTimeScaleWheelFire(e);
@@ -287,6 +382,7 @@ class Timeline extends React.Component {
draggerVisibleB,
animationStartLocation,
animationEndLocation,
+ // eslint-disable-next-line react/destructuring-assignment
}, hoverTime = this.state.hoverTime) => {
this.setState({
hasMoved,
@@ -354,6 +450,7 @@ class Timeline extends React.Component {
isTimelineDragging,
position,
transformX,
+ // eslint-disable-next-line react/destructuring-assignment
}, hoverTime = this.state.hoverTime) => {
this.setState({
hasMoved,
@@ -406,6 +503,7 @@ class Timeline extends React.Component {
const maxDate = new Date(timelineEndDateLimit);
this.onDateChange(getNextTimeSelection(delta, timeScaleChangeUnit, selectedDate, minDate, maxDate));
}
+ // eslint-disable-next-line react/no-unused-state
this.setState({ isArrowDown: true });
}
@@ -415,6 +513,7 @@ class Timeline extends React.Component {
*/
stopLeftArrow = () => {
this.throttleDecrementDate.cancel();
+ // eslint-disable-next-line react/no-unused-state
this.setState({ isArrowDown: false });
}
@@ -424,6 +523,7 @@ class Timeline extends React.Component {
*/
stopRightArrow = () => {
this.throttleIncrementDate.cancel();
+ // eslint-disable-next-line react/no-unused-state
this.setState({ isArrowDown: false });
}
@@ -773,80 +873,6 @@ class Timeline extends React.Component {
});
}
- static getDerivedStateFromProps(props, currentState) {
- // Update animation Date states when animation is initiated
- if (!currentState.animationEndLocationDate
- && !currentState.animationStartLocationDate
- && props.animStartLocationDate
- && props.animEndLocationDate) {
- const { position, transformX } = currentState;
- const { timeScale } = props;
- const startDate = props.animStartLocationDate;
- const endDate = props.animEndLocationDate;
- const options = timeScaleOptions[timeScale].timeAxis;
- const { gridWidth } = options;
-
- const frontDate = moment.utc(currentState.frontDate);
- const startLocation = frontDate.diff(startDate, timeScale, true) * gridWidth;
- const endLocation = frontDate.diff(endDate, timeScale, true) * gridWidth;
- return {
- animationStartLocationDate: props.animStartLocationDate,
- animationEndLocationDate: props.animEndLocationDate,
- animationStartLocation: position - startLocation + transformX,
- animationEndLocation: position - endLocation + transformX,
- };
- }
- return null;
- }
-
- componentDidUpdate(prevProps, prevState) {
- const prevStartLocationDate = prevProps.animStartLocationDate;
- const prevEndLocationDate = prevProps.animEndLocationDate;
- const {
- animStartLocationDate,
- animEndLocationDate,
- dateA,
- dateB,
- isAnimationPlaying,
- isAnimationWidgetOpen,
- isGifActive,
- hasSubdailyLayers,
- } = this.props;
-
- // handle update animation positioning and local state from play button/gif creation
- const didAnimationTurnOn = !prevProps.isAnimationPlaying && isAnimationPlaying;
- const didGifTurnOn = !prevProps.isGifActive && isGifActive;
- if (didAnimationTurnOn || didGifTurnOn) {
- this.animationDraggerDateUpdateLocal(animStartLocationDate, animEndLocationDate);
- }
-
- // handle location update triggered from animation start/end date change from animation widget
- if (isAnimationWidgetOpen) {
- if (prevStartLocationDate && prevEndLocationDate) {
- const animStartDateChanged = prevStartLocationDate.getTime() !== animStartLocationDate.getTime();
- const animEndDateChanged = prevEndLocationDate.getTime() !== animEndLocationDate.getTime();
- const frontDateChanged = prevState.frontDate !== this.state.frontDate;
- if (animStartDateChanged || animEndDateChanged || frontDateChanged) {
- this.animationDraggerDateUpdate(animStartLocationDate, animEndLocationDate);
- }
- }
- }
-
- // if user adds a subdaily layer (and none were active) adjust the time backwards if needed
- // and change the time scale to hourly
- if (hasSubdailyLayers && !prevProps.hasSubdailyLayers) {
- this.moveSelectedDateBackwards();
- this.changeTimeScale(4);
- }
-
- if (dateA !== prevProps.dateA && dateA !== this.state.draggerTimeState) {
- this.updateDraggerTimeState(dateA, false);
- }
- if (dateB !== prevProps.dateB && dateB !== this.state.draggerTimeStateB) {
- this.updateDraggerTimeState(dateB, true);
- }
- }
-
/**
* If a user adds a subdaily layer and the current selected time is too recent
* it is likely they will see no layer content. Here we are moving the selected time
@@ -912,25 +938,6 @@ class Timeline extends React.Component {
});
}
- componentDidMount() {
- document.addEventListener('keydown', this.handleKeyDown);
- document.addEventListener('keyup', this.handleKeyUp);
- // prevent default react synthetic event passive event listener
- // that allows browser resize/zoom on certain wheel events
- document.querySelector('.timeline-container').addEventListener('wheel', preventDefaultFunc, { passive: false });
-
- this.checkAndUpdateAppNow = this.checkAndUpdateAppNow.bind(this);
- this.appNowUpdateInterval = setInterval(this.checkAndUpdateAppNow, 60000 * 15);
- this.setInitialState();
- }
-
- componentWillUnmount() {
- if (this.appNowUpdateInterval) clearInterval(this.appNowUpdateInterval);
- document.removeEventListener('keydown', this.handleKeyDown);
- document.removeEventListener('keyup', this.handleKeyUp);
- document.querySelector('.timeline-container').removeEventListener('wheel', preventDefaultFunc);
- }
-
setInitialState = () => {
const {
dateA,
@@ -950,6 +957,7 @@ class Timeline extends React.Component {
* @param {String} draggerSelected - default to props draggerSelected
* @returns {void}
*/
+ // eslint-disable-next-line react/destructuring-assignment
onDateChange = (date, draggerSelected = this.props.draggerSelected) => {
const dateObj = new Date(date);
const dateISOFormatted = getISODateFormatted(date);
@@ -1378,13 +1386,13 @@ function mapStateToProps(state) {
customSelected,
selected,
selectedB,
- selectedZoom,
- interval,
delta,
- customInterval,
customDelta,
appNow,
timelineCustomModalOpen,
+ selectedZoom,
+ interval,
+ customInterval,
} = date;
const { screenWidth, lessThan } = browser;
const { isCompareA, activeString } = compare;
@@ -1541,11 +1549,11 @@ export default connect(
)(Timeline);
Timeline.propTypes = {
+ appNow: PropTypes.object,
activeLayers: PropTypes.array,
animationDisabled: PropTypes.bool,
animEndLocationDate: PropTypes.object,
animStartLocationDate: PropTypes.object,
- appNow: PropTypes.object,
axisWidth: PropTypes.number,
changeCustomInterval: PropTypes.func,
changeDate: PropTypes.func,
diff --git a/web/js/containers/toolbar.js b/web/js/containers/toolbar.js
index b7c1fd375..664d9db25 100644
--- a/web/js/containers/toolbar.js
+++ b/web/js/containers/toolbar.js
@@ -13,7 +13,7 @@ import {
faShareSquare, faGlobeAsia, faCamera, faInfoCircle,
} from '@fortawesome/free-solid-svg-icons';
import { openCustomContent, onToggle } from '../modules/modal/actions';
-import { toggleDistractionFreeMode } from '../modules/ui/actions';
+import toggleDistractionFreeMode from '../modules/ui/actions';
import ImageDownload from './image-download';
import Projection from './projection';
import InfoList from './info';
@@ -31,7 +31,7 @@ import { clearCustoms, refreshPalettes } from '../modules/palettes/actions';
import { clearRotate, refreshRotation } from '../modules/map/actions';
import { clearGraticule, refreshGraticule } from '../modules/layers/actions';
import { notificationWarnings } from '../modules/image-download/constants';
-import { Notify } from '../components/image-download/notify';
+import Notify from '../components/image-download/notify';
import { hasCustomPaletteInActiveProjection } from '../modules/palettes/util';
import { getLayers } from '../modules/layers/selectors';
@@ -343,5 +343,4 @@ toolbarContainer.propTypes = {
refreshStateAfterImageDownload: PropTypes.func,
requestNotifications: PropTypes.func,
rotation: PropTypes.number,
- toggleDistractionFreeMode: PropTypes.func,
};
diff --git a/web/js/containers/tour.js b/web/js/containers/tour.js
index b35692e00..406780a59 100644
--- a/web/js/containers/tour.js
+++ b/web/js/containers/tour.js
@@ -21,7 +21,7 @@ import { layersParse12 } from '../modules/layers/util';
import { endTour, selectStory, startTour } from '../modules/tour/actions';
import ErrorBoundary from './error-boundary';
-import { history } from '../main';
+import history from '../main';
import util from '../util/util';
class Tour extends React.Component {
@@ -68,11 +68,12 @@ class Tour extends React.Component {
toggleModalStart(e) {
e.preventDefault();
+ const { endTour } = this.props;
this.setState((prevState) => {
const toggleModal = !prevState.modalStart;
// if closing modal
if (!toggleModal) {
- this.props.endTour();
+ endTour();
}
return {
modalStart: toggleModal,
@@ -81,6 +82,9 @@ class Tour extends React.Component {
}
selectTour(e, currentStory, currentStoryIndex, currentStoryId) {
+ const {
+ config, renderedPalettes, selectTour, processStepLink,
+ } = this.props;
if (e) e.preventDefault();
this.setState({
currentStep: 1,
@@ -93,20 +97,20 @@ class Tour extends React.Component {
currentStoryId,
totalSteps: currentStory.steps.length,
});
- this.props.selectTour(currentStoryId);
+ selectTour(currentStoryId);
this.fetchMetadata(currentStory, 0);
const storyStep = currentStory.steps[0];
const transition = getTransitionAttr(
storyStep.transition.element,
storyStep.transition.action,
);
- this.props.processStepLink(
+ processStepLink(
currentStoryId,
1,
currentStory.steps.length,
`${storyStep.stepLink}&tr=${currentStoryId}${transition}`,
- this.props.config,
- this.props.renderedPalettes,
+ config,
+ renderedPalettes,
);
}
@@ -138,9 +142,10 @@ class Tour extends React.Component {
}
resetTour(e) {
+ const { startTour } = this.props;
if (e) e.preventDefault();
// Tour startup modal shown by clicking "More Stories" button at end of story
- this.props.startTour();
+ startTour();
googleTagManager.pushEvent({
event: 'tour_more_stories_button',
});
@@ -161,6 +166,7 @@ class Tour extends React.Component {
}
toggleModalComplete(e) {
+ const { currentStoryId } = this.state;
e.preventDefault();
this.setState((prevState) => ({
modalComplete: !prevState.modalComplete,
@@ -171,7 +177,7 @@ class Tour extends React.Component {
googleTagManager.pushEvent({
event: 'tour_completed',
story: {
- id: this.state.currentStoryId,
+ id: currentStoryId,
},
});
}
@@ -183,6 +189,9 @@ class Tour extends React.Component {
totalSteps,
currentStoryId,
} = this.state;
+ const {
+ config, renderedPalettes, processStepLink,
+ } = this.props;
if (currentStep + 1 <= totalSteps) {
const newStep = currentStep + 1;
@@ -193,7 +202,7 @@ class Tour extends React.Component {
storyStep.transition.element,
storyStep.transition.action,
);
- this.props.processStepLink(
+ processStepLink(
currentStoryId,
newStep,
currentStory.steps.length,
@@ -201,8 +210,8 @@ class Tour extends React.Component {
}&tr=${
currentStoryId
}${transition}`,
- this.props.config,
- this.props.renderedPalettes,
+ config,
+ renderedPalettes,
);
}
if (currentStep + 1 === totalSteps + 1) {
@@ -212,7 +221,12 @@ class Tour extends React.Component {
}
decreaseStep(e) {
- const { currentStep, currentStory, currentStoryId } = this.state;
+ const {
+ config, renderedPalettes, processStepLink,
+ } = this.props;
+ const {
+ currentStep, currentStory, currentStoryId,
+ } = this.state;
if (currentStep - 1 >= 1) {
const newStep = currentStep - 1;
this.fetchMetadata(currentStory, newStep - 1);
@@ -222,7 +236,7 @@ class Tour extends React.Component {
storyStep.transition.element,
storyStep.transition.action,
);
- this.props.processStepLink(
+ processStepLink(
currentStoryId,
newStep,
currentStory.steps.length,
@@ -230,8 +244,8 @@ class Tour extends React.Component {
}&tr=${
currentStoryId
}${transition}`,
- this.props.config,
- this.props.renderedPalettes,
+ config,
+ renderedPalettes,
);
} else {
this.setState({
@@ -244,19 +258,22 @@ class Tour extends React.Component {
endTour(e) {
e.preventDefault();
- if (!this.state.showDisabledAlert) {
- this.props.endTour();
+ const { showDisabledAlert } = this.state;
+ const { endTour } = this.props;
+ if (!showDisabledAlert) {
+ endTour();
} else {
this.setState({ tourEnded: true });
}
}
renderSupportAlert() {
+ const { endTour } = this.props;
return (
<AlertUtil
isOpen
timeout={10000}
- onDismiss={this.props.endTour}
+ onDismiss={endTour}
iconClassName=" "
message="Sorry, this tour is no longer supported."
/>
@@ -264,11 +281,12 @@ class Tour extends React.Component {
}
renderDisableAlert() {
+ const { endTour } = this.props;
return (
<AlertUtil
isOpen
timeout={10000}
- onDismiss={this.props.endTour}
+ onDismiss={endTour}
iconClassName=" "
message="To view these tours again, click the 'Explore Worldview' link in the “i” menu."
/>
@@ -507,8 +525,6 @@ Tour.propTypes = {
showTourAlert: PropTypes.func.isRequired,
stories: PropTypes.object.isRequired,
storyOrder: PropTypes.array.isRequired,
- currentStep: PropTypes.number,
- currentStory: PropTypes.object,
currentStoryId: PropTypes.string,
endTour: PropTypes.func,
isActive: PropTypes.bool,
@@ -517,5 +533,4 @@ Tour.propTypes = {
screenHeight: PropTypes.number,
screenWidth: PropTypes.number,
startTour: PropTypes.func,
- totalSteps: PropTypes.number,
};
diff --git a/web/js/containers/vector-dialog.js b/web/js/containers/vector-dialog.js
index 3848ffa70..051175e93 100644
--- a/web/js/containers/vector-dialog.js
+++ b/web/js/containers/vector-dialog.js
@@ -16,6 +16,7 @@ class VectorDialog extends React.Component {
}
updateIndex(activeIndex) {
+ // eslint-disable-next-line react/destructuring-assignment
if (activeIndex === this.state.activeIndex) return;
this.setState({ activeIndex });
}
@@ -45,7 +46,7 @@ class VectorDialog extends React.Component {
</NavLink>
</NavItem>,
);
- i++;
+ i += 1;
}
const activeMetaArray = vectorMetaObject[keyArray[activeIndex]];
@@ -78,6 +79,5 @@ VectorDialog.propTypes = {
dialogKey: PropTypes.number,
modalHeight: PropTypes.number,
toggleWithClose: PropTypes.func,
- vectorMetaArray: PropTypes.array,
vectorMetaObject: PropTypes.object,
};
diff --git a/web/js/edsc.js b/web/js/edsc.js
index f13e6a3a2..a93ebad7a 100644
--- a/web/js/edsc.js
+++ b/web/js/edsc.js
@@ -77,4 +77,5 @@ edsc.geoutil = edscGeoUtil(L, edsc.Coordinate, edsc.Arc, edsc.config);
edsc.interpolation = edscInterpolation(L, edsc.geoutil.gcInterpolate);
edsc.L.sphericalPolygon = edscSphericalPolygon(L, edsc.geoutil, edsc.Arc, edsc.Coordinate);
+// eslint-disable-next-line import/prefer-default-export
export { L as dataHelper };
diff --git a/web/js/edsc/geoutil.js b/web/js/edsc/geoutil.js
index 2495c7186..b403d8082 100644
--- a/web/js/edsc/geoutil.js
+++ b/web/js/edsc/geoutil.js
@@ -128,7 +128,7 @@ export default function (L, Coordinate, Arc, config) {
latlngs = (function () {
var j, len1, results;
results = [];
- for (j = 0, len1 = latlngs.length; j < len1; j++) {
+ for (j = 0, len1 = latlngs.length; j < len1; j+= 1) {
latlng = latlngs[j];
results.push(L.latLng(latlng));
}
@@ -173,7 +173,7 @@ export default function (L, Coordinate, Arc, config) {
angles = (function () {
var k, len1, results;
results = [];
- for (k = 0, len1 = latlngs.length; k < len1; k++) {
+ for (k = 0, len1 = latlngs.length; k < len1; k+= 1) {
latlng = latlngs[k];
results.push(latlng.lng);
}
diff --git a/web/js/edsc/interpolation.js b/web/js/edsc/interpolation.js
index 0e82a714b..d259d2f64 100644
--- a/web/js/edsc/interpolation.js
+++ b/web/js/edsc/interpolation.js
@@ -43,7 +43,7 @@ export default function (L, gcInterpolate) {
points = (function () {
var i, len, results;
results = [];
- for (i = 0, len = latLngs.length; i < len; i++) {
+ for (i = 0, len = latLngs.length; i < len; i+= 1) {
ll = latLngs[i];
results.push(proj(ll));
}
@@ -131,7 +131,7 @@ export default function (L, gcInterpolate) {
var i, len, ref, results;
ref = holes != null ? holes : [];
results = [];
- for (i = 0, len = ref.length; i < len; i++) {
+ for (i = 0, len = ref.length; i < len; i+= 1) {
hole = ref[i];
results.push(projectLatLngPath(hole, proj, fn, tolerance, maxDepth));
}
diff --git a/web/js/edsc/spherical-polygon.js b/web/js/edsc/spherical-polygon.js
index 28923e00e..c946995f8 100644
--- a/web/js/edsc/spherical-polygon.js
+++ b/web/js/edsc/spherical-polygon.js
@@ -6,7 +6,7 @@ export default function (L, geoutil, Arc, Coordinate) {
convertLatLngs = function (latlngs) {
var j, latlng, len1, original, result;
result = [];
- for (j = 0, len1 = latlngs.length; j < len1; j++) {
+ for (j = 0, len1 = latlngs.length; j < len1; j+= 1) {
original = latlngs[j];
latlng = L.latLng(original);
while (latlng.lng > 180) {
@@ -49,7 +49,7 @@ export default function (L, geoutil, Arc, Coordinate) {
return ((function () {
var j, len1, results;
results = [];
- for (j = 0, len1 = latlngs.length; j < len1; j++) {
+ for (j = 0, len1 = latlngs.length; j < len1; j+= 1) {
ll = latlngs[j];
results.push('(' + ll.lat + ', ' + ll.lng + ')');
}
@@ -65,7 +65,7 @@ export default function (L, geoutil, Arc, Coordinate) {
var j, len1, ref, results;
ref = latlngs.concat(latlngs[0]);
results = [];
- for (j = 0, len1 = ref.length; j < len1; j++) {
+ for (j = 0, len1 = ref.length; j < len1; j+= 1) {
ll = ref[j];
results.push(ll.lng + ',' + ll.lat);
}
@@ -105,7 +105,7 @@ export default function (L, geoutil, Arc, Coordinate) {
// Handle a list containing holes
if (latlngs && L.Util.isArray(latlngs[0]) && typeof latlngs[0][0] !== 'number') {
ref = latlngs.slice(1);
- for (j = 0, len1 = ref.length; j < len1; j++) {
+ for (j = 0, len1 = ref.length; j < len1; j+= 1) {
hole = ref[j];
hole = convertLatLngs(hole);
denormalizePath(hole);
@@ -159,7 +159,7 @@ export default function (L, geoutil, Arc, Coordinate) {
} else if (latlng2.lng === -180 && latlng1.lng > 0) {
extras = [[latlng2.lat, 180]];
}
- for (l = 0, len2 = extras.length; l < len2; l++) {
+ for (l = 0, len2 = extras.length; l < len2; l+= 1) {
extra = extras[l];
lat = extra[0], lng = extra[1];
split.push(L.latLng(lat, lng));
@@ -277,7 +277,7 @@ export default function (L, geoutil, Arc, Coordinate) {
latlngs = (function () {
var j, len1, results;
results = [];
- for (j = 0, len1 = latlngs.length; j < len1; j++) {
+ for (j = 0, len1 = latlngs.length; j < len1; j+= 1) {
latlng = latlngs[j];
results.push(L.latLng(latlng));
}
diff --git a/web/js/feedback.js b/web/js/feedback.js
index 42218d713..e9afb833c 100644
--- a/web/js/feedback.js
+++ b/web/js/feedback.js
@@ -6,7 +6,7 @@
*/
import util from './util/util';
-export function feedbackUi() {
+export default function feedbackUi() {
const self = {};
let feedbackInit = false;
diff --git a/web/js/location.js b/web/js/location.js
index 78642a94d..9bd4da850 100644
--- a/web/js/location.js
+++ b/web/js/location.js
@@ -24,9 +24,9 @@ import { resetLayers, hasSubDaily } from './modules/layers/selectors';
import { eventsReducerState } from './modules/natural-events/reducers';
import { mapLocationToPaletteState } from './modules/palettes/util';
import { mapLocationToAnimationState } from './modules/animation/util';
-import { mapLocationToSidebarState } from './modules/sidebar/util';
+import mapLocationToSidebarState from './modules/sidebar/util';
import util from './util/util';
-import { mapLocationToDataState } from './modules/data/util';
+import mapLocationToDataState from './modules/data/util';
/**
* Override state with information from location.search when "REDUX-LOCATION-POP-ACTION"
diff --git a/web/js/main.js b/web/js/main.js
index bfbf55a7b..f96c17a37 100644
--- a/web/js/main.js
+++ b/web/js/main.js
@@ -15,7 +15,7 @@ import {
} from 'redux-location-state';
import { createBrowserHistory } from 'history';
import { uniqBy } from 'lodash';
-import { getMiddleware } from './combine-middleware';
+import getMiddleware from './combine-middleware';
import { mapLocationToState, getParamObject } from './location';
import { stateToParams } from './redux-location-state-customs';
import reducers, { getInitialState } from './modules/combine-reducers';
@@ -23,19 +23,19 @@ import App from './app';
import util from './util/util';
import loadingIndicator from './ui/indicator';
import Brand from './brand';
-import { combineModels } from './combine-models';
-import { parse } from './parse';
-import { combineUi } from './combine-ui';
+import combineModels from './combine-models';
+import parse from './parse';
+import combineUi from './combine-ui';
import { preloadPalettes, hasCustomTypePalette } from './modules/palettes/util';
import {
validate as layerValidate,
layersParse12,
} from './modules/layers/util';
-import { polyfill } from './polyfill';
+import polyfill from './polyfill';
import { debugConfig } from './debug';
import { CUSTOM_PALETTE_TYPE_ARRAY } from './modules/palettes/constants';
-export const history = createBrowserHistory();
+const history = createBrowserHistory();
const isDebugMode = typeof DEBUG !== 'undefined';
const configURI = Brand.url('config/wv.json');
@@ -163,3 +163,5 @@ const render = (config, parameters, legacyState) => {
combineUi(models, config, mouseMoveEvents, store); // Legacy UI
util.errorReport(errors);
};
+
+export default history;
diff --git a/web/js/map/animate.js b/web/js/map/animate.js
index 9305b1597..350905f0d 100644
--- a/web/js/map/animate.js
+++ b/web/js/map/animate.js
@@ -2,7 +2,7 @@ import * as olExtent from 'ol/extent';
import OlGeomLineString from 'ol/geom/LineString';
import Promise from 'bluebird';
-export function mapAnimate(config, ui, store) {
+export default function mapAnimate(config, ui, store) {
const self = {};
/**
diff --git a/web/js/map/compare/compare.js b/web/js/map/compare/compare.js
index 9e78f079d..5255a78b0 100644
--- a/web/js/map/compare/compare.js
+++ b/web/js/map/compare/compare.js
@@ -1,6 +1,6 @@
-import { Swipe } from './swipe';
-import { Opacity } from './opacity';
-import { Spy } from './spy';
+import Swipe from './swipe';
+import Opacity from './opacity';
+import Spy from './spy';
import util from '../../util/util';
import { setValue } from '../../modules/compare/actions';
@@ -16,7 +16,7 @@ const MOUSE_EVENT = {
move: 'mousemove',
end: 'mouseup',
};
-export function mapCompare(config, store) {
+export default function mapCompare(config, store) {
const self = {};
let comparison = null;
let mode = 'swipe';
diff --git a/web/js/map/compare/opacity.js b/web/js/map/compare/opacity.js
index 55a7e6307..1e453cdb5 100644
--- a/web/js/map/compare/opacity.js
+++ b/web/js/map/compare/opacity.js
@@ -5,7 +5,7 @@ import OpacitySlider from '../../components/compare/opacity-slider';
let slider;
let value = 50;
-export class Opacity {
+export default class Opacity {
constructor(olMap, isAactive, events, eventListenerStringObj, valueOverride) {
this.map = olMap;
this.compareEvents = events;
@@ -57,9 +57,8 @@ export class Opacity {
* @param {Number} newValue
*/
oninput(newValue) {
- let convertedValue;
value = newValue;
- convertedValue = value / 100;
+ const convertedValue = value / 100;
this.firstLayer.setOpacity(1 - convertedValue);
this.secondLayer.setOpacity(convertedValue);
this.compareEvents.trigger('moveend', value);
diff --git a/web/js/map/compare/spy.js b/web/js/map/compare/spy.js
index 1aee12a12..186202d74 100644
--- a/web/js/map/compare/spy.js
+++ b/web/js/map/compare/spy.js
@@ -8,7 +8,7 @@ const DEFAULT_RADIUS = 140;
let radius = DEFAULT_RADIUS;
let label = null;
-export class Spy {
+export default class Spy {
constructor(olMap, isBInside) {
this.mapCase = document.getElementById('wv-map');
this.map = olMap;
@@ -60,10 +60,9 @@ export class Spy {
* @param {Object} e | mousemove event object
*/
updateSpy(e) {
- let offSetXandY;
mousePosition = e.pixel || this.map.getEventPixel(e);
radius = DEFAULT_RADIUS;
- offSetXandY = Math.sqrt((radius * radius) / 2);
+ const offSetXandY = Math.sqrt((radius * radius) / 2);
label.style.top = `${mousePosition[1] + offSetXandY - 10}px`;
label.style.left = `${mousePosition[0] + offSetXandY - 5}px`;
this.map.render();
diff --git a/web/js/map/compare/swipe.js b/web/js/map/compare/swipe.js
index 8ed38601b..b095357f6 100644
--- a/web/js/map/compare/swipe.js
+++ b/web/js/map/compare/swipe.js
@@ -15,7 +15,7 @@ let percentSwipe = null;
const SWIPE_PADDING = 30;
let dragging = false;
-export class Swipe {
+export default class Swipe {
constructor(
olMap,
isActive,
@@ -41,9 +41,7 @@ export class Swipe {
this.update();
}
- getSwipeOffset() {
- return swipeOffset;
- }
+ getSwipeOffset = () => swipeOffset
/**
* Recursively apply listeners to layers
@@ -77,7 +75,7 @@ export class Swipe {
* Clip the top layer at the right xOffset
* @param {Object} event | OL Precompose event object
*/
- clip(event) {
+ clip = (event) => {
const ctx = event.context;
const viewportWidth = event.frameState.size[0];
const width = ctx.canvas.width * (swipeOffset / viewportWidth);
@@ -92,7 +90,7 @@ export class Swipe {
* Layer group is transparent
* @param {Object} event | OL Precompose event object
*/
- reverseClip(event) {
+ reverseClip = (event) => {
const ctx = event.context;
const viewportWidth = event.frameState.size[0];
const width = ctx.canvas.width * (1 - swipeOffset / viewportWidth);
diff --git a/web/js/map/data/data.js b/web/js/map/data/data.js
index 39a163b84..bd7121c57 100644
--- a/web/js/map/data/data.js
+++ b/web/js/map/data/data.js
@@ -1,4 +1,4 @@
-export function dataParser(state, errors, config) {
+export default function dataParser(state, errors, config) {
if (state.dataDownload) {
state.download = state.dataDownload;
delete state.dataDownload;
diff --git a/web/js/map/data/data.test.js b/web/js/map/data/data.test.js
index f0dd6e8ab..fdf7e1a58 100644
--- a/web/js/map/data/data.test.js
+++ b/web/js/map/data/data.test.js
@@ -1,4 +1,4 @@
-import { dataParser } from './data';
+import dataParser from './data';
function testConfig() {
return {
diff --git a/web/js/map/data/map.js b/web/js/map/data/map.js
index d89ef2a37..fb92cc596 100644
--- a/web/js/map/data/map.js
+++ b/web/js/map/data/map.js
@@ -13,7 +13,7 @@ import { toggleGranule } from '../../modules/data/actions';
import { CRS_WGS_84, mapToPolys, mapDistanceX } from '../map';
-export function dataMap(store, maps, dataUi, ui) {
+export default function dataMap(store, maps, dataUi, ui) {
const self = {};
let map = null;
diff --git a/web/js/map/data/results.js b/web/js/map/data/results.js
index 6f28c993b..14d02e39a 100644
--- a/web/js/map/data/results.js
+++ b/web/js/map/data/results.js
@@ -330,13 +330,13 @@ export function dataResultsDensify() {
.getCoordinates();
var points = [];
var end;
- for (var i = 0; i < ring.length - 2; i++) {
+ for (var i = 0; i < ring.length - 2; i+= 1) {
var start = ring[i];
end = ring[i + 1];
var distance = mapDistance2D(start, end);
var numPoints = Math.floor(distance / MAX_DISTANCE);
points.push(lodashClone(start));
- for (var j = 1; j < numPoints - 1; j++) {
+ for (var j = 1; j < numPoints - 1; j+= 1) {
var d = j / numPoints;
// This is what REVERB does, so we will do the same
var p = mapInterpolate2D(start, end, d);
diff --git a/web/js/map/data/ui.js b/web/js/map/data/ui.js
index 6b8488390..616b82af7 100644
--- a/web/js/map/data/ui.js
+++ b/web/js/map/data/ui.js
@@ -5,7 +5,7 @@ import lodashFind from 'lodash/find';
import googleTagManager from 'googleTagManager';
import * as olExtent from 'ol/extent';
import { dataHandlerGetByName } from './handler';
-import { dataMap } from './map';
+import dataMap from './map';
import uiIndicator from '../../ui/indicator';
import util from '../../util/util';
import wvui from '../../ui/ui';
@@ -23,7 +23,7 @@ import * as LAYER_CONSTANTS from '../../modules/layers/constants';
import { CHANGE_PROJECTION } from '../../modules/projection/constants';
import { faIconInfoCircleSVGDomEl } from '../fa-map-icons';
-export function dataUi(store, ui, config) {
+export default function dataUi(store, ui, config) {
let queryActive = false;
let mapController = null;
let selectionListPanel = null;
@@ -335,7 +335,7 @@ const dataUiBulkDownloadPage = (function() {
};
let checkCount = 0;
const timer = setInterval(() => {
- checkCount++;
+ checkCount += 1;
if (loaded) {
clearInterval(timer);
return;
@@ -549,7 +549,7 @@ const dataUiDownloadListPanel = function(config, store) {
if (!product.counts[link.href]) {
product.counts[link.href] = 1;
} else {
- product.counts[link.href]++;
+ product.counts[link.href] += 1;
}
}
});
diff --git a/web/js/map/datelinebuilder.js b/web/js/map/datelinebuilder.js
index 2e0e5b50e..e7e7ef6bb 100644
--- a/web/js/map/datelinebuilder.js
+++ b/web/js/map/datelinebuilder.js
@@ -22,7 +22,7 @@ let textLeft;
let textRight;
let proj;
-export function mapDateLineBuilder(models, config, store, ui) {
+export default function mapDateLineBuilder(models, config, store, ui) {
const self = {};
// formatted YYYY-MM-DD (e.g., 2019-06-25) for checking daily change for dateline
self.date = {};
@@ -214,14 +214,11 @@ export function mapDateLineBuilder(models, config, store, ui) {
* @returns {void}
*/
const drawDatelines = function(map, date) {
- let height; let leftLineCase; let rightLineCase; let leftTextCase; let
- rightTextCase;
-
- leftLineCase = document.createElement('div');
- rightLineCase = document.createElement('div');
- leftTextCase = document.createElement('div');
- rightTextCase = document.createElement('div');
- height = 0;
+ const leftLineCase = document.createElement('div');
+ const rightLineCase = document.createElement('div');
+ const leftTextCase = document.createElement('div');
+ const rightTextCase = document.createElement('div');
+ const height = 0;
overlay1 = drawOverlay([-180, 90], leftLineCase);
overlay2 = drawOverlay([180, 90], rightLineCase);
@@ -272,8 +269,7 @@ export function mapDateLineBuilder(models, config, store, ui) {
* @returns {void}
*/
const onHover = function(pixels, overlay, lineX, tooltip) {
- let coords;
- coords = map.getCoordinateFromPixel(pixels);
+ const coords = map.getCoordinateFromPixel(pixels);
overlay.setPosition([lineX, coords[1]]);
tooltip.setState({
active: true,
@@ -325,24 +321,18 @@ export function mapDateLineBuilder(models, config, store, ui) {
* @returns {void}
*/
const position = function(map) {
- let extent;
- let top;
let topY;
let bottomY;
- let bottom;
- let height;
let startY;
- let topExtent;
- let bottomExtent;
if (map.getSize()[0] === 0) {
return;
}
- extent = map.getView().calculateExtent(map.getSize());
- top = [extent[2] - 1, extent[3] + 5];
- bottom = [extent[2] - 1, extent[1] - 5];
- topExtent = map.getPixelFromCoordinate([extent[2] - 1, extent[3] - 1]);
- bottomExtent = map.getPixelFromCoordinate([extent[0] + 1, extent[1] + 1]);
+ const extent = map.getView().calculateExtent(map.getSize());
+ const top = [extent[2] - 1, extent[3] + 5];
+ const bottom = [extent[2] - 1, extent[1] - 5];
+ const topExtent = map.getPixelFromCoordinate([extent[2] - 1, extent[3] - 1]);
+ const bottomExtent = map.getPixelFromCoordinate([extent[0] + 1, extent[1] + 1]);
topY = Math.round(topExtent[1] + 5);
bottomY = Math.round(bottomExtent[1] - 5);
startY = Math.round(extent[3] + 5);
@@ -358,7 +348,7 @@ export function mapDateLineBuilder(models, config, store, ui) {
} else {
[, bottomY] = map.getPixelFromCoordinate([extent[2], -90]);
}
- height = Math.round(Math.abs(bottomY - topY));
+ const height = Math.round(Math.abs(bottomY - topY));
return [height, startY];
};
diff --git a/web/js/map/layerbuilder.js b/web/js/map/layerbuilder.js
index 6aa7edba0..13e1082ae 100644
--- a/web/js/map/layerbuilder.js
+++ b/web/js/map/layerbuilder.js
@@ -12,7 +12,7 @@ import lodashCloneDeep from 'lodash/cloneDeep';
import lodashMerge from 'lodash/merge';
import lodashEach from 'lodash/each';
import util from '../util/util';
-import { lookupFactory } from '../ol/lookupimagetile';
+import lookupFactory from '../ol/lookupimagetile';
import { datesinDateRanges, prevDateInDateRange } from '../modules/layers/util';
import {
isActive as isPaletteActive,
@@ -28,7 +28,7 @@ import {
nearestInterval,
} from '../modules/layers/util';
-export function mapLayerBuilder(models, config, cache, ui, store) {
+export default function mapLayerBuilder(models, config, cache, ui, store) {
const self = {};
self.init = function() {
@@ -355,13 +355,16 @@ export function mapLayerBuilder(models, config, cache, ui, store) {
*/
const createLayerVector = function(def, options, day, state) {
const { proj, compare } = state;
- let date; let urlParameters; let gridExtent; let source; let matrixSet; let matrixIds; let start; let
- layerExtent;
+ let date;
+ let gridExtent;
+ let matrixIds;
+ let start;
+ let layerExtent;
const selectedProj = proj.selected;
const activeDateStr = compare.isCompareA ? 'selected' : 'selectedB';
const activeGroupStr = options.group ? options.group : compare.activeString;
- source = config.sources[def.source];
+ const source = config.sources[def.source];
gridExtent = selectedProj.maxExtent;
layerExtent = gridExtent;
start = [selectedProj.maxExtent[0], selectedProj.maxExtent[3]];
@@ -369,7 +372,7 @@ export function mapLayerBuilder(models, config, cache, ui, store) {
if (!source) {
throw new Error(`${def.id}: Invalid source: ${def.source}`);
}
- matrixSet = source.matrixSets[def.matrixSet];
+ const matrixSet = source.matrixSets[def.matrixSet];
if (!matrixSet) {
throw new Error(`${def.id}: Undefined matrix set: ${def.matrixSet}`);
}
@@ -402,7 +405,7 @@ export function mapLayerBuilder(models, config, cache, ui, store) {
date = util.dateAdd(date, 'day', day);
}
- urlParameters = `${'?'
+ const urlParameters = `${'?'
+ 'TIME='}${
util.toISOStringSeconds(util.roundTimeOneMinute(date))
}&layer=${
@@ -468,16 +471,13 @@ export function mapLayerBuilder(models, config, cache, ui, store) {
const { proj, compare } = state;
const activeDateStr = compare.isCompareA ? 'selected' : 'selectedB';
const selectedProj = proj.selected;
- let source;
let urlParameters;
- let transparent;
let date;
let extent;
let start;
let res;
- let parameters;
- source = config.sources[def.source];
+ const source = config.sources[def.source];
extent = selectedProj.maxExtent;
start = [selectedProj.maxExtent[0], selectedProj.maxExtent[3]];
res = selectedProj.resolutions;
@@ -485,7 +485,7 @@ export function mapLayerBuilder(models, config, cache, ui, store) {
throw new Error(`${def.id}: Invalid source: ${def.source}`);
}
- transparent = def.format === 'image/png';
+ const transparent = def.format === 'image/png';
if (selectedProj.id === 'geographic') {
res = [
0.28125,
@@ -510,7 +510,7 @@ export function mapLayerBuilder(models, config, cache, ui, store) {
start = [180, 90];
}
}
- parameters = {
+ const parameters = {
LAYERS: def.layer || def.id,
FORMAT: def.format,
TRANSPARENT: transparent,
diff --git a/web/js/map/map.js b/web/js/map/map.js
index cfc611561..9ec6f6375 100644
--- a/web/js/map/map.js
+++ b/web/js/map/map.js
@@ -162,7 +162,7 @@ export function getLayerByName(map, name) {
export function mapIsPolygonValid(polygon, maxDistance) {
const outerRing = polygon.getLinearRing(0);
const points = outerRing.getCoordinates();
- for (let i = 0; i < points.length - 1; i++) {
+ for (let i = 0; i < points.length - 1; i += 1) {
const p1 = points[i];
const p2 = points[i + 1];
if (Math.abs(p2[0] - p1[0]) > maxDistance) {
@@ -197,7 +197,7 @@ export function mapAdjustAntiMeridian(polygon, adjustSign) {
const points = outerRing.getCoordinates()
.slice();
- for (let i = 0; i < points.length; i++) {
+ for (let i = 0; i < points.length; i += 1) {
if (adjustSign > 0 && points[i][0] < 0) {
points[i] = [points[i][0] + 360, points[i][1]];
}
diff --git a/web/js/map/measure/ui.js b/web/js/map/measure/ui.js
index db582cc34..c834a3294 100644
--- a/web/js/map/measure/ui.js
+++ b/web/js/map/measure/ui.js
@@ -21,7 +21,7 @@ import {
} from './util';
import { toggleMeasureActive } from '../../modules/measure/actions';
-export function measure(map, mapUiEvents, store) {
+export default function measure(map, mapUiEvents, store) {
let draw;
let sketch;
let measureTooltipElement;
diff --git a/web/js/map/model.js b/web/js/map/model.js
index 0eb7b6e8a..2738f5aad 100644
--- a/web/js/map/model.js
+++ b/web/js/map/model.js
@@ -5,7 +5,7 @@ import lodashClone from 'lodash/clone';
import { intersects } from 'ol/extent';
import util from '../util/util';
-export function mapModel(models, config) {
+export default function mapModel(models, config) {
const self = {};
self.extent = null;
diff --git a/web/js/map/natural-events/markers.js b/web/js/map/natural-events/markers.js
index 7bc8c579f..21a3b859f 100644
--- a/web/js/map/natural-events/markers.js
+++ b/web/js/map/natural-events/markers.js
@@ -113,7 +113,7 @@ export default function markers(ui, store) {
pinEl.addEventListener(
type,
(e) => {
- moveCount++;
+ moveCount += 1;
if (moveCount > 2) {
willSelect = false;
}
diff --git a/web/js/map/natural-events/track.js b/web/js/map/natural-events/track.js
index a460f5700..7a1b05bfd 100644
--- a/web/js/map/natural-events/track.js
+++ b/web/js/map/natural-events/track.js
@@ -13,7 +13,7 @@ import {
debounce as lodashDebounce,
} from 'lodash';
-import { naturalEventsUtilGetEventById } from './util';
+import naturalEventsUtilGetEventById from './util';
import {
naturalEventsClusterPointToGeoJSON,
naturalEventsClusterGetPoints,
@@ -319,9 +319,6 @@ const createTrack = function(proj, eventObj, map, selectedDate, callback) {
let pointObject = {};
const geoJSONPointsBeforeSelected = [];
const geoJSONPointsAfterSelected = [];
- let clustersBeforeSelected;
- let clustersAfterSelected;
-
let selectedPoint;
let clusters;
let afterSelected = false;
@@ -370,13 +367,13 @@ const createTrack = function(proj, eventObj, map, selectedDate, callback) {
secondClusterObj.options.setGeo();
}
- clustersBeforeSelected = naturalEventsClusterGetPoints(
+ const clustersBeforeSelected = naturalEventsClusterGetPoints(
firstClusterObj,
geoJSONPointsBeforeSelected,
zoom,
extent,
);
- clustersAfterSelected = naturalEventsClusterGetPoints(
+ const clustersAfterSelected = naturalEventsClusterGetPoints(
secondClusterObj,
geoJSONPointsAfterSelected,
zoom,
diff --git a/web/js/map/natural-events/ui.js b/web/js/map/natural-events/ui.js
index 70762221c..f7e72e26d 100644
--- a/web/js/map/natural-events/ui.js
+++ b/web/js/map/natural-events/ui.js
@@ -5,7 +5,7 @@ import markers from './markers';
import track from './track';
import wvui from '../../ui/ui';
import util from '../../util/util';
-import { naturalEventsUtilGetEventById } from './util';
+import naturalEventsUtilGetEventById from './util';
import { CHANGE_TAB as CHANGE_SIDEBAR_TAB } from '../../modules/sidebar/constants';
import * as EVENT_CONSTANTS from '../../modules/natural-events/constants';
import { activateLayersForEventCategory } from '../../modules/layers/actions';
@@ -395,7 +395,7 @@ export default function naturalEventsUI(ui, config, store, models) {
if (isVisible || isSelectedEvent) {
visibleListEvents[naturalEvent.id] = true;
} else {
- hiddenEventsCounter++;
+ hiddenEventsCounter += 1;
}
});
diff --git a/web/js/map/natural-events/util.js b/web/js/map/natural-events/util.js
index b9bed82de..01531c195 100644
--- a/web/js/map/natural-events/util.js
+++ b/web/js/map/natural-events/util.js
@@ -7,6 +7,6 @@ import lodashFind from 'lodash/find';
* @param {String} id Event Id
* @return {Object} Eonet Event Object
*/
-export function naturalEventsUtilGetEventById(events, id) {
+export default function naturalEventsUtilGetEventById(events, id) {
return lodashFind(events, (e) => e.id === id);
}
diff --git a/web/js/map/precachetile.js b/web/js/map/precachetile.js
index faec4a03a..f4c7b00eb 100644
--- a/web/js/map/precachetile.js
+++ b/web/js/map/precachetile.js
@@ -2,7 +2,7 @@ import lodashEach from 'lodash/each';
import * as olExtent from 'ol/extent';
import OlRendererCanvasTileLayer from 'ol/renderer/canvas/TileLayer';
-export function mapPrecacheTile(models, config, cache, parent) {
+export default function mapPrecacheTile(models, config, cache, parent) {
/**
* Loads the layers that are needed for any one date.
* Checks the cache to see if a layer has already been added to cache.
@@ -13,23 +13,14 @@ export function mapPrecacheTile(models, config, cache, parent) {
*/
/* eslint-disable no-restricted-globals */
self.promiseDay = function(date) {
- let viewState;
- let frameState;
- let pixelRatio;
- let layers;
- let map;
- let promiseArray;
-
- layers = getActiveLayersWithData(date);
- map = parent.selected;
- frameState = parent.selected.frameState_; // OL object describing the current map frame
- pixelRatio = frameState.pixelRatio;
- viewState = frameState.viewState;
- promiseArray = layers.map((def) => {
- let key;
+ const layers = getActiveLayersWithData(date);
+ const map = parent.selected;
+ const frameState = parent.selected.frameState_; // OL object describing the current map frame
+ const { pixelRatio } = frameState;
+ const { viewState } = frameState;
+ const promiseArray = layers.map((def) => {
let layer;
-
- key = parent.layerKey(def, {
+ const key = parent.layerKey(def, {
date,
});
layer = cache.getItem(key);
@@ -57,9 +48,8 @@ export function mapPrecacheTile(models, config, cache, parent) {
* @return {array} An array of visible layers within the date.
*/
const getActiveLayersWithData = function(date) {
- let layers;
const arra = [];
- layers = models.layers.get();
+ const layers = models.layers.get();
lodashEach(layers, (layer) => {
if (layer.visible && new Date(layer.startDate > date)) {
arra.push(layer);
@@ -125,8 +115,7 @@ export function mapPrecacheTile(models, config, cache, parent) {
const promiseLayerGroup = function(layer, viewState, pixelRatio, map) {
let extent;
return new Promise((resolve, reject) => {
- let layers; let
- layerPromiseArray;
+ let layers;
// Current layer's 3 layer array (prev, current, next days)
layers = layer.values_.layers;
if (layer.values_.layers) {
@@ -136,7 +125,7 @@ export function mapPrecacheTile(models, config, cache, parent) {
}
// Calculate the extent of each layer in the layer group
// and create a promiseTileLayer for prev, current, next day
- layerPromiseArray = layers.map((layer) => {
+ const layerPromiseArray = layers.map((layer) => {
extent = calculateExtent(
layer.getExtent(),
map.getView().calculateExtent(map.getSize()),
@@ -180,8 +169,7 @@ export function mapPrecacheTile(models, config, cache, parent) {
renderer.zDirection,
);
tileGrid.forEachTileCoord(extent, currentZ, (tileCoord) => {
- let tile;
- tile = tileSource.getTile(
+ const tile = tileSource.getTile(
tileCoord[0],
tileCoord[1],
tileCoord[2],
@@ -191,7 +179,7 @@ export function mapPrecacheTile(models, config, cache, parent) {
tile.load();
const loader = function(e) {
if (e.type === 'tileloadend') {
- --i;
+ i -= 1;
if (i === 0) {
resolve();
}
@@ -204,7 +192,7 @@ export function mapPrecacheTile(models, config, cache, parent) {
};
tileSource.on('tileloadend', loader);
tileSource.on('tileloaderror', loader);
- ++i;
+ i += 1;
});
}
});
diff --git a/web/js/map/rotation.js b/web/js/map/rotation.js
index cae86020e..0c86ef6cd 100644
--- a/web/js/map/rotation.js
+++ b/web/js/map/rotation.js
@@ -3,7 +3,7 @@ import { debounce } from 'lodash';
import util from '../util/util';
import { faIconUndoSVGDomEl, faIconRedoSVGDomEl } from './fa-map-icons';
-export function MapRotate(ui, models, store) {
+export default function MapRotate(ui, models, store) {
this.evts = util.events();
this.intervalId = null;
const self = this;
@@ -184,15 +184,12 @@ export function MapRotate(ui, models, store) {
* @returns {void}
*/
this.updateRotation = function() {
- let radians; let currentView; let
- currentDeg;
-
- currentView = ui.selected.getView();
- radians = currentView.getRotation();
+ const currentView = ui.selected.getView();
+ const radians = currentView.getRotation();
debounceRotationDispatcher(radians);
self.setResetButton(radians);
- currentDeg = currentView.getRotation() * (180.0 / Math.PI);
+ const currentDeg = currentView.getRotation() * (180.0 / Math.PI);
this.saveRotation(currentDeg, currentView);
};
diff --git a/web/js/map/runningdata.js b/web/js/map/runningdata.js
index 4ff521cf3..66284993a 100644
--- a/web/js/map/runningdata.js
+++ b/web/js/map/runningdata.js
@@ -13,10 +13,8 @@ import {
isFromActiveCompareRegion,
} from '../modules/compare/util';
-export function MapRunningData(models, compareUi, store) {
- let self;
-
- self = this;
+export default function MapRunningData(models, compareUi, store) {
+ const self = this;
let dataObj = {};
/**
* Clear running data value
diff --git a/web/js/map/ui.js b/web/js/map/ui.js
index 2993a4518..0299749ab 100644
--- a/web/js/map/ui.js
+++ b/web/js/map/ui.js
@@ -27,14 +27,14 @@ import OlLayerGroup from 'ol/layer/Group';
import * as olProj from 'ol/proj';
import { CALCULATE_RESPONSIVE_STATE } from 'redux-responsive';
import Cache from 'cachai';
-import { MapRotate } from './rotation';
-import { mapDateLineBuilder } from './datelinebuilder';
-import { mapLayerBuilder } from './layerbuilder';
-import { MapRunningData } from './runningdata';
-import { mapPrecacheTile } from './precachetile';
+import MapRotate from './rotation';
+import mapDateLineBuilder from './datelinebuilder';
+import mapLayerBuilder from './layerbuilder';
+import MapRunningData from './runningdata';
+import mapPrecacheTile from './precachetile';
import { mapUtilZoomAction, getActiveLayerGroup } from './util';
-import { mapCompare } from './compare/compare';
-import { measure } from './measure/ui';
+import mapCompare from './compare/compare';
+import measure from './measure/ui';
import { LOCATION_POP_ACTION } from '../redux-location-state-customs';
import { CHANGE_PROJECTION } from '../modules/projection/constants';
import { SELECT_DATE } from '../modules/date/constants';
@@ -58,9 +58,7 @@ import { getLeadingExtent } from '../modules/map/util';
import { updateVectorSelection } from '../modules/vector-styles/util';
import { faIconPlusSVGDomEl, faIconMinusSVGDomEl } from './fa-map-icons';
-export function mapui(models, config, store, ui) {
- let layerBuilder; let
- createLayer;
+export default function mapui(models, config, store, ui) {
const id = 'wv-map';
const selector = `#${id}`;
const animationDuration = 250;
@@ -85,7 +83,7 @@ export function mapui(models, config, store, ui) {
self.proj = {}; // One map for each projection
self.selected = null; // The map for the selected projection
self.events = util.events();
- layerBuilder = self.layerBuilder = mapLayerBuilder(
+ const layerBuilder = self.layerBuilder = mapLayerBuilder(
models,
config,
cache,
@@ -93,7 +91,7 @@ export function mapui(models, config, store, ui) {
store,
);
self.layerKey = layerBuilder.layerKey;
- createLayer = self.createLayer = layerBuilder.createLayer;
+ const createLayer = self.createLayer = layerBuilder.createLayer;
self.promiseDay = precache.promiseDay;
self.selectedVectors = {};
/**
@@ -895,15 +893,8 @@ export function mapui(models, config, store, ui) {
const { date, compare } = state;
const activeDate = compare.isCompareA ? 'selected' : 'selectedB';
dateSelected = dateSelected || date[activeDate];
- let id;
- let $map;
- let scaleMetric;
- let scaleImperial;
- let rotateInteraction;
- let map;
- let mobileRotation;
- id = `wv-map-${proj.id}`;
- $map = $('<div></div>')
+ const id = `wv-map-${proj.id}`;
+ const $map = $('<div></div>')
.attr('id', id)
.attr('data-proj', proj.id)
.addClass('wv-map')
@@ -911,23 +902,22 @@ export function mapui(models, config, store, ui) {
$(selector).append($map);
// Create two specific controls
- scaleMetric = new OlControlScaleLine({
+ const scaleMetric = new OlControlScaleLine({
className: 'wv-map-scale-metric',
units: 'metric',
});
- scaleImperial = new OlControlScaleLine({
+ const scaleImperial = new OlControlScaleLine({
className: 'wv-map-scale-imperial',
units: 'imperial',
});
-
- rotateInteraction = new OlInteractionDragRotate({
+ const rotateInteraction = new OlInteractionDragRotate({
condition: altKeyOnly,
duration: animationDuration,
});
- mobileRotation = new OlInteractionPinchRotate({
+ const mobileRotation = new OlInteractionPinchRotate({
duration: animationDuration,
});
- map = new OlMap({
+ const map = new OlMap({
view: new OlView({
maxResolution: proj.resolutions[0],
projection: olProj.get(proj.crs),
@@ -997,6 +987,8 @@ export function mapui(models, config, store, ui) {
self.mapIsbeingZoomed = true;
self.events.trigger('zooming');
break;
+ default:
+ break;
}
});
map.on('moveend', (e) => {
@@ -1118,8 +1110,6 @@ export function mapui(models, config, store, ui) {
let hoverThrottle;
function onMouseMove(e) {
- let coords;
- let pixels;
const state = store.getState();
if (self.mapIsbeingZoomed) return;
if (compareMapUi && compareMapUi.dragging) return;
@@ -1134,8 +1124,8 @@ export function mapui(models, config, store, ui) {
) {
return;
}
- pixels = map.getEventPixel(e.originalEvent);
- coords = map.getCoordinateFromPixel(pixels);
+ const pixels = map.getEventPixel(e.originalEvent);
+ const coords = map.getCoordinateFromPixel(pixels);
if (!coords) return;
// setting a limit on running-data retrievel
diff --git a/web/js/map/util.js b/web/js/map/util.js
index b8ec6264f..f1455b127 100644
--- a/web/js/map/util.js
+++ b/web/js/map/util.js
@@ -28,7 +28,7 @@ export function mapUtilZoomAction(map, amount, duration, center) {
export function getActiveLayerGroup(map, layerGroupString) {
let group = null;
const array = map.getLayers().getArray();
- for (let i = 0, len = array.length; i < len; i++) {
+ for (let i = 0, len = array.length; i < len; i += 1) {
const layerGroup = array[i];
if (layerGroup.get('group') === layerGroupString) {
group = layerGroup;
diff --git a/web/js/modules/animation/selectors.js b/web/js/modules/animation/selectors.js
index adf9a1aab..2edeb6c76 100644
--- a/web/js/modules/animation/selectors.js
+++ b/web/js/modules/animation/selectors.js
@@ -17,7 +17,7 @@ import { timeScaleFromNumberKey } from '../date/constants';
* @returns {array} array of jpg urls
*
*/
-export function getImageArray(
+export default function getImageArray(
gifComponentState,
gifComponentProps,
dimensions,
@@ -47,7 +47,7 @@ export function getImageArray(
: timeScaleFromNumberKey[interval];
while (current <= toDate) {
- j++;
+ j += 1;
if (isSubDaily) {
strDate = util.toISOStringMinutes(current);
} else {
diff --git a/web/js/modules/animation/util.js b/web/js/modules/animation/util.js
index 94941d7cf..09f01c668 100644
--- a/web/js/modules/animation/util.js
+++ b/web/js/modules/animation/util.js
@@ -73,7 +73,6 @@ export function getStampProps(
}
export function svgToPng(svgURL, stampHeight) {
- let newImage;
const canvasEl = document.createElement('canvas');
const canvgOptions = {
log: false,
@@ -81,7 +80,7 @@ export function svgToPng(svgURL, stampHeight) {
scaleHeight: stampHeight,
};
canvg(canvasEl, svgURL, canvgOptions);
- newImage = new Image();
+ const newImage = new Image();
newImage.src = canvasEl.toDataURL('image/png');
newImage.width = canvasEl.width;
newImage.height = canvasEl.height;
@@ -114,6 +113,8 @@ export function getMaxQueueLength(speed) {
case speed > 0 && speed <= 3:
queueLength = 10;
break;
+ default:
+ break;
}
return queueLength;
}
@@ -135,7 +136,7 @@ export function getQueueLength(startDate, endDate, speed, interval, delta) {
let i = 0;
const maxQueueLength = getMaxQueueLength(speed);
while (i <= maxQueueLength) {
- i++;
+ i += 1;
day = util.dateAdd(day, interval, delta);
if (day > endDate) {
return i;
diff --git a/web/js/modules/compare/reducers.js b/web/js/modules/compare/reducers.js
index 1f098b6e1..75f396055 100644
--- a/web/js/modules/compare/reducers.js
+++ b/web/js/modules/compare/reducers.js
@@ -38,6 +38,8 @@ export function compareReducer(state = initialCompareState, action) {
return lodashAssign({}, state, {
value: action.value,
});
+ default:
+ break;
}
return state;
}
diff --git a/web/js/modules/data/selectors.js b/web/js/modules/data/selectors.js
index 88df598f4..5e49b61f9 100644
--- a/web/js/modules/data/selectors.js
+++ b/web/js/modules/data/selectors.js
@@ -23,7 +23,7 @@ export function getSelectionCounts(layers, selectedGranules) {
}
}
for (const granule of Object.values(selectedGranules)) {
- counts[granule.product]++;
+ counts[granule.product] += 1;
}
return counts;
}
@@ -125,7 +125,7 @@ export function findAvailableProduct(layers) {
let foundProduct = null;
// Find the top most layer that has a product entry in CMR
- for (let i = layers.length - 1; i >= 0; i--) {
+ for (let i = layers.length - 1; i >= 0; i -= 1) {
if (layers[i].product) {
foundProduct = layers[i].product;
// If the layer has more than one product, select the first.
diff --git a/web/js/modules/data/util.js b/web/js/modules/data/util.js
index 563fa3766..de9ad048c 100644
--- a/web/js/modules/data/util.js
+++ b/web/js/modules/data/util.js
@@ -8,7 +8,7 @@ import { find as lodashFind, get as lodashGet } from 'lodash';
* @param {Object} state | initial state before location POP action
* @param {Object} config
*/
-export function mapLocationToDataState(
+export default function mapLocationToDataState(
parameters,
stateFromLocation,
state,
diff --git a/web/js/modules/data/util.test.js b/web/js/modules/data/util.test.js
index fb46a5244..14a4ed791 100644
--- a/web/js/modules/data/util.test.js
+++ b/web/js/modules/data/util.test.js
@@ -1,4 +1,4 @@
-import { mapLocationToDataState } from './util';
+import mapLocationToDataState from './util';
import fixtures from '../../fixtures';
const globalState = fixtures.getState();
diff --git a/web/js/modules/date/selectors.js b/web/js/modules/date/selectors.js
deleted file mode 100644
index dd453f056..000000000
--- a/web/js/modules/date/selectors.js
+++ /dev/null
@@ -1,5 +0,0 @@
-import util from '../../util/util';
-
-export function addDate(interval, amount, activeDate) {
- return util.dateAdd(activeDate, interval, amount);
-}
diff --git a/web/js/modules/feedback/actions.js b/web/js/modules/feedback/actions.js
index 51de45ff0..f1d434c0a 100644
--- a/web/js/modules/feedback/actions.js
+++ b/web/js/modules/feedback/actions.js
@@ -1,6 +1,6 @@
import { INIT_FEEDBACK } from './constants';
-export function initFeedback() {
+export default function initFeedback() {
return {
type: INIT_FEEDBACK,
};
diff --git a/web/js/modules/feedback/util.js b/web/js/modules/feedback/util.js
index 0e6fb20b0..6c8d6f862 100644
--- a/web/js/modules/feedback/util.js
+++ b/web/js/modules/feedback/util.js
@@ -7,7 +7,7 @@
import util from '../../util/util';
-export function onClickFeedback(wasInitiated) {
+export default function onClickFeedback(wasInitiated) {
if (!util.browser.small && window.feedback) {
// eslint-disable-next-line no-restricted-globals
event.preventDefault();
diff --git a/web/js/modules/image-download/util.js b/web/js/modules/image-download/util.js
index cd8983a3b..59f63d0f3 100644
--- a/web/js/modules/image-download/util.js
+++ b/web/js/modules/image-download/util.js
@@ -75,7 +75,6 @@ export function imageUtilCalculateResolution(
resolutions,
) {
let resolution;
- let resolutionEstimate;
const nZoomLevels = resolutions.length;
const currentZoom = zoom < 0 ? 0 : zoom;
const curResolution = currentZoom >= nZoomLevels
@@ -83,7 +82,7 @@ export function imageUtilCalculateResolution(
: resolutions[currentZoom];
// Estimate the option value used by "wv-image-resolution"
- resolutionEstimate = imageUtilEstimateResolution(
+ const resolutionEstimate = imageUtilEstimateResolution(
curResolution,
isGeoProjection,
);
@@ -95,7 +94,7 @@ export function imageUtilCalculateResolution(
let bestDiff = Infinity;
let bestIdx = -1;
let currDiff = 0;
- for (let i = 0; i < possibleResolutions.length; i++) {
+ for (let i = 0; i < possibleResolutions.length; i += 1) {
currDiff = Math.abs(possibleResolutions[i] - resolutionEstimate);
if (currDiff < bestDiff) {
resolution = possibleResolutions[i];
@@ -113,6 +112,9 @@ export function imageUtilCalculateResolution(
case 6:
case 7:
resolution = possibleResolutions[bestIdx - 1];
+ break;
+ default:
+ break;
}
} else {
switch (currentZoom) {
@@ -121,6 +123,9 @@ export function imageUtilCalculateResolution(
case 4:
case 5:
resolution = possibleResolutions[bestIdx - 1];
+ break;
+ default:
+ break;
}
}
}
diff --git a/web/js/modules/key-press/actions.js b/web/js/modules/key-press/actions.js
index a745e1c50..a5ce1de44 100644
--- a/web/js/modules/key-press/actions.js
+++ b/web/js/modules/key-press/actions.js
@@ -11,7 +11,7 @@ import { CLOSE as CLOSE_MODAL } from '../modal/constants';
* @param {Number} keyCode
* @param {Boolean} is shiftKey down
*/
-export function keyPress(keyCode, shiftKey, ctrlOrCmdKey) {
+export default function keyPress(keyCode, shiftKey, ctrlOrCmdKey) {
return (dispatch, getState) => {
const {
modal, animation, tour, ui,
diff --git a/web/js/modules/layers/selectors.js b/web/js/modules/layers/selectors.js
index 0c739d4df..756b23e30 100644
--- a/web/js/modules/layers/selectors.js
+++ b/web/js/modules/layers/selectors.js
@@ -92,7 +92,7 @@ function decodeHtml(html) {
*/
export function hasSubDaily(layers) {
if (layers && layers.length) {
- for (let i = 0; i < layers.length; i++) {
+ for (let i = 0; i < layers.length; i += 1) {
if (layers[i].period === 'subdaily') {
return true;
}
@@ -401,7 +401,7 @@ export function moveBefore(sourceId, targetId, layers) {
}
layers.splice(targetIndex, 0, sourceDef);
if (sourceIndex > targetIndex) {
- sourceIndex++;
+ sourceIndex += 1;
}
layers.splice(sourceIndex, 1);
return layers;
diff --git a/web/js/modules/link/util.js b/web/js/modules/link/util.js
index 5639f6b2b..af2a490cd 100644
--- a/web/js/modules/link/util.js
+++ b/web/js/modules/link/util.js
@@ -61,8 +61,9 @@ export function getSharelink(type, url) {
return redditUrlParams(url, shareMessage);
case 'email':
return emailUrlParams(shareMessage, emailBody);
+ default:
+ // return undefined
}
- return undefined;
}
export function openPromisedSocial(url, win) {
win.location.assign(url);
diff --git a/web/js/modules/map/selectors.js b/web/js/modules/map/selectors.js
index 3e2f91c99..ab864272f 100644
--- a/web/js/modules/map/selectors.js
+++ b/web/js/modules/map/selectors.js
@@ -4,7 +4,7 @@ import { promiseLayerGroup } from './util';
* @param {object} time of data to be displayed on the map.
* @return {object} Promise.all
*/
-export function promiseImageryForTime(date, layers, state) {
+export default function promiseImageryForTime(date, layers, state) {
const { map } = state;
const { cache } = map.ui;
const mapUi = map.ui;
diff --git a/web/js/modules/map/util.js b/web/js/modules/map/util.js
index d75acb6c7..d034431a7 100644
--- a/web/js/modules/map/util.js
+++ b/web/js/modules/map/util.js
@@ -158,8 +158,7 @@ export function getLeadingExtent(loadtime) {
export function promiseLayerGroup(layer, viewState, pixelRatio, map, def) {
let extent;
return new Promise((resolve, reject) => {
- let layers; let
- layerPromiseArray;
+ let layers;
// Current layer's 3 layer array (prev, current, next days)
layers = layer.values_.layers;
if (layer.values_.layers) {
@@ -169,7 +168,7 @@ export function promiseLayerGroup(layer, viewState, pixelRatio, map, def) {
}
// Calculate the extent of each layer in the layer group
// and create a promiseTileLayer for prev, current, next day
- layerPromiseArray = layers.map((layer) => {
+ const layerPromiseArray = layers.map((layer) => {
extent = calculateExtent(
layer.getExtent(),
map.getView().calculateExtent(map.getSize()),
@@ -261,8 +260,7 @@ function promiseTileLayer(layer, extent, viewState, pixelRatio) {
renderer.zDirection,
);
tileGrid.forEachTileCoord(extent, currentZ, (tileCoord) => {
- let tile;
- tile = tileSource.getTile(
+ const tile = tileSource.getTile(
tileCoord[0],
tileCoord[1],
tileCoord[2],
@@ -275,7 +273,7 @@ function promiseTileLayer(layer, extent, viewState, pixelRatio) {
const loader = function(e) {
if (e.type === 'tileloadend') {
- --i;
+ i -= 1;
if (i === 0) {
resolve();
}
@@ -288,7 +286,7 @@ function promiseTileLayer(layer, extent, viewState, pixelRatio) {
};
tileSource.on('tileloadend', loader);
tileSource.on('tileloaderror', loader);
- ++i;
+ i += 1;
});
}
});
diff --git a/web/js/modules/notifications/util.js b/web/js/modules/notifications/util.js
index 932c760d5..f36e5c16d 100644
--- a/web/js/modules/notifications/util.js
+++ b/web/js/modules/notifications/util.js
@@ -13,7 +13,7 @@ export function separateByType(array) {
const alerts = [];
const outages = [];
- for (let i = 0, len = array.length; i < len; i++) {
+ for (let i = 0, len = array.length; i < len; i += 1) {
subObj = array[i];
type = subObj.notification_type;
@@ -94,15 +94,12 @@ export function getPriority(sortedNotifications) {
* @returns {Number}
*/
export function getCount(sortedNotifications) {
- let outageCount; let messageCount; let
- alertCount;
-
- messageCount = getNumberOfTypeNotSeen(
+ const messageCount = getNumberOfTypeNotSeen(
'message',
sortedNotifications.messages,
); // Number of messages not yet seen
- alertCount = getNumberOfTypeNotSeen('alert', sortedNotifications.alerts); // Number of alerts not yet seen
- outageCount = getNumberOfTypeNotSeen('outage', sortedNotifications.outages); // Number of outages not yet seen
+ const alertCount = getNumberOfTypeNotSeen('alert', sortedNotifications.alerts); // Number of alerts not yet seen
+ const outageCount = getNumberOfTypeNotSeen('outage', sortedNotifications.outages); // Number of outages not yet seen
return messageCount + outageCount + alertCount;
}
@@ -137,19 +134,16 @@ export function getNumberOfTypeNotSeen(type, arra) {
return arra.length;
}
const storageItem = localStorage.getItem(type);
- let count; let
- len;
-
- len = arra.length;
- count = 0;
+ const len = arra.length;
+ let count = 0;
if (!storageItem) {
return len;
}
- for (let i = 0; i < len; i++) {
+ for (let i = 0; i < len; i += 1) {
if (new Date(storageItem) < new Date(arra[i].created_at)) {
- count++;
+ count += 1;
} else {
return count;
}
@@ -165,13 +159,10 @@ export function getNumberOfTypeNotSeen(type, arra) {
* @returns {void}
*/
function objectAlreadySeen(obj) {
- let fieldExists; let fieldValueMatches; let type; let
- idString;
-
- type = obj.notification_type;
- idString = obj.created_at.toString();
- fieldValueMatches = false;
- fieldExists = util.browser.localStorage && !!localStorage.getItem(type);
+ const type = obj.notification_type;
+ const idString = obj.created_at.toString();
+ let fieldValueMatches = false;
+ const fieldExists = util.browser.localStorage && !!localStorage.getItem(type);
if (fieldExists) {
fieldValueMatches = localStorageValueMatches(type, idString);
diff --git a/web/js/modules/palettes/selectors.js b/web/js/modules/palettes/selectors.js
index 5a3efaffd..cf610ba3b 100644
--- a/web/js/modules/palettes/selectors.js
+++ b/web/js/modules/palettes/selectors.js
@@ -59,7 +59,7 @@ export function getRenderedPalette(layerId, index, state) {
export function getPaletteLegends(layerId, groupName, state) {
const paletteLegends = [];
const count = getCount(layerId, state);
- for (let i = 0; i < count; i++) {
+ for (let i = 0; i < count; i += 1) {
paletteLegends.push(getPaletteLegend(layerId, i, groupName, state));
}
return paletteLegends;
@@ -258,10 +258,8 @@ const toggleLookup = function(layerId, palettesObj, state) {
if (disabled.includes(index)) {
targetColor = '00000000';
} else {
- let sourcePercent; let
- targetIndex;
- sourcePercent = index / sourceCount;
- targetIndex = Math.floor(sourcePercent * targetCount);
+ const sourcePercent = index / sourceCount;
+ const targetIndex = Math.floor(sourcePercent * targetCount);
targetColor = target[targetIndex];
}
const colormapRef = entries.refs[index];
@@ -381,7 +379,7 @@ export function initDisabledSelector(
state,
) {
const disabled = disabledStr.split('-');
- for (let i = 0; i < disabled.length; i++) { disabled[i] = +disabled[i]; }
+ for (let i = 0; i < disabled.length; i += 1) { disabled[i] = +disabled[i]; }
let newPalettes = prepare(layerId, palettes, state);
newPalettes = update(newPalettes, {
[layerId]: {
diff --git a/web/js/modules/palettes/util.js b/web/js/modules/palettes/util.js
index 1ffad2b02..c38c5fd99 100644
--- a/web/js/modules/palettes/util.js
+++ b/web/js/modules/palettes/util.js
@@ -239,7 +239,7 @@ export function getPaletteAttributeArray(layerId, palettes, state) {
let squashObj = lodashAssign({}, { key: 'squash', array: [] }, DEFAULT_OBJ);
let disabledObj = lodashAssign({}, { key: 'disabled', array: [] }, DEFAULT_OBJ);
const attrArray = [];
- for (let i = 0; i < count; i++) {
+ for (let i = 0; i < count; i += 1) {
if (!palettes[layerId].maps[i]) {
console.warn('NO PALETTE');
}
@@ -426,7 +426,7 @@ export function loadPalettes(permlinkState, state) {
}
if (min.length > 0 || max.length > 0) {
count = getCount(layerId, state);
- for (let i = 0; i < count; i++) {
+ for (let i = 0; i < count; i += 1) {
const vmin = min.length > 0 ? min[i] : undefined;
const vmax = max.length > 0 ? max[i] : undefined;
const vsquash = squash.length > 0 ? squash[i] : undefined;
@@ -533,7 +533,7 @@ export function hasCustomPaletteInActiveProjection(
activeLayers,
activePalettes,
) {
- for (let i = 0, len = activeLayers.length; i < len; i++) {
+ for (let i = 0, len = activeLayers.length; i < len; i += 1) {
if (activePalettes[activeLayers[i].id]) {
return true;
}
diff --git a/web/js/modules/projection/actions.js b/web/js/modules/projection/actions.js
index 10f54c1a0..7b849457b 100644
--- a/web/js/modules/projection/actions.js
+++ b/web/js/modules/projection/actions.js
@@ -1,6 +1,6 @@
import { CHANGE_PROJECTION } from './constants';
-export function changeProjection(id) {
+export default function changeProjection(id) {
return (dispatch, getState) => {
const { config } = getState();
const proj = config.projections[id];
diff --git a/web/js/modules/projection/constants.js b/web/js/modules/projection/constants.js
index 7606ac3ef..7621d89d4 100644
--- a/web/js/modules/projection/constants.js
+++ b/web/js/modules/projection/constants.js
@@ -1 +1,2 @@
+// eslint-disable-next-line import/prefer-default-export
export const CHANGE_PROJECTION = 'PROJECTION/CHANGE_PROJECTION';
diff --git a/web/js/modules/sidebar/util.js b/web/js/modules/sidebar/util.js
index 5377d9950..c061ff560 100644
--- a/web/js/modules/sidebar/util.js
+++ b/web/js/modules/sidebar/util.js
@@ -9,7 +9,7 @@ import { assign as lodashAssign, get } from 'lodash';
* @param {Object} state | initial state before location POP action
* @param {Object} config
*/
-export function mapLocationToSidebarState(
+export default function mapLocationToSidebarState(
parameters,
stateFromLocation,
state,
diff --git a/web/js/modules/ui/actions.js b/web/js/modules/ui/actions.js
index 242feb688..3b40b20aa 100644
--- a/web/js/modules/ui/actions.js
+++ b/web/js/modules/ui/actions.js
@@ -1,7 +1,7 @@
import { TOGGLE_DISTRACTION_FREE_MODE } from './constants';
import { CLOSE as CLOSE_MODAL } from '../modal/constants';
-export function toggleDistractionFreeMode() {
+export default function toggleDistractionFreeMode() {
return (dispatch, getState) => {
const { modal, ui } = getState();
const { isDistractionFreeModeActive } = ui;
diff --git a/web/js/modules/ui/constants.js b/web/js/modules/ui/constants.js
index 107968a74..3a58f1ab2 100644
--- a/web/js/modules/ui/constants.js
+++ b/web/js/modules/ui/constants.js
@@ -1 +1,2 @@
+// eslint-disable-next-line import/prefer-default-export
export const TOGGLE_DISTRACTION_FREE_MODE = 'UI/TOGGLE_DISTRACTION_FREE_MODE';
diff --git a/web/js/modules/vector-styles/selectors.js b/web/js/modules/vector-styles/selectors.js
index 136c8feb2..0b4f6972c 100644
--- a/web/js/modules/vector-styles/selectors.js
+++ b/web/js/modules/vector-styles/selectors.js
@@ -203,7 +203,6 @@ export function isActive(layerId, group, state) {
}
export function clearStyleFunction(def, vectorStyleId, vectorStyles, layer, state) {
- let styleFunction;
const layerId = def.id;
const glStyle = vectorStyles[layerId];
const olMap = lodashGet(state, 'legacy.map.ui.selected');
@@ -214,7 +213,7 @@ export function clearStyleFunction(def, vectorStyleId, vectorStyles, layer, stat
}
});
}
- styleFunction = stylefunction(layer, glStyle, vectorStyleId);
+ const styleFunction = stylefunction(layer, glStyle, vectorStyleId);
if (glStyle.name === 'Orbit Tracks') {
// Filter time by 5 mins
layer.setStyle((feature, resolution) => {
diff --git a/web/js/ol/lookupimagetile.js b/web/js/ol/lookupimagetile.js
index 88837853e..6b3d7d327 100644
--- a/web/js/ol/lookupimagetile.js
+++ b/web/js/ol/lookupimagetile.js
@@ -51,7 +51,7 @@ LookupImageTile.prototype.load = function() {
}
};
-export function lookupFactory(lookup, sourceOptions) {
+export default function lookupFactory(lookup, sourceOptions) {
return function(tileCoord, state, src, crossOrigin, tileLoadFunction) {
return new LookupImageTile(lookup, tileCoord, state, src,
crossOrigin, tileLoadFunction, sourceOptions);
diff --git a/web/js/parse.js b/web/js/parse.js
index 4214d7ec6..568130eb7 100644
--- a/web/js/parse.js
+++ b/web/js/parse.js
@@ -1,7 +1,7 @@
import { each as lodashEach } from 'lodash';
import { mapParser } from './map/map';
-export function parse(parameters, config, errors) {
+export default function parse(parameters, config, errors) {
const state = parameters;
const parsers = [mapParser];
diff --git a/web/js/polyfill.js b/web/js/polyfill.js
index e75d7b147..f5ff31607 100644
--- a/web/js/polyfill.js
+++ b/web/js/polyfill.js
@@ -8,7 +8,7 @@
/* eslint-disable no-extend-native */
-export function polyfill() {
+export default function polyfill() {
/*
* Date.toISOString
*
diff --git a/web/js/util/browser.js b/web/js/util/browser.js
index c2791fde6..3526dd740 100644
--- a/web/js/util/browser.js
+++ b/web/js/util/browser.js
@@ -232,9 +232,8 @@ export default (function() {
}
try {
const uid = new Date().toString();
- let result;
localStorage.setItem(uid, uid);
- result = localStorage.getItem(uid) === uid;
+ const result = localStorage.getItem(uid) === uid;
localStorage.removeItem(uid);
return result && true;
} catch (error) {
diff --git a/web/js/util/events.js b/web/js/util/events.js
index 0d444688e..9555346c6 100644
--- a/web/js/util/events.js
+++ b/web/js/util/events.js
@@ -1,7 +1,7 @@
import lodashEach from 'lodash/each';
import lodashPull from 'lodash/pull';
-export function events() {
+export default function events() {
const self = {};
// Object of event types. Each event type is an array of listeners.
diff --git a/web/js/util/events.test.js b/web/js/util/events.test.js
index d78471d69..a2c8864f7 100644
--- a/web/js/util/events.test.js
+++ b/web/js/util/events.test.js
@@ -1,4 +1,4 @@
-import { events } from './events';
+import events from './events';
test('triggers an event', () => {
const e = events();
diff --git a/web/js/util/util.js b/web/js/util/util.js
index f2df1bfca..7edfedec4 100644
--- a/web/js/util/util.js
+++ b/web/js/util/util.js
@@ -7,7 +7,7 @@ import Cache from 'cachai';
import moment from 'moment';
import wvui from '../ui/ui';
import browser from './browser';
-import { events } from './events';
+import events from './events';
import load from './load';
export default (function(self) {
@@ -48,7 +48,7 @@ export default (function(self) {
self.repeat = function(value, length) {
let result = '';
- for (let i = 0; i < length; i++) {
+ for (let i = 0; i < length; i += 1) {
result += value;
}
return result;
@@ -97,7 +97,7 @@ export default (function(self) {
}
const parameters = queryString.split('&');
const result = {};
- for (let i = 0; i < parameters.length; i++) {
+ for (let i = 0; i < parameters.length; i += 1) {
const index = parameters[i].indexOf('=');
const key = parameters[i].substring(0, index);
const value = parameters[i].substring(index + 1);
@@ -342,10 +342,8 @@ export default (function(self) {
* @return {string} Julian date string in the form of `YYYYDDD`
*/
self.toJulianDate = function(date) {
- let jStart; let
- jDate;
- jStart = self.parseDateUTC(`${date.getUTCFullYear()}-01-01`);
- jDate = `00${1 + Math.ceil((date.getTime() - jStart) / 86400000)}`;
+ const jStart = self.parseDateUTC(`${date.getUTCFullYear()}-01-01`);
+ const jDate = `00${1 + Math.ceil((date.getTime() - jStart) / 86400000)}`;
return date.getUTCFullYear() + jDate.substr(jDate.length - 3);
};
@@ -482,7 +480,7 @@ export default (function(self) {
let i = 1;
let currentDate = start;
while (currentDate < end) {
- i++;
+ i += 1;
currentDate = self.dateAdd(currentDate, interval, increment);
// if checking for a max number limit, break out after reaching it
if (maxToCheck && i >= maxToCheck) {
@@ -507,10 +505,8 @@ export default (function(self) {
};
self.daysInYear = function(date) {
- let jStart; let
- jDate;
- jStart = self.parseDateUTC(`${date.getUTCFullYear()}-01-01`);
- jDate = `00${Math.ceil((date.getTime() - jStart) / 86400000) + 1}`;
+ const jStart = self.parseDateUTC(`${date.getUTCFullYear()}-01-01`);
+ const jDate = `00${Math.ceil((date.getTime() - jStart) / 86400000) + 1}`;
return jDate.substr(jDate.length - 3);
};
@@ -1090,7 +1086,7 @@ export default (function(self) {
// usage example: wv.util.format("{1}{2}",'World','view')
self.format = function(...args) {
let [formatted] = args;
- for (let i = 1; i < args.length; i++) {
+ for (let i = 1; i < args.length; i += 1) {
const regexp = new RegExp(`\\{${i}\\}`, 'gi');
formatted = formatted.replace(regexp, args[i]);
}
@@ -1121,8 +1117,8 @@ export default (function(self) {
let month1 = startDate.getMonth();
let month2 = endDate.getMonth();
if (month1 === 0) {
- month1++;
- month2++;
+ month1 += 1;
+ month2 += 1;
}
const numberOfMonths = (year2 - year1) * 12 + (month2 - month1);
return numberOfMonths;
@@ -1172,7 +1168,7 @@ export default (function(self) {
* @return {Number}
*/
self.stringInArray = function(arra, value) {
- for (let i = 0, len = arra.length; i < len; i++) {
+ for (let i = 0, len = arra.length; i < len; i += 1) {
if (arra[i] === value) {
return i;
}