Skip to content

Interactive interface for browsing global, full-resolution satellite imagery

Implement redux-location-state library #1576

Benjamin King9edb60bdd498
diff --git a/package-lock.json b/package-lock.json
index e00612e87..46441e478 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -5039,6 +5039,12 @@
"integrity": "sha1-6zkTMzRYd1y4TNGh+uBiEGu4dUU=",
"dev": true
},
+ "deep-diff": {
+ "version": "0.3.8",
+ "resolved": "https://registry.npmjs.org/deep-diff/-/deep-diff-0.3.8.tgz",
+ "integrity": "sha1-wB3mPvsO7JeYgB1Ax+Da4ltYLIQ=",
+ "dev": true
+ },
"deep-eql": {
"version": "0.1.3",
"resolved": "http://registry.npmjs.org/deep-eql/-/deep-eql-0.1.3.tgz",
@@ -8296,6 +8302,18 @@
"integrity": "sha512-l9sfDFsuqtOqKDsQdqrMRk0U85RZc0RtOR9yPI7mRVOa4FsR/BVnZ0shmQRM96Ji99kYZP/7hn1cedc1+ApsTQ==",
"dev": true
},
+ "history": {
+ "version": "4.7.2",
+ "resolved": "https://registry.npmjs.org/history/-/history-4.7.2.tgz",
+ "integrity": "sha512-1zkBRWW6XweO0NBcjiphtVJVsIQ+SXF29z9DVkceeaSLVMFXHool+fdCZD4spDCfZJCILPILc3bm7Bc+HRi0nA==",
+ "requires": {
+ "invariant": "2.2.4",
+ "loose-envify": "1.3.1",
+ "resolve-pathname": "2.2.0",
+ "value-equal": "0.4.0",
+ "warning": "3.0.0"
+ }
+ },
"hmac-drbg": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/hmac-drbg/-/hmac-drbg-1.0.1.tgz",
@@ -10879,7 +10897,7 @@
"acorn-globals": "1.0.9",
"cssom": "0.3.4",
"cssstyle": "0.2.37",
- "escodegen": "1.11.0",
+ "escodegen": "1.11.1",
"nwmatcher": "1.4.4",
"parse5": "1.5.1",
"request": "2.87.0",
@@ -10899,9 +10917,9 @@
"optional": true
},
"escodegen": {
- "version": "1.11.0",
- "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-1.11.0.tgz",
- "integrity": "sha512-IeMV45ReixHS53K/OmfKAIztN/igDHzTJUhZM3k1jMhIZWjk45SMwAtBsEXiJp3vSPmTcu6CXn7mDvFHRN66fw==",
+ "version": "1.11.1",
+ "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-1.11.1.tgz",
+ "integrity": "sha512-JwiqFD9KdGVVpeuRa68yU3zZnBEOcPs0nKW7wZzXky8Z7tffdYUHbe11bPCV5jYlK6DVdKLWLm0f5I/QlL0Kmw==",
"dev": true,
"optional": true,
"requires": {
@@ -18408,6 +18426,24 @@
}
}
},
+ "redux-location-state": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/redux-location-state/-/redux-location-state-2.1.1.tgz",
+ "integrity": "sha512-/L0U4HlzMrNrisZvCXdT5K92Xdvd0i2OGlhvzYKuvKftEdTTagn9o9Rq8tSV3XsnoYKn8Gxok4YkIXpq5xgJjQ==",
+ "dev": true,
+ "requires": {
+ "lodash": "4.15.0"
+ }
+ },
+ "redux-logger": {
+ "version": "3.0.6",
+ "resolved": "https://registry.npmjs.org/redux-logger/-/redux-logger-3.0.6.tgz",
+ "integrity": "sha1-91VZZvMJjzyIYExEnPC69XeCdL8=",
+ "dev": true,
+ "requires": {
+ "deep-diff": "0.3.8"
+ }
+ },
"redux-mock-store": {
"version": "1.5.3",
"resolved": "https://registry.npmjs.org/redux-mock-store/-/redux-mock-store-1.5.3.tgz",
@@ -18900,6 +18936,11 @@
"integrity": "sha1-Jsv+k10a7uq7Kbw/5a6wHpPUQiY=",
"dev": true
},
+ "resolve-pathname": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/resolve-pathname/-/resolve-pathname-2.2.0.tgz",
+ "integrity": "sha512-bAFz9ld18RzJfddgrO2e/0S2O81710++chRMUxHjXOYKF6jTAMrUNZrEZ1PvV0zlhfjidm08iRPdTLPno1FuRg=="
+ },
"resolve-protobuf-schema": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/resolve-protobuf-schema/-/resolve-protobuf-schema-2.0.0.tgz",
@@ -23099,6 +23140,11 @@
"spdx-expression-parse": "3.0.0"
}
},
+ "value-equal": {
+ "version": "0.4.0",
+ "resolved": "https://registry.npmjs.org/value-equal/-/value-equal-0.4.0.tgz",
+ "integrity": "sha512-x+cYdNnaA3CxvMaTX0INdTCN8m8aF2uY9BvEqmxuYp8bL09cs/kWVQPVGcA35fMktdOsP69IgU7wFj/61dJHEw=="
+ },
"vary": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
@@ -23180,7 +23226,6 @@
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/warning/-/warning-3.0.0.tgz",
"integrity": "sha1-MuU3fLVy3kqwR1O9+IIcAe1gW3w=",
- "dev": true,
"requires": {
"loose-envify": "1.3.1"
}
diff --git a/package.json b/package.json
index 6cc1a0664..ae9be21c1 100644
--- a/package.json
+++ b/package.json
@@ -128,6 +128,8 @@
"precss": "^3.1.2",
"rc-slider": "8.6.3",
"react-test-renderer": "^16.5.2",
+ "redux-location-state": "^2.1.1",
+ "redux-logger": "^3.0.6",
"redux-mock-store": "^1.5.3",
"run-script-os": "^1.0.3",
"sass-loader": "^7.1.0",
@@ -159,6 +161,7 @@
"clipboard": "^1.7.1",
"date-fns": "^1.29.0",
"file-saver": "^1.3.8",
+ "history": "^4.7.2",
"icheck": "^1.0.2",
"immutability-helper": "^2.9.0",
"isotope-layout": "^3.0.6",
diff --git a/web/js/animation/model.js b/web/js/animation/model.js
index 75a8c82a2..66c4908c2 100644
--- a/web/js/animation/model.js
+++ b/web/js/animation/model.js
@@ -51,6 +51,7 @@ export function animationModel(models, config) {
if (state.al) {
self.rangeState.loop = Boolean(state.al);
}
+ return self;
};
/*
diff --git a/web/js/app.js b/web/js/app.js
index 24766b43d..e88a7a5cc 100644
--- a/web/js/app.js
+++ b/web/js/app.js
@@ -2,80 +2,19 @@ import React from 'react';
import { connect } from 'react-redux';
import 'whatwg-fetch';
-import { debounce as lodashDebounce, each as lodashEach } from 'lodash';
+import { each as lodashEach } from 'lodash';
import googleTagManager from 'googleTagManager';
-// Permalink
-import Permalink from './containers/permalink';
// Utils
import util from './util/util';
// Date
-import { parse as dateParser } from './date/date';
-import { dateModel } from './date/model';
-import { dateLabel } from './date/label';
-import dateWheels from './date/wheels';
-
-// Timeline
-import { timeline } from './date/timeline';
-import { timelineData } from './date/timeline-data';
-import { timelineConfig } from './date/config';
-import { timelineZoom } from './date/timeline-zoom';
-import { timelineTicks } from './date/timeline-ticks';
-import { timelinePick } from './date/timeline-pick';
-import { timelinePan } from './date/timeline-pan';
-import { timelineInput } from './date/timeline-input';
-import { timelineCompare } from './date/compare-picks';
-
// Layers
-import {
- parse as layerParser,
- validate as layerValidate
-} from './layers/layers';
-import { layersModel } from './layers/model';
-import { layersModal } from './layers/modal';
-
-import { layersActive } from './layers/active';
-import { layersOptions } from './layers/options';
-
-import { sidebarUi } from './sidebar/ui';
+import { validate as layerValidate } from './layers/layers';
// Map
-import { mapParser } from './map/map';
-import { mapModel } from './map/model';
-import { mapui } from './map/ui';
-import { MapRotate } from './map/rotation';
-import { MapRunningData } from './map/runningdata';
-import { mapLayerBuilder } from './map/layerbuilder';
-import { mapDateLineBuilder } from './map/datelinebuilder';
-import { mapPrecacheTile } from './map/precachetile';
-import { mapAnimate } from './map/animate';
-import OlCoordinates from './components/map/ol-coordinates';
-
-// Animation
-import { parse as animationParser } from './animation/anim';
-import { animationModel } from './animation/model';
-import { animationUi } from './animation/ui';
-import { animationWidget } from './animation/widget';
-import { animationRangeSelect } from './animation/range-select';
-import { animationGif } from './animation/gif';
-
-// Palettes
-import palettes from './palettes/palettes';
-import { palettesModel } from './palettes/model';
-
-// Data
-import { dataParser } from './data/data';
-import { dataModel } from './data/model';
-import { dataUi } from './data/ui';
-// NaturalEvents
-import naturalEventsModel from './natural-events/model';
-import naturalEventsUI from './natural-events/ui';
-import naturalEventsRequest from './natural-events/request';
-
-// UI
-import loadingIndicator from './ui/indicator';
+import OlCoordinates from './components/map/ol-coordinates';
// Toolbar
import Toolbar from './containers/toolbar';
@@ -93,28 +32,15 @@ import {
setNotifications
} from './modules/notifications/actions';
// Link
-import { linkModel } from './link/model';
// Projections
-import { parse as projectionParser } from './projection/projection';
-import { projectionModel } from './projection/model';
-// A|B comparison
-import { compareModel } from './compare/model';
-import { compareUi } from './compare/ui';
-
-// Tour
-import { tourModel } from './tour/model';
-import { tourUi } from './tour/ui';
-// Alert
-import { alertUi } from './alert/ui';
// Other
-import { debugConfig, debugLayers } from './debug';
+import { debugConfig } from './debug';
import Brand from './brand';
// Crutch between state systems
-import { sendConfigToStore } from './modules/migration/actions';
-import { updatePermalink } from './modules/link/actions';
+import { updateLegacyInitComplete } from './modules/migration/actions';
// Dependency CSS
import '../../node_modules/bootstrap/dist/css/bootstrap.css';
import '../../node_modules/jquery-ui-bundle/jquery-ui.structure.css';
@@ -178,13 +104,11 @@ class App extends React.Component {
this.state = {
maps: null
};
- this.mapMouseEvents = util.events();
this.onload();
}
render() {
return (
<div className="wv-content" id="wv-content" data-role="content">
- <Permalink />
<Toolbar />
<section id="wv-sidebar" />
<div id="layer-modal" className="layer-modal" />
@@ -287,7 +211,7 @@ class App extends React.Component {
</svg>
</div>
</section>
- <OlCoordinates mouseEvents={this.mapMouseEvents} />
+ <OlCoordinates mouseEvents={this.props.mapMouseEvents} />
<Modal />
</div>
);
@@ -296,77 +220,24 @@ class App extends React.Component {
onload() {
var self = this;
var errors = [];
- var requirements;
- var startTime;
- var wvx = {};
var config;
- var parsers;
- var state = util.fromQueryString(location.search);
- var parameters = util.fromQueryString(location.search);
-
- var main = function() {
- if (parameters.elapsed) {
- startTime = new Date().getTime();
- } else {
- elapsed = function() {};
- }
- elapsed('start');
- loadConfig();
- };
-
- var loadConfig = function() {
- elapsed('loading config');
- var configURI = Brand.url('config/wv.json');
- var promise = $.getJSON(configURI);
- promise.done(util.wrap(onConfigLoaded)).fail(util.error);
- loadingIndicator.delayed(promise, 1000);
- };
-
- var onConfigLoaded = function(data) {
- elapsed('config loaded');
- config = data;
- config.parameters = parameters;
-
- // Attach to wvx object for debugging
- wvx.config = config;
+ var state = self.props.parameters;
- debugConfig(config);
-
- // Load any additional scripts as needed
- if (config.scripts) {
- lodashEach(config.scripts, function(script) {
- $.getScript(script);
- });
- }
+ config = self.props.config;
+ config.parameters = state;
+ debugConfig(config);
- layerValidate(errors, config);
-
- parsers = [
- projectionParser,
- layerParser,
- dateParser,
- mapParser,
- palettes.parse
- ];
- if (config.features.dataDownload) {
- parsers.push(dataParser);
- }
- if (config.features.animation) {
- parsers.push(animationParser);
- }
- lodashEach(parsers, function(parser) {
- parser(state, errors, config);
+ // Load any additional scripts as needed
+ if (config.scripts) {
+ lodashEach(config.scripts, function(script) {
+ $.getScript(script);
});
- requirements = [palettes.requirements(state, config, true)];
-
- $.when
- .apply(null, requirements)
- .then(util.wrap(init))
- .fail(util.error);
+ }
+ const main = function() {
+ layerValidate(errors, config);
+ util.wrap(init);
};
-
var init = function() {
- elapsed('init');
// If at the beginning of the day, wait on the previous day until GIBS
// catches up (about three hours)
var initialDate;
@@ -378,133 +249,12 @@ class App extends React.Component {
initialDate.setUTCDate(initialDate.getUTCDate() - 1);
}
}
- // Models
- var models = {
- wv: {
- events: util.events()
- }
- };
- var ui = {};
- // Attach to wvx object for debugging
- wvx.models = models;
-
- wvx.ui = ui;
-
- models.proj = projectionModel(config);
- models.palettes = palettesModel(models, config);
- models.layers = layersModel(models, config);
- models.date = dateModel(models, config, {
- initial: initialDate
- });
- models.map = mapModel(models, config);
- models.link = linkModel(config);
-
- if (config.features.compare) {
- models.compare = compareModel(models, config);
- models.link.register(models.compare);
- }
- models.link
- .register(models.proj)
- .register(models.layers)
- .register(models.date)
- .register(models.palettes)
- .register(models.map);
- models.link.load(state);
+ const models = self.props.models;
if (config.features.googleTagManager) {
googleTagManager.init(config.features.googleTagManager.id); // Insert google tag manager
}
- // HACK: Map needs to be created before the data download model
- var mapComponents = {
- Rotation: MapRotate,
- Runningdata: MapRunningData,
- Layerbuilder: mapLayerBuilder,
- Dateline: mapDateLineBuilder,
- Precache: mapPrecacheTile
- };
- ui.map = mapui(models, config, mapComponents);
- registerMapMouseHandlers(ui.map.proj, self.mapMouseEvents);
-
- ui.map.animate = mapAnimate(models, config, ui);
- if (config.features.animation) {
- models.anim = animationModel(models, config);
- models.link.register(models.anim);
- }
- if (config.features.dataDownload) {
- models.data = dataModel(models, config);
- models.link.register(models.data);
- }
- if (config.features.naturalEvents) {
- models.naturalEvents = naturalEventsModel(models, config, ui);
- models.link.register(models.naturalEvents);
- }
- if (config.features.tour) {
- models.tour = tourModel(config, ui);
- models.link.register(models.tour);
- }
- // HACK: Map needs permalink state loaded before starting. But
- // data download now needs it too.
- models.link.load(state); // needs to be loaded twice
- self.props.updateConfig(models, config); // crutch between old state system and redux
- elapsed('ui');
- // Create widgets
- ui.alert = alertUi(ui);
- ui.sidebar = sidebarUi(models, config, ui);
- ui.tour = tourUi(models, ui, config);
- ui.activeLayers = layersActive(models, ui, config);
- ui.addModal = layersModal(models, ui, config);
- ui.layerSettingsModal = layersOptions(models, ui, config);
-
- // Test via a getter in the options object to see if the passive property is accessed
- ui.supportsPassive = false;
- try {
- var opts = Object.defineProperty({}, 'passive', {
- get: function() {
- ui.supportsPassive = true;
- }
- });
- window.addEventListener('testPassive', null, opts);
- window.removeEventListener('testPassive', null, opts);
- } catch (e) {}
-
- function timelineInit() {
- ui.timeline = timeline(models, config, ui);
- ui.timeline.data = timelineData(models, config, ui);
- ui.timeline.zoom = timelineZoom(models, config, ui);
- ui.timeline.ticks = timelineTicks(models, config, ui);
- ui.timeline.pick = timelinePick(models, config, ui);
- ui.timeline.pan = timelinePan(models, config, ui);
- ui.timeline.input = timelineInput(models, config, ui);
- ui.timeline.config = timelineConfig(models, config, ui);
- if (config.features.animation) {
- ui.anim = {};
- ui.anim.rangeselect = animationRangeSelect(models, config, ui); // SETS STATE: NEEDS TO LOAD BEFORE ANIMATION WIDGET
- ui.anim.widget = animationWidget(models, config, ui);
- ui.anim.gif = animationGif(models, config, ui);
- ui.anim.ui = animationUi(models, ui);
- }
- if (config.features.compare) {
- ui.timeline.compare = timelineCompare(models, config, ui);
- }
-
- ui.dateLabel = dateLabel(models);
- }
- if (config.startDate) {
- if (!util.browser.small) {
- // If mobile device, do not build timeline
- timelineInit();
- }
- ui.dateWheels = dateWheels(models, config);
- }
-
- if (config.features.dataDownload) {
- ui.data = dataUi(models, ui, config);
- }
- if (config.features.naturalEvents) {
- var request = naturalEventsRequest(models, ui, config);
- ui.naturalEvents = naturalEventsUI(models, ui, config, request);
- }
- // ui.link = linkUi(models, config);
+ // registerMapMouseHandlers(ui.map.proj, self.mapMouseEvents);
if (config.features.alert) {
let notificationURL = config.features.alert
? config.features.alert.url
@@ -520,48 +270,10 @@ class App extends React.Component {
}
self.props.requestNotifications(notificationURL);
}
- if (config.features.compare) {
- ui.compare = compareUi(models, ui, config);
- }
- // permalink Cruch
- models.link.events.on(
- 'update',
- lodashDebounce(
- () => self.props.updatePermalink(models.link.toQueryString()),
- 100
- )
- );
- // FIXME: Old hack
- $(window).resize(function() {
- if (util.browser.small) {
- $('#productsHoldertabs li.first a').trigger('click');
- }
- if (!ui.timeline) {
- timelineInit();
- }
- });
-
document.activeElement.blur();
$('input').blur();
$('#eventsHolder').hide();
- if (config.features.dataDownload) {
- models.data.events.on('queryResults', function() {
- ui.data.onViewChange();
- });
- ui.map.events.on('extent', function() {
- ui.data.onViewChange();
- });
- // FIXME: This is a hack
- models.map.events.on('projection', models.data.updateProjection);
- }
- // Sink all focus on inputs if click unhandled
- $(document).click(function(event) {
- if (event.target.nodeName !== 'INPUT') {
- $('input').blur();
- }
- });
-
// Console notifications
if (Brand.release()) {
console.info(
@@ -574,17 +286,16 @@ class App extends React.Component {
} else {
console.warn('Development version');
}
- debugLayers(ui, models, config);
errorReport();
models.wv.events.trigger('startup');
- elapsed('done');
// Reset Worldview when clicking on logo
$(document).click(function(e) {
if (e.target.id === 'wv-logo') resetWorldview(e);
});
+ self.props.updateLegacyInitComplete();
};
var resetWorldview = function(e) {
@@ -606,38 +317,22 @@ class App extends React.Component {
}
});
};
-
- var elapsed = function(message) {
- if (!parameters.elapsed) return;
- var t = new Date().getTime() - startTime;
- console.log(t, message);
- };
util.wrap(main)();
}
}
-
-function registerMapMouseHandlers(maps, events) {
- Object.values(maps).forEach(map => {
- let element = map.getTargetElement();
- let crs = map
- .getView()
- .getProjection()
- .getCode();
- element.addEventListener('mousemove', event => {
- events.trigger('mousemove', event, map, crs);
- });
- element.addEventListener('mouseout', event => {
- events.trigger('mouseout', event, map, crs);
- });
- });
+function mapStateToProps(state, ownProps) {
+ return {
+ legacy: state.legacy,
+ state: state,
+ config: state.config,
+ parameters: state.parameters,
+ models: ownProps.models,
+ mapMouseEvents: ownProps.mapMouseEvents
+ };
}
-
const mapDispatchToProps = dispatch => ({
- updateConfig: (models, configObject) => {
- dispatch(sendConfigToStore(models, configObject));
- },
- updatePermalink: permalink => {
- dispatch(updatePermalink(permalink));
+ updateLegacyInitComplete: () => {
+ dispatch(updateLegacyInitComplete());
},
requestNotifications: location => {
const promise = dispatch(
@@ -653,6 +348,6 @@ const mapDispatchToProps = dispatch => ({
});
export default connect(
- null,
+ mapStateToProps,
mapDispatchToProps
)(App);
diff --git a/web/js/combine-models.js b/web/js/combine-models.js
new file mode 100644
index 000000000..bc8918fc5
--- /dev/null
+++ b/web/js/combine-models.js
@@ -0,0 +1,53 @@
+import util from './util/util';
+import { dateModel } from './date/model';
+import { layersModel } from './layers/model';
+
+import { mapModel } from './map/model';
+import { animationModel } from './animation/model';
+import { palettesModel } from './palettes/model';
+import { dataModel } from './data/model';
+import { projectionModel } from './projection/model';
+import { compareModel } from './compare/model';
+import { tourModel } from './tour/model';
+import naturalEventsModel from './natural-events/model';
+
+export function combineModels(config, state) {
+ let models = {
+ wv: {
+ events: util.events()
+ }
+ };
+ var initialDate;
+ if (config.defaults.startDate) {
+ initialDate = util.parseDateUTC(config.defaults.startDate);
+ } else {
+ initialDate = util.now();
+ if (initialDate.getUTCHours() < 3) {
+ initialDate.setUTCDate(initialDate.getUTCDate() - 1);
+ }
+ }
+ models.proj = projectionModel(config);
+ models.palettes = palettesModel(models, config);
+ models.layers = layersModel(models, config);
+ models.date = dateModel(models, config, {
+ initial: initialDate
+ });
+ models.map = mapModel(models, config);
+ if (config.features.compare) {
+ models.compare = compareModel(models, config);
+ }
+ if (config.features.tour) {
+ models.tour = tourModel(config);
+ }
+ if (config.features.animation) {
+ models.anim = animationModel(models, config);
+ }
+ if (config.features.dataDownload) {
+ models.data = dataModel(models, config);
+ }
+ if (config.features.naturalEvents) {
+ models.naturalEvents = naturalEventsModel(models, config);
+ }
+
+ return models;
+}
diff --git a/web/js/combine-ui.js b/web/js/combine-ui.js
new file mode 100644
index 000000000..9ce8ed1bd
--- /dev/null
+++ b/web/js/combine-ui.js
@@ -0,0 +1,152 @@
+import util from './util/util';
+import { dateLabel } from './date/label';
+
+// compare
+import { compareUi } from './compare/ui';
+import { alertUi } from './alert/ui';
+// Timeline
+import dateWheels from './date/wheels';
+import { timeline } from './date/timeline';
+import { timelineData } from './date/timeline-data';
+import { timelineConfig } from './date/config';
+import { timelineZoom } from './date/timeline-zoom';
+import { timelineTicks } from './date/timeline-ticks';
+import { timelinePick } from './date/timeline-pick';
+import { timelinePan } from './date/timeline-pan';
+import { timelineInput } from './date/timeline-input';
+import { timelineCompare } from './date/compare-picks';
+// Tour
+import { tourUi } from './tour/ui';
+import { layersModal } from './layers/modal';
+import { layersActive } from './layers/active';
+import { layersOptions } from './layers/options';
+import { sidebarUi } from './sidebar/ui';
+import { mapui } from './map/ui';
+import { MapRotate } from './map/rotation';
+import { MapRunningData } from './map/runningdata';
+import { mapLayerBuilder } from './map/layerbuilder';
+import { mapDateLineBuilder } from './map/datelinebuilder';
+import { mapPrecacheTile } from './map/precachetile';
+import { mapAnimate } from './map/animate';
+import { dataUi } from './data/ui';
+import { animationUi } from './animation/ui';
+import { animationWidget } from './animation/widget';
+import { animationRangeSelect } from './animation/range-select';
+import { animationGif } from './animation/gif';
+// NaturalEvents
+import naturalEventsUI from './natural-events/ui';
+import naturalEventsRequest from './natural-events/request';
+import { debugLayers } from './debug';
+export function combineUi(models, config, MapMouseEvents) {
+ let ui = {};
+ let mapComponents = {
+ Rotation: MapRotate,
+ Runningdata: MapRunningData,
+ Layerbuilder: mapLayerBuilder,
+ Dateline: mapDateLineBuilder,
+ Precache: mapPrecacheTile
+ };
+ ui.map = mapui(models, config, mapComponents);
+ ui.map.animate = mapAnimate(models, config, ui);
+ ui.sidebar = sidebarUi(models, config, ui);
+ if (config.features.tour) {
+ ui.alert = alertUi(ui, config);
+ ui.tour = tourUi(models, ui, config);
+ }
+ ui.activeLayers = layersActive(models, ui, config);
+ ui.addModal = layersModal(models, ui, config);
+ ui.layerSettingsModal = layersOptions(models, ui, config);
+ // Test via a getter in the options object to see if the passive property is accessed
+ ui.supportsPassive = false;
+ try {
+ var opts = Object.defineProperty({}, 'passive', {
+ get: function() {
+ ui.supportsPassive = true;
+ }
+ });
+ window.addEventListener('testPassive', null, opts);
+ window.removeEventListener('testPassive', null, opts);
+ } catch (e) {}
+ function timelineInit() {
+ ui.timeline = timeline(models, config, ui);
+ ui.timeline.data = timelineData(models, config, ui);
+ ui.timeline.zoom = timelineZoom(models, config, ui);
+ ui.timeline.ticks = timelineTicks(models, config, ui);
+ ui.timeline.pick = timelinePick(models, config, ui);
+ ui.timeline.pan = timelinePan(models, config, ui);
+ ui.timeline.input = timelineInput(models, config, ui);
+ ui.timeline.config = timelineConfig(models, config, ui);
+ if (config.features.animation) {
+ ui.anim = {};
+ ui.anim.rangeselect = animationRangeSelect(models, config, ui); // SETS STATE: NEEDS TO LOAD BEFORE ANIMATION WIDGET
+ ui.anim.widget = animationWidget(models, config, ui);
+ ui.anim.gif = animationGif(models, config, ui);
+ ui.anim.ui = animationUi(models, ui);
+ }
+ if (config.features.compare) {
+ ui.timeline.compare = timelineCompare(models, config, ui);
+ }
+
+ ui.dateLabel = dateLabel(models);
+ }
+ if (config.startDate) {
+ if (!util.browser.small) {
+ // If mobile device, do not build timeline
+ timelineInit();
+ }
+ ui.dateWheels = dateWheels(models, config);
+ }
+ // FIXME: Old hack
+ $(window).resize(function() {
+ if (util.browser.small) {
+ $('#productsHoldertabs li.first a').trigger('click');
+ }
+ if (!ui.timeline) {
+ timelineInit();
+ }
+ });
+ if (config.features.dataDownload) {
+ ui.data = dataUi(models, ui, config);
+ }
+ if (config.features.naturalEvents) {
+ var request = naturalEventsRequest(models, ui, config);
+ ui.naturalEvents = naturalEventsUI(models, ui, config, request);
+ }
+ if (config.features.compare) {
+ ui.compare = compareUi(models, ui, config);
+ }
+ if (config.features.dataDownload) {
+ models.data.events.on('queryResults', function() {
+ ui.data.onViewChange();
+ });
+ ui.map.events.on('extent', function() {
+ ui.data.onViewChange();
+ });
+ // FIXME: This is a hack
+ models.map.events.on('projection', models.data.updateProjection);
+ }
+ registerMapMouseHandlers(ui.map.proj, MapMouseEvents);
+ // Sink all focus on inputs if click unhandled
+ $(document).click(function(event) {
+ if (event.target.nodeName !== 'INPUT') {
+ $('input').blur();
+ }
+ });
+ debugLayers(ui, models, config);
+ return ui;
+}
+function registerMapMouseHandlers(maps, events) {
+ Object.values(maps).forEach(map => {
+ let element = map.getTargetElement();
+ let crs = map
+ .getView()
+ .getProjection()
+ .getCode();
+ element.addEventListener('mousemove', event => {
+ events.trigger('mousemove', event, map, crs);
+ });
+ element.addEventListener('mouseout', event => {
+ events.trigger('mouseout', event, map, crs);
+ });
+ });
+}
diff --git a/web/js/compare/model.js b/web/js/compare/model.js
index 7a826d563..4452404c4 100644
--- a/web/js/compare/model.js
+++ b/web/js/compare/model.js
@@ -6,6 +6,7 @@ export function compareModel(models, config) {
self.active = false;
self.isCompareA = true;
self.mode = 'swipe';
+ self.value = 50;
self.events = util.events();
self.toggle = function() {
@@ -68,6 +69,7 @@ export function compareModel(models, config) {
self.value = Number(state.cv);
}
}
+ return self;
};
return self;
}
diff --git a/web/js/components/image-download/panel.js b/web/js/components/image-download/panel.js
index 8729a087b..86517e883 100644
--- a/web/js/components/image-download/panel.js
+++ b/web/js/components/image-download/panel.js
@@ -130,12 +130,12 @@ export default class ImageResSelection extends React.Component {
render() {
const { projection, lonlats, resolutions, maxImageSize } = this.props;
const { resolution, debugUrl } = this.state;
- const dimensions = getDimensions(projection, lonlats, resolution);
+ const dimensions = getDimensions(projection.id, lonlats, resolution);
const height = dimensions.height;
const width = dimensions.width;
const filetypeSelect = this._renderFileTypeSelect();
const worldfileSelect = this._renderWorldfileSelect();
-
+ console.log(projection, lonlats, resolution);
return (
<div className="wv-re-pick-wrapper wv-image">
<div
diff --git a/web/js/components/util/image-crop.js b/web/js/components/util/image-crop.js
index cc2c9bcf9..3cbb79ebf 100644
--- a/web/js/components/util/image-crop.js
+++ b/web/js/components/util/image-crop.js
@@ -34,14 +34,14 @@ export default class Crop extends React.Component {
<React.Fragment>
<div
id="wv-image-top"
- className="wv-image-coords wv-image-top"
+ className="wv-image-coords wv-image-top noselect"
style={topRightStyle}
>
{coordinates.topRight}
</div>
<div
id="wv-image-bottom"
- className="wv-image-coords wv-image-bottom"
+ className="wv-image-coords wv-image-bottom noselect"
style={bottomLeftStyle}
>
{coordinates.bottomLeft}
diff --git a/web/js/containers/image-download.js b/web/js/containers/image-download.js
index 4bf68d83b..6206c57a7 100644
--- a/web/js/containers/image-download.js
+++ b/web/js/containers/image-download.js
@@ -70,30 +70,30 @@ class ImageDownloadContainer extends Component {
});
}
render() {
- const { projection, models, url, onClose } = this.props;
+ const { proj, map, url, onClose, models } = this.props;
const { boundaries, windowWidth, windowHeight } = this.state;
const { x, y, x2, y2 } = boundaries;
- const isGeoProjection = projection === 'geographic';
+ const isGeoProjection = proj.id === 'geographic';
const fileTypes = isGeoProjection ? fileTypesGeo : fileTypesPolar;
const resolutions = isGeoProjection ? resolutionsGeo : resolutionsPolar;
const lonlats = imageUtilGetCoordsFromPixelValues(
boundaries,
- models.map.selectedMap
+ map.selectedMap
);
- const crs = models.proj.selected.crs;
+ const crs = proj.selected.crs;
const geolonlat1 = olProj.transform(lonlats[0], crs, 'EPSG:4326');
const geolonlat2 = olProj.transform(lonlats[1], crs, 'EPSG:4326');
const resolution = imageUtilCalculateResolution(
- Math.round(models.map.getZoom()),
+ Math.round(map.getZoom()),
isGeoProjection,
- models.proj.selected.resolutions
+ proj.selected.resolutions
);
-
+ console.log(proj.selected.resolutions);
return (
<React.Fragment>
<Panel
- projection={projection}
+ projection={proj}
fileTypes={fileTypes}
resolutions={resolutions}
lonlats={lonlats}
@@ -133,8 +133,8 @@ class ImageDownloadContainer extends Component {
}
function mapStateToProps(state) {
- const { id } = state.projection;
- const { config, models } = state.legacy;
+ const { config, models, proj } = state;
+ const { map } = state.legacy;
let url = DEFAULT_URL;
if (config.features.imageDownload && config.features.imageDownload.url) {
url = config.features.imageDownload.url;
@@ -143,10 +143,10 @@ function mapStateToProps(state) {
url = config.parameters.imageDownload;
util.warn('Redirecting image download to: ' + url);
}
-
return {
- projection: id,
+ proj,
url,
+ map,
models
};
}
@@ -162,7 +162,8 @@ export default connect(
)(ImageDownloadContainer);
ImageDownloadContainer.propTypes = {
- projection: PropTypes.string,
+ proj: PropTypes.object.isRequired,
+ map: PropTypes.object.isRequired,
models: PropTypes.object.isRequired,
url: PropTypes.string.isRequired,
onClose: PropTypes.func.isRequired
diff --git a/web/js/containers/info.js b/web/js/containers/info.js
index bd9b47ddb..0a104d251 100644
--- a/web/js/containers/info.js
+++ b/web/js/containers/info.js
@@ -41,7 +41,9 @@ class InfoList extends Component {
sendFeedback,
feedbackIsInitiated,
aboutClick,
- notifications
+ notifications,
+ config,
+ models
} = this.props;
let arr = [
{
@@ -52,11 +54,6 @@ class InfoList extends Component {
sendFeedback(feedbackIsInitiated);
}
},
- {
- text: 'Explore Worldview',
- iconClass: 'ui-icon fa fa-truck fa-fw',
- id: 'start_tour_info_item'
- },
{
text: 'Source Code',
iconClass: 'ui-icon fa fa-code fa-fw',
@@ -78,6 +75,23 @@ class InfoList extends Component {
}
}
];
+ if (
+ config.features.tour &&
+ config.stories &&
+ config.storyOrder &&
+ window.innerWidth >= 740 &&
+ window.innerHeight >= 615
+ ) {
+ const exploreWorlviewObj = {
+ text: 'Explore Worldview',
+ iconClass: 'ui-icon fa fa-truck fa-fw',
+ id: 'start_tour_info_item',
+ onClick: () => {
+ models.tour.events.trigger('start-tour');
+ }
+ };
+ arr.splice(1, 0, exploreWorlviewObj);
+ }
if (notifications.isActive) {
let obj = this.getNotificationListItem();
arr.splice(4, 0, obj);
@@ -95,7 +109,9 @@ function mapStateToProps(state) {
return {
feedbackIsInitiated: isInitiated,
- notifications: state.notifications
+ notifications: state.notifications,
+ config: state.config,
+ models: state.models
};
}
const mapDispatchToProps = dispatch => ({
diff --git a/web/js/containers/projection.js b/web/js/containers/projection.js
index 1aec60404..6d50187de 100644
--- a/web/js/containers/projection.js
+++ b/web/js/containers/projection.js
@@ -27,9 +27,9 @@ const infoArray = [
class ProjectionList extends Component {
updateProjection(id) {
- const { updateProjection, models } = this.props;
+ const { updateProjection, models, config } = this.props;
models.proj.select(id); // state migration crutch
- updateProjection(id);
+ updateProjection(id, config);
}
render() {
const { projection } = this.props;
@@ -45,13 +45,14 @@ class ProjectionList extends Component {
}
function mapStateToProps(state) {
return {
- models: state.legacy.models,
- projection: state.projection.id
+ models: state.models,
+ config: state.config,
+ projection: state.proj.id
};
}
const mapDispatchToProps = (dispatch, ownProps) => ({
- updateProjection: id => {
- dispatch(changeProjection(id));
+ updateProjection: (id, config) => {
+ dispatch(changeProjection(id, config));
}
});
diff --git a/web/js/containers/share.js b/web/js/containers/share.js
index 452f60830..15ca131c7 100644
--- a/web/js/containers/share.js
+++ b/web/js/containers/share.js
@@ -60,7 +60,7 @@ class ShareLinkContainer extends Component {
let url = window.location.href;
let prefix = url.split('?')[0];
prefix = prefix !== null && prefix !== undefined ? prefix : url;
- return !queryString ? prefix : prefix + '?' + queryString;
+ return !queryString ? prefix : prefix + queryString;
}
onLinkClick(type) {
const permalink = this.getPermalink();
@@ -185,7 +185,7 @@ class ShareLinkContainer extends Component {
function mapStateToProps(state) {
const { queryString } = state.link;
- const { config } = state.legacy;
+ const { config } = state;
return {
queryString: queryString,
@@ -211,5 +211,5 @@ ShareLinkContainer.propTypes = {
projection: PropTypes.string,
queryString: PropTypes.string,
requestShortLink: PropTypes.function,
- mock: PropTypes.function
+ mock: PropTypes.string
};
diff --git a/web/js/data/model.js b/web/js/data/model.js
index 43225ce0d..ee3f68818 100644
--- a/web/js/data/model.js
+++ b/web/js/data/model.js
@@ -302,6 +302,8 @@ export function dataModel(models, config) {
});
}
}
+ self.loaded = true;
+ return self;
};
var query = function() {
diff --git a/web/js/date/model.js b/web/js/date/model.js
index a219cd5c4..a9806ee9f 100644
--- a/web/js/date/model.js
+++ b/web/js/date/model.js
@@ -5,8 +5,8 @@ export function dateModel(models, config, spec) {
var self = {};
self.events = util.events();
- self.selected = null;
- self.selectedB = null;
+ self.selected = util.now();
+ self.selectedB = util.dateAdd(self.selected, 'day', -7);
self.activeDate = 'selected';
self.monthAbbr = [
@@ -158,6 +158,7 @@ export function dateModel(models, config, spec) {
if (state.t1) {
self.select(state.t1, 'selectedB');
}
+ return self;
};
init();
return self;
diff --git a/web/js/layers/model.js b/web/js/layers/model.js
index d835d3439..91068c831 100644
--- a/web/js/layers/model.js
+++ b/web/js/layers/model.js
@@ -506,8 +506,9 @@ export function layersModel(models, config) {
});
};
self.load = function(state, errors) {
- if (self.loaded) return;
-
+ if (self.loaded) {
+ return self;
+ }
var layers;
if (config.features.compare) {
layers = [
@@ -564,6 +565,7 @@ export function layersModel(models, config) {
self.activeLayers = 'activeB';
}
self.loaded = true;
+ return self;
};
var forGroup = function(group, spec, activeLayers) {
spec = spec || {};
diff --git a/web/js/layers/options.js b/web/js/layers/options.js
index 5fe2cd277..62c9f8d96 100644
--- a/web/js/layers/options.js
+++ b/web/js/layers/options.js
@@ -57,6 +57,7 @@ export function layersOptions(models, ui, config) {
* Mount component once customs Config is loaded
*/
var loaded = function() {
+ console.log(config);
self.reactComponent = render(
<LayerSettings
setCustom={models.palettes.setCustom}
diff --git a/web/js/link/model.js b/web/js/link/model.js
index d7ff5092a..e05da8fcc 100644
--- a/web/js/link/model.js
+++ b/web/js/link/model.js
@@ -2,6 +2,7 @@ import lodashEach from 'lodash/each';
import lodashMap from 'lodash/map';
import lodashIsArray from 'lodash/isArray';
import lodashIsObject from 'lodash/isObject';
+import { assign, isEmpty, forOwn, keys as lodashKeys } from 'lodash';
import util from '../util/util';
export function linkModel(config) {
@@ -25,11 +26,11 @@ export function linkModel(config) {
var init = function() {};
- self.register = function(component) {
+ self.register = function(component, key, dispatchLegacyUpdate, legacy) {
components.push(component);
if (component.events) {
component.events.any(function() {
- self.events.trigger('update');
+ // self.events.trigger('update');
});
}
return self;
@@ -71,12 +72,20 @@ export function linkModel(config) {
return strings.join('&');
};
- self.load = function(state, errors) {
- errors = errors || [];
- lodashEach(components, function(component) {
- component.load(state, errors);
- });
- };
+ // self.load = function(state, errors, dispatchLegacyUpdate, legacy) {
+ // errors = errors || [];
+ // console.log(components);
+ // lodashEach(components, function(component, i) {
+ // // component.load(state, errors);
+ // console.log(component);
+ // // if (!isEmpty(legacy[keys[i]])) {
+ // // forOwn(legacy[keys[i]], (value, subKey) => {
+ // // console.log(component[subKey], value);
+ // // component[subKey] = value;
+ // // });
+ // // }
+ // });
+ // };
var encode = function(value) {
var encoded = encodeURIComponent(value);
diff --git a/web/js/location.js b/web/js/location.js
new file mode 100644
index 000000000..9d6c114cc
--- /dev/null
+++ b/web/js/location.js
@@ -0,0 +1,121 @@
+import { merge as lodashMerge, assign, has, set } from 'lodash';
+
+// legacy crutches
+import { getLayersParameterSetup } from './modules/layers/util';
+import { getDateParameterSetup } from './modules/date/util';
+import { getNaturalEventsParameterSetup } from './modules/natural-events/util';
+import { getDataDownloadParameterSetup } from './modules/data/util';
+import { getCompareParameterSetup } from './modules/compare/util';
+import { getAnimationParameterSetup } from './modules/animation/util';
+import { getTourParameterSetup } from './modules/tour/util';
+import { getMapParameterSetup } from './modules/map/util';
+import util from './util/util';
+
+export function mapLocationToState(state, location) {
+ if (location.search) {
+ let parameters = util.fromQueryString(location.search);
+ let stateFromLocation = location.query;
+ if (has(parameters, 'ca')) {
+ set(stateFromLocation, 'legacy.compare.active', true);
+ } else {
+ set(stateFromLocation, 'legacy.compare.active', false);
+ }
+ return lodashMerge({}, state, stateFromLocation);
+ } else return state;
+}
+const simpleParameters = {
+ p: {
+ stateKey: 'proj.id',
+ initialState: 'geographic'
+ }
+};
+export function getParamObject(parameters, config, models, legacyState) {
+ let errors = [];
+
+ let compareParamObject = {};
+ let eventParamObject = {};
+ let tourParamObject = {};
+ let animationParamObject = {};
+ models.proj.load(legacyState, []);
+
+ const mapParamObject = getMapParameterSetup(
+ parameters,
+ config,
+ models,
+ legacyState,
+ errors
+ );
+ if (config.features.compare) {
+ compareParamObject = getCompareParameterSetup(
+ parameters,
+ config,
+ models,
+ legacyState,
+ errors
+ );
+ }
+ if (config.features.tour) {
+ tourParamObject = getTourParameterSetup(
+ parameters,
+ config,
+ models,
+ legacyState,
+ errors
+ );
+ }
+ if (config.features.animation) {
+ animationParamObject = getAnimationParameterSetup(
+ parameters,
+ config,
+ models,
+ legacyState,
+ errors
+ );
+ }
+ const layersParamObject = getLayersParameterSetup(
+ parameters,
+ config,
+ models,
+ legacyState,
+ errors
+ );
+ const dateParamObject = getDateParameterSetup(
+ parameters,
+ config,
+ models,
+ legacyState,
+ errors
+ );
+ if (config.features.naturalEvents) {
+ eventParamObject = getNaturalEventsParameterSetup(
+ parameters,
+ config,
+ models,
+ legacyState,
+ errors
+ );
+ }
+ const dataParamObject = getDataDownloadParameterSetup(
+ parameters,
+ config,
+ models,
+ legacyState,
+ errors
+ );
+
+ const obj = assign(
+ {},
+ simpleParameters, // Once migrated completely to redux most configurations should be here
+ dateParamObject,
+ layersParamObject,
+ animationParamObject,
+ eventParamObject,
+ dataParamObject,
+ compareParamObject,
+ tourParamObject,
+ mapParamObject
+ );
+ return {
+ global: obj
+ };
+}
diff --git a/web/js/main.js b/web/js/main.js
index 7bf21b9cc..128c6faaa 100644
--- a/web/js/main.js
+++ b/web/js/main.js
@@ -3,19 +3,111 @@ import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
-import thunk from 'redux-thunk';
-
-import reducers from './modules/reducers';
+import { each as lodashEach, debounce as lodashDebounce } from 'lodash';
+import { getMiddleware } from './redux-config-helpers';
+import {
+ createReduxLocationActions,
+ listenForHistoryChange
+} from 'redux-location-state';
+import { mapLocationToState, getParamObject } from './location';
+import { stateToParams } from './redux-location-state-customs';
+import createBrowserHistory from 'history/createBrowserHistory';
+import reducers, { getInitialState } from './modules/combine-reducers';
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 { updatePermalink } from './modules/link/actions';
+import { combineUi } from './combine-ui';
+import palettes from './palettes/palettes';
+import { updateLegacyModule } from './modules/migration/actions';
+
+const isDevelop = !!(
+ process &&
+ process.env &&
+ process.env.NODE_ENV === 'development'
+);
+let parameters = util.fromQueryString(location.search);
+const configURI = Brand.url('config/wv.json');
+const startTime = new Date().getTime();
-const store = createStore(reducers, applyMiddleware(thunk));
+let elapsed = util.elapsed;
// Document ready function
window.onload = () => {
+ if (!parameters.elapsed) {
+ elapsed = function() {};
+ }
+ elapsed('loading config', startTime, parameters);
+ var promise = $.getJSON(configURI);
+
+ loadingIndicator.delayed(promise, 1000);
+ promise
+ .done(config => {
+ elapsed('Config loaded', startTime, parameters);
+ let legacyState = parse(parameters, config);
+ let requirements = [palettes.requirements(legacyState, config, true)];
+ $.when
+ .apply(null, requirements)
+ .then(() => render(config, parameters, legacyState));
+ })
+ .fail(util.error);
+};
+
+const render = (config, parameters, legacyState) => {
+ config.parameters = parameters;
+ let models = combineModels(config, legacyState);
+
+ const paramSetup = getParamObject(parameters, config, models, legacyState);
+ let errors = [];
+ const history = createBrowserHistory();
+
+ const {
+ locationMiddleware,
+ reducersWithLocation
+ } = createReduxLocationActions(
+ paramSetup,
+ mapLocationToState,
+ history,
+ reducers,
+ stateToParams
+ );
+ const middleware = getMiddleware(isDevelop, locationMiddleware);
+ const store = createStore(
+ reducersWithLocation,
+ getInitialState(models, config, parameters),
+ applyMiddleware(...middleware)
+ );
+ lodashEach(models, function(component, i) {
+ if (component.load && !component.loaded) {
+ component.load(legacyState, errors);
+ }
+ const dispatchUpdate = lodashDebounce(() => {
+ store.dispatch(updateLegacyModule(i, component));
+ }, 100);
+ // replace link register
+ component.events.any(dispatchUpdate);
+ });
+
+ let queryString = '';
+ history.listen((location, action) => {
+ const newString = location.search;
+ if (queryString !== newString) {
+ queryString = newString;
+ store.dispatch(updatePermalink(queryString));
+ }
+ });
+ listenForHistoryChange(store, history);
+ elapsed('Render', startTime, parameters);
+
+ let mouseMoveEvents = util.events();
ReactDOM.render(
<Provider store={store}>
- <App />
+ <App models={models} mapMouseEvents={mouseMoveEvents} />
</Provider>,
document.getElementById('app')
);
+ combineUi(models, config, mouseMoveEvents);
};
diff --git a/web/js/map/model.js b/web/js/map/model.js
index 44255cca5..6ff4dec3e 100644
--- a/web/js/map/model.js
+++ b/web/js/map/model.js
@@ -1,4 +1,7 @@
import util from '../util/util';
+import * as olProj from 'ol/proj';
+import { register } from 'ol/proj/proj4';
+import proj4 from 'proj4';
import lodashClone from 'lodash/clone';
import { intersects } from 'ol/extent';
@@ -9,6 +12,24 @@ export function mapModel(models, config) {
self.selectedMap = null;
self.events = util.events();
self.rotation = 0;
+ const init = function() {
+ if (!config.projections) {
+ return;
+ }
+
+ Object.values(config.projections).forEach(proj => {
+ if (proj.crs && proj.proj4) {
+ self.register(proj.crs, proj.proj4);
+ }
+ });
+ };
+ self.register = function(crs, def) {
+ if (def && proj4) {
+ proj4.defs(crs, def);
+ register(proj4);
+ olProj.get(crs).setExtent(def.maxExtent);
+ }
+ };
/*
* Emits update event
*
@@ -26,6 +47,7 @@ export function mapModel(models, config) {
// Give other components access to zoom Level
self.updateMap = function(map) {
self.selectedMap = map;
+ self.events.trigger('update-map');
};
self.getZoom = function() {
return self.selectedMap ? self.selectedMap.getView().getZoom() : null;
@@ -66,6 +88,8 @@ export function mapModel(models, config) {
self.rotation = state.r * (Math.PI / 180.0);
} // convert to radians
}
+ self.loaded = true;
+ return self;
};
/*
@@ -125,6 +149,6 @@ export function mapModel(models, config) {
return [minLon, minLat, maxLon, maxLat];
};
-
+ init();
return self;
}
diff --git a/web/js/map/ui.js b/web/js/map/ui.js
index f8efdeb03..97ab67190 100644
--- a/web/js/map/ui.js
+++ b/web/js/map/ui.js
@@ -42,9 +42,7 @@ export function mapui(models, config) {
var dateline = mapDateLineBuilder(models, config);
var precache = mapPrecacheTile(models, config, cache, self);
var compare = mapCompare(models, config);
-
var dataRunner = (self.runningdata = new MapRunningData(models, compare));
-
self.mapIsbeingDragged = false;
self.mapIsbeingZoomed = false;
self.proj = {}; // One map for each projection
diff --git a/web/js/modules/animation/util.js b/web/js/modules/animation/util.js
new file mode 100644
index 000000000..2dd494d42
--- /dev/null
+++ b/web/js/modules/animation/util.js
@@ -0,0 +1,98 @@
+import { cloneDeep as lodashCloneDeep, get } from 'lodash';
+
+export function getAnimationParameterSetup(
+ parameters,
+ config,
+ models,
+ legacyState,
+ errors
+) {
+ const loadedModel = lodashCloneDeep(models.anim.load(legacyState, errors)); // use legacy parser
+ const initialEnd = get(models, 'date.selected');
+ const initialStart = get(models, 'date.selectedB');
+
+ return {
+ ab: {
+ stateKey: 'legacy.anim.rangeState.state',
+ initialState: 'off',
+ options: {
+ parse: () => {
+ return get(loadedModel, 'rangeState.state') || 'off';
+ },
+ serialize: () => {
+ return get(models, 'anim.rangeState.state') || 'off';
+ }
+ }
+ },
+ as: {
+ stateKey: 'legacy.anim.rangeState.startDate',
+ initialState: initialEnd,
+ type: 'date',
+ options: {
+ parse: () => {
+ return get(loadedModel, 'rangeState.startDate');
+ },
+ serialize: () => {
+ const isAnimationActive =
+ get(models, 'anim.rangeState.state') === 'on';
+ return isAnimationActive
+ ? get(models, 'anim.rangeState.startDate')
+ : undefined;
+ }
+ }
+ },
+ ae: {
+ stateKey: 'legacy.anim.rangeState.endDate',
+ initialState: initialStart,
+ type: 'date',
+ options: {
+ parse: () => {
+ return get(loadedModel, 'rangeState.endDate') || undefined;
+ },
+ serialize: () => {
+ const isAnimationActive =
+ get(models, 'anim.rangeState.state') === 'on';
+ return isAnimationActive
+ ? get(models, 'anim.rangeState.endDate')
+ : undefined;
+ }
+ }
+ },
+ av: {
+ stateKey: 'legacy.anim.rangeState.speed',
+ initialState: 3.0,
+ type: 'number',
+ options: {
+ serializeNeedsGlobalState: true,
+ parse: () => {
+ return get(loadedModel, 'anim.rangeState.speed') || 3.0;
+ },
+ serialize: (currentItemState, state) => {
+ const isAnimationActive =
+ get(models, 'anim.rangeState.state') === 'on';
+ return isAnimationActive
+ ? get(models, 'anim.rangeState.speed')
+ : undefined;
+ }
+ }
+ },
+ al: {
+ stateKey: 'legacy.anim.rangeState.loop',
+ type: 'bool',
+ initialState: false,
+ options: {
+ setAsEmptyItem: true,
+ parse: () => {
+ return get(loadedModel, 'rangeState.loop');
+ },
+ serialize: (currentItemState, state) => {
+ const isAnimationActive =
+ get(models, 'anim.rangeState.state') === 'on';
+ return isAnimationActive
+ ? get(models, 'anim.rangeState.loop')
+ : undefined;
+ }
+ }
+ }
+ };
+}
diff --git a/web/js/modules/reducers.js b/web/js/modules/combine-reducers.js
similarity index 63%
rename from web/js/modules/reducers.js
rename to web/js/modules/combine-reducers.js
index 908645f5f..1f5cb2f60 100644
--- a/web/js/modules/reducers.js
+++ b/web/js/modules/combine-reducers.js
@@ -8,14 +8,28 @@ import {
notificationsRequest,
notificationsReducer
} from './notifications/reducers';
+import { getProjInitialState } from './projection/util';
+export function getInitialState(models, config, parameters) {
+ return {
+ parameters,
+ config,
+ models,
+ legacy: models,
+ proj: getProjInitialState(config)
+ };
+}
+const defaultReducer = (state = {}) => state;
const reducers = {
- projection: projectionReducer,
+ proj: projectionReducer,
modal: modalReducer,
legacy: legacyReducer,
feedback: feedbackReducer,
link: linkReducer,
notifications: notificationsReducer,
+ config: defaultReducer,
+ models: defaultReducer,
+ parameters: defaultReducer,
modalAboutPage,
shortLink,
notificationsRequest
diff --git a/web/js/modules/compare/util.js b/web/js/modules/compare/util.js
new file mode 100644
index 000000000..6d103d030
--- /dev/null
+++ b/web/js/modules/compare/util.js
@@ -0,0 +1,58 @@
+import { cloneDeep as lodashCloneDeep, get } from 'lodash';
+
+export function getCompareParameterSetup(
+ parameters,
+ config,
+ models,
+ legacyState,
+ errors
+) {
+ const loadedModel = lodashCloneDeep(models.compare.load(legacyState, errors)); // use legacy parser
+ return {
+ ca: {
+ stateKey: 'legacy.compare.isCompareA',
+ initialState: true,
+ type: 'bool',
+ options: {
+ setAsEmptyItem: true,
+ serializeNeedsGlobalState: true,
+ parse: () => {
+ return loadedModel.isCompareA;
+ },
+ serialize: (currentItemState, state) => {
+ const compareIsActive = get(state, 'legacy.compare.active');
+ return compareIsActive ? currentItemState : undefined;
+ }
+ }
+ },
+ cm: {
+ stateKey: 'legacy.compare.mode',
+ initialState: 'swipe',
+ options: {
+ serializeNeedsGlobalState: true,
+ parse: () => {
+ return loadedModel.mode || 'swipe';
+ },
+ serialize: (currentItemState, state) => {
+ const compareIsActive = get(state, 'legacy.compare.active');
+ return compareIsActive ? currentItemState || 'swipe' : undefined;
+ }
+ }
+ },
+ cv: {
+ stateKey: 'legacy.compare.value',
+ initialState: 50,
+ type: 'number',
+ options: {
+ serializeNeedsGlobalState: true,
+ parse: () => {
+ return loadedModel.value || 50;
+ },
+ serialize: (currentItemState, state) => {
+ const compareIsActive = get(state, 'legacy.compare.active');
+ return compareIsActive ? currentItemState || 50 : undefined;
+ }
+ }
+ }
+ };
+}
diff --git a/web/js/modules/data/util.js b/web/js/modules/data/util.js
new file mode 100644
index 000000000..605599c11
--- /dev/null
+++ b/web/js/modules/data/util.js
@@ -0,0 +1,31 @@
+import { get } from 'redux-location-state/lib/helpers';
+import { encode } from '../link/util';
+export function getDataDownloadParameterSetup(
+ parameters,
+ config,
+ models,
+ legacyState,
+ errors
+) {
+ const loadedModel = models.data.load(legacyState, errors);
+ return {
+ download: {
+ stateKey: 'legacy.data.active',
+ initialState: false,
+ type: 'bool',
+ options: {
+ delimiter: ',',
+ serializeNeedsGlobalState: true,
+ parse: () => {
+ return loadedModel.active || false;
+ },
+ serialize: (currentItemState, currentState) => {
+ const selected = get(currentState, 'legacy.data.selectedProduct');
+ if (!currentItemState) return false;
+
+ return encode(selected);
+ }
+ }
+ }
+ };
+}
diff --git a/web/js/modules/date/constants.js b/web/js/modules/date/constants.js
new file mode 100644
index 000000000..e69de29bb
diff --git a/web/js/modules/date/util.js b/web/js/modules/date/util.js
new file mode 100644
index 000000000..705b7a671
--- /dev/null
+++ b/web/js/modules/date/util.js
@@ -0,0 +1,156 @@
+import util from '../../util/util';
+import { get } from 'lodash';
+
+export function getDateParameterSetup(
+ parameters,
+ config,
+ models,
+ legacyState,
+ errors
+) {
+ const initialState = models.date.selected;
+ const modelLoaded = models.date.load(legacyState, errors);
+ const bInit = util.dateAdd(initialState, 'day', -7);
+ return {
+ t: {
+ stateKey: 'legacy.date.selected',
+ initialState: initialState,
+ type: 'date',
+ options: {
+ serializeNeedsGlobalState: true,
+ setAsEmptyItem: true,
+ serialize: (currentItemState, state) => {
+ // intense hacking!
+ // just a temporary crutch
+ const isActive = get(state, 'legacy.compare.active');
+ const isCompareA = get(models, 'compare.isCompareA');
+ const dateB = get(models, 'date.selectedB');
+ if (!currentItemState) currentItemState = initialState;
+ return !isActive && !isCompareA
+ ? serializeDate(dateB)
+ : initialState === currentItemState
+ ? undefined
+ : serializeDate(currentItemState);
+ },
+ parse: () => {
+ return modelLoaded.selected;
+ }
+ }
+ },
+ t1: {
+ stateKey: 'legacy.date.selectedB',
+ initialState: bInit,
+ type: 'date',
+ options: {
+ serializeNeedsGlobalState: true,
+ serialize: (currentItemState, state) => {
+ const isActive = get(state, 'legacy.compare.active');
+ if (!isActive) return undefined;
+ if (!currentItemState) currentItemState = bInit;
+ return serializeDate(currentItemState || bInit);
+ },
+ parse: () => {
+ return modelLoaded.selectedB || bInit;
+ }
+ }
+ },
+ z: {
+ stateKey: 'legacy.date.selectedZoom',
+ initialState: 3,
+ type: 'number',
+ options: {
+ parse: () => modelLoaded.selectedZoom,
+ serialize: () => {
+ return models.date.selectedZoom.toString();
+ }
+ }
+ }
+ // now: {
+ // stateKey: 'legacy.date.now',
+ // initialState: ''
+ // }
+ };
+}
+export function serializeDate(date) {
+ return (
+ date.toISOString().split('T')[0] +
+ '-' +
+ 'T' +
+ date
+ .toISOString()
+ .split('T')[1]
+ .slice(0, -5) +
+ 'Z'
+ );
+}
+// return {
+// stateKey: stateKey,
+// initialState: initialState,
+// type: 'date',
+// options: {
+// serialize: date => {
+// if (!date) date = initialState;
+// return serializeDate(date);
+// },
+// parse: str => {
+// return parseDate(str, initialState);
+// }
+// }
+// };
+// export function getDateParameterSetup(parameters) {
+// const nowInital = util.now();
+// const now = parseNow(parameters.now);
+// return {
+// t: getPermalinkManagementObject(now, 'legacy.date.selected'),
+// t1: getPermalinkManagementObject(
+// util.dateAdd(now, 'day', -7),
+// 'legacy.date.selectedB'
+// ),
+// now: {
+// stateKey: 'legacy.date.now',
+// initialState: nowInital,
+// type: 'date',
+// options: {
+// serialize: serializeDate,
+// parse: parseNow
+// }
+// }
+// };
+// }
+// export function getPermalinkManagementObject(initialState, stateKey) {
+// return {
+// stateKey: stateKey,
+// initialState: initialState,
+// type: 'date',
+// options: {
+// serialize: date => {
+// if (!date) date = initialState;
+// return serializeDate(date);
+// },
+// parse: str => {
+// return parseDate(str, initialState);
+// }
+// }
+// };
+// }
+
+// export function parseNow(date) {
+// try {
+// const now = util.parseDateUTC(date);
+// util.now = function() {
+// return new Date(now.getTime());
+// };
+// return util.now();
+// } catch (error) {
+// util.warn('Invalid now: ' + date + error);
+// return util.now();
+// }
+// }
+// export function parseDate(str, initialState) {
+// try {
+// return util.parseDateUTC(str);
+// } catch (error) {
+// util.warn('Invalid date:' + str + error);
+// return initialState;
+// }
+// }
diff --git a/web/js/modules/image-download/util.js b/web/js/modules/image-download/util.js
index d0d5950e6..02c2d9d09 100644
--- a/web/js/modules/image-download/util.js
+++ b/web/js/modules/image-download/util.js
@@ -173,6 +173,7 @@ export function imageSizeValid(imgHeight, imgWidth, maxSize) {
return true;
}
export function getDimensions(projection, bounds, resolution) {
+ console.log(projection);
const conversionFactor = imageUtilGetConversionFactor(projection);
const imgWidth = Math.round(
Math.abs(bounds[1][0] - bounds[0][0]) /
diff --git a/web/js/modules/layers/constants.js b/web/js/modules/layers/constants.js
new file mode 100644
index 000000000..2ab30bab3
--- /dev/null
+++ b/web/js/modules/layers/constants.js
@@ -0,0 +1,8 @@
+export const LAYER_PARAM_SETUP = {
+ stateKey: 'legacy.layers.active',
+ initialState: null,
+ type: 'array',
+ options: {
+ delimiter: ','
+ }
+};
diff --git a/web/js/modules/layers/util.js b/web/js/modules/layers/util.js
new file mode 100644
index 000000000..3f1a1ef16
--- /dev/null
+++ b/web/js/modules/layers/util.js
@@ -0,0 +1,124 @@
+import { cloneDeep as lodashCloneDeep, isEmpty } from 'lodash';
+import { get } from 'redux-location-state/lib/helpers';
+import util from '../../util/util';
+
+export function getLayersParameterSetup(
+ parameters,
+ config,
+ models,
+ legacyState,
+ errors
+) {
+ const initialState = lodashCloneDeep(models.layers.active);
+ models.palettes.load(legacyState, errors);
+ if (models.compare.active) {
+ models.layers.activeB = lodashCloneDeep(initialState);
+ }
+ const layerModelLoaded = models.layers.load(legacyState, errors);
+
+ return {
+ l: getPermalinkManagementObject(
+ initialState,
+ 'legacy.layers.active',
+ () => {
+ return layerModelLoaded.active ? layerModelLoaded.active : initialState;
+ },
+ (currentItemState, state) => {
+ const isActive = get(models, 'compare.active');
+ const isCompareA = get(models, 'compare.isCompareA');
+ const layersB = get(models, 'layers.activeB');
+ const layersA = get(models, 'layers.active');
+ return !isActive && !isCompareA
+ ? serializeLayers(layersB, models, 'activeB')
+ : serializeLayers(layersA, models, 'active');
+ }
+ ),
+ l1: getPermalinkManagementObject(
+ initialState,
+ 'legacy.layers.activeB',
+ () => {
+ return layerModelLoaded.activeB;
+ },
+ (currentItemState, state) => {
+ const isActive = get(models, 'compare.active');
+ const layersB = get(models, 'layers.activeB');
+ return isActive
+ ? serializeLayers(layersB, models, 'activeB')
+ : undefined;
+ }
+ )
+ };
+}
+function serializeLayers(layers, models, groupStr) {
+ return layers.map(def => {
+ var item = {};
+
+ if (def.id) {
+ item = {
+ id: def.id
+ };
+ }
+ if (!item.attributes) {
+ item.attributes = [];
+ }
+ if (!def.visible) {
+ item.attributes.push({
+ id: 'hidden'
+ });
+ }
+ if (def.opacity < 1) {
+ item.attributes.push({
+ id: 'opacity',
+ value: def.opacity
+ });
+ }
+ if (!isEmpty(def.custom)) {
+ let def1 = models.palettes.get(def.id, undefined, groupStr);
+
+ if (def1.custom) {
+ item.attributes.push({
+ id: 'palette',
+ value: def1.custom
+ });
+ }
+ if (def1.min) {
+ var minValue = def1.entries.values[def1.min];
+ item.attributes.push({
+ id: 'min',
+ value: minValue
+ });
+ }
+ if (def1.max) {
+ var maxValue = def1.entries.values[def1.max];
+ item.attributes.push({
+ id: 'max',
+ value: maxValue
+ });
+ }
+ if (def1.squash) {
+ item.attributes.push({
+ id: 'squash'
+ });
+ }
+ }
+ return util.appendAttributesForURL(item);
+ });
+}
+function getPermalinkManagementObject(
+ initialState,
+ stateKey,
+ parser,
+ serialize
+) {
+ return {
+ stateKey: stateKey,
+ initialState: initialState,
+ type: 'array',
+ options: {
+ delimiter: ',',
+ serializeNeedsGlobalState: true,
+ parse: parser,
+ serialize: serialize
+ }
+ };
+}
diff --git a/web/js/modules/link/constants.js b/web/js/modules/link/constants.js
index 39f428ce0..560d726f1 100644
--- a/web/js/modules/link/constants.js
+++ b/web/js/modules/link/constants.js
@@ -20,3 +20,18 @@ export const MOCK_SHORT_LINK_RESPONSE = {
success: true,
notifications: MOCK_SHORT_LINK_RESPONSE_BODY
};
+
+export const ENCODING_EXCEPTIONS = [
+ {
+ match: new RegExp('%2C', 'g'),
+ replace: ','
+ },
+ {
+ match: new RegExp('%3B', 'g'),
+ replace: ';'
+ },
+ {
+ match: new RegExp('%3D', 'g'),
+ replace: '='
+ }
+];
diff --git a/web/js/modules/link/reducers.js b/web/js/modules/link/reducers.js
index d8009c1ee..048c528fb 100644
--- a/web/js/modules/link/reducers.js
+++ b/web/js/modules/link/reducers.js
@@ -1,4 +1,4 @@
-import { UPDATE_PERMALINK, REQUEST_SHORT_LINK } from './constants';
+import { REQUEST_SHORT_LINK, UPDATE_PERMALINK } from './constants';
import { requestReducer } from '../core/reducers';
import { assign as lodashAssign } from 'lodash';
@@ -14,7 +14,7 @@ export function linkReducer(state = deafultLinkState, action) {
switch (action.type) {
case UPDATE_PERMALINK:
return lodashAssign({}, state, {
- queryString: action.queryString
+ queryString: action.queryString || ''
});
default:
return state;
diff --git a/web/js/modules/link/util.js b/web/js/modules/link/util.js
index 81003e032..22bf05001 100644
--- a/web/js/modules/link/util.js
+++ b/web/js/modules/link/util.js
@@ -1,3 +1,5 @@
+import { each as lodashEach } from 'lodash';
+import { ENCODING_EXCEPTIONS } from './constants';
// Facebook: https://developers.facebook.com/docs/sharing/reference/share-dialog#redirect
export function facebookUrlParams(appId, href, redirectUri, display) {
return (
@@ -65,3 +67,10 @@ export function getSharelink(type, url) {
export function openPromisedSocial(url, win) {
win.location.assign(url);
}
+export function encode(value) {
+ var encoded = encodeURIComponent(value);
+ lodashEach(ENCODING_EXCEPTIONS, function(exception) {
+ encoded = encoded.replace(exception.match, exception.replace);
+ });
+ return encoded;
+}
diff --git a/web/js/modules/map/constants.js b/web/js/modules/map/constants.js
new file mode 100644
index 000000000..e88c0f420
--- /dev/null
+++ b/web/js/modules/map/constants.js
@@ -0,0 +1,13 @@
+import { getLeadingExtent, serializeExtent, parseMapExtent } from './util';
+const LEADING_EXTENT = getLeadingExtent();
+
+export const EXTENT_PARAM_SETUP = {
+ stateKey: 'legacy.map.extent',
+ initialState: LEADING_EXTENT,
+ type: 'array',
+ options: {
+ delimiter: ',',
+ parse: parseMapExtent,
+ serialize: serializeExtent
+ }
+};
diff --git a/web/js/modules/map/util.js b/web/js/modules/map/util.js
new file mode 100644
index 000000000..de2838e73
--- /dev/null
+++ b/web/js/modules/map/util.js
@@ -0,0 +1,92 @@
+// import { isUndefined as lodashIsUndefined, each as lodashEach } from 'lodash';
+import util from '../../util/util';
+import { encode } from '../link/util';
+
+export function getMapParameterSetup(
+ parameters,
+ config,
+ models,
+ legacyState,
+ errors
+) {
+ const loadedModel = models.map.load(legacyState, errors);
+ const leadingExtent = getLeadingExtent();
+ return {
+ v: {
+ stateKey: 'legacy.map.extent',
+ initialState: leadingExtent,
+ type: 'array',
+ options: {
+ delimiter: ',',
+ parse: () => {
+ return loadedModel.extent || leadingExtent;
+ },
+ serialize: (currentItemState, currentState) => {
+ return encode(models.map.extent || leadingExtent);
+ }
+ }
+ }
+ };
+}
+
+// const LEADING_EXTENT = getLeadingExtent();
+
+// export function serializeExtent(arr) {
+// if (!arr || !arr.length || arr.length !== 4) return LEADING_EXTENT;
+// return encode(arr.join(','));
+// }
+
+export function getLeadingExtent() {
+ var curHour = util.now().getUTCHours();
+
+ // For earlier hours when data is still being filled in, force a far eastern perspective
+ if (curHour < 3) {
+ curHour = 23;
+ } else if (curHour < 9) {
+ curHour = 0;
+ }
+
+ // Compute east/west bounds
+ var minLon = 20.6015625 + curHour * (-200.53125 / 23.0);
+ var maxLon = minLon + 159.328125;
+
+ var minLat = -46.546875;
+ var maxLat = 53.015625;
+
+ return [minLon, minLat, maxLon, maxLat];
+}
+
+// export function parseMapExtent(str) {
+// const extent = str.split(',').map(parseFloat);
+// var valid = mapIsExtentValid(extent);
+// if (!valid) {
+// util.warn('Invalid extent: ' + extent);
+// return getLeadingExtent();
+// } else {
+// return extent;
+// }
+// }
+// /**
+// * Determines if an exent object contains valid values.
+// *
+// * @method isExtentValid
+// * @static
+// *
+// * @param extent {OpenLayers.Bound} The extent to check.
+// *
+// * @return {boolean} False if any of the values is NaN, otherwise returns
+// * true.
+// */
+// export function mapIsExtentValid(extent) {
+// if (lodashIsUndefined(extent)) {
+// return false;
+// }
+// var valid = true;
+// lodashEach(extent, function(value) {
+// if (isNaN(value)) {
+// valid = false;
+// return false;
+// }
+// });
+// return valid;
+// }
diff --git a/web/js/modules/migration/actions.js b/web/js/modules/migration/actions.js
index b87aa073d..2be34440e 100644
--- a/web/js/modules/migration/actions.js
+++ b/web/js/modules/migration/actions.js
@@ -1,4 +1,8 @@
-import { CONFIG_HAS_BEEN_LOADED } from './constants';
+import {
+ CONFIG_HAS_BEEN_LOADED,
+ INIT_COMPLETE,
+ UPDATE_IN_LEGACY_STATE
+} from './constants';
export function sendConfigToStore(models, config) {
return {
@@ -7,3 +11,16 @@ export function sendConfigToStore(models, config) {
config: config
};
}
+
+export function updateLegacyModule(key, model) {
+ return {
+ type: UPDATE_IN_LEGACY_STATE,
+ key: key,
+ model: model
+ };
+}
+export function updateLegacyInitComplete() {
+ return {
+ type: INIT_COMPLETE
+ };
+}
diff --git a/web/js/modules/migration/constants.js b/web/js/modules/migration/constants.js
index b630296bd..197ce7628 100644
--- a/web/js/modules/migration/constants.js
+++ b/web/js/modules/migration/constants.js
@@ -1 +1,4 @@
export const CONFIG_HAS_BEEN_LOADED = 'CONFIG_AND_MODELS_HAVE_BEEN_LOADED';
+export const UPDATE_IN_LEGACY_STATE =
+ 'AN_UPDATE_TO_LEGACY_STATE_MODULE_HAS_OCCURED';
+export const INIT_COMPLETE = 'LEGACY_MODELS_INIT_COMPLETE';
diff --git a/web/js/modules/migration/reducers.js b/web/js/modules/migration/reducers.js
index e59fe991c..6cd494694 100644
--- a/web/js/modules/migration/reducers.js
+++ b/web/js/modules/migration/reducers.js
@@ -1,10 +1,26 @@
-import { CONFIG_HAS_BEEN_LOADED } from './constants';
-import { assign as lodashAssign } from 'lodash';
+import {
+ CONFIG_HAS_BEEN_LOADED,
+ INIT_COMPLETE,
+ UPDATE_IN_LEGACY_STATE
+} from './constants';
+import { assign as lodashAssign, cloneDeep as lodashCloneDeep } from 'lodash';
const legacyState = {
loaded: false,
models: {},
- config: {}
+ config: {},
+ compare: {
+ active: false
+ },
+ date: {
+ now: ''
+ },
+ layers: {
+ active: [],
+ activeB: []
+ },
+ map: { selectedMap: null },
+ initComplete: false
};
export default function legacyReducer(state = legacyState, action) {
@@ -15,6 +31,11 @@ export default function legacyReducer(state = legacyState, action) {
config: action.config,
loaded: true
});
+ case UPDATE_IN_LEGACY_STATE:
+ const model = lodashCloneDeep(action.model);
+ return lodashAssign({}, state, { [action.key]: model });
+ case INIT_COMPLETE:
+ return lodashAssign({}, state, { initComplete: true });
default:
return state;
}
diff --git a/web/js/modules/migration/util.js b/web/js/modules/migration/util.js
new file mode 100644
index 000000000..e69de29bb
diff --git a/web/js/modules/natural-events/util.js b/web/js/modules/natural-events/util.js
new file mode 100644
index 000000000..ca252d6b5
--- /dev/null
+++ b/web/js/modules/natural-events/util.js
@@ -0,0 +1,32 @@
+import { get } from 'redux-location-state/lib/helpers';
+import { encode } from '../link/util';
+export function getNaturalEventsParameterSetup(
+ parameters,
+ config,
+ models,
+ legacyState,
+ errors
+) {
+ const loadedModel = models.naturalEvents.load(legacyState, errors);
+
+ return {
+ e: {
+ stateKey: 'legacy.naturalEvents.active',
+ initialState: false,
+ type: 'boolean',
+ options: {
+ delimiter: ',',
+ serializeNeedsGlobalState: true,
+ parse: () => {
+ return loadedModel.active || false;
+ },
+ serialize: (currentItemState, currentState) => {
+ const selected = get(currentState, 'legacy.naturalEvents.selected');
+ if (!currentItemState) return false;
+
+ return encode(selected);
+ }
+ }
+ }
+ };
+}
diff --git a/web/js/modules/projection/actions.js b/web/js/modules/projection/actions.js
index a224f007a..1382b085f 100644
--- a/web/js/modules/projection/actions.js
+++ b/web/js/modules/projection/actions.js
@@ -1,8 +1,13 @@
import { CHANGE_PROJECTION } from './constants';
-export function changeProjection(id) {
+export function changeProjection(id, config) {
+ const proj = config.projections[id];
+ if (!proj) {
+ throw new Error('Invalid projection: ' + id);
+ }
return {
type: CHANGE_PROJECTION,
- id: id
+ id: id,
+ selected: proj
};
}
diff --git a/web/js/modules/projection/reducer.js b/web/js/modules/projection/reducer.js
index 0d6d04a20..61e359c1d 100644
--- a/web/js/modules/projection/reducer.js
+++ b/web/js/modules/projection/reducer.js
@@ -1,14 +1,17 @@
import { CHANGE_PROJECTION } from './constants';
import { assign as lodashAssign } from 'lodash';
-const projectionState = {
- id: 'geographic'
+
+export const projectionState = {
+ id: 'geographic',
+ selected: {}
};
export default function projectionReducer(state = projectionState, action) {
switch (action.type) {
case CHANGE_PROJECTION:
return lodashAssign({}, state, {
- id: action.id
+ id: action.id,
+ selected: action.selected
});
default:
return state;
diff --git a/web/js/modules/projection/util.js b/web/js/modules/projection/util.js
new file mode 100644
index 000000000..a1db23b21
--- /dev/null
+++ b/web/js/modules/projection/util.js
@@ -0,0 +1,15 @@
+export function getProjInitialState(config) {
+ const defaults = config.defaults;
+ const projections = config.projections;
+
+ return {
+ id: 'geographic',
+ selected:
+ defaults &&
+ projections &&
+ defaults.projection &&
+ projections[defaults.projection]
+ ? projections[defaults.projection]
+ : {}
+ };
+}
diff --git a/web/js/modules/tour/util.js b/web/js/modules/tour/util.js
new file mode 100644
index 000000000..4471091ef
--- /dev/null
+++ b/web/js/modules/tour/util.js
@@ -0,0 +1,29 @@
+import { cloneDeep as lodashCloneDeep, get } from 'lodash';
+
+export function getTourParameterSetup(
+ parameters,
+ config,
+ models,
+ legacyState,
+ errors
+) {
+ const loadedModel = lodashCloneDeep(models.tour.load(legacyState, errors)); // use legacy parser
+
+ return {
+ tr: {
+ stateKey: 'legacy.tour.selected.id',
+ initialState: '',
+ options: {
+ setAsEmptyItem: true,
+ parse: () => {
+ return get(loadedModel, 'selected.id') || false;
+ },
+ serialize: () => {
+ const tourActive = get(models, 'tour.active');
+ const tourId = get(models, 'tour.selected.id');
+ return tourActive && tourId ? tourId : undefined;
+ }
+ }
+ }
+ };
+}
diff --git a/web/js/natural-events/model.js b/web/js/natural-events/model.js
index 3d1ce624e..c984b6f0f 100644
--- a/web/js/natural-events/model.js
+++ b/web/js/natural-events/model.js
@@ -5,7 +5,6 @@ export default function naturalEventsModel(models, config, ui) {
self.selected = null;
self.active = false;
self.layers = config.naturalEvents.layers;
-
/**
* Handler for events fired by this class.
*
@@ -15,17 +14,19 @@ export default function naturalEventsModel(models, config, ui) {
*/
self.events = util.events();
+ self.events.on('selected-event', function(selected) {
+ var id = selected.id;
+ var date = selected.date;
+ self.selected = id ? (date ? [id, date].join(',') : id) : 'true';
+ });
self.save = function(state) {
if (self.active) {
- var id = ui.naturalEvents.selected.id;
- var date = ui.naturalEvents.selected.date;
- var value = id ? (date ? [id, date].join(',') : id) : true;
- state.e = value;
+ state.e = self.selected;
}
};
self.load = function(state) {
- if (!state.e) return;
+ if (!state.e) return self;
models.wv.events.on('startup', function() {
self.events.trigger('activate');
});
@@ -36,9 +37,11 @@ export default function naturalEventsModel(models, config, ui) {
date = date.match(/\d{4}-\d{2}-\d{2}/) ? values[1] : null;
if (id) {
self.events.on('hasData', function() {
- ui.naturalEvents.selectEvent(id, date, null, true);
+ self.events.trigger('select-init-event', id, date, null, true);
});
}
+ self.loaded = true;
+ return self;
};
return self;
diff --git a/web/js/natural-events/ui.js b/web/js/natural-events/ui.js
index 6f7759d5b..2a567518e 100644
--- a/web/js/natural-events/ui.js
+++ b/web/js/natural-events/ui.js
@@ -33,7 +33,7 @@ export default function naturalEventsUI(models, ui, config, request) {
// Display loading information for user feedback on slow network
view = map.getView();
-
+ model.events.on('select-init-event', self.selectEvent);
request.events.on('queryResults', function() {
if (!(model.data.events || model.data.sources)) return;
@@ -60,7 +60,12 @@ export default function naturalEventsUI(models, ui, config, request) {
// Reselect previously selected event
if (self.selected.id) {
- self.selectEvent(self.selected.id, self.selected.date || null, null, true);
+ self.selectEvent(
+ self.selected.id,
+ self.selected.date || null,
+ null,
+ true
+ );
}
});
ui.sidebar.events.on('selectTab', function(tab) {
@@ -175,7 +180,13 @@ export default function naturalEventsUI(models, ui, config, request) {
}
});
};
- var getZoomPromise = function(event, date, rotation, isIdChange, isInitialLoad) {
+ var getZoomPromise = function(
+ event,
+ date,
+ rotation,
+ isIdChange,
+ isInitialLoad
+ ) {
return isInitialLoad
? new Promise(function(resolve, reject) {
resolve();
@@ -203,7 +214,13 @@ export default function naturalEventsUI(models, ui, config, request) {
var isSameCategory = category === prevCategory;
date = date || self.getDefaultEventDate(event);
- const zoomPromise = getZoomPromise(event, date, rotation, !isIdChange, isInitialLoad);
+ const zoomPromise = getZoomPromise(
+ event,
+ date,
+ rotation,
+ !isIdChange,
+ isInitialLoad
+ );
self.selected.date = date;
// highlightEventInList(id, date);
diff --git a/web/js/palettes/model.js b/web/js/palettes/model.js
index 07cab56bc..be2878273 100644
--- a/web/js/palettes/model.js
+++ b/web/js/palettes/model.js
@@ -4,6 +4,7 @@ import lodashCloneDeep from 'lodash/cloneDeep';
import lodashIsNaN from 'lodash/isNaN';
import lodashIsUndefined from 'lodash/isUndefined';
import lodashParseInt from 'lodash/parseInt';
+import lodashFindIndex from 'lodash/findIndex';
import util from '../util/util';
import palettes from './palettes';
import Promise from 'bluebird';
@@ -77,6 +78,11 @@ export function palettesModel(models, config) {
updateLookup(layerId, groupStr);
self.events.trigger('set-custom', layerId, active, groupStr);
self.events.trigger('change');
+ const layerIndex = lodashFindIndex(models.layers[groupStr], { id: layerId } );
+ if (layerIndex >= 0) {
+ models.layers[groupStr][layerIndex].custom = self[groupStr][layerId];
+ models.layers.events.trigger('change');
+ }
};
self.clearCustom = function(layerId, index, groupStr) {
@@ -94,6 +100,11 @@ export function palettesModel(models, config) {
updateLookup(layerId, groupStr);
self.events.trigger('clear-custom', layerId, groupStr);
self.events.trigger('change');
+ const layerIndex = lodashFindIndex(models.layers[groupStr], { id: layerId } );
+ if (layerIndex >= 0) {
+ models.layers[groupStr][layerIndex].custom = self[groupStr][layerId];
+ models.layers.events.trigger('change');
+ }
};
self.setRange = function(layerId, min, max, squash, index, groupStr) {
@@ -114,6 +125,11 @@ export function palettesModel(models, config) {
updateLookup(layerId, groupStr);
self.events.trigger('range', layerId, palette.min, palette.max, groupStr);
self.events.trigger('change');
+ const layerIndex = lodashFindIndex(models.layers[groupStr], { id: layerId } );
+ if (layerIndex >= 0) {
+ models.layers[groupStr][layerIndex].custom = self[groupStr][layerId];
+ models.layers.events.trigger('change');
+ }
};
self.getCount = function(layerId) {
@@ -258,6 +274,7 @@ export function palettesModel(models, config) {
id: layerId
}).attributes;
var def = self.get(layerId, undefined, groupStr);
+
if (def.custom) {
attr.push({
id: 'palette',
@@ -383,7 +400,7 @@ export function palettesModel(models, config) {
self.load = function(state, errors) {
var stateArray = [{ stateStr: 'l', groupStr: 'active' }];
if (!palettes.supported) {
- return;
+ return self;
}
if (state.l1) {
stateArray = [
@@ -470,6 +487,8 @@ export function palettesModel(models, config) {
}
});
});
+ self.loaded = true;
+ return self;
};
var findIndex = function(layerId, type, value, index, groupStr) {
diff --git a/web/js/parse.js b/web/js/parse.js
new file mode 100644
index 000000000..42bfd695c
--- /dev/null
+++ b/web/js/parse.js
@@ -0,0 +1,30 @@
+import { each as lodashEach } from 'lodash';
+import { mapParser } from './map/map';
+import { parse as dateParser } from './date/date';
+import { parse as projectionParser } from './projection/projection';
+import { parse as layerParser } from './layers/layers';
+import { parse as animationParser } from './animation/anim';
+import palettes from './palettes/palettes';
+import { dataParser } from './data/data';
+
+export function parse(parameters, config) {
+ let state = parameters;
+ var errors = [];
+ let parsers = [
+ projectionParser,
+ layerParser,
+ dateParser,
+ mapParser,
+ palettes.parse
+ ];
+ if (config.features.dataDownload) {
+ parsers.push(dataParser);
+ }
+ if (config.features.animation) {
+ parsers.push(animationParser);
+ }
+ lodashEach(parsers, function(parser) {
+ parser(state, errors, config);
+ });
+ return state;
+}
diff --git a/web/js/projection/model.js b/web/js/projection/model.js
index 0fc0038ba..e75658665 100644
--- a/web/js/projection/model.js
+++ b/web/js/projection/model.js
@@ -8,7 +8,7 @@ export function projectionModel(config) {
self.selected = null;
self.events = util.events();
- var init = function () {
+ var init = function() {
self.selectDefault();
// Return if no projections have been defined
@@ -16,14 +16,14 @@ export function projectionModel(config) {
return;
}
- Object.values(config.projections).forEach((proj) => {
+ Object.values(config.projections).forEach(proj => {
if (proj.crs && proj.proj4) {
self.register(proj.crs, proj.proj4);
}
});
};
- self.select = function (id) {
+ self.select = function(id) {
var proj = config.projections[id];
if (!proj) {
throw new Error('Invalid projection: ' + id);
@@ -36,24 +36,24 @@ export function projectionModel(config) {
return updated;
};
- self.selectDefault = function () {
+ self.selectDefault = function() {
if (config.defaults && config.defaults.projection) {
self.select(config.defaults.projection);
}
};
- self.save = function (state) {
+ self.save = function(state) {
state.p = self.selected.id;
};
- self.load = function (state) {
+ self.load = function(state) {
var projId = state.p;
if (projId) {
self.select(projId);
}
};
- self.register = function (crs, def) {
+ self.register = function(crs, def) {
if (def && proj4) {
proj4.defs(crs, def);
register(proj4);
@@ -63,4 +63,4 @@ export function projectionModel(config) {
init();
return self;
-};
+}
diff --git a/web/js/redux-config-helpers.js b/web/js/redux-config-helpers.js
new file mode 100644
index 000000000..3a6bebb72
--- /dev/null
+++ b/web/js/redux-config-helpers.js
@@ -0,0 +1,9 @@
+import thunkMiddleware from 'redux-thunk'; // For ASYNC actions
+import { compact } from 'lodash';
+import { createLogger } from 'redux-logger';
+const loggerMiddleware = createLogger({ collapsed: true });
+export function getMiddleware(isDevelop, locationMiddleware) {
+ return isDevelop
+ ? compact([thunkMiddleware, locationMiddleware, loggerMiddleware])
+ : compact([thunkMiddleware, locationMiddleware]);
+}
diff --git a/web/js/redux-location-state-customs.js b/web/js/redux-location-state-customs.js
new file mode 100644
index 000000000..cb372ab6b
--- /dev/null
+++ b/web/js/redux-location-state-customs.js
@@ -0,0 +1,114 @@
+import { each as lodashEach } from 'lodash';
+import {
+ get,
+ createObjectFromConfig,
+ isEqual
+} from 'redux-location-state/lib/helpers';
+import isEqualDate from 'date-fns/is_equal';
+import { typeHandles } from 'redux-location-state/lib/typeHandles';
+
+const ENCODING_EXCEPTIONS = [
+ {
+ match: new RegExp('%2C', 'g'),
+ replace: ','
+ },
+ {
+ match: new RegExp('%3B', 'g'),
+ replace: ';'
+ },
+ {
+ match: new RegExp('%3D', 'g'),
+ replace: '='
+ }
+];
+function isNotDefined(value) {
+ return typeof value === 'undefined' || value === null;
+}
+export function encode(value) {
+ var encoded = encodeURIComponent(value);
+ lodashEach(ENCODING_EXCEPTIONS, function(exception) {
+ encoded = encoded.replace(exception.match, exception.replace);
+ });
+ return encoded;
+}
+export function createParamsString(qp) {
+ const paramArray = Object.keys(qp).reduce((prev, key) => {
+ const keyString = key.toString();
+ const valueString = qp[key].toString();
+ if (
+ isNotDefined(valueString) ||
+ (Array.isArray(valueString) && !valueString.length)
+ ) {
+ return prev;
+ }
+ return [...prev, `${encodeURIComponent(keyString)}=${encode(valueString)}`];
+ }, []);
+
+ return paramArray.length ? `?${paramArray.join('&')}` : '';
+}
+
+export function stateToParams(initialState, currentState, location) {
+ const pathConfig = createObjectFromConfig(initialState, location);
+ if (!pathConfig) {
+ return { location: { ...location } };
+ }
+ let shouldPush = false;
+ // check the original config for values
+ const newQueryParams = Object.keys(pathConfig).reduce((prev, curr) => {
+ const {
+ stateKey,
+ options = {},
+ initialState: initialValue,
+ type
+ } = pathConfig[curr];
+ let currentItemState = get(currentState, stateKey);
+ let isDefault;
+ // check if the date is the same as the one in initial value
+ if (type === 'date') {
+ isDefault = isEqualDate(initialValue, currentItemState);
+ } else {
+ // if an empty object, make currentItemState undefined
+ if (
+ currentItemState &&
+ typeof currentItemState === 'object' &&
+ !Object.keys(currentItemState).length
+ ) {
+ currentItemState = undefined;
+ }
+ // check if the item is default
+ isDefault =
+ typeof currentItemState === 'object'
+ ? isEqual(initialValue, currentItemState)
+ : currentItemState === initialValue;
+ }
+ // if it is default or doesn't exist don't make a query parameter
+ if ((!currentItemState || isDefault) && !options.setAsEmptyItem) {
+ return prev;
+ }
+ // otherwise, check if there is a serialize function
+ if (options.serialize) {
+ const itemState = options.serialize(
+ currentItemState,
+ options.serializeNeedsGlobalState ? currentState : undefined
+ );
+ // short circuit if specialized serializer returns specifically undefined
+ if (typeof itemState === 'undefined') {
+ return prev;
+ }
+ currentItemState = itemState;
+ } else if (type) {
+ currentItemState = typeHandles[type].serialize(currentItemState, options);
+ }
+ // add new params to reduced object
+ prev[curr] = currentItemState; // check if a shouldPush property has changed
+ return prev;
+ }, {});
+
+ return {
+ location: {
+ ...location,
+ search: createParamsString(newQueryParams)
+ },
+ shouldPush
+ };
+}
diff --git a/web/js/tour/model.js b/web/js/tour/model.js
index 7477ec651..cc00f3db4 100644
--- a/web/js/tour/model.js
+++ b/web/js/tour/model.js
@@ -11,7 +11,7 @@ export function tourModel(config) {
self.events.trigger('toggle');
};
- self.select = function (storyId) {
+ self.select = function(storyId) {
var story = config.stories[storyId];
if (!story) {
console.warn('Unsupported tour: ' + storyId);
@@ -24,7 +24,7 @@ export function tourModel(config) {
return updated;
};
- self.save = function (state) {
+ self.save = function(state) {
if (!self.active) {
if (state.tr) delete state.tr;
} else {
@@ -32,12 +32,13 @@ export function tourModel(config) {
}
};
- self.load = function (state) {
+ self.load = function(state) {
var storyId = state.tr;
if (storyId) {
self.select(storyId);
}
+ return self;
};
return self;
-};
+}
diff --git a/web/js/tour/ui.js b/web/js/tour/ui.js
index aada06250..6ca3fddc7 100644
--- a/web/js/tour/ui.js
+++ b/web/js/tour/ui.js
@@ -18,7 +18,7 @@ export function tourUi(models, ui, config) {
React.createElement(Tour, getInitialProps()),
document.getElementById('wv-tour')
);
-
+ models.tour.events.on('start-tour', self.startTour);
models.wv.events.on('startup', function() {
let story = models.tour.selected;
let storyLoaded = false;
@@ -73,9 +73,9 @@ export function tourUi(models, ui, config) {
let tourDate = new Date(hideTour);
// Tour hidden when visiting fresh URL
googleTagManager.pushEvent({
- 'event': 'tour_start_hidden',
- 'buildDate': buildDate,
- 'tourDate': tourDate
+ event: 'tour_start_hidden',
+ buildDate: buildDate,
+ tourDate: tourDate
});
if (buildDate > tourDate) {
localStorage.removeItem('hideTour');
@@ -88,7 +88,7 @@ export function tourUi(models, ui, config) {
} else {
// Tour shown when visiting fresh URL
googleTagManager.pushEvent({
- 'event': 'tour_start'
+ event: 'tour_start'
});
return true;
}
@@ -98,7 +98,7 @@ export function tourUi(models, ui, config) {
if (e) e.preventDefault();
// Tour startup modal shown by clicking "More Stories" button at end of story
googleTagManager.pushEvent({
- 'event': 'tour_more_stories_button'
+ event: 'tour_more_stories_button'
});
self.startTour();
};
@@ -107,7 +107,7 @@ export function tourUi(models, ui, config) {
if (e) e.preventDefault();
// Tour shown by manually clicking "Start Tour" button
googleTagManager.pushEvent({
- 'event': 'tour_start_button'
+ event: 'tour_start_button'
});
self.reactComponent.setState({
modalStart: true,
@@ -117,7 +117,12 @@ export function tourUi(models, ui, config) {
});
};
- self.selectTour = function(e, currentStory, currentStoryIndex, currentStoryId) {
+ self.selectTour = function(
+ e,
+ currentStory,
+ currentStoryIndex,
+ currentStoryId
+ ) {
let totalSteps = currentStory.steps;
if (e) e.preventDefault();
self.reactComponent.setState({
@@ -141,7 +146,7 @@ export function tourUi(models, ui, config) {
// Checkbox to "hide tour modal until a new story has been added" has been checked
googleTagManager.pushEvent({
- 'event': 'tour_hide_checked'
+ event: 'tour_hide_checked'
});
if (!util.browser.localStorage) return;
@@ -155,7 +160,7 @@ export function tourUi(models, ui, config) {
// Checkbox to "hide tour modal until a new story has been added" has been checked
googleTagManager.pushEvent({
- 'event': 'tour_hide_unchecked'
+ event: 'tour_hide_unchecked'
});
if (!util.browser.localStorage) return;
diff --git a/web/js/util/util.js b/web/js/util/util.js
index f522e899b..7cbac65b5 100644
--- a/web/js/util/util.js
+++ b/web/js/util/util.js
@@ -5,8 +5,11 @@
* which is included via config.scripts in web/config/wv.json
*/
-import lodashEach from 'lodash/each';
-import lodashIsNull from 'lodash/isNull';
+import {
+ isObject as lodashIsObject,
+ each as lodashEach,
+ isNull as lodashIsNull
+} from 'lodash';
import wvui from '../ui/ui';
import browser from './browser';
import { events } from './events';
@@ -114,7 +117,12 @@ export default (function (self) {
}
return result;
};
-
+ self.elapsed = function(message, startTime, parameters) {
+ if (parameters && !parameters.elapsed) return;
+ var t = new Date().getTime() - startTime;
+ console.log(t, message);
+ return t;
+ };
/**
* Converts an object to a query string. For exaple, the following
* object:
@@ -218,7 +226,6 @@ export default (function (self) {
second = hhmmss[2] || 0;
millisecond = hhmmss[3] || 0;
}
-
var date = new Date(Date.UTC(year, month, day, hour, minute, second,
millisecond));
if (isNaN(date.getTime())) {
@@ -226,6 +233,25 @@ export default (function (self) {
}
return date;
};
+ self.appendAttributesForURL = function (item) {
+ if (lodashIsObject(item)) {
+ let part = item.id || '';
+ let attributes = [];
+ if (item.attributes && item.attributes.length > 0) {
+ lodashEach(item.attributes, function(attribute) {
+ if (attribute.value) {
+ attributes.push(attribute.id + '=' + attribute.value);
+ } else {
+ attributes.push(attribute.id);
+ }
+ });
+ part += '(' + attributes.join(',') + ')';
+ }
+ return part;
+ }
+ self.warn('Is not an object: ' + item);
+ return '';
+ };
/**
* Test if is valid Date
* @param {Object} d | Date object