Interactive interface for browsing global, full-resolution satellite imagery
Add animation redux rendering #1623 #1622
Benjamin King466686c1f29a
diff --git a/web/js/app.js b/web/js/app.jsindex ce4218aa9..e9698f69d 100644--- a/web/js/app.js+++ b/web/js/app.js@@ -83,9 +83,18 @@ class App extends React.Component {constructor(props) {super(props);this.onload();+ this.handleKeyPress = this.handleKeyPress.bind(this);+ }+ handleKeyPress(event) {+ this.props.keyPressAction(event.keyCode);+ }+ componentDidMount() {+ document.addEventListener('keypress', this.handleKeyPress);+ }+ componentWillUnmount() {+ document.removeEventListener('keypress', this.handleKeyPress);}render() {- // const { config } = this.props;return (<div className="wv-content" id="wv-content" data-role="content"><Toolbar />@@ -101,9 +110,6 @@ class App extends React.Component {<div id="timewheels" style={{ display: 'none' }} /><Timeline /><OlCoordinates mouseEvents={this.props.mapMouseEvents} />- {/* <div id="wv-animation-widet-case"> */}- {/* {config.features.animation ? <AnimationWidget /> : ''} */}- {/* </div> */}<Modal /><ErrorBoundary><Debug parameters={this.props.parameters} />@@ -169,6 +175,9 @@ const mapDispatchToProps = dispatch => ({updateLegacyInitComplete: () => {dispatch(updateLegacyInitComplete());},+ keyPressAction: keyCode => {+ dispatch({ type: 'KEY_PRESS_ACTION', keyCode });+ },screenResize: (width, height) => {dispatch(calculateResponsiveState(window));}@@ -179,5 +188,6 @@ export default connect(mapDispatchToProps)(App);App.propTypes = {- mapMouseEvents: PropTypes.object+ mapMouseEvents: PropTypes.object,+ keyPressAction: PropTypes.func};diff --git a/web/js/components/animation-widget/animation-widget.js b/web/js/components/animation-widget/animation-widget.jsindex d07f1e914..d67ff3391 100644--- a/web/js/components/animation-widget/animation-widget.js+++ b/web/js/components/animation-widget/animation-widget.js@@ -134,7 +134,8 @@ class AnimationWidget extends React.Component {<divid="wv-animation-widget"className={- 'wv-animation-widget' + (this.state.hasSubdailyLayers ? ' subdaily' : '')+ 'wv-animation-widget' ++ (this.state.hasSubdailyLayers ? ' subdaily' : '')}><AnimWidgetHeaderdiff --git a/web/js/components/animation-widget/play-queue.js b/web/js/components/animation-widget/play-queue.jsindex 56b2e9c21..bac3e7b00 100644--- a/web/js/components/animation-widget/play-queue.js+++ b/web/js/components/animation-widget/play-queue.js@@ -1,9 +1,11 @@import React from 'react';import PropTypes from 'prop-types';import { Modal, ModalBody, ModalHeader } from 'reactstrap';+import { isEmpty as lodashIsEmpty } from 'lodash';import Spinner from 'react-loader';import util from '../../util/util';-import * as animUtil from '../../modules/animation/util';+import Queue from 'promise-queue';+import { getLayersActiveAtDate } from '../../modules/date/util';/** Preload and play animation@@ -12,11 +14,330 @@ import * as animUtil from '../../modules/animation/util';* @extends React.Component*/class PlayAnimation extends React.Component {+ constructor(props) {+ super(props);+ this.state = {+ isPlaying: false+ };+ this.queue = new Queue(5, Infinity);+ this.preloadObject = {};+ this.inQueueObject = {};+ this.preloadedArray = [];+ this.pastDates = {};+ this.interval = 0;+ this.currentPlayingDate = this.getStartDate();+ this.checkQueue(props.queueLength, this.currentPlayingDate);+ this.checkShouldPlay();+ }+ componentWillUnmount() {+ if (this.interval) {+ clearInterval(this.interval);+ }+ }/*- * gets next date to add to- * queue+ * Determines whether to start at+ * current date or to start at the+ * selected start date*- * @method addItemToQueue+ * @method getStartDate+ * @static+ *+ * @returns {string} ISO string Date+ *+ */+ getStartDate() {+ const { endDate, startDate, currentDate } = this.props;++ // if not index+1 of 4 ('10-Minute'), zero out start/end times and resave++ // # causes UTC zeroing of dates in date model - need to rework if this+ // # functionality is still going to be used or handle zeroing out+ // # at actual layer building only+ // if (dateSelectedZoom < 4) {+ // let zeroDate = dateModel.selected;+ // debugger;+ // util.clearTimeUTC(zeroDate);+ // util.clearTimeUTC(startDate);+ // dateModel.selected = zeroDate;+ // }+ if (currentDate > startDate && this.nextDate(currentDate) < endDate) {+ return util.toISOStringSeconds(this.nextDate(currentDate));+ }+ return util.toISOStringSeconds(startDate);+ }+ /*+ * Gets the last date that should be added+ * to the queuer+ *+ * @method getLastBufferDateStr+ * @static+ *+ * @param currentDate {object} JS date+ * @param startDate {object} JS date+ * @param endDate {object} JS date+ *+ * @returns {string} Date string+ *+ */+ getLastBufferDateStr = function(currentDate, startDate, endDate) {+ const { queueLength, loop } = this.props;+ var day = currentDate;+ var i = 1;++ while (i < queueLength) {+ if (this.nextDate(day) > endDate) {+ if (!loop) {+ return util.toISOStringSeconds(day);+ }+ day = startDate;+ } else {+ day = this.nextDate(day);+ }+ i++;+ }+ return util.toISOStringSeconds(day);+ };++ /*+ * adds dates to precache queuer+ *+ * @method initialPreload+ * @static+ *+ * @param currentDate {object} JS date+ * @param startDate {object} JS date+ * @param endDate {object} JS date+ * @param lastToQueue {string} date String+ *+ * @returns {void}+ *+ */+ initialPreload(currentDate, startDate, endDate, lastToQueue) {+ const { queueLength, selectDate, togglePlaying } = this.props;+ var day = currentDate;+ if (queueLength <= 1) {+ // if only one frame will play just move to that date+ selectDate(startDate);+ togglePlaying();+ return;+ }+ for (var i = 0; i < queueLength; i++) {+ this.addDate(day);+ day = this.getNextBufferDate(day, startDate, endDate);+ if (util.toISOStringSeconds(day) === lastToQueue) {+ this.addDate(day);+ }+ }+ }+ /*+ * Gets the last date that should be added+ * to the queuer+ *+ * @method checkShouldPlay+ * @static+ *+ * @param currentPlayingDateJSDate {object} JS date+ * that is currently being shown+ *+ * @returns {void}+ *+ */+ checkShouldPlay = function(isLoopStart) {+ const { startDate, endDate, hasCustomPalettes } = this.props;+ var currentDate = util.parseDateUTC(this.currentPlayingDate);+ const getLastBufferDateStr = this.getLastBufferDateStr(+ currentDate,+ startDate,+ endDate+ );++ if (this.state.isPlaying && !isLoopStart) {+ return false;+ }+ if (this.preloadObject[getLastBufferDateStr]) {+ return this.play(this.currentPlayingDate);+ }+ if (+ hasCustomPalettes &&+ this.preloadObject[this.currentPlayingDate] &&+ lodashIsEmpty(this.inQueueObject)+ ) {+ return this.play(this.currentPlayingDate);+ }+ this.shiftCache();+ };+ /*+ * Gets the last date that should be added+ * to the queuer+ *+ * @method checkShouldLoop+ * @static+ *+ * @param currentPlayingDateJSDate {object} JS date+ * that is currently being shown+ *+ * @returns {void}+ *+ */+ checkShouldLoop(currentPlayingDateJSDate) {+ const { loop, startDate, queueLength, togglePlaying } = this.props;+ if (loop) {+ this.shiftCache();+ this.currentPlayingDate = util.toISOStringSeconds(startDate);+ setTimeout(() => {+ this.checkShouldPlay(true);+ this.checkQueue(queueLength, this.currentPlayingDate);+ }, 1000);+ } else {+ togglePlaying();+ }+ }+ /*+ * Determines what dates should+ * be queued+ *+ * @method checkQueue+ * @static+ *+ * @param bufferLength {number} number+ * @param index {string}+ * @returns {void}+ *+ */+ checkQueue(bufferLength, index) {+ const { startDate, endDate, hasCustomPalettes, canPreloadAll } = this.props;+ var currentDate = util.parseDateUTC(index);+ var lastToQueue = this.getLastBufferDateStr(+ currentDate,+ startDate,+ endDate+ );++ if (!this.preloadedArray[0] && !this.inQueueObject[index]) {+ this.initialPreload(currentDate, startDate, endDate, lastToQueue);+ } else if (+ !this.preloadedArray[lastToQueue] &&+ !this.inQueueObject[lastToQueue] &&+ !hasCustomPalettes &&+ !canPreloadAll+ ) {+ // if last preload date doesn't exist+ this.addItemToQueue(currentDate, startDate, endDate);+ } else if (hasCustomPalettes && this.preloadedArray[0]) {+ this.customQueuer(currentDate, startDate, endDate);+ }+ }+ /*+ * Clears precache+ *+ * @method clearCache+ * @static+ *+ *+ * @returns {void}+ *+ */+ clearCache() {+ this.preloadObject = {};+ this.preloadedArray = [];+ }++ /*+ * Gets next date based on current+ * increments+ *+ * @method nextDate+ * @static+ *+ * @param date {object} JS date obj+ *+ * @returns {object} JS Date+ *+ */++ // # need to change subdaily argument for custom intervals - rework for all zoom levels presumably+ nextDate(date) {+ const { interval, delta } = this.props;+ return util.dateAdd(date, interval, delta);+ }+ /*+ * Custom date queuer created for+ * custom colormaps+ *+ * @method customQueuer+ * @static+ *+ * @param currentDate {object} JS date+ * @param startDate {object} JS date+ * @param endDate {object} JS date+ *+ * @returns {void}+ *+ */+ customQueuer(currentDate, startDate, endDate) {+ var nextDateStr;+ var nextDate = this.nextDate(currentDate);+ if (nextDate > endDate) {+ nextDate = startDate;+ }++ nextDateStr = util.toISOStringSeconds(nextDate);++ if (+ !this.preloadedArray[nextDateStr] &&+ !this.inQueueObject[nextDateStr] &&+ !this.state.isplaying+ ) {+ this.clearCache();+ this.checkQueue(this.props.queueLength, this.currentPlayingDate);+ }+ }+ /*+ * Add date to loading Queue+ * obj+ *+ * @method addToInQueue+ * @static+ *+ * @param date {object} JS date obj+ *+ * @returns {void}+ *+ */+ addToInQueue(date) {+ var strDate = util.toISOStringSeconds(date);+ this.inQueueObject[strDate] = date;+ this.preloadedArray.push(strDate);+ }+ /*+ * removes item from cache after it has+ * been played and quelimit reached+ *+ *+ *+ * @method shiftCache+ * @static+ *+ * @returns {void}+ *+ */+ shiftCache() {+ const { queueLength, canPreloadAll } = this.props;+ if (+ this.preloadObject[this.preloadedArray[0]] &&+ util.objectLength(this.preloadObject) > queueLength &&+ this.pastDates[this.preloadedArray[0]] &&+ !this.isInToPlayGroup(this.preloadedArray[0]) &&+ !canPreloadAll+ ) {+ let key = this.preloadedArray.shift();+ delete this.preloadObject[key];+ delete this.pastDates[key];+ }+ }+ /*+ *+ * @method getNextBufferDate* @static** @param currentDate {object} JS date@@ -27,15 +348,14 @@ class PlayAnimation extends React.Component {**/getNextBufferDate(currentDate, startDate, endDate) {- const { preloadedArray } = this.state;var lastInBuffer = util.parseDateUTC(- preloadedArray[preloadedArray.length - 1]+ this.preloadedArray[this.preloadedArray.length - 1]);- var nextDate = self.nextDate(lastInBuffer);- if (lastInBuffer >= endDate || self.nextDate(lastInBuffer) > endDate) {+ var nextDate = this.nextDate(lastInBuffer);+ if (lastInBuffer >= endDate || nextDate > endDate) {return startDate;}- return nextDate(lastInBuffer);+ return nextDate;}/** Verifies that date is@@ -51,21 +371,149 @@ class PlayAnimation extends React.Component {**/addItemToQueue(currentDate, startDate, endDate) {- const { queueLength, playIndex, inQueue } = this.state;- var nextDate = animUtil.getNextBufferDate(currentDate, startDate, endDate);+ const { queueLength } = this.props;+ var nextDate = this.getNextBufferDate(currentDate, startDate, endDate);var nextDateStr = util.toISOStringSeconds(nextDate);if (- !inQueue[nextDateStr] &&- !preload[nextDateStr] &&+ !this.inQueueObject[nextDateStr] &&+ !this.preloadObject[nextDateStr] &&nextDate <= endDate &&nextDate >= startDate) {- self.addDate(nextDate);- self.checkQueue(queueLength, playIndex);+ this.addDate(nextDate);+ this.checkQueue(queueLength, this.currentPlayingDate);+ }+ }+ /*+ * checks if this date is in array of+ * dates that need to play in future+ * within buffer length+ *+ *+ * @method isInToPlayGroup+ * @static+ *+ * @param testDate {string} JS date string+ *+ * @returns {boolean}+ *+ */+ isInToPlayGroup(testDate) {+ const { startDate, endDate, loop, queueLength } = this.props;+ var i = 0;+ var day = util.parseDateUTC(this.currentPlayingDate);+ var jsTestDate = util.parseDateUTC(testDate);+ while (i < queueLength) {+ if (this.nextDate(day) > endDate) {+ if (!loop) {+ return false;+ }+ day = startDate;+ } else {+ day = this.nextDate(day);+ }+ if (day.valueOf() === jsTestDate.valueOf()) {+ return true;+ }+ i++;+ }+ return false;+ }+ /*+ * Gets next date based on current+ * increments+ *+ * @method nextDate+ * @static+ *+ * @param date {object} JS date obj+ *+ * @returns {object} JS Date+ *+ */+ addDate(date) {+ const { layers, promiseImageryForTime } = this.props;+ const activeLayers = getLayersActiveAtDate(layers, date);+ const strDate = util.toISOStringSeconds(date);+ if (this.inQueueObject[strDate] || this.preloadObject[strDate]) return;+ this.addToInQueue(date);+ this.queue+ .add(function() {+ return promiseImageryForTime(date, activeLayers);+ })+ .then(date => {+ this.preloadObject[strDate] = date;+ delete this.inQueueObject[strDate];+ this.shiftCache();+ this.checkQueue(this.queueLength, this.currentPlayingDate);+ this.checkShouldPlay();+ });+ }+ /*+ * removes loader and starts the+ * animation+ *+ * @method play+ * @static+ *+ * @param index {string} date string+ *+ * @returns {void}+ *+ */+ play(dateStr) {+ const { togglePlaying } = this.props;+ if (!this.state.isPlaying) this.setState({ isPlaying: true });++ this.animate(dateStr);+ if (document.hidden) {+ togglePlaying();}}+ /*+ * function that loops through frames+ * at a specified time interval+ *+ * @method animate+ * @static+ *+ * @param index {string} Date string+ * @returns {void}+ *+ */+ animate(index) {+ const { selectDate, endDate, queueLength, speed } = this.props;+ var currentPlayingDate = index;+ var currentPlayingDateJSDate;+ var player = () => {+ this.shiftCache();+ this.checkQueue(queueLength, currentPlayingDate);+ selectDate(util.parseDateUTC(currentPlayingDate));+ this.pastDates[currentPlayingDate] = util.parseDateUTC(+ currentPlayingDate+ ); // played record+ this.currentPlayingDate = currentPlayingDate;+ currentPlayingDate = util.toISOStringSeconds(+ this.nextDate(util.parseDateUTC(currentPlayingDate))+ );+ currentPlayingDateJSDate = util.parseDateUTC(currentPlayingDate);+ if (currentPlayingDateJSDate > endDate) {+ clearInterval(this.interval);+ return this.checkShouldLoop(currentPlayingDateJSDate);+ }+ if (!this.preloadObject[currentPlayingDate]) {+ clearInterval(this.interval);+ this.setState({ isPlaying: false });+ this.shiftCache();+ return this.checkQueue(queueLength, this.currentPlayingDate);+ }+ this.checkQueue(queueLength, this.currentPlayingDate);+ this.interval = setTimeout(player, 1000 / this.props.speed);+ };+ this.interval = setTimeout(player, speed);+ }renderSpinner() {const { onClose } = this.props;return (@@ -82,8 +530,8 @@ class PlayAnimation extends React.Component {);}render() {- const { isReadyToPlay } = this.state;- return isReadyToPlay ? '' : this.renderSpinner();+ const { isPlaying } = this.state;+ return !isPlaying ? this.renderSpinner() : '';}}diff --git a/web/js/components/timeline/timeline-controls/animation-button.js b/web/js/components/timeline/timeline-controls/animation-button.jsindex b33667f48..7e51db701 100644--- a/web/js/components/timeline/timeline-controls/animation-button.js+++ b/web/js/components/timeline/timeline-controls/animation-button.js@@ -3,9 +3,12 @@ import PropTypes from 'prop-types';class AnimationButton extends PureComponent {render() {+ const className = 'button-action-group animate-button';return (<div- className="button-action-group animate-button"+ className={+ this.props.disabled ? 'wv-disabled-button ' + className : className+ }id="animate-button"title="Set up animation"onClick={this.props.clickAnimationButton}diff --git a/web/js/containers/animation-widget.js b/web/js/containers/animation-widget.jsindex 617a8da9b..f76f6ca33 100644--- a/web/js/containers/animation-widget.js+++ b/web/js/containers/animation-widget.js@@ -1,6 +1,10 @@import React from 'react';import { connect } from 'react-redux';-import { without as lodashWithout } from 'lodash';+import {+ without as lodashWithout,+ isEmpty as lodashIsEmpty,+ get as lodashGet+} from 'lodash';import ErrorBoundary from './error-boundary';import PropTypes from 'prop-types';import Slider, { Handle } from 'rc-slider';@@ -9,7 +13,18 @@ import LoopButton from '../components/animation-widget/loop-button';import PlayButton from '../components/animation-widget/play-button';import AnimWidgetHeader from '../components/animation-widget/header';import googleTagManager from 'googleTagManager';-import { hasSubDaily as hasSubDailySelector } from '../modules/layers/selectors';+import PlayQueue from '../components/animation-widget/play-queue';++import { promiseImageryForTime } from '../modules/map/util';+import { selectDate } from '../modules/date/actions';+import GifContainer from './gif';+import { timeScaleFromNumberKey } from '../modules/date/constants';+import { getQueueLength, getMaxQueueLength } from '../modules/animation/util';+import {+ hasSubDaily as hasSubDailySelector,+ lastDate as layersLastDateTime,+ getLayers+} from '../modules/layers/selectors';import {play,onClose,@@ -20,9 +35,6 @@ import {changeEndDate,toggleComponentGifActive} from '../modules/animation/actions';-import GifContainer from './gif';--import { timeScaleFromNumberKey } from '../modules/date/constants';const RangeHandle = props => {const { value, offset, dragging, ...restProps } = props;@@ -114,7 +126,15 @@ class AnimationWidget extends React.Component {endDate,onPushPlay,onPushPause,- isActive+ isActive,+ interval,+ delta,+ layers,+ hasCustomPalettes,+ promiseImageryForTime,+ map,+ selectDate,+ currentDate} = this.props;if (!isActive) {return '';@@ -127,8 +147,39 @@ class AnimationWidget extends React.Component {/>);} else {+ const maxLength = getMaxQueueLength(this.state.speed);+ const queueLength = getQueueLength(+ startDate,+ endDate,+ this.state.speed,+ interval,+ delta+ );return (<ErrorBoundary>+ {isPlaying ? (+ <PlayQueue+ endDate={endDate}+ loop={looping}+ currentDate={currentDate}+ canPreloadAll={queueLength <= maxLength}+ startDate={startDate}+ hasCustomPalettes={hasCustomPalettes}+ map={map}+ maxQueueLength={maxLength}+ queueLength={queueLength}+ layers={layers}+ interval={interval}+ delta={delta}+ speed={this.state.speed}+ selectDate={selectDate}+ togglePlaying={onPushPause}+ promiseImageryForTime={promiseImageryForTime}+ onClose={onPushPause}+ />+ ) : (+ ''+ )}<divid="wv-animation-widget"className={@@ -212,32 +263,58 @@ class AnimationWidget extends React.Component {}}function mapStateToProps(state) {- const { layers, compare, animation, date, sidebar, modal } = state;+ const {+ layers,+ compare,+ animation,+ date,+ sidebar,+ modal,+ palettes,+ config,+ legacy+ } = state;const { startDate, endDate, speed, loop, isPlaying, isActive } = animation;- const { minDate, maxDate } = date;const activeStr = compare.activeString;+ const activeDateStr = compare.isCompareA ? 'selected' : 'selectedB';const hasSubdailyLayers = hasSubDailySelector(layers[activeStr]);const zoomObj = getZoomObject(date, hasSubdailyLayers);-+ let { customSelected, interval, delta, customInterval, customDelta } = date;+ const hasCustomPalettes = !lodashIsEmpty(palettes[activeStr]);return {startDate,endDate,- // minDate,- // maxDate,+ currentDate: date[activeDateStr],+ minDate: config.startDate,+ maxDate: layersLastDateTime(layers[activeStr], config),isActive:isActive &&+ lodashGet(legacy, 'map.selectedMap.frameState_') &&sidebar.activeTab !== 'download' && // No Animation when data download is active!(modal.isOpen && modal.id === 'TOOLBAR_SNAPSHOT'), // No Animation when Image download is openhasSubdailyLayers,incrementArray: zoomObj.array,increment: zoomObj.increment,sliderLabel: 'Frames Per Second',+ layers: getLayers(layers[activeStr], {}, state),speed,isPlaying,- looping: loop+ looping: loop,+ delta: customSelected ? customDelta : delta,+ interval: customSelected+ ? timeScaleFromNumberKey[customInterval]+ : timeScaleFromNumberKey[interval],+ hasCustomPalettes,+ map: legacy.map,+ promiseImageryForTime: (date, layers) => {+ return promiseImageryForTime(date, layers, state);+ }};}const mapDispatchToProps = dispatch => ({+ selectDate: val => {+ dispatch(selectDate(val));+ },onClose: () => {dispatch(onClose());},@@ -251,7 +328,7 @@ const mapDispatchToProps = dispatch => ({dispatch(toggleLooping());},toggleGif: () => {- dispatch(toggleComponentGifActive())+ dispatch(toggleComponentGifActive());},onSlide: num => {dispatch(changeFrameRate(num));diff --git a/web/js/containers/timeline/timeline.js b/web/js/containers/timeline/timeline.jsindex 8f46b26bc..e840e062d 100644--- a/web/js/containers/timeline/timeline.js+++ b/web/js/containers/timeline/timeline.js@@ -20,10 +20,21 @@ import {hasSubDaily,lastDate as layersLastDateTime} from '../../modules/layers/selectors';-import { selectDate, changeTimeScale, selectInterval, changeCustomInterval } from '../../modules/date/actions';+import {+ selectDate,+ changeTimeScale,+ selectInterval,+ changeCustomInterval+} from '../../modules/date/actions';import { toggleActiveCompareState } from '../../modules/compare/actions';-import { onActivate as openAnimation, onClose as closeAnimation } from '../../modules/animation/actions';-import { timeScaleFromNumberKey, timeScaleToNumberKey } from '../../modules/date/constants';+import {+ onActivate as openAnimation,+ onClose as closeAnimation+} from '../../modules/animation/actions';+import {+ timeScaleFromNumberKey,+ timeScaleToNumberKey+} from '../../modules/date/constants';const ANIMATION_DELAY = 500;@@ -56,7 +67,7 @@ class Timeline extends React.Component {this.setState({animationInProcess: false});- }+ };/*** Add timeout to date change when buttons are being held so that* date changes don't happen too quickly@@ -114,7 +125,7 @@ class Timeline extends React.Component {// handle SET of custom time scale panelchangeCustomInterval = (delta, timeScale) => {this.props.changeCustomInterval(Number(delta), Number(timeScale));- }+ };// handle SELECT of LEFT/RIGHT interval selectionsetTimeScaleIntervalChangeUnit = (@@ -134,24 +145,18 @@ class Timeline extends React.Component {this.setState({customIntervalModalOpen: !!customIntervalModalOpen});- }+ };// right arrow increment dateincrementDate = () => {let delta = this.props.customSelected ? this.props.intervalChangeAmt : 1;- this.animateByIncrement(- Number(delta),- this.props.timeScaleChangeUnit- );- }+ this.animateByIncrement(Number(delta), this.props.timeScaleChangeUnit);+ };// left arrow decrement datedecrementDate = () => {let delta = this.props.customSelected ? this.props.intervalChangeAmt : 1;- this.animateByIncrement(- Number(delta * -1),- this.props.timeScaleChangeUnit- );+ this.animateByIncrement(Number(delta * -1), this.props.timeScaleChangeUnit);};// open animation dialog@@ -170,12 +175,12 @@ class Timeline extends React.Component {this.setState({timelineHidden: !this.state.timelineHidden});- }+ };// toggle selected dragger for comparison mode/focused date used in date selectoronChangeSelectedDragger = () => {this.props.toggleActiveCompareState();- }+ };// update range of animation draggersupdateAnimationRange = (startDate, endDate) => {@@ -184,23 +189,27 @@ class Timeline extends React.Component {};// handles left/right arrow down to decrement/increment date- handleKeyDown = lodashDebounce((e) => {- if (e.keyCode === 37) {- this.decrementDate();- e.preventDefault();- } else if (e.keyCode === 39) {- this.incrementDate();- e.preventDefault();- }- }, 0, { leading: true, trailing: false })+ handleKeyDown = lodashDebounce(+ e => {+ if (e.keyCode === 37) {+ this.decrementDate();+ e.preventDefault();+ } else if (e.keyCode === 39) {+ this.incrementDate();+ e.preventDefault();+ }+ },+ 0,+ { leading: true, trailing: false }+ );// handles stopping change date in process and to allow faster key downs- handleKeyUp = (e) => {+ handleKeyUp = e => {if (e.keyCode === 37 || e.keyCode === 39) {this.stopper();e.preventDefault();}- }+ };componentDidMount() {document.addEventListener('keydown', this.handleKeyDown);@@ -226,7 +235,8 @@ class Timeline extends React.Component {parentOffset,animStartLocationDate,animEndLocationDate,- isAnimationWidgetOpen+ isAnimationWidgetOpen,+ animationDisabled} = this.props;return dateFormatted ? (<ErrorBoundary>@@ -252,7 +262,9 @@ class Timeline extends React.Component {setTimeScaleIntervalChangeUnit={this.setTimeScaleIntervalChangeUnit}- customIntervalZoomLevel={timeScaleFromNumberKey[customIntervalZoomLevel]}+ customIntervalZoomLevel={+ timeScaleFromNumberKey[customIntervalZoomLevel]+ }customSelected={customSelected}customDelta={customIntervalValue}timeScaleChangeUnit={timeScaleChangeUnit}@@ -268,16 +280,17 @@ class Timeline extends React.Component {/></div>- <AnimationButton clickAnimationButton={this.clickAnimationButton} />+ <AnimationButton+ disabled={animationDisabled}+ clickAnimationButton={this.clickAnimationButton}+ /></div>- <div id="timeline-footer"+ <div+ id="timeline-footer"style={{ display: this.state.timelineHidden ? 'none' : 'block' }}><div id="wv-animation-widet-case">- { isAnimationWidgetOpen- ? <AnimationWidget />- : null- }+ {isAnimationWidgetOpen ? <AnimationWidget /> : null}</div>{/* Timeline */}<TimelineAxis@@ -333,7 +346,16 @@ class Timeline extends React.Component {}}function mapStateToProps(state) {- const { config, compare, layers, browser, date, animation } = state;+ const {+ config,+ compare,+ legacy,+ layers,+ browser,+ date,+ animation,+ sidebar+ } = state;let {customSelected,selected,@@ -422,7 +444,9 @@ function mapStateToProps(state) {parentOffset: dimensionsAndOffsetValues.parentOffset,timelineEndDateLimit,leftArrowDisabled,- rightArrowDisabled+ rightArrowDisabled,+ animationDisabled:+ !legacy.map.selectedMap || !legacy.map.selectedMap.frameState_ || sidebar.activeTab === 'download'};}@@ -514,21 +538,23 @@ const getNextTimeSelection = (delta, increment, prevDate) => {};// check if left arrow should be disabled on predicted decrement-const checkLeftArrowDisabled = (date, delta, timeScaleChangeUnit, timelineStartDateLimit) => {- let nextDecrementDate = moment- .utc(date)- .subtract(delta, timeScaleChangeUnit);- return nextDecrementDate.isSameOrBefore(- timelineStartDateLimit- );+const checkLeftArrowDisabled = (+ date,+ delta,+ timeScaleChangeUnit,+ timelineStartDateLimit+) => {+ let nextDecrementDate = moment.utc(date).subtract(delta, timeScaleChangeUnit);+ return nextDecrementDate.isSameOrBefore(timelineStartDateLimit);};// check if right arrow should be disabled on predicted increment-const checkRightArrowDisabled = (date, delta, timeScaleChangeUnit, timelineEndDateLimit) => {- let nextIncrementDate = moment- .utc(date)- .add(delta, timeScaleChangeUnit);- return nextIncrementDate.isSameOrAfter(- timelineEndDateLimit- );+const checkRightArrowDisabled = (+ date,+ delta,+ timeScaleChangeUnit,+ timelineEndDateLimit+) => {+ let nextIncrementDate = moment.utc(date).add(delta, timeScaleChangeUnit);+ return nextIncrementDate.isSameOrAfter(timelineEndDateLimit);};diff --git a/web/js/map/model.js b/web/js/map/model.jsindex 0c2c343a5..4bdeb998f 100644--- a/web/js/map/model.js+++ b/web/js/map/model.js@@ -4,6 +4,7 @@ import { register } from 'ol/proj/proj4';import proj4 from 'proj4';import lodashClone from 'lodash/clone';import { intersects } from 'ol/extent';+import Cache from 'cachai';export function mapModel(models, config) {var self = {};@@ -11,6 +12,8 @@ export function mapModel(models, config) {self.extent = null;self.selectedMap = null;self.events = util.events();+ self.cache = new Cache(400);+ self.ui = null;self.rotation = 0;const init = function() {if (!config.projections) {@@ -45,8 +48,9 @@ export function mapModel(models, config) {self.events.trigger('update', extent);};// Give other components access to zoom Level- self.updateMap = function(map) {+ self.updateMap = function(map, ui) {self.selectedMap = map;+ self.ui = ui;self.events.trigger('update-map');};self.getZoom = function() {diff --git a/web/js/map/ui.js b/web/js/map/ui.jsindex 8d9b872c5..27fbe4230 100644--- a/web/js/map/ui.js+++ b/web/js/map/ui.js@@ -41,15 +41,15 @@ import {getLayers,isRenderable as isRenderableLayer} from '../modules/layers/selectors';-import Cache from 'cachai';+export function mapui(models, config, store) {var layerBuilder, createLayer;var id = 'wv-map';var selector = '#' + id;- var cache = new Cache(400); // Save layers from days visitedvar animationDuration = 250;var self = {};+ var cache = models.map.cache;// Save layers from days visitedvar rotation = new MapRotate(self, models);var dateline = mapDateLineBuilder(models, config, store);var precache = mapPrecacheTile(models, config, cache, self);@@ -178,7 +178,7 @@ export function mapui(models, config, store) {}self.selected = self.proj[proj.id];var map = self.selected;- models.map.updateMap(map);+ models.map.updateMap(map, self);reloadLayers();// Update the rotation buttons if polar projection to display correct value@@ -906,7 +906,10 @@ export function mapui(models, config, store) {self.mapIsbeingZoomed = false;}, 200);});-+ const completeKey = map.on('rendercomplete', () => {+ models.map.updateMap(self.selected, self);+ map.unset(completeKey, true);+ });// Clicking on a vector shows it's attributes in console.map.on('click', function(e) {map.forEachFeatureAtPixel(e.pixel, function(feature, layer) {diff --git a/web/js/modules/animation/reducers.js b/web/js/modules/animation/reducers.jsindex a82bb0b27..5b7333977 100644--- a/web/js/modules/animation/reducers.js+++ b/web/js/modules/animation/reducers.js@@ -67,6 +67,14 @@ export function animationReducer(state = defaultState, action) {return lodashAssign({}, state, {gifActive: !state.gifActive});+ case 'KEY_PRESS_ACTION':+ if (action.keyCode === 32 && state.isActive) {+ return lodashAssign({}, state, {+ isPlaying: !state.isPlaying+ });+ } else {+ return state;+ }default:return state;}diff --git a/web/js/modules/animation/util.js b/web/js/modules/animation/util.jsindex 1d09fa95a..6290109ee 100644--- a/web/js/modules/animation/util.js+++ b/web/js/modules/animation/util.js@@ -4,6 +4,7 @@ import {round as lodashRound} from 'lodash';import canvg from 'canvg-browser';+import util from '../../util/util';export function getAnimationParameterSetup(parameters,@@ -196,12 +197,13 @@ export function getMaxQueueLength(speed) {* @returns {number} new buffer length**/-export function getQueueLength(startDate, endDate, maxQueueLength) {+export function getQueueLength(startDate, endDate, speed, interval, delta) {var day = startDate;var i = 0;- while (i < maxQueueLength) {+ const maxQueueLength = getMaxQueueLength(speed);+ while (i <= maxQueueLength) {i++;- day = self.nextDate(day);+ day = util.dateAdd(day, interval, delta);if (day > endDate) {return i;}diff --git a/web/js/modules/date/util.js b/web/js/modules/date/util.jsindex 7b1e578a9..e530df4cb 100644--- a/web/js/modules/date/util.js+++ b/web/js/modules/date/util.js@@ -1,5 +1,5 @@import util from '../../util/util';-import { get } from 'lodash';+import { get, each as lodashEach } from 'lodash';export function getDateParameterSetup(parameters,@@ -91,4 +91,21 @@ export function tryCatchDate(str, initialState) {console.warn('Invalid date: ' + str);return initialState;}-};+}+/**+ * Checks the date provided against the active layers.+ *+ * @method getLayersActiveAtDate+ * @param {Array} layers+ * @param {object} date Date of data to be displayed on the map.+ * @return {array} An array of visible layers within the date.+ */+export function getLayersActiveAtDate(layers, date) {+ var arra = [];+ lodashEach(layers, function(layer) {+ if (layer.visible && layer.startDate && new Date(layer.startDate > date)) {+ arra.push(layer);+ }+ });+ return arra;+}diff --git a/web/js/modules/layers/util.js b/web/js/modules/layers/util.jsindex 47b0032fe..d0cf73b19 100644--- a/web/js/modules/layers/util.js+++ b/web/js/modules/layers/util.js@@ -397,4 +397,4 @@ export function mapLocationToLayerState(});}return stateFromLocation;-}+}\ No newline at end of filediff --git a/web/js/modules/map/util.js b/web/js/modules/map/util.jsindex aa9bc8f6f..30d878f86 100644--- a/web/js/modules/map/util.js+++ b/web/js/modules/map/util.js@@ -1,11 +1,13 @@import util from '../../util/util';import { encode } from '../link/util';+import * as olExtent from 'ol/extent';import {each as lodashEach,isUndefined as lodashIsUndefined,map as lodashMap} from 'lodash';-+import OlRendererCanvasTileLayer from 'ol/renderer/canvas/TileLayer';+import Promise from 'bluebird';export function getMapParameterSetup(parameters,config,@@ -106,3 +108,189 @@ export function getLeadingExtent() {return [minLon, minLat, maxLon, maxLat];}+/*+ * @method promiseImageryForTime+ * @param {object} time of data to be displayed on the map.+ * @return {object} Promise.all+ */+export function promiseImageryForTime(date, layers, state) {+ var viewState;+ var frameState;+ var pixelRatio;+ var promiseArray;+ const map = state.legacy.map;+ var cache = map.cache;+ var mapUi = map.ui;+ var selectedMap = map.selectedMap;+ frameState = selectedMap.frameState_; // OL object describing the current map frame++ pixelRatio = frameState.pixelRatio;+ viewState = frameState.viewState;+ promiseArray = layers.map(function(def) {+ var key;+ var layer;++ key = mapUi.layerKey(+ def,+ {+ date: date+ },+ state+ );+ layer = cache.getItem(key);+ if (layer) {+ cache.removeItem(key);+ }+ layer = mapUi.createLayer(def, {+ date: date,+ precache: true+ });+ return promiseLayerGroup(layer, viewState, pixelRatio, selectedMap, def);+ });+ return new Promise(function(resolve) {+ Promise.all(promiseArray).then(function() {+ resolve(date);+ });+ });+}+/**+ * Once a layer's group of layers (prev, current, next day) are fulfilled,+ * a promise with an array of their fulfilled values is returned.+ *+ * @method promiseLayerGroup+ * @param {object} layer ol_Layer_Group object, contains values.layers for prev, current, next days+ * @param {object} viewState Contains center, projection, resolution, rotation and zoom parameters+ * @param {number} pixelRatio The window.devicePixelRatio, used to detect retina displays+ * @param {object} map _ol_Map_ object+ * @return {object} Promise.all+ */+var promiseLayerGroup = function(layer, viewState, pixelRatio, map, def) {+ var extent;+ return new Promise(function(resolve, reject) {+ var layers, layerPromiseArray;+ // Current layer's 3 layer array (prev, current, next days)+ layers = layer.values_.layers;+ if (layer.values_.layers) {+ layers = layer.getLayers().getArray();+ } else {+ layers = [layer];+ }+ // Calculate the extent of each layer in the layer group+ // and create a promiseTileLayer for prev, current, next day+ layerPromiseArray = layers.map(function(layer) {+ extent = calculateExtent(+ layer.getExtent(),+ map.getView().calculateExtent(map.getSize())+ );+ return promiseTileLayer(layer, extent, viewState, pixelRatio);+ });+ Promise.all(layerPromiseArray).then(function() {+ resolve('resolve layer group');+ });+ });+};+/**+ * Calculate the current extent from the map's extent (boundaries) &+ * the viewport extent (boundaries).+ *+ * @method calculateExtent+ * @param {array} extent The map extent (boundaries)+ * @param {array} viewportExtent The current viewport extecnt (boundaries)+ * @return {array} An extent array. Used to calculate+ * the extent for prev, next & current day+ */+var calculateExtent = function(extent, viewportExtent) {+ if (extent[1] < -180) {+ // Previous day+ extent = getExtent(viewportExtent, extent);+ extent[1] = extent[1] + 360;+ extent[3] = extent[3] + 360;+ } else if (extent[1] > 180) {+ // Next day+ extent = getExtent(viewportExtent, extent);+ extent[1] = extent[1] - 360;+ extent[3] = extent[3] - 360;+ } else {+ // Current day (within map extent)+ extent = getExtent(extent, viewportExtent);+ }+ if (!isFinite(extent[0])) {+ return null;+ }+ return extent;+};++/**+ * Get the intersection of two extents.+ *+ * @method getExtent+ * @param {array} extent1 Extent 1.+ * @param {array} extent2 Extent 2.+ * @return {array} A new extent with intersecting points+ */+var getExtent = function(extent1, extent2) {+ return olExtent.getIntersection(extent1, extent2);+};+/**+ * Returns a promise of the layer tilegrid.+ *+ * @method promiseTileLayer+ * @param {object} layer _ol_layer_Tile_+ * @param {array} extent An array of map boundaries [180, -90, 250, 90]+ * @param {object} viewState Contains center, projection, resolution, rotation and zoom parameters+ * @param {number} pixelRatio The window.devicePixelRatio, used to detect retina displays+ * @return {object} promise+ */+var promiseTileLayer = function(layer, extent, viewState, pixelRatio) {+ var renderer, tileSource, currentZ, i, tileGrid, projection;+ return new Promise(function(resolve, reject) {+ if (!extent) {+ resolve('resolve tile layer');+ }+ projection = viewState.projection;+ i = 0;+ if (layer.type === 'VECTOR_TILE') {+ // No need to look up tiles, vectors can resolve ASAP+ resolve();+ } else {+ renderer = new OlRendererCanvasTileLayer(layer);+ tileSource = layer.getSource();+ // tileSource.expireCache(projection);+ tileGrid = tileSource.getTileGridForProjection(projection);+ currentZ = tileGrid.getZForResolution(+ viewState.resolution,+ renderer.zDirection+ );+ tileGrid.forEachTileCoord(extent, currentZ, function(tileCoord) {+ var tile;+ tile = tileSource.getTile(+ tileCoord[0],+ tileCoord[1],+ tileCoord[2],+ pixelRatio,+ projection+ );+ tile.load();++ if (tile.state === 2) resolve();++ var loader = function(e) {+ if (e.type === 'tileloadend') {+ --i;+ if (i === 0) {+ resolve();+ }+ } else {+ reject(new Error('No response at this URL'));+ // resolve();// some gibs data is not accurate and rejecting this will break the animation if tile doesn't exist+ }+ this.un('tileloadend', loader); // remove event listeners from memory+ this.un('tileloaderror', loader);+ };+ tileSource.on('tileloadend', loader);+ tileSource.on('tileloaderror', loader);+ ++i;+ });+ }+ });+};