diff --git a/buildprocess/ci-deploy.sh b/buildprocess/ci-deploy.sh index d567c96166b..e0904d696dd 100644 --- a/buildprocess/ci-deploy.sh +++ b/buildprocess/ci-deploy.sh @@ -23,7 +23,7 @@ yarn add -W request@2.83.0 # Clone and build TerriaMap, using this version of TerriaJS TERRIAJS_COMMIT_HASH=$(git rev-parse HEAD) -git clone -b main https://github.com/TerriaJS/TerriaMap.git +git clone -b cjs-to-esm https://github.com/TerriaJS/TerriaMap.git cd TerriaMap TERRIAMAP_COMMIT_HASH=$(git rev-parse HEAD) sed -i -e 's@"terriajs": ".*"@"terriajs": "'$GITHUB_REPOSITORY'#'${GITHUB_BRANCH}'"@g' package.json diff --git a/lib/CopyrightModule.js b/lib/CopyrightModule.js index 58f875fe404..fde6e4d34fb 100755 --- a/lib/CopyrightModule.js +++ b/lib/CopyrightModule.js @@ -1,6 +1,6 @@ /** * @license - * Copyright(c) 2012-2014 National ICT Australia Limited (NICTA). + * Copyright(c) 2014-2024 Terria Pty Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,4 +15,4 @@ * limitations under the License. * */ -module.exports = {}; +export default {}; diff --git a/lib/Core/ConsoleAnalytics.js b/lib/Core/ConsoleAnalytics.js new file mode 100644 index 00000000000..c747d7c9f22 --- /dev/null +++ b/lib/Core/ConsoleAnalytics.js @@ -0,0 +1,50 @@ +import defined from "terriajs-cesium/Source/Core/defined"; +import i18next from "i18next"; + +const ConsoleAnalytics = function () { + // either set enableConsoleAnalytics here to true, + // or pass true in `configParameters.enableConsoleAnalytics` for verbose app analytics + this.enableConsoleAnalytics = false; +}; + +ConsoleAnalytics.prototype.start = function (configParameters) { + if ( + configParameters.googleAnalyticsKey || + configParameters.googleAnalyticsOptions + ) { + console.log(i18next.t("core.consoleAnalytics.logStartedWithGAParameters")); + } + if (defined(configParameters.enableConsoleAnalytics)) { + console.log(i18next.t("core.consoleAnalytics.started")); + this.enableConsoleAnalytics = configParameters.enableConsoleAnalytics; + } else if ( + !defined(configParameters.enableConsoleAnalytics) || + !configParameters.enableConsoleAnalytics + ) { + console.log( + i18next.t("core.consoleAnalytics.startedNoenableConsoleAnalytics") + ); + } +}; + +ConsoleAnalytics.prototype.logEvent = function ( + category, + action, + label, + value +) { + if (this.enableConsoleAnalytics) { + var labelString = defined(label) ? " Label: " + label : ""; + var valueString = defined(value) ? " Value: " + value : ""; + console.log( + "** Event ** Category: " + + category + + " Action: " + + action + + labelString + + valueString + ); + } +}; + +export default ConsoleAnalytics; diff --git a/lib/Core/GoogleAnalytics.ts b/lib/Core/GoogleAnalytics.ts index 9929f72f6f9..6b4bd92025a 100644 --- a/lib/Core/GoogleAnalytics.ts +++ b/lib/Core/GoogleAnalytics.ts @@ -1,5 +1,3 @@ -"use strict"; - import i18next from "i18next"; import ReactGA from "react-ga4"; import { Analytics, ConfigParameters } from "../Models/Terria"; diff --git a/lib/Core/ServerConfig.js b/lib/Core/ServerConfig.js index 0d9a3b45725..d0b21b475da 100644 --- a/lib/Core/ServerConfig.js +++ b/lib/Core/ServerConfig.js @@ -1,8 +1,8 @@ -const i18next = require("i18next").default; -var defaultValue = require("terriajs-cesium/Source/Core/defaultValue").default; -var loadJson = require("./loadJson").default; +import i18next from "i18next"; +import defaultValue from "terriajs-cesium/Source/Core/defaultValue"; +import loadJson from "./loadJson"; -var DEFAULT_URL = "serverconfig/"; +const DEFAULT_URL = "serverconfig/"; /** * Provides information about the configuration of the Terria server, by querying /serverconfig */ diff --git a/lib/Core/TerriaError.ts b/lib/Core/TerriaError.ts index 0e4b23afd2e..80cfd23c500 100644 --- a/lib/Core/TerriaError.ts +++ b/lib/Core/TerriaError.ts @@ -1,5 +1,3 @@ -"use strict"; - import i18next from "i18next"; import { observable, makeObservable } from "mobx"; import RequestErrorEvent from "terriajs-cesium/Source/Core/RequestErrorEvent"; diff --git a/lib/Core/arrayProduct.js b/lib/Core/arrayProduct.js deleted file mode 100644 index 6637cd16f18..00000000000 --- a/lib/Core/arrayProduct.js +++ /dev/null @@ -1,41 +0,0 @@ -"use strict"; - -var flatten = require("./flatten"); - -/** - * Find the "product" of a set of arrays, equivalent to the python one-liner: list(itertools.product(*pools)). - * Eg. [[a,b,c], [d], [e,f]] => [[a,d,e], [a,d,f], [b,d,e], [b,d,f], [c,d,e], [c,d,f]]. - * - * @param {Array[]} pools The arrays of arrays. - * @return {Array[]} The product of the arrays. - */ -function arrayProduct(pools) { - // This code is based on the python equivalent at https://docs.python.org/2/library/itertools.html#itertools.product : - // def product(*args): - // # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy - // pools = map(tuple, args) - // result = [[]] - // for pool in pools: - // result = [x+[y] for x in result for y in pool] - // for prod in result: - // yield tuple(prod) - // - // Note for A = [1, 2, 3], B = [10, 20] in python, [a + b for a in A for b in B] = [11, 21, 12, 22, 13, 23]. - // In js, A.map(function(a) { return B.map(function(b) { return a + b}) }) = [ [ 11, 21 ], [ 12, 22 ], [ 13, 23 ] ]. - // For A = [[]], B = [1], in python [a+[b] for a in A for b in B] = [[1]]. - // In js, A.map(function(a) { return B.map(function(b) { return a.concat(b); }) }) = [ [ [ 1 ] ] ]. - // So we need to flatten the js result to make it match itertool's. - var result = [[]]; - pools.forEach(function (pool) { - result = flatten( - result.map(function (partialResult) { - return pool.map(function (poolMember) { - return partialResult.concat(poolMember); - }); - }) - ); - }); - return result; -} - -module.exports = arrayProduct; diff --git a/lib/Core/closeWhenEscapeIsPressed.js b/lib/Core/closeWhenEscapeIsPressed.js deleted file mode 100644 index ffaa17cd713..00000000000 --- a/lib/Core/closeWhenEscapeIsPressed.js +++ /dev/null @@ -1,18 +0,0 @@ -"use strict"; - -var defined = require("terriajs-cesium/Source/Core/defined").default; - -var closeWhenEscapeIsPressed = function (obj) { - var x = init.bind(obj); - var key; - function init(event) { - key = event.which || event.keyCode; - if (key === 27 && defined(obj)) { - obj.close(); - document.removeEventListener("keydown", x); - } - } - document.addEventListener("keydown", x); -}; - -module.exports = closeWhenEscapeIsPressed; diff --git a/lib/Core/combineData.js b/lib/Core/combineData.js deleted file mode 100644 index 0dcc88886ca..00000000000 --- a/lib/Core/combineData.js +++ /dev/null @@ -1,61 +0,0 @@ -"use strict"; - -/** - * Combines two data arrays, each with the format [[x1, y1], [x2, y2], ...] - * maintaining the order of the x's. - * The x and y can be anything with order (integers, floats, dates, etc) - * @param {Array} array Array of arrays, eg. [[[x1, y1], [x2, y2]], [[a1, b1], [a2, b2]]] - * @return {Number[]|Date[]} Combined array. - */ -function combineData(arrays) { - // This implementation works, but could be streamlined. - var numArrays = arrays.length; - if (numArrays === 1) { - return arrays[0]; - } - var expandedArrays = arrays.map(function (array, arrayIndex) { - return array.map(function (a) { - var element = nullArray(numArrays + 1); - element[0] = a[0]; - element[arrayIndex + 1] = a[1]; - return element; - }); - }); - var result = Array.prototype.concat.apply([], expandedArrays); - result.sort(compareFunction); - for (var i = result.length - 2; i >= 0; i--) { - if (compareFunction(result[i], result[i + 1]) === 0) { - // merge the two rows and delete the old one - result[i] = mergeElements(result[i], result[i + 1]); - result.splice(i + 1, 1); - } - } - return result; -} - -function compareFunction(a, b) { - return a[0] - b[0]; - // should be the same as: - // if (a[0] < b[0]) { - // return -1; - // } - // if (a[0] > b[0]) { - // return 1; - // } - // return 0; -} - -function nullArray(len) { - return Array.apply(null, new Array(len)).map(function () { - return null; - }); -} - -function mergeElements(e, f) { - // eg. e = [1, null, null, 0] and f = [1, 15, null, null] should give [1, 15, null, 0] - return e.map(function (a, i) { - return a === null ? f[i] : a; - }); -} - -module.exports = combineData; diff --git a/lib/Core/combineFilters.js b/lib/Core/combineFilters.js deleted file mode 100644 index e09aaec6f6c..00000000000 --- a/lib/Core/combineFilters.js +++ /dev/null @@ -1,54 +0,0 @@ -"use strict"; - -var defined = require("terriajs-cesium/Source/Core/defined").default; - -/** - * Combines a number of functions that return a boolean into a single function that executes all of them and returns - * true only if all them do. Maintains an set of filter functions, so if the same function is combined - * more than once, it is only executed one time. This means that it is also safe to call combineFilter on its own result - * to combine the result with another filter - the set of filters from the previous result will simply - * be merged into that of the new result so that only individual filter functions are executed. - * - * @param {Array} filters A number of functions to combine into one logical function. - * @returns {Function} The resulting function. - */ -function combineFilters(filters) { - var allFilters, returnFn; - - allFilters = filters - .filter(function (filter) { - return defined(filter); - }) - .reduce(function (filtersSoFar, thisFilter) { - if (thisFilter._filterIndex) { - // If a filter is an instance of this function just pull that filter's index into this one's. - thisFilter._filterIndex.forEach( - addToListUnique.bind(undefined, filtersSoFar) - ); - } else { - // Otherwise add it. - addToListUnique(filtersSoFar, thisFilter); - } - - return filtersSoFar; - }, []); - - returnFn = function () { - var outerArgs = arguments; - - return !allFilters.some(function (filter) { - return !filter.apply(this, outerArgs); - }, this); - }; - returnFn._filterIndex = allFilters; - - return returnFn; -} - -function addToListUnique(list, filter) { - if (list.indexOf(filter) === -1) { - list.push(filter); - } -} - -module.exports = combineFilters; diff --git a/lib/Core/createFragmentFromTemplate.js b/lib/Core/createFragmentFromTemplate.js deleted file mode 100644 index 58bef75a2ed..00000000000 --- a/lib/Core/createFragmentFromTemplate.js +++ /dev/null @@ -1,15 +0,0 @@ -"use strict"; - -var createFragmentFromTemplate = function (htmlString) { - var holder = document.createElement("div"); - holder.innerHTML = htmlString; - - var fragment = document.createDocumentFragment(); - while (holder.firstChild) { - fragment.appendChild(holder.firstChild); - } - - return fragment; -}; - -module.exports = createFragmentFromTemplate; diff --git a/lib/Core/flatten.ts b/lib/Core/flatten.ts index 079deb703e3..8aff5b3ea8a 100644 --- a/lib/Core/flatten.ts +++ b/lib/Core/flatten.ts @@ -1,5 +1,3 @@ -"use strict"; - /** * Flattens an array of arrays, into an array, eg. [[0, 1], [2, 3], [4, 5]] => [0, 1, 2, 3, 4, 5]. * Based on the example at diff --git a/lib/Core/flattenNested.ts b/lib/Core/flattenNested.ts index 091dad03975..8e5e3fcbc4d 100644 --- a/lib/Core/flattenNested.ts +++ b/lib/Core/flattenNested.ts @@ -1,5 +1,3 @@ -"use strict"; - type NestedArray = NestedArray[] | T[]; /** diff --git a/lib/Core/inherit.js b/lib/Core/inherit.js deleted file mode 100644 index 507b859be82..00000000000 --- a/lib/Core/inherit.js +++ /dev/null @@ -1,10 +0,0 @@ -"use strict"; - -var inherit = function (base, derived) { - function F() {} - F.prototype = base.prototype; - derived.prototype = new F(); - derived.prototype.constructor = derived; -}; - -module.exports = inherit; diff --git a/lib/Core/isBrowserCompatible.js b/lib/Core/isBrowserCompatible.js deleted file mode 100644 index 7a94cdfa572..00000000000 --- a/lib/Core/isBrowserCompatible.js +++ /dev/null @@ -1,22 +0,0 @@ -"use strict"; - -/** - * Determines if this browser has any hope of running TerriaJS. Specifically, this function checks for the presence - * of the basic ECMAScript 5 function "Object.create". - * - * @return {Boolean} true if this web browser has a chance of running TerriaJS, or false if the browser is so old (pre-IE9) - * that there is no chance of a good result. - */ -var isBrowserCompatible = function () { - // IE9 doesn't have a console object until the debugging tools are opened. - // Add a shim. - if (typeof window.console === "undefined") { - window.console = { - log: function () {} - }; - } - - return typeof Object.create !== "undefined"; -}; - -module.exports = isBrowserCompatible; diff --git a/lib/Core/isCommonMobilePlatform.js b/lib/Core/isCommonMobilePlatform.js deleted file mode 100644 index 462c266ee35..00000000000 --- a/lib/Core/isCommonMobilePlatform.js +++ /dev/null @@ -1,18 +0,0 @@ -"use strict"; - -var defined = require("terriajs-cesium/Source/Core/defined").default; - -/** - * Determines if this is a common mobile platform such as iOS, Android, or Windows Phone. - * @param {String} [userAgentString] The user agent string to check. If this property is not specified, `window.navigator.userAgent` is used. - * @return {Boolean} [description] - */ -var isCommonMobilePlatform = function (userAgentString) { - if (!defined(userAgentString)) { - userAgentString = window.navigator.userAgent; - } - - return /(Android|iPhone|iPad|Windows Phone|IEMobile)/.test(userAgentString); -}; - -module.exports = isCommonMobilePlatform; diff --git a/lib/Core/loadWithXhr.js b/lib/Core/loadWithXhr.js index d656fe46f32..eadf871285c 100644 --- a/lib/Core/loadWithXhr.js +++ b/lib/Core/loadWithXhr.js @@ -1,6 +1,5 @@ -const defaultValue = - require("terriajs-cesium/Source/Core/defaultValue").default; -const Resource = require("terriajs-cesium/Source/Core/Resource").default; +import defaultValue from "terriajs-cesium/Source/Core/defaultValue"; +import Resource from "terriajs-cesium/Source/Core/Resource"; function loadWithXhr(options) { // Take advantage that most parameters are the same diff --git a/lib/Core/polyfill.js b/lib/Core/polyfill.js index 18c1487ec8c..20b1c806158 100644 --- a/lib/Core/polyfill.js +++ b/lib/Core/polyfill.js @@ -8,4 +8,4 @@ function polyfill(callback) { callback(); } -module.exports = polyfill; +export default polyfill; diff --git a/lib/Core/printWindow.ts b/lib/Core/printWindow.ts deleted file mode 100644 index aed070eb8c4..00000000000 --- a/lib/Core/printWindow.ts +++ /dev/null @@ -1,74 +0,0 @@ -import TerriaError from "./TerriaError"; - -import i18next from "i18next"; - -/** - * Tells the web browser to print a given window, which my be an iframe window, and - * returns a promise that resolves when printing is safely over so that, for example - * the window can be removed. - * @param windowToPrint The window to print. - * @returns A promise that resolves when printing is safely over. The promise is rejected if - * there is no indication that the browser's print - */ -export default function printWindow(windowToPrint: Window): Promise { - const deferred = new Promise((resolve, reject) => { - let printInProgressCount = 0; - - const timeout = setTimeout(function () { - reject( - new TerriaError({ - title: i18next.t("core.printWindow.errorTitle"), - message: i18next.t("core.printWindow.errorMessage") - }) - ); - }, 10000); - - function cancelTimeout() { - clearTimeout(timeout); - } - - function resolveIfZero() { - if (printInProgressCount <= 0) { - resolve(); - } - } - - if (windowToPrint.matchMedia) { - windowToPrint.matchMedia("print").addListener((evt: any) => { - cancelTimeout(); - if (evt.matches) { - console.log(i18next.t("core.printWindow.printMediaStart")); - ++printInProgressCount; - } else { - console.log(i18next.t("core.printWindow.printMediaEnd")); - --printInProgressCount; - resolveIfZero(); - } - }); - } - - windowToPrint.onbeforeprint = () => { - cancelTimeout(); - console.log(i18next.t("core.printWindow.onbeforeprint")); - ++printInProgressCount; - }; - windowToPrint.onafterprint = () => { - cancelTimeout(); - console.log(i18next.t("core.printWindow.onafterprint")); - --printInProgressCount; - resolveIfZero(); - }; - - // First try printing with execCommand, because, in IE11, `printWindow.print()` - // prints the entire page instead of just the embedded iframe (if the window - // is an iframe, anyway). - const result = windowToPrint.document.execCommand("print", true, undefined); - if (!result) { - windowToPrint.print(); - } - }); - - return deferred; -} - -module.exports = printWindow; diff --git a/lib/Core/promiseFunctionToExplicitDeferred.js b/lib/Core/promiseFunctionToExplicitDeferred.js deleted file mode 100644 index 946737da97c..00000000000 --- a/lib/Core/promiseFunctionToExplicitDeferred.js +++ /dev/null @@ -1,11 +0,0 @@ -"use strict"; - -function promiseFunctionToExplicitDeferred(deferred, f, args) { - try { - deferred.resolve(f.apply(undefined, args)); - } catch (e) { - deferred.reject(e); - } -} - -module.exports = promiseFunctionToExplicitDeferred; diff --git a/lib/Core/rectangleToPolygonArray.js b/lib/Core/rectangleToPolygonArray.js deleted file mode 100644 index 4dbd6098214..00000000000 --- a/lib/Core/rectangleToPolygonArray.js +++ /dev/null @@ -1,22 +0,0 @@ -"use strict"; - -var CesiumMath = require("terriajs-cesium/Source/Core/Math").default; -var Rectangle = require("terriajs-cesium/Source/Core/Rectangle").default; - -var rectangleToPolygonArray = function (rectangle) { - var sw = Rectangle.southwest(rectangle), - se = Rectangle.southeast(rectangle), - nw = Rectangle.northwest(rectangle), - ne = Rectangle.northeast(rectangle); - return [ - [ - [CesiumMath.toDegrees(sw.longitude), CesiumMath.toDegrees(sw.latitude)], - [CesiumMath.toDegrees(se.longitude), CesiumMath.toDegrees(se.latitude)], - [CesiumMath.toDegrees(ne.longitude), CesiumMath.toDegrees(ne.latitude)], - [CesiumMath.toDegrees(nw.longitude), CesiumMath.toDegrees(nw.latitude)], - [CesiumMath.toDegrees(sw.longitude), CesiumMath.toDegrees(sw.latitude)] - ] - ]; -}; - -module.exports = rectangleToPolygonArray; diff --git a/lib/Core/removeView.js b/lib/Core/removeView.js deleted file mode 100644 index 32719675371..00000000000 --- a/lib/Core/removeView.js +++ /dev/null @@ -1,12 +0,0 @@ -"use strict"; - -var removeView = function (domNodes) { - for (var i = 0; i < domNodes.length; ++i) { - var node = domNodes[i]; - if (node.parentNode) { - node.parentNode.removeChild(node); - } - } -}; - -module.exports = removeView; diff --git a/lib/Core/serializeToJson.js b/lib/Core/serializeToJson.js deleted file mode 100644 index 58dc3d06490..00000000000 --- a/lib/Core/serializeToJson.js +++ /dev/null @@ -1,39 +0,0 @@ -"use strict"; - -var defaultValue = require("terriajs-cesium/Source/Core/defaultValue").default; - -/** - * Serializes an object to JSON. - * @param {Object} target The object to serialize. - * @param {Function} filterFunction A function that, when passed the name of a property as its only parameter, returns true if that property should be serialized and false otherwise. - * @param {Object} [options] Optional parameters to custom serializers. - * @return {Object} An object literal corresponding to the serialized object, ready to pass to `JSON.stringify`. - */ -function serializeToJson(target, filterFunction, options) { - options = defaultValue(options, defaultValue.EMPTY_OBJECT); - filterFunction = defaultValue(filterFunction, function () { - return true; - }); - - var result = {}; - - for (var propertyName in target) { - if ( - Object.prototype.hasOwnProperty.call(target, propertyName) && - propertyName.length > 0 && - propertyName[0] !== "_" && - propertyName !== "parent" && - filterFunction(propertyName, target) - ) { - if (target.serializers && target.serializers[propertyName]) { - target.serializers[propertyName](target, result, propertyName, options); - } else { - result[propertyName] = target[propertyName]; - } - } - } - - return result; -} - -module.exports = serializeToJson; diff --git a/lib/Core/sortedIndices.js b/lib/Core/sortedIndices.js index 4c34b3eba31..37f4bd54a44 100644 --- a/lib/Core/sortedIndices.js +++ b/lib/Core/sortedIndices.js @@ -1,5 +1,3 @@ -"use strict"; - /** * Returns indices such that array[indices[i]] = sortedArray[i]. * Eg. sortedIndices(['c', 'a', 'b', 'd']) => [1, 2, 0, 3]. (The sorted array is [a, b, c, d], and "a" was in position 1, "b" in position 2, etc.) @@ -34,4 +32,4 @@ function sortedIndices(array, compareFunction) { // expect(inverseIndices).toEqual([2, 0, 1, 3]); // }); -module.exports = sortedIndices; +export default sortedIndices; diff --git a/lib/Core/supportsWebGL.js b/lib/Core/supportsWebGL.js index 3a75017e2d6..d394491848a 100644 --- a/lib/Core/supportsWebGL.js +++ b/lib/Core/supportsWebGL.js @@ -1,8 +1,6 @@ -"use strict"; +import defined from "terriajs-cesium/Source/Core/defined"; -var defined = require("terriajs-cesium/Source/Core/defined").default; - -var result; +let result; /** * Determines if the current browser supports WebGL. @@ -55,4 +53,4 @@ function supportsWebGL() { return result; } -module.exports = supportsWebGL; +export default supportsWebGL; diff --git a/lib/Core/updateFromJson.js b/lib/Core/updateFromJson.js deleted file mode 100644 index c9583d64ae3..00000000000 --- a/lib/Core/updateFromJson.js +++ /dev/null @@ -1,49 +0,0 @@ -"use strict"; - -var defaultValue = require("terriajs-cesium/Source/Core/defaultValue").default; -var defined = require("terriajs-cesium/Source/Core/defined").default; - -/** - * Updates an object from a JSON representation of the object. Only properties that actually exist on the object are read from the JSON, - * and the object has the opportunity to inject specialized deserialization logic by providing an `updaters` property. - * @param {Object} target The object to update from the JSON. - * @param {Object} json The JSON description. The JSON should be in the form of an object literal, not a string. - * @param {Object} [options] Optional parameters to custom updaters. - * @return {Promise} A promise that resolves when the update completes. - */ -function updateFromJson(target, json, options) { - options = defaultValue(options, defaultValue.EMPTY_OBJECT); - - var promises = []; - - for (var propertyName in target) { - if ( - Object.prototype.hasOwnProperty.call(target, propertyName) && - shouldBeUpdated(target, propertyName, json) - ) { - if (target.updaters && target.updaters[propertyName]) { - promises.push( - target.updaters[propertyName](target, json, propertyName, options) - ); - } else { - target[propertyName] = json[propertyName]; - } - } - } - - return Promise.all(promises); -} - -/** - * Determines whether this property is valid for updating. - */ -function shouldBeUpdated(target, propertyName, json) { - return ( - json[propertyName] !== undefined && // Must have a value to update to - propertyName.length > 0 && // Must have a name to update - propertyName[0] !== "_" && // Must not be a private property - (propertyName !== "id" || !defined(target.id)) - ); // Must not be overwriting 'id' -} - -module.exports = updateFromJson; diff --git a/lib/Map/Cesium/createCredit.js b/lib/Map/Cesium/createCredit.js deleted file mode 100644 index 2a9f11630bb..00000000000 --- a/lib/Map/Cesium/createCredit.js +++ /dev/null @@ -1,21 +0,0 @@ -const Credit = require("terriajs-cesium/Source/Core/Credit").default; - -function createCredit(text, url) { - if (!text && !url) { - return undefined; - } - - if (text && !url) { - return new Credit(text); - } - - text = text || url; - - const a = document.createElement("a"); - a.href = url; - a.target = "_blank"; - a.innerText = text; - return new Credit(a.outerHTML); -} - -module.exports = createCredit; diff --git a/lib/Map/DragPoints/CesiumDragPoints.js b/lib/Map/DragPoints/CesiumDragPoints.js index 18f1a57b3aa..bfcccb47bb6 100644 --- a/lib/Map/DragPoints/CesiumDragPoints.js +++ b/lib/Map/DragPoints/CesiumDragPoints.js @@ -1,12 +1,7 @@ -"use strict"; - -var defined = require("terriajs-cesium/Source/Core/defined").default; -var ScreenSpaceEventHandler = - require("terriajs-cesium/Source/Core/ScreenSpaceEventHandler").default; -var ScreenSpaceEventType = - require("terriajs-cesium/Source/Core/ScreenSpaceEventType").default; -var CustomDataSource = - require("terriajs-cesium/Source/DataSources/CustomDataSource").default; +import defined from "terriajs-cesium/Source/Core/defined"; +import ScreenSpaceEventHandler from "terriajs-cesium/Source/Core/ScreenSpaceEventHandler"; +import ScreenSpaceEventType from "terriajs-cesium/Source/Core/ScreenSpaceEventType"; +import CustomDataSource from "terriajs-cesium/Source/DataSources/CustomDataSource"; /** * Callback for when a point is moved. @@ -23,7 +18,7 @@ var CustomDataSource = * @param {Terria} terria The Terria instance. * @param {PointMovedCallback} pointMovedCallback A function that is called when a point is moved. */ -var CesiumDragPoints = function (terria, pointMovedCallback) { +const CesiumDragPoints = function (terria, pointMovedCallback) { this._terria = terria; this._setUp = false; this.type = "Cesium"; @@ -164,4 +159,4 @@ CesiumDragPoints.prototype._setCameraMotion = function (state) { this._scene.screenSpaceCameraController.enableTranslate = state; }; -module.exports = CesiumDragPoints; +export default CesiumDragPoints; diff --git a/lib/Map/DragPoints/DragPoints.js b/lib/Map/DragPoints/DragPoints.js index 0062d4b6c97..bd081fba7fd 100644 --- a/lib/Map/DragPoints/DragPoints.js +++ b/lib/Map/DragPoints/DragPoints.js @@ -1,7 +1,7 @@ -var defined = require("terriajs-cesium/Source/Core/defined").default; -var CesiumDragPoints = require("./CesiumDragPoints"); -var LeafletDragPoints = require("./LeafletDragPoints"); -var ViewerMode = require("../../Models/ViewerMode").default; +import defined from "terriajs-cesium/Source/Core/defined"; +import CesiumDragPoints from "./CesiumDragPoints"; +import LeafletDragPoints from "./LeafletDragPoints"; +import ViewerMode from "../../Models/ViewerMode"; /** * Callback for when a point is moved. diff --git a/lib/Map/DragPoints/LeafletDragPoints.js b/lib/Map/DragPoints/LeafletDragPoints.js index a5896610c01..0d5098ee706 100644 --- a/lib/Map/DragPoints/LeafletDragPoints.js +++ b/lib/Map/DragPoints/LeafletDragPoints.js @@ -1,8 +1,6 @@ -"use strict"; -var defined = require("terriajs-cesium/Source/Core/defined").default; -var Cartesian3 = require("terriajs-cesium/Source/Core/Cartesian3").default; -var CustomDataSource = - require("terriajs-cesium/Source/DataSources/CustomDataSource").default; +import defined from "terriajs-cesium/Source/Core/defined"; +import Cartesian3 from "terriajs-cesium/Source/Core/Cartesian3"; +import CustomDataSource from "terriajs-cesium/Source/DataSources/CustomDataSource"; /** * Callback for when a point is moved. @@ -19,7 +17,7 @@ var CustomDataSource = * @param {Terria} terria The Terria instance. * @param {PointMovedCallback} pointMovedCallback A function that is called when a point is moved. */ -var LeafletDragPoints = function (terria, pointMovedCallback) { +const LeafletDragPoints = function (terria, pointMovedCallback) { this._terria = terria; this._setUp = false; this.type = "Leaflet"; @@ -160,4 +158,4 @@ LeafletDragPoints.prototype.destroy = function () { this._setUp = false; }; -module.exports = LeafletDragPoints; +export default LeafletDragPoints; diff --git a/lib/Map/Geocoder/AddressGeocoder.js b/lib/Map/Geocoder/AddressGeocoder.js deleted file mode 100644 index dd937edbc5c..00000000000 --- a/lib/Map/Geocoder/AddressGeocoder.js +++ /dev/null @@ -1,32 +0,0 @@ -"use strict"; - -const i18next = require("i18next").default; -var DeveloperError = - require("terriajs-cesium/Source/Core/DeveloperError").default; - -/** - * Determine lat and long coordinates for a given address. - * If TableStructure has address column, adds two new columns: lat and long. - * - * @alias AddressGeocoder - * @constructor - */ -var AddressGeocoder = function () {}; - -/** - * Convert addresses in miniumum number of calls to the server. When the promise fulfills, the tableStructure has been - * updated with new lat and lon columns. - * - * @param {TableStructure} [tableStructure] A tableStructure that contains an address column. - * @param {CorsProxy} [corsProxy] Proxy for cross origin resource sharing - * - * @return {Promise} Promise that resolves to an BulkAddressGeocoderResult object. - */ -AddressGeocoder.prototype.bulkConvertAddresses = function ( - tableStructure, - corsProxy -) { - throw new DeveloperError(i18next.t("map.addressGeocoder.devError")); -}; - -module.exports = AddressGeocoder; diff --git a/lib/Map/Geocoder/BulkAddressGeocoderResult.js b/lib/Map/Geocoder/BulkAddressGeocoderResult.js deleted file mode 100644 index e4dc4e0e91f..00000000000 --- a/lib/Map/Geocoder/BulkAddressGeocoderResult.js +++ /dev/null @@ -1,39 +0,0 @@ -"use strict"; - -/** - * Holds data for what the AddressGeocoder returns. - * - * @alias BulkAddressGeocoderResult - * @constructor - */ -var BulkAddressGeocoderResult = function ( - startTime, - numberOfAddressesConverted, - nullAddresses, - missingAddresses -) { - /** - * Time geocoder started. - * @type {JulianDate} - */ - this.startTime = startTime; - - /** - * Number of addresses converted to lat-long coordinates. - * @type {Number} - */ - this.numberOfAddressesConverted = numberOfAddressesConverted; - - /** - * Number of addresses that were null. - * @type {Number} - */ - this.nullAddresses = nullAddresses; - /** - * Addresses that couldn't be geocoded. - * @type {Array} - */ - this.missingAddresses = missingAddresses; -}; - -module.exports = BulkAddressGeocoderResult; diff --git a/lib/Map/ImageryProvider/ProtomapsImageryProvider.ts b/lib/Map/ImageryProvider/ProtomapsImageryProvider.ts index c99ccfcda26..8611c8c07de 100644 --- a/lib/Map/ImageryProvider/ProtomapsImageryProvider.ts +++ b/lib/Map/ImageryProvider/ProtomapsImageryProvider.ts @@ -42,8 +42,7 @@ import { import { default as TerriaFeature } from "../../Models/Feature/Feature"; import Terria from "../../Models/Terria"; import { ImageryProviderWithGridLayerSupport } from "../Leaflet/ImageryProviderLeafletGridLayer"; - -const geojsonvt = require("geojson-vt").default; +import geojsonvt from "geojson-vt"; type GeojsonVtFeature = { id: any; diff --git a/lib/Map/Leaflet/LeafletSelectionIndicator.ts b/lib/Map/Leaflet/LeafletSelectionIndicator.ts index 69fe7239620..d7d5777bc04 100644 --- a/lib/Map/Leaflet/LeafletSelectionIndicator.ts +++ b/lib/Map/Leaflet/LeafletSelectionIndicator.ts @@ -5,7 +5,6 @@ import Ellipsoid from "terriajs-cesium/Source/Core/Ellipsoid"; import CesiumMath from "terriajs-cesium/Source/Core/Math"; import TweenCollection from "terriajs-cesium/Source/Scene/TweenCollection"; import isDefined from "../../Core/isDefined"; - import Leaflet from "../../Models/Leaflet"; const selectionIndicatorUrl = require("../../../wwwroot/images/NM-LocationTarget.svg"); diff --git a/lib/Map/PickedFeatures/featureDataToGeoJson.ts b/lib/Map/PickedFeatures/featureDataToGeoJson.ts index 9f0711c1815..4c10a89b1f6 100644 --- a/lib/Map/PickedFeatures/featureDataToGeoJson.ts +++ b/lib/Map/PickedFeatures/featureDataToGeoJson.ts @@ -1,5 +1,3 @@ -"use strict"; - import Point from "@mapbox/point-geometry"; import { Feature as GeoJsonFeature, @@ -26,8 +24,7 @@ import { toFeatureCollection } from "../../ModelMixins/GeojsonMixin"; import computeRingWindingOrder from "../Vector/computeRingWindingOrder"; - -const pointInPolygon = require("point-in-polygon"); +import pointInPolygon from "point-in-polygon"; /** * Converts feature data, such as from a WMS GetFeatureInfo or an Esri Identify, to diff --git a/lib/Map/VarType.js b/lib/Map/VarType.js deleted file mode 100644 index 5f973aa8965..00000000000 --- a/lib/Map/VarType.js +++ /dev/null @@ -1,16 +0,0 @@ -"use strict"; - -var VarType = { - LON: 0, - LAT: 1, - ALT: 2, - TIME: 3, - SCALAR: 4, - ENUM: 5, - REGION: 6, - TAG: 7, - HIDDEN: 8, - ADDR: 9 -}; - -module.exports = VarType; diff --git a/lib/Map/Vector/EarthGravityModel1996.js b/lib/Map/Vector/EarthGravityModel1996.js index cd301cff88b..b375fc7f2b6 100644 --- a/lib/Map/Vector/EarthGravityModel1996.js +++ b/lib/Map/Vector/EarthGravityModel1996.js @@ -1,8 +1,6 @@ -"use strict"; - -var CesiumMath = require("terriajs-cesium/Source/Core/Math").default; -var defined = require("terriajs-cesium/Source/Core/defined").default; -var loadArrayBuffer = require("../../Core/loadArrayBuffer").default; +import CesiumMath from "terriajs-cesium/Source/Core/Math"; +import defined from "terriajs-cesium/Source/Core/defined"; +import loadArrayBuffer from "../../Core/loadArrayBuffer"; /** * The Earth Gravity Model 1996 (EGM96) geoid. @@ -131,4 +129,4 @@ function getHeightValue(data, recordIndex, heightIndex) { return data[recordIndex * 1440 + heightIndex]; } -module.exports = EarthGravityModel1996; +export default EarthGravityModel1996; diff --git a/lib/Map/Vector/computeRingWindingOrder.ts b/lib/Map/Vector/computeRingWindingOrder.ts index f929c383429..cc27193f987 100644 --- a/lib/Map/Vector/computeRingWindingOrder.ts +++ b/lib/Map/Vector/computeRingWindingOrder.ts @@ -1,5 +1,3 @@ -"use strict"; - import i18next from "i18next"; import WindingOrder from "terriajs-cesium/Source/Core/WindingOrder"; import DeveloperError from "terriajs-cesium/Source/Core/DeveloperError"; diff --git a/lib/Map/Vector/geoJsonGeometryFromGeoRssSimpleGeometry.js b/lib/Map/Vector/geoJsonGeometryFromGeoRssSimpleGeometry.js index 90e7c4e2325..33a92bfbebe 100644 --- a/lib/Map/Vector/geoJsonGeometryFromGeoRssSimpleGeometry.js +++ b/lib/Map/Vector/geoJsonGeometryFromGeoRssSimpleGeometry.js @@ -1,6 +1,6 @@ -var defined = require("terriajs-cesium/Source/Core/defined").default; -var RuntimeError = require("terriajs-cesium/Source/Core/RuntimeError").default; -var i18next = require("i18next").default; +import defined from "terriajs-cesium/Source/Core/defined"; +import RuntimeError from "terriajs-cesium/Source/Core/RuntimeError"; +import i18next from "i18next"; var featureCreators = { point: createPointGeometry, @@ -83,4 +83,4 @@ function geom2coord(posList) { return coords; } -module.exports = geoJsonGeometryFromGeoRssSimpleGeometry; +export default geoJsonGeometryFromGeoRssSimpleGeometry; diff --git a/lib/Map/Vector/geoJsonGeometryFromGmlGeometry.js b/lib/Map/Vector/geoJsonGeometryFromGmlGeometry.js index a19b07bdee6..448e17d966a 100644 --- a/lib/Map/Vector/geoJsonGeometryFromGmlGeometry.js +++ b/lib/Map/Vector/geoJsonGeometryFromGmlGeometry.js @@ -1,7 +1,8 @@ -var RuntimeError = require("terriajs-cesium/Source/Core/RuntimeError").default; -var i18next = require("i18next").default; -var defined = require("terriajs-cesium/Source/Core/defined").default; -var gmlNamespace = "http://www.opengis.net/gml"; +import RuntimeError from "terriajs-cesium/Source/Core/RuntimeError"; +import i18next from "i18next"; +import defined from "terriajs-cesium/Source/Core/defined"; + +const gmlNamespace = "http://www.opengis.net/gml"; function createLineStringFromGmlGeometry(geometry) { var coordinates = []; @@ -211,4 +212,4 @@ function gml2coord(posList) { return coords; } -module.exports = geoJsonGeometryFeatureFromGmlGeometry; +export default geoJsonGeometryFeatureFromGmlGeometry; diff --git a/lib/Map/Vector/geoJsonGeometryFromW3cGeometry.js b/lib/Map/Vector/geoJsonGeometryFromW3cGeometry.js index be142227b3e..0b3524fc3d4 100644 --- a/lib/Map/Vector/geoJsonGeometryFromW3cGeometry.js +++ b/lib/Map/Vector/geoJsonGeometryFromW3cGeometry.js @@ -1,6 +1,6 @@ -var defined = require("terriajs-cesium/Source/Core/defined").default; -var RuntimeError = require("terriajs-cesium/Source/Core/RuntimeError").default; -var i18next = require("i18next").default; +import defined from "terriajs-cesium/Source/Core/defined"; +import RuntimeError from "terriajs-cesium/Source/Core/RuntimeError"; +import i18next from "i18next"; var featureCreators = { Point: createPointGeometry @@ -34,4 +34,4 @@ function createPointGeometry(geometry) { }; } -module.exports = geoJsonGeometryFromW3cGeometry; +export default geoJsonGeometryFromW3cGeometry; diff --git a/lib/Map/Vector/geoRssConvertor.js b/lib/Map/Vector/geoRssConvertor.js index 6f9a765c6ee..ddee681ce6a 100644 --- a/lib/Map/Vector/geoRssConvertor.js +++ b/lib/Map/Vector/geoRssConvertor.js @@ -1,9 +1,7 @@ -"use strict"; - -var defined = require("terriajs-cesium/Source/Core/defined").default; -var geoJsonGeometryFromGeoRssSimpleGeometry = require("./geoJsonGeometryFromGeoRssSimpleGeometry"); -var geoJsonGeometryFromGmlGeometry = require("./geoJsonGeometryFromGmlGeometry"); -var geoJsonGeometryFromW3cGeometry = require("./geoJsonGeometryFromW3cGeometry"); +import defined from "terriajs-cesium/Source/Core/defined"; +import geoJsonGeometryFromGeoRssSimpleGeometry from "./geoJsonGeometryFromGeoRssSimpleGeometry"; +import geoJsonGeometryFromGmlGeometry from "./geoJsonGeometryFromGmlGeometry"; +import geoJsonGeometryFromW3cGeometry from "./geoJsonGeometryFromW3cGeometry"; /** * Converts a GeoRss v2.0 document to GeoJSON. diff --git a/lib/Map/Vector/gmlToGeoJson.js b/lib/Map/Vector/gmlToGeoJson.js index 0472a3429ab..6b7886acc81 100644 --- a/lib/Map/Vector/gmlToGeoJson.js +++ b/lib/Map/Vector/gmlToGeoJson.js @@ -1,8 +1,7 @@ -"use strict"; +import defined from "terriajs-cesium/Source/Core/defined"; +import geoJsonGeometryFromGmlGeometry from "./geoJsonGeometryFromGmlGeometry"; -var defined = require("terriajs-cesium/Source/Core/defined").default; -var geoJsonGeometryFromGmlGeometry = require("./geoJsonGeometryFromGmlGeometry"); -var gmlNamespace = "http://www.opengis.net/gml"; +const gmlNamespace = "http://www.opengis.net/gml"; /** * Converts a GML v3.1.1 simple features document to GeoJSON. @@ -104,4 +103,4 @@ function getGmlGeometry(gmlNode) { return result; } -module.exports = gmlToGeoJson; +export default gmlToGeoJson; diff --git a/lib/Map/Vector/prettifyProjection.ts b/lib/Map/Vector/prettifyProjection.ts index bb1274351a1..a1571ef3d1c 100644 --- a/lib/Map/Vector/prettifyProjection.ts +++ b/lib/Map/Vector/prettifyProjection.ts @@ -1,4 +1,4 @@ -const proj4 = require("proj4/lib/index.js").default; +import proj4 from "proj4"; /** * Turns the longitude / latitude in degrees into a human readable pretty UTM zone representation. diff --git a/lib/Map/Vector/unionRectangleArray.js b/lib/Map/Vector/unionRectangleArray.js deleted file mode 100644 index 8798a66443f..00000000000 --- a/lib/Map/Vector/unionRectangleArray.js +++ /dev/null @@ -1,32 +0,0 @@ -"use strict"; - -var defined = require("terriajs-cesium/Source/Core/defined").default; -var Rectangle = require("terriajs-cesium/Source/Core/Rectangle").default; -var unionRectangles = require("./unionRectangles"); - -/** - * Computes the union of an array of rectangles. This function is not 180-meridian safe. - * @param {Rectangle[]} rectangles The array of rectangles to union. - * @return {Rectangle} The union of the rectangles, or undefined if the array of rectangles is empty. - */ -var unionRectangleArray = function (rectangles) { - var result; - for (var i = 0; i < rectangles.length; ++i) { - if (!defined(rectangles[i])) { - continue; - } - - if (!defined(result)) { - result = Rectangle.clone(rectangles[i]); - } else { - var rectangle = rectangles[i]; - if (defined(rectangle)) { - result = unionRectangles(result, rectangle, result); - } - } - } - - return result; -}; - -module.exports = unionRectangleArray; diff --git a/lib/Map/Vector/unionRectangles.js b/lib/Map/Vector/unionRectangles.js deleted file mode 100644 index 2de58ea7cfd..00000000000 --- a/lib/Map/Vector/unionRectangles.js +++ /dev/null @@ -1,40 +0,0 @@ -"use strict"; - -var defined = require("terriajs-cesium/Source/Core/defined").default; -var DeveloperError = - require("terriajs-cesium/Source/Core/DeveloperError").default; -var Rectangle = require("terriajs-cesium/Source/Core/Rectangle").default; - -/** - * Computes the union of two rectangles. This function is not 180-meridian safe. - * @param {Rectangle} first The first rectangle to union. - * @param {Rectangle} second The second rectangle to union. - * @param {Rectangle} [result] The existing {@link Rectangle} to which to copy the result instead of creating and returning a new instance. - * @return {Rectangle} The union of the two rectangles. - */ -var unionRectangles = function (first, second, result) { - if (!defined(first)) { - throw new DeveloperError("first is required"); - } - if (!defined(second)) { - throw new DeveloperError("second is required"); - } - - var west = Math.min(first.west, second.west); - var south = Math.min(first.south, second.south); - var east = Math.max(first.east, second.east); - var north = Math.max(first.north, second.north); - - if (!defined(result)) { - result = new Rectangle(west, south, east, north); - } else { - result.west = west; - result.south = south; - result.east = east; - result.north = north; - } - - return result; -}; - -module.exports = unionRectangles; diff --git a/lib/Map/Vector/zoomRectangleFromPoint.js b/lib/Map/Vector/zoomRectangleFromPoint.js index 402878fa7ff..931113c258f 100644 --- a/lib/Map/Vector/zoomRectangleFromPoint.js +++ b/lib/Map/Vector/zoomRectangleFromPoint.js @@ -1,11 +1,11 @@ -var Rectangle = require("terriajs-cesium/Source/Core/Rectangle").default; -var defaultValue = require("terriajs-cesium/Source/Core/defaultValue").default; +import Rectangle from "terriajs-cesium/Source/Core/Rectangle"; +import defaultValue from "terriajs-cesium/Source/Core/defaultValue"; // Server does not return information of a bounding box, just a location. // BOUNDING_BOX_SIZE is used to expand a point -var DEFAULT_BOUNDING_BOX_SIZE = 0.2; +const DEFAULT_BOUNDING_BOX_SIZE = 0.2; -module.exports = function createZoomToFunction( +export default function createZoomToFunction( latitude, longitude, boundingBoxSize @@ -17,4 +17,4 @@ module.exports = function createZoomToFunction( var north = parseFloat(latitude) + boundingBoxSize / 2; var east = parseFloat(longitude) + boundingBoxSize / 2; return Rectangle.fromDegrees(west, south, east, north); -}; +} diff --git a/lib/ModelMixins/GroupMixin.ts b/lib/ModelMixins/GroupMixin.ts index 9037a0e20c6..3077d3eb188 100644 --- a/lib/ModelMixins/GroupMixin.ts +++ b/lib/ModelMixins/GroupMixin.ts @@ -19,8 +19,8 @@ import GroupTraits from "../Traits/TraitsClasses/GroupTraits"; import { ItemPropertiesTraits } from "../Traits/TraitsClasses/ItemPropertiesTraits"; import CatalogMemberMixin, { getName } from "./CatalogMemberMixin"; import ReferenceMixin from "./ReferenceMixin"; +import naturalSort from "javascript-natural-sort"; -const naturalSort = require("javascript-natural-sort"); naturalSort.insensitive = true; const MERGED_GROUP_ID_PREPEND = "__merged__"; diff --git a/lib/Models/Catalog/CatalogItems/GpxCatalogItem.ts b/lib/Models/Catalog/CatalogItems/GpxCatalogItem.ts index 77e4b039781..ecbeb4d2a57 100644 --- a/lib/Models/Catalog/CatalogItems/GpxCatalogItem.ts +++ b/lib/Models/Catalog/CatalogItems/GpxCatalogItem.ts @@ -12,8 +12,7 @@ import GpxCatalogItemTraits from "../../../Traits/TraitsClasses/GpxCatalogItemTr import CreateModel from "../../Definition/CreateModel"; import { ModelConstructorParameters } from "../../Definition/Model"; import proxyCatalogItemUrl from "../proxyCatalogItemUrl"; - -const toGeoJSON = require("@mapbox/togeojson"); +import toGeoJSON from "@mapbox/togeojson"; class GpxCatalogItem extends GeoJsonMixin(CreateModel(GpxCatalogItemTraits)) { static readonly type = "gpx"; diff --git a/lib/Models/Catalog/Esri/ArcGisFeatureServerCatalogItem.ts b/lib/Models/Catalog/Esri/ArcGisFeatureServerCatalogItem.ts index e3adac2009b..5fe960b552a 100644 --- a/lib/Models/Catalog/Esri/ArcGisFeatureServerCatalogItem.ts +++ b/lib/Models/Catalog/Esri/ArcGisFeatureServerCatalogItem.ts @@ -38,8 +38,7 @@ import StratumFromTraits from "../../Definition/StratumFromTraits"; import StratumOrder from "../../Definition/StratumOrder"; import { ModelConstructorParameters } from "../../Definition/Model"; import proxyCatalogItemUrl from "../proxyCatalogItemUrl"; - -const proj4 = require("proj4").default; +import proj4 from "proj4"; interface DocumentInfo { Author?: string; @@ -257,7 +256,9 @@ class FeatureServerStratum extends LoadableStratum( return undefined; } + // @ts-expect-error @types/proj4 doesn't define a constructor type const source = new proj4.Proj((proj4definitions as any)[wkid]); + // @ts-expect-error @types/proj4 doesn't define a constructor type const dest = new proj4.Proj("EPSG:4326"); let p = proj4(source, dest, [extent.xmin, extent.ymin]); diff --git a/lib/Models/Catalog/Esri/ArcGisMapServerCatalogItem.ts b/lib/Models/Catalog/Esri/ArcGisMapServerCatalogItem.ts index 7eedbc52d98..619286a4056 100644 --- a/lib/Models/Catalog/Esri/ArcGisMapServerCatalogItem.ts +++ b/lib/Models/Catalog/Esri/ArcGisMapServerCatalogItem.ts @@ -41,8 +41,7 @@ import getToken from "../../getToken"; import proxyCatalogItemUrl from "../proxyCatalogItemUrl"; import MinMaxLevelMixin from "./../../../ModelMixins/MinMaxLevelMixin"; import { Extent, Layer, Legends, MapServer } from "./ArcGisInterfaces"; - -const proj4 = require("proj4").default; +import proj4 from "proj4"; class MapServerStratum extends LoadableStratum( ArcGisMapServerCatalogItemTraits @@ -702,7 +701,9 @@ export function getRectangleFromLayer( return; } + // @ts-expect-error @types/proj4 doesn't define a constructor type const source = new proj4.Proj(Proj4Definitions[wkid]); + // @ts-expect-error @types/proj4 doesn't define a constructor type const dest = new proj4.Proj("EPSG:4326"); let p = proj4(source, dest, [extent.xmin, extent.ymin]); diff --git a/lib/Models/Catalog/Ows/WebMapServiceCatalogItem.ts b/lib/Models/Catalog/Ows/WebMapServiceCatalogItem.ts index a9c28efbb7b..bc4aa79f815 100644 --- a/lib/Models/Catalog/Ows/WebMapServiceCatalogItem.ts +++ b/lib/Models/Catalog/Ows/WebMapServiceCatalogItem.ts @@ -1,5 +1,3 @@ -// const mobx = require('mobx'); -// const mobxUtils = require('mobx-utils'); // Problems in current architecture: // 1. After loading, can't tell what user actually set versus what came from e.g. GetCapabilities. // Solution: layering diff --git a/lib/Models/Catalog/createCatalogMemberFromType.js b/lib/Models/Catalog/createCatalogMemberFromType.js deleted file mode 100644 index 43c9e79a16d..00000000000 --- a/lib/Models/Catalog/createCatalogMemberFromType.js +++ /dev/null @@ -1,41 +0,0 @@ -"use strict"; - -var defined = require("terriajs-cesium/Source/Core/defined").default; - -var TerriaError = require("../../Core/TerriaError").default; -var i18next = require("i18next").default; - -var mapping = {}; - -/** - * Creates a type derived from {@link CatalogMember} based on a given type string. - * - * @param {String} type The derived type name. - * @param {Terria} terria The Terria instance. - */ -var createCatalogMemberFromType = function (type, terria) { - var Constructor = mapping[type]; - if (!defined(Constructor)) { - throw new TerriaError({ - title: i18next.t("models.catalog.unsupportedTypeTitle"), - message: i18next.t("models.catalog.unsupportedTypeMessage", { - type - }) - }); - } - - return new Constructor(terria); -}; - -/** - * Registers a constructor for a given type of {@link CatalogMember}. - * - * @param {String} type The type name for which to register a constructor. - * @param {Function} constructor The constructor for data items of this type. The constructor is expected to take a - * {@link Terria} as its first and only required parameter. - */ -createCatalogMemberFromType.register = function (type, constructor) { - mapping[type] = constructor; -}; - -module.exports = createCatalogMemberFromType; diff --git a/lib/Models/Catalog/proxyCatalogItemUrl.ts b/lib/Models/Catalog/proxyCatalogItemUrl.ts index de05080ed7a..1c4a47b17d0 100644 --- a/lib/Models/Catalog/proxyCatalogItemUrl.ts +++ b/lib/Models/Catalog/proxyCatalogItemUrl.ts @@ -1,5 +1,3 @@ -"use strict"; - import defaultValue from "terriajs-cesium/Source/Core/defaultValue"; import isDefined from "../../Core/isDefined"; import UrlMixin from "../../ModelMixins/UrlMixin"; diff --git a/lib/Models/FunctionParameters/BooleanParameterGroup.js b/lib/Models/FunctionParameters/BooleanParameterGroup.js deleted file mode 100644 index 3c6ea0c109f..00000000000 --- a/lib/Models/FunctionParameters/BooleanParameterGroup.js +++ /dev/null @@ -1,179 +0,0 @@ -"use strict"; - -var BooleanParameter = require("./BooleanParameter"); -var FunctionParameter = require("../FunctionParameter"); -var inherit = require("../../Core/inherit"); - -/** - * A catalog input type that groups Boolean Parameters for a category. - * - * @alias BooleanParameterGroup - * @constructor - * - * @param {Object} [options] Object with the following properties: - * @param {Terria} options.terria The Terria instance. - * @param {String} options.id The unique ID of this parameter. - * @param {String} [options.name] The name of this parameter. If not specified, the ID is used as the name. - * @param {String} [options.description] The description of the parameter. - * @param {Boolean} [options.allValue] Whether or not to have {id: OneForAll.id, value: OneForAll.value} in this.value - * @param {Boolean} [options.allCascade] Whether OneForAll being true passes all {id: ParameterList.id, value: true} values through to this.value - * @param {BooleanParameter} [options.OneForAll] A Boolean Parameter that checks and disables the BooleanParameters in the ParameterList when checked, and unchecks and enables them when unchecked. Used to send one option for the entire category/have one option click/reset all options in the category - * @param {BooleanParameter[]} [options.ParameterList] An array of Boolean Parameters that belong to a category - */ - -var BooleanParameterGroup = function (options) { - /* - * OneForAll and ParameterList can't be specified directly becase they get - * infinite recursion issues when getting. - * ES6 has Proxy objects, which should work as a neater way of indirectly - * manipulating variables than having public get and set for private - * properties, and as long as Proxy objects count as existing members, - * dont have to change lib/Core/updateFromJson - */ - this.OneForAll = new Proxy({}, {}); - this.ParameterList = new Proxy([], {}); - this.allValue = true; - this.allCascade = false; - FunctionParameter.call(this, options); - Object.defineProperty(this, "value", { - get: function () { - return this.getValue(); - } - }); - Object.defineProperty(this, "_value", { - get: function () { - return this.getValue(); - } - }); -}; - -BooleanParameterGroup.AvailableFormatters = { - default: formatAsArrayOfObjects, - groupIsOpaque: formatAsStringOfKeyEqualsBoolean, - groupIsTransparent: formatAsArrayOfObjects -}; - -function formatAsArrayOfObjects(value) { - return value; -} - -function formatAsStringOfKeyEqualsBoolean(value) { - return value - .map((param) => param.id + "=" + param.value.toString()) - .join("&"); -} - -function makeBooleanEditorFromJson(object, inTerria, inCatalogFunction) { - if (!isEmpty(object) && object.id) { - object.terria = inTerria; //BooleanParameter needs terria - object.catalogFunction = inCatalogFunction; //BooleanParameter belongs to the same catalogFunction - return new BooleanParameter(object); - } - return {}; -} - -function makeBooleanEditorArrayFromJson( - objectArray, - inTerria, - inCatalogFunction -) { - var ParameterObjects = []; - if (typeof objectArray !== "undefined" && objectArray.length > 0) { - objectArray.forEach(function (object) { - ParameterObjects.push( - makeBooleanEditorFromJson(object, inTerria, inCatalogFunction) - ); - }); - } - return ParameterObjects; -} - -inherit(FunctionParameter, BooleanParameterGroup); - -function isEmpty(obj) { - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - return false; - } - } - return true; -} - -BooleanParameterGroup.defaultUpdaters = {}; - -BooleanParameterGroup.defaultUpdaters.OneForAll = function ( - functionParameter, - json, - propertyName, - options -) { - functionParameter.OneForAll = makeBooleanEditorFromJson( - json[propertyName], - functionParameter.terria, - functionParameter.catalogFunction - ); -}; - -BooleanParameterGroup.defaultUpdaters.ParameterList = function ( - functionParameter, - json, - propertyName, - options -) { - functionParameter.ParameterList = makeBooleanEditorArrayFromJson( - json[propertyName], - functionParameter.terria, - functionParameter.catalogFunction - ); -}; - -BooleanParameterGroup.prototype.getValue = function () { - var param_values = this.ParameterList.map((parameter) => - parameter.value - ? { - id: parameter.id, - value: parameter.value - } - : undefined - ); - if (this.allValue === true && this.OneForAll.value === true) { - if (this.allCascade === true) { - param_values.unshift({ - id: this.OneForAll.id, - value: this.OneForAll.value - }); - } else { - param_values = [ - { - id: this.OneForAll.id, - value: this.OneForAll.value - } - ]; - } - } - /*param_values.unshift(this.OneForAll.value ? { - [this.OneForAll.id] : this.OneForAll.value - } : undefined - );*/ - return param_values.filter((item) => item !== undefined); -}; - -Object.defineProperties(BooleanParameterGroup.prototype, { - /** - * Gets the type of this parameter. - * @memberof BooleanParameterGroup.prototype - * @type {String} - */ - type: { - get: function () { - return "boolean-group"; - } - }, - updaters: { - get: function () { - return BooleanParameterGroup.defaultUpdaters; - } - } -}); - -module.exports = BooleanParameterGroup; diff --git a/lib/Models/FunctionParameters/RegionDataValue.js b/lib/Models/FunctionParameters/RegionDataValue.js deleted file mode 100644 index 6deb938e3a3..00000000000 --- a/lib/Models/FunctionParameters/RegionDataValue.js +++ /dev/null @@ -1,26 +0,0 @@ -"use strict"; - -/** - * Holds a collection of region data. - * - * @param {String[]} regionCodes The list of region codes. - * @param {String[]} columnHeadings The list of column headings describing the values associated with each region. - * @param {Number[][]} table An array of arrays where each array in the outer array corresponds to a single region in the regionCodes list - * and each inner array has a value corresponding to each colum in columnHeadings. For a {@link RegionDataParameter#singleSelect} - * parameter, this property should be undefined. - * @param {Number[]} singleSelectValues The single value for each region. For a parameter that is not {@link RegionDataParameter#singleSelect}, this - * property should be undefined. - */ -function RegionDataValue( - regionCodes, - columnHeadings, - table, - singleSelectValues -) { - this.regionCodes = regionCodes; - this.columnHeadings = columnHeadings; - this.table = table; - this.singleSelectValues = singleSelectValues; -} - -module.exports = RegionDataValue; diff --git a/lib/Models/FunctionParameters/createParameterFromType.js b/lib/Models/FunctionParameters/createParameterFromType.js deleted file mode 100644 index 6d7517cb43f..00000000000 --- a/lib/Models/FunctionParameters/createParameterFromType.js +++ /dev/null @@ -1,62 +0,0 @@ -"use strict"; - -var defined = require("terriajs-cesium/Source/Core/defined").default; -var TerriaError = require("../../Core/TerriaError").default; -var i18next = require("i18next").default; - -var LineParameter = require("./LineParameter"); -var RectangleParameter = require("./RectangleParameter"); -var PolygonParameter = require("./PolygonParameter"); -var DateTimeParameter = require("./DateTimeParameter"); -var EnumerationParameter = require("./EnumerationParameter"); -var StringParameter = require("./StringParameter"); -var NumberParameter = require("./NumberParameter"); -var PointParameter = require("./PointParameter"); -var BooleanParameter = require("./BooleanParameter"); -var BooleanParameterGroup = require("./BooleanParameterGroup"); - -var mapping = { - [StringParameter.prototype.type]: StringParameter, - [NumberParameter.prototype.type]: NumberParameter, - [EnumerationParameter.prototype.type]: EnumerationParameter, - [BooleanParameter.prototype.type]: BooleanParameter, - [BooleanParameterGroup.prototype.type]: BooleanParameterGroup, - [DateTimeParameter.prototype.type]: DateTimeParameter, - [PointParameter.prototype.type]: PointParameter, - [LineParameter.prototype.type]: LineParameter, - [PolygonParameter.prototype.type]: PolygonParameter, - [RectangleParameter.prototype.type]: RectangleParameter -}; - -/** - * Creates a type derived from {@link FunctionParameter} based on a given type string. - * - * @param {String} type The derived type name. - * @param {Object} options Options to pass to the constructor. - */ -var createParameterFromType = function (type, options) { - var Constructor = mapping[type]; - if (!defined(Constructor)) { - throw new TerriaError({ - title: i18next.t("models.createParameter.unsupportedErrorTitle"), - message: i18next.t("models.createParameter.unsupportedErrorMessage", { - type: type - }) - }); - } - - return new Constructor(options); -}; - -/** - * Registers a constructor for a given type of {@link FunctionParameter}. - * - * @param {String} type The type name for which to register a constructor. - * @param {Function} constructor The constructor for function parameters of this type. The constructor is expected to take an options - * object as its first and only parameter. - */ -createParameterFromType.register = function (type, constructor) { - mapping[type] = constructor; -}; - -module.exports = createParameterFromType; diff --git a/lib/ReactViews/Analytics/BooleanParameterGroupEditor.jsx b/lib/ReactViews/Analytics/BooleanParameterGroupEditor.jsx index 572a54270f7..d05995c7693 100644 --- a/lib/ReactViews/Analytics/BooleanParameterGroupEditor.jsx +++ b/lib/ReactViews/Analytics/BooleanParameterGroupEditor.jsx @@ -2,9 +2,7 @@ import React from "react"; import createReactClass from "create-react-class"; import PropTypes from "prop-types"; import MoreOrLess from "../Generic/MoreOrLess.jsx"; - import BooleanParameterEditor from "./BooleanParameterEditor.tsx"; - import Styles from "./parameter-editors.scss"; const BooleanParameterGroupEditor = createReactClass({ @@ -122,4 +120,5 @@ const BooleanParameterGroupEditor = createReactClass({ return
{this.renderCheckboxGroup()}
; } }); -module.exports = BooleanParameterGroupEditor; + +export default BooleanParameterGroupEditor; diff --git a/lib/ReactViews/Analytics/GeoJsonParameterEditor.jsx b/lib/ReactViews/Analytics/GeoJsonParameterEditor.jsx index fe9b4000a30..371fe61b0c8 100644 --- a/lib/ReactViews/Analytics/GeoJsonParameterEditor.jsx +++ b/lib/ReactViews/Analytics/GeoJsonParameterEditor.jsx @@ -1,5 +1,3 @@ -"use strict"; - import React from "react"; import PropTypes from "prop-types"; import defined from "terriajs-cesium/Source/Core/defined"; @@ -144,4 +142,4 @@ function getDisplayValue(value, parameter) { return getRegionPickerDisplayValue(value, parameter); } -module.exports = withTranslation()(GeoJsonParameterEditor); +export default withTranslation()(GeoJsonParameterEditor); diff --git a/lib/ReactViews/Analytics/InvokeFunction.jsx b/lib/ReactViews/Analytics/InvokeFunction.jsx index 2b9d06dee52..a866c67bf54 100644 --- a/lib/ReactViews/Analytics/InvokeFunction.jsx +++ b/lib/ReactViews/Analytics/InvokeFunction.jsx @@ -154,4 +154,4 @@ class InvokeFunction extends React.Component { } } -module.exports = withTranslation()(InvokeFunction); +export default withTranslation()(InvokeFunction); diff --git a/lib/ReactViews/Analytics/ParameterEditor.jsx b/lib/ReactViews/Analytics/ParameterEditor.jsx index 2b9668bbe58..f134c32202c 100644 --- a/lib/ReactViews/Analytics/ParameterEditor.jsx +++ b/lib/ReactViews/Analytics/ParameterEditor.jsx @@ -1,11 +1,6 @@ -"use strict"; - import React from "react"; - import createReactClass from "create-react-class"; - import PropTypes from "prop-types"; - import PointParameterEditor from "./PointParameterEditor"; import LineParameterEditor from "./LineParameterEditor"; import PolygonParameterEditor from "./PolygonParameterEditor"; @@ -21,10 +16,8 @@ import GenericParameterEditor from "./GenericParameterEditor"; import NumberParameterEditor from "./NumberParameterEditor"; import GeoJsonParameterEditor from "./GeoJsonParameterEditor"; import defined from "terriajs-cesium/Source/Core/defined"; - import Styles from "./parameter-editors.scss"; import InfoParameterEditor from "./InfoParameterEditor"; - import parseCustomMarkdownToReact from "../Custom/parseCustomMarkdownToReact"; const ParameterEditor = createReactClass({ @@ -400,4 +393,4 @@ ParameterEditor.parameterTypeConverters = [ } ]; -module.exports = ParameterEditor; +export default ParameterEditor; diff --git a/lib/ReactViews/Analytics/RegionDataParameterEditor.jsx b/lib/ReactViews/Analytics/RegionDataParameterEditor.jsx deleted file mode 100644 index ac3851207c5..00000000000 --- a/lib/ReactViews/Analytics/RegionDataParameterEditor.jsx +++ /dev/null @@ -1,254 +0,0 @@ -import React from "react"; - -import createReactClass from "create-react-class"; - -import PropTypes from "prop-types"; - -import defined from "terriajs-cesium/Source/Core/defined"; -import knockout from "terriajs-cesium/Source/ThirdParty/knockout"; -import VarType from "../../Map/VarType"; -import CatalogItem, { ButtonState } from "../DataCatalog/CatalogItem"; -import CatalogGroup from "../DataCatalog/CatalogGroup"; - -import Styles from "./parameter-editors.scss"; -import CommonStrata from "../../Models/Definition/CommonStrata"; - -const RegionDataParameterEditor = createReactClass({ - displayName: "RegionDataParameterEditor", - - propTypes: { - previewed: PropTypes.object, - parameter: PropTypes.object - }, - - /* eslint-disable-next-line camelcase */ - UNSAFE_componentWillMount() { - this.catalogItemDetails = {}; - }, - - /* eslint-disable-next-line camelcase */ - UNSAFE_componentWillReceiveProps(nextProps) { - this.catalogItemDetails = {}; - }, - - getValue() { - return this.props.parameter.value; - }, - - setValue(value) { - this.props.parameter.setValue(CommonStrata.user, value); - }, - - regionProvider() { - return this.props.parameter.regionProvider; - }, - - catalogItemsWithMatchingRegion() { - return this.props.parameter.getEnabledItemsWithMatchingRegionType(); - }, - - toggleActive(catalogItem, column) { - const value = this.getValue(); - const newValue = !this.isActive(catalogItem, column); - - if (newValue) { - value[column.name] = { - regionProvider: this.regionProvider(), - regionColumn: - catalogItem.regionMapping.tableStructure.getColumnWithNameOrId( - catalogItem.regionMapping.regionDetails[0].columnName - ), - valueColumn: column - }; - - // If only one dataset can be active at a time, deactivate all others. - if (this.props.parameter.singleSelect) { - for (const columnName in value) { - if ( - Object.prototype.hasOwnProperty.call(value, columnName) && - columnName !== column.name - ) { - value[columnName] = false; - } - } - } - } else { - value[column.name] = false; - this.getCatalogItemDetails( - this.catalogItemDetails, - catalogItem - ).isEntirelyActive = false; - } - }, - - isActive(catalogItem, column) { - let value = this.getValue(); - - if (!defined(value)) { - value = {}; - this.setValue(value); - } - - if (!defined(value[column.name])) { - value[column.name] = false; - knockout.track(value, [column.name]); - - if ( - !this.props.parameter.singleSelect || - Object.keys(value).length === 1 - ) { - value[column.name] = { - regionProvider: this.regionProvider(), - regionColumn: - catalogItem.regionMapping.tableStructure.getColumnWithNameOrId( - catalogItem.regionMapping.regionDetails[0].columnName - ), - valueColumn: column - }; - } - } - - return ( - defined(value[column.name]) && - value[column.name] && - value[column.name].regionColumn === - catalogItem.regionMapping.tableStructure.getColumnWithNameOrId( - catalogItem.regionMapping.regionDetails[0].columnName - ) && - value[column.name].valueColumn === column - ); - }, - - getCatalogItemDetails(catalogItemDetails, catalogItem) { - if (!defined(catalogItemDetails[catalogItem.uniqueId])) { - catalogItemDetails[catalogItem.uniqueId] = { - isOpen: true, - isEntirelyActive: true - }; - knockout.track(catalogItemDetails, [catalogItem.uniqueId]); - knockout.track(catalogItemDetails[catalogItem.uniqueId], [ - "isOpen", - "isEntirelyActive" - ]); - } - - return catalogItemDetails[catalogItem.uniqueId]; - }, - - toggleEntireCatalogItem(catalogItem) { - const details = this.getCatalogItemDetails( - this.catalogItemDetails, - catalogItem - ); - details.isEntirelyActive = !details.isEntirelyActive; - - const columns = catalogItem.regionMapping.tableStructure.columns; - for (let i = 0; i < columns.length; ++i) { - const column = columns[i]; - if (this.columnIsScalar(catalogItem, column)) { - const isActive = this.isActive(catalogItem, column); - if ( - (!isActive && details.isEntirelyActive) || - (isActive && !details.isEntirelyActive) - ) { - this.toggleActive(catalogItem, column); - } - } - } - }, - - catalogItemIsOpen(catalogItem) { - const details = this.getCatalogItemDetails( - this.catalogItemDetails, - catalogItem - ); - return details.isOpen; - }, - - toggleOpenCatalogItem(catalogItem) { - const details = this.getCatalogItemDetails( - this.catalogItemDetails, - catalogItem - ); - details.isOpen = !details.isOpen; - }, - - isEntireCatalogItemActive(catalogItem) { - const details = this.getCatalogItemDetails( - this.catalogItemDetails, - catalogItem - ); - return details.isEntirelyActive; - }, - - render() { - return
{this.renderContent()}
; - }, - - renderContent() { - if (this.catalogItemsWithMatchingRegion().length > 0) { - return ( -
-
    - {this.catalogItemsWithMatchingRegion().map((catalogItem, i) => ( - - {this.renderItemChildren(catalogItem)} - - ))} -
-
- ); - } - return ( - // Don't break the lines around the link to csv-geo-au, or whitespace stripping will ruin the formatting in - // the rendered version. -
- No characteristics are available because you have not added any data to - the map for this region type,{" "} - {this.regionProvider() ? this.regionProvider().regionType : "None"}. You - may use your own data with this analysis by creating a CSV following the{" "} - - csv-geo-au - {" "} - guidelines and dragging and dropping it onto the map. -
- ); - }, - - renderItemChildren(catalogItem) { - return ( -
    - {catalogItem.regionMapping.tableStructure.columns.map((column, i) => { - if (column.type === VarType.SCALAR) { - return ( - - ); - } - })} -
- ); - } -}); -module.exports = RegionDataParameterEditor; diff --git a/lib/ReactViews/Analytics/RegionParameterEditor.jsx b/lib/ReactViews/Analytics/RegionParameterEditor.jsx index f403f6bc441..c848140bf30 100644 --- a/lib/ReactViews/Analytics/RegionParameterEditor.jsx +++ b/lib/ReactViews/Analytics/RegionParameterEditor.jsx @@ -1,11 +1,6 @@ -"use strict"; - import React from "react"; - import createReactClass from "create-react-class"; - import PropTypes from "prop-types"; - import Styles from "./parameter-editors.scss"; import RegionPicker, { getDisplayValue } from "./RegionPicker"; import MapInteractionMode from "../../Models/MapInteractionMode"; @@ -83,4 +78,4 @@ RegionParameterEditor.selectOnMap = function (viewState, parameter, previewed) { viewState.explorerPanelIsVisible = false; }; -module.exports = RegionParameterEditor; +export default RegionParameterEditor; diff --git a/lib/ReactViews/Analytics/RegionTypeParameterEditor.jsx b/lib/ReactViews/Analytics/RegionTypeParameterEditor.jsx index 8ad54ddf202..05e5ce2bb43 100644 --- a/lib/ReactViews/Analytics/RegionTypeParameterEditor.jsx +++ b/lib/ReactViews/Analytics/RegionTypeParameterEditor.jsx @@ -1,5 +1,3 @@ -"use strict"; - import React from "react"; import createReactClass from "create-react-class"; import PropTypes from "prop-types"; @@ -64,4 +62,4 @@ const RegionTypeParameterEditor = createReactClass({ } }); -module.exports = RegionTypeParameterEditor; +export default RegionTypeParameterEditor; diff --git a/lib/ReactViews/BadgeBar.tsx b/lib/ReactViews/BadgeBar.tsx index ba42103e45c..9f6fe1dc002 100644 --- a/lib/ReactViews/BadgeBar.tsx +++ b/lib/ReactViews/BadgeBar.tsx @@ -1,7 +1,7 @@ import React from "react"; import { useTheme } from "styled-components"; import { TextSpan } from "../Styled/Text"; -const Box = require("../Styled/Box").default; +import Box from "../Styled/Box"; interface IProps { label: string; diff --git a/lib/ReactViews/BottomDock/Timeline/CesiumTimeline.jsx b/lib/ReactViews/BottomDock/Timeline/CesiumTimeline.jsx index bd253190735..0be5969a51c 100644 --- a/lib/ReactViews/BottomDock/Timeline/CesiumTimeline.jsx +++ b/lib/ReactViews/BottomDock/Timeline/CesiumTimeline.jsx @@ -1,5 +1,3 @@ -"use strict"; - import Styles from "!style-loader!css-loader?modules&sourceMap!sass-loader?sourceMap!./cesium-timeline.scss"; import createReactClass from "create-react-class"; import dateFormat from "dateformat"; @@ -105,4 +103,4 @@ const CesiumTimeline = createReactClass({ } }); -module.exports = CesiumTimeline; +export default CesiumTimeline; diff --git a/lib/ReactViews/BottomDock/Timeline/DateTimePicker.tsx b/lib/ReactViews/BottomDock/Timeline/DateTimePicker.tsx index 42752c32d30..7b255a6985a 100644 --- a/lib/ReactViews/BottomDock/Timeline/DateTimePicker.tsx +++ b/lib/ReactViews/BottomDock/Timeline/DateTimePicker.tsx @@ -22,8 +22,7 @@ import Spacing from "../../../Styled/Spacing"; import Icon from "../../../Styled/Icon"; import { formatDateTime } from "./DateFormats"; import dateFormat from "dateformat"; - -const DatePicker = require("react-datepicker").default; +import DatePicker from "react-datepicker"; function daysInMonth(month: number, year: number) { const n = new Date(year, month, 0).getDate(); diff --git a/lib/ReactViews/Custom/Chart/ChartPanelDownloadButton.tsx b/lib/ReactViews/Custom/Chart/ChartPanelDownloadButton.tsx index 20bb45d247c..40e74e99fa6 100644 --- a/lib/ReactViews/Custom/Chart/ChartPanelDownloadButton.tsx +++ b/lib/ReactViews/Custom/Chart/ChartPanelDownloadButton.tsx @@ -1,4 +1,3 @@ -"use strict"; import FileSaver from "file-saver"; import { runInAction, toJS } from "mobx"; import { observer } from "mobx-react"; diff --git a/lib/ReactViews/Custom/Collapsible/Collapsible.tsx b/lib/ReactViews/Custom/Collapsible/Collapsible.tsx index 62a566d19ac..dae2bc7f29e 100644 --- a/lib/ReactViews/Custom/Collapsible/Collapsible.tsx +++ b/lib/ReactViews/Custom/Collapsible/Collapsible.tsx @@ -1,5 +1,3 @@ -"use strict"; - import { observer } from "mobx-react"; import React, { useEffect, useState } from "react"; import Box, { IBoxProps } from "../../../Styled/Box"; diff --git a/lib/ReactViews/Custom/ExternalLink.tsx b/lib/ReactViews/Custom/ExternalLink.tsx index 5d6669b974e..7644b69831d 100644 --- a/lib/ReactViews/Custom/ExternalLink.tsx +++ b/lib/ReactViews/Custom/ExternalLink.tsx @@ -2,9 +2,7 @@ import { AnchorHTMLAttributes, default as React } from "react"; import { useTranslation } from "react-i18next"; import styled from "styled-components"; import { useViewState } from "../Context"; - -const Icon = require("../../Styled/Icon").default; -const { StyledIcon } = require("../../Styled/Icon"); +import Icon, { StyledIcon } from "../../Styled/Icon"; interface Props { attributes: AnchorHTMLAttributes; diff --git a/lib/ReactViews/Custom/parseCustomHtmlToReact.ts b/lib/ReactViews/Custom/parseCustomHtmlToReact.ts index 7d83108bca0..615084d9940 100644 --- a/lib/ReactViews/Custom/parseCustomHtmlToReact.ts +++ b/lib/ReactViews/Custom/parseCustomHtmlToReact.ts @@ -12,9 +12,8 @@ import CustomComponent, { ProcessNodeContext } from "./CustomComponent"; import { ExternalLinkIcon, ExternalLinkWithWarning } from "./ExternalLink"; - -const HtmlToReact = require("html-to-react"); -const utils = require("html-to-react/lib/utils"); +import HtmlToReact from "html-to-react"; +import utils from "html-to-react/lib/utils"; const htmlToReactParser = new HtmlToReact.Parser({ decodeEntities: true diff --git a/lib/ReactViews/Custom/registerCustomComponentTypes.ts b/lib/ReactViews/Custom/registerCustomComponentTypes.ts index df3ef59552d..42f6df306fd 100644 --- a/lib/ReactViews/Custom/registerCustomComponentTypes.ts +++ b/lib/ReactViews/Custom/registerCustomComponentTypes.ts @@ -1,5 +1,3 @@ -"use strict"; - import { when } from "mobx"; import { addOrReplaceRemoteFileUploadType } from "../../Core/getDataType"; import Terria from "../../Models/Terria"; diff --git a/lib/ReactViews/DataCatalog/DataCatalogGroup.jsx b/lib/ReactViews/DataCatalog/DataCatalogGroup.jsx index 626069488e0..98467822f9e 100644 --- a/lib/ReactViews/DataCatalog/DataCatalogGroup.jsx +++ b/lib/ReactViews/DataCatalog/DataCatalogGroup.jsx @@ -152,4 +152,4 @@ class DataCatalogGroup extends React.Component { } } -module.exports = withTranslation()(DataCatalogGroup); +export default withTranslation()(DataCatalogGroup); diff --git a/lib/ReactViews/DataCatalog/DataCatalogMember.jsx b/lib/ReactViews/DataCatalog/DataCatalogMember.jsx index e80a919e861..85f4b9a9019 100644 --- a/lib/ReactViews/DataCatalog/DataCatalogMember.jsx +++ b/lib/ReactViews/DataCatalog/DataCatalogMember.jsx @@ -1,5 +1,3 @@ -"use strict"; - import { observer } from "mobx-react"; import PropTypes from "prop-types"; import React from "react"; diff --git a/lib/ReactViews/DragWrapper.jsx b/lib/ReactViews/DragWrapper.jsx index 29ff3f83ae0..95ec12809e3 100644 --- a/lib/ReactViews/DragWrapper.jsx +++ b/lib/ReactViews/DragWrapper.jsx @@ -63,4 +63,4 @@ DragWrapper.propTypes = { children: PropTypes.node.isRequired }; -module.exports = DragWrapper; +export default DragWrapper; diff --git a/lib/ReactViews/ExplorerWindow/Tabs/MyDataTab/AddData.jsx b/lib/ReactViews/ExplorerWindow/Tabs/MyDataTab/AddData.jsx index bd9d73ce2fc..5cac3511977 100644 --- a/lib/ReactViews/ExplorerWindow/Tabs/MyDataTab/AddData.jsx +++ b/lib/ReactViews/ExplorerWindow/Tabs/MyDataTab/AddData.jsx @@ -336,4 +336,4 @@ function buildExtensionsList(extensions) { return extensions.map((ext) => `.${ext}`).join(", "); } -module.exports = withTranslation()(AddData); +export default withTranslation()(AddData); diff --git a/lib/ReactViews/ExplorerWindow/Tabs/MyDataTab/FileInput.jsx b/lib/ReactViews/ExplorerWindow/Tabs/MyDataTab/FileInput.jsx index b182f93f6eb..2c2c5d2d036 100644 --- a/lib/ReactViews/ExplorerWindow/Tabs/MyDataTab/FileInput.jsx +++ b/lib/ReactViews/ExplorerWindow/Tabs/MyDataTab/FileInput.jsx @@ -3,7 +3,6 @@ import PropTypes from "prop-types"; import createReactClass from "create-react-class"; import classNames from "classnames"; import { withTranslation } from "react-i18next"; - import Styles from "./file-input.scss"; // When uploading a file @@ -58,4 +57,4 @@ const FileInput = createReactClass({ } }); -module.exports = withTranslation()(FileInput); +export default withTranslation()(FileInput); diff --git a/lib/ReactViews/ExplorerWindow/Tabs/MyDataTab/MyDataTab.jsx b/lib/ReactViews/ExplorerWindow/Tabs/MyDataTab/MyDataTab.jsx index db9954653d5..a6227c07885 100644 --- a/lib/ReactViews/ExplorerWindow/Tabs/MyDataTab/MyDataTab.jsx +++ b/lib/ReactViews/ExplorerWindow/Tabs/MyDataTab/MyDataTab.jsx @@ -1,6 +1,5 @@ import React from "react"; import { observer } from "mobx-react"; - import classNames from "classnames"; import Icon from "../../../../Styled/Icon"; import Box from "../../../../Styled/Box"; @@ -8,7 +7,6 @@ import PropTypes from "prop-types"; import DataPreview from "../../../Preview/DataPreview.jsx"; import AddData from "./AddData.jsx"; import { withTranslation, Trans } from "react-i18next"; - import Styles from "./my-data-tab.scss"; import DataCatalogMember from "../../../DataCatalog/DataCatalogMember"; @@ -210,4 +208,4 @@ class MyDataTab extends React.Component { } } -module.exports = withTranslation()(MyDataTab); +export default withTranslation()(MyDataTab); diff --git a/lib/ReactViews/FeatureInfo/FeatureInfoPanel.tsx b/lib/ReactViews/FeatureInfo/FeatureInfoPanel.tsx index 2893bbaa00d..d1241ab45e0 100644 --- a/lib/ReactViews/FeatureInfo/FeatureInfoPanel.tsx +++ b/lib/ReactViews/FeatureInfo/FeatureInfoPanel.tsx @@ -30,8 +30,7 @@ import Loader from "../Loader"; import { withViewState } from "../Context"; import Styles from "./feature-info-panel.scss"; import FeatureInfoCatalogItem from "./FeatureInfoCatalogItem"; - -const DragWrapper = require("../DragWrapper"); +import DragWrapper from "../DragWrapper"; interface Props { viewState: ViewState; diff --git a/lib/ReactViews/Generic/MoreOrLess.jsx b/lib/ReactViews/Generic/MoreOrLess.jsx index 449db68a953..197cfc06b41 100644 --- a/lib/ReactViews/Generic/MoreOrLess.jsx +++ b/lib/ReactViews/Generic/MoreOrLess.jsx @@ -31,4 +31,5 @@ const MoreOrLess = createReactClass({ ); } }); -module.exports = MoreOrLess; + +export default MoreOrLess; diff --git a/lib/ReactViews/Generic/Responsive.tsx b/lib/ReactViews/Generic/Responsive.tsx index 9a107aa8b6c..31ba80d6cf5 100644 --- a/lib/ReactViews/Generic/Responsive.tsx +++ b/lib/ReactViews/Generic/Responsive.tsx @@ -1,6 +1,6 @@ import PropTypes, { InferProps } from "prop-types"; import React from "react"; -const MediaQuery = require("react-responsive").default; +import MediaQuery from "react-responsive"; // This should come from some config some where const small = 768; diff --git a/lib/ReactViews/Generic/Timer/Timer.jsx b/lib/ReactViews/Generic/Timer/Timer.jsx index 23781b3285e..8b6b80b1d65 100644 --- a/lib/ReactViews/Generic/Timer/Timer.jsx +++ b/lib/ReactViews/Generic/Timer/Timer.jsx @@ -1,12 +1,7 @@ -"use strict"; - import React from "react"; import PropTypes from "prop-types"; - import createGuid from "terriajs-cesium/Source/Core/createGuid"; - import { createTimer, startTimer as startTimerAnimation } from "./drawTimer"; - import Styles from "./timer.scss"; // Set the name of the hidden property and the change event for visibility @@ -118,4 +113,4 @@ Timer.propTypes = { tooltipText: PropTypes.string }; -module.exports = Timer; +export default Timer; diff --git a/lib/ReactViews/HelpScreens/HelpPrompt.tsx b/lib/ReactViews/HelpScreens/HelpPrompt.tsx index 42f03ea3476..80d3ef11b73 100644 --- a/lib/ReactViews/HelpScreens/HelpPrompt.tsx +++ b/lib/ReactViews/HelpScreens/HelpPrompt.tsx @@ -3,13 +3,10 @@ */ import React, { useState } from "react"; import { useTheme } from "styled-components"; - import FadeIn from "../Transitions/FadeIn/FadeIn"; import SlideUpFadeIn from "../Transitions/SlideUpFadeIn/SlideUpFadeIn"; - -const TourExplanationBox: any = require("../Tour/TourExplanationBox").default; -const TourPrefaceBox: any = require("../Tour/TourPrefaceBox").default; - +import TourExplanationBox from "../Tour/TourExplanationBox"; +import TourPrefaceBox from "../Tour/TourPrefaceBox"; import CloseButton from "../Generic/CloseButton"; import ViewState from "../../ReactViewModels/ViewState"; import Text from "../../Styled/Text"; diff --git a/lib/ReactViews/Map/BottomBar/Credits/index.ts b/lib/ReactViews/Map/BottomBar/Credits/index.ts index ebd9ea095ca..433dc58a52e 100644 --- a/lib/ReactViews/Map/BottomBar/Credits/index.ts +++ b/lib/ReactViews/Map/BottomBar/Credits/index.ts @@ -1,2 +1,2 @@ -export { ICredit } from "./Credit.type"; +export { type ICredit } from "./Credit.type"; export { MapCredits } from "./MapCredits"; diff --git a/lib/ReactViews/Map/BottomBar/DistanceLegend.tsx b/lib/ReactViews/Map/BottomBar/DistanceLegend.tsx index 4b5f4dd7456..6c85d89dab4 100644 --- a/lib/ReactViews/Map/BottomBar/DistanceLegend.tsx +++ b/lib/ReactViews/Map/BottomBar/DistanceLegend.tsx @@ -1,4 +1,3 @@ -"use strict"; import L from "leaflet"; import { runInAction } from "mobx"; import { observer } from "mobx-react"; diff --git a/lib/ReactViews/Map/MapNavigation/Items/Compass/Compass.tsx b/lib/ReactViews/Map/MapNavigation/Items/Compass/Compass.tsx index 89b1b011186..cd95bb392dc 100644 --- a/lib/ReactViews/Map/MapNavigation/Items/Compass/Compass.tsx +++ b/lib/ReactViews/Map/MapNavigation/Items/Compass/Compass.tsx @@ -33,9 +33,7 @@ import Icon, { StyledIcon } from "../../../../../Styled/Icon"; import { GyroscopeGuidance } from "./GyroscopeGuidance"; import { withTerriaRef } from "../../../../HOCs/withTerriaRef"; import FadeIn from "../../../../Transitions/FadeIn/FadeIn"; - -const CameraFlightPath = - require("terriajs-cesium/Source/Scene/CameraFlightPath").default; +import CameraFlightPath from "terriajs-cesium/Source/Scene/CameraFlightPath"; export const COMPASS_LOCAL_PROPERTY_KEY = "CompassHelpPrompted"; diff --git a/lib/ReactViews/Map/MapNavigation/Items/MeasureTool.ts b/lib/ReactViews/Map/MapNavigation/Items/MeasureTool.ts index d56632bbcb0..75ccedd9da2 100644 --- a/lib/ReactViews/Map/MapNavigation/Items/MeasureTool.ts +++ b/lib/ReactViews/Map/MapNavigation/Items/MeasureTool.ts @@ -1,4 +1,3 @@ -"use strict"; import i18next from "i18next"; import React from "react"; import ArcType from "terriajs-cesium/Source/Core/ArcType"; diff --git a/lib/ReactViews/Map/Panels/SharePanel/BuildShareLink.ts b/lib/ReactViews/Map/Panels/SharePanel/BuildShareLink.ts index 9c4adee89dd..f4827b6b808 100644 --- a/lib/ReactViews/Map/Panels/SharePanel/BuildShareLink.ts +++ b/lib/ReactViews/Map/Panels/SharePanel/BuildShareLink.ts @@ -1,5 +1,3 @@ -"use strict"; - import { uniq } from "lodash-es"; import { runInAction, toJS } from "mobx"; import Ellipsoid from "terriajs-cesium/Source/Core/Ellipsoid"; diff --git a/lib/ReactViews/Map/Panels/SharePanel/SharePanel.tsx b/lib/ReactViews/Map/Panels/SharePanel/SharePanel.tsx index a70f16cf43f..3ccf4e1fc6e 100644 --- a/lib/ReactViews/Map/Panels/SharePanel/SharePanel.tsx +++ b/lib/ReactViews/Map/Panels/SharePanel/SharePanel.tsx @@ -12,10 +12,8 @@ import { canShorten } from "./BuildShareLink"; import Styles from "./share-panel.scss"; import { SharePanelContent } from "./SharePanelContent"; import { ShareUrl } from "./ShareUrl"; - -const MenuPanel = - require("../../../StandardUserInterface/customizable/MenuPanel").default; -const StorySharePanel = require("./StorySharePanel").default; +import MenuPanel from "../../../StandardUserInterface/customizable/MenuPanel"; +import StorySharePanel from "./StorySharePanel"; interface PropTypes extends WithTranslation { terria: Terria; @@ -144,6 +142,7 @@ class SharePanel extends React.Component { : t("share.btnMapShareTitle"); return !storyShare ? ( + //@ts-expect-error - not yet ready to tackle tsfying MenuPanel { viewState={this.props.viewState} btnTitle={btnTitle} isOpen={this.state.isOpen} + //@ts-expect-error - not yet ready to tackle tsfying StorySharePanel onOpenChanged={this.changeOpenState} showDropdownAsModal={storyShare} modalWidth={modalWidth} diff --git a/lib/ReactViews/Map/Panels/SharePanel/ShareUrl/index.ts b/lib/ReactViews/Map/Panels/SharePanel/ShareUrl/index.ts index f8c1163527e..3c31d1d9c08 100644 --- a/lib/ReactViews/Map/Panels/SharePanel/ShareUrl/index.ts +++ b/lib/ReactViews/Map/Panels/SharePanel/ShareUrl/index.ts @@ -1,2 +1,2 @@ -export { IShareUrlRef, ShareUrl } from "./ShareUrl"; +export { type IShareUrlRef, ShareUrl } from "./ShareUrl"; export { ShareUrlBookmark } from "./ShareUrlBookmark"; diff --git a/lib/ReactViews/Map/Panels/ToolsPanel/CountDatasets.tsx b/lib/ReactViews/Map/Panels/ToolsPanel/CountDatasets.tsx index e2e8e8d3e98..93771d4ed28 100644 --- a/lib/ReactViews/Map/Panels/ToolsPanel/CountDatasets.tsx +++ b/lib/ReactViews/Map/Panels/ToolsPanel/CountDatasets.tsx @@ -1,5 +1,3 @@ -"use strict"; - import { observer } from "mobx-react"; import React, { useState } from "react"; import { useTranslation } from "react-i18next"; diff --git a/lib/ReactViews/MapIconButton/MapIconButton.tsx b/lib/ReactViews/MapIconButton/MapIconButton.tsx index 63da09f4a22..9a52859b6fd 100644 --- a/lib/ReactViews/MapIconButton/MapIconButton.tsx +++ b/lib/ReactViews/MapIconButton/MapIconButton.tsx @@ -1,4 +1,3 @@ -"use strict"; import React, { useRef, useState } from "react"; import styled, { useTheme } from "styled-components"; import Box from "../../Styled/Box"; diff --git a/lib/ReactViews/Mobile/MobileModalWindow.jsx b/lib/ReactViews/Mobile/MobileModalWindow.jsx index d91c6154856..48be3970150 100644 --- a/lib/ReactViews/Mobile/MobileModalWindow.jsx +++ b/lib/ReactViews/Mobile/MobileModalWindow.jsx @@ -142,4 +142,5 @@ class MobileModalWindow extends React.Component { ); } } -module.exports = withTranslation()(MobileModalWindow); + +export default withTranslation()(MobileModalWindow); diff --git a/lib/ReactViews/Mobile/MobileSearch.jsx b/lib/ReactViews/Mobile/MobileSearch.jsx index 71603ea0b3c..c0f7dfb0b60 100644 --- a/lib/ReactViews/Mobile/MobileSearch.jsx +++ b/lib/ReactViews/Mobile/MobileSearch.jsx @@ -1,9 +1,7 @@ import React from "react"; import { runInAction } from "mobx"; import { observer } from "mobx-react"; - import PropTypes from "prop-types"; - import { addMarker } from "../../Models/LocationMarkerUtils"; import LocationSearchResults from "../Search/LocationSearchResults"; import SearchResult from "../Search/SearchResult"; @@ -97,4 +95,4 @@ class MobileSearch extends React.Component { } } -module.exports = withTranslation()(MobileSearch); +export default withTranslation()(MobileSearch); diff --git a/lib/ReactViews/Notification/MapInteractionWindow.tsx b/lib/ReactViews/Notification/MapInteractionWindow.tsx index 8c3d2ede0a1..963e288ec4c 100644 --- a/lib/ReactViews/Notification/MapInteractionWindow.tsx +++ b/lib/ReactViews/Notification/MapInteractionWindow.tsx @@ -1,5 +1,3 @@ -"use strict"; - import classNames from "classnames"; import { Lambda, observable, reaction, makeObservable } from "mobx"; import { observer } from "mobx-react"; diff --git a/lib/ReactViews/Notification/Notification.tsx b/lib/ReactViews/Notification/Notification.tsx index 5ef6b16f9eb..57eeb71d795 100644 --- a/lib/ReactViews/Notification/Notification.tsx +++ b/lib/ReactViews/Notification/Notification.tsx @@ -2,9 +2,7 @@ import { observer } from "mobx-react"; import React from "react"; import triggerResize from "../../Core/triggerResize"; import { useViewState } from "../Context"; - -// Avoid type error caused by importing untyped jsx -const NotificationWindow = require("./NotificationWindow").default; +import NotificationWindow from "./NotificationWindow"; const Notification = observer(() => { const viewState = useViewState(); diff --git a/lib/ReactViews/Notification/NotificationWindow.jsx b/lib/ReactViews/Notification/NotificationWindow.jsx index ab6ca48d149..cff79fbbfb7 100644 --- a/lib/ReactViews/Notification/NotificationWindow.jsx +++ b/lib/ReactViews/Notification/NotificationWindow.jsx @@ -1,5 +1,3 @@ -"use strict"; - import classNames from "classnames"; import createReactClass from "create-react-class"; import PropTypes from "prop-types"; @@ -110,4 +108,4 @@ const NotificationWindow = createReactClass({ } }); -module.exports.default = NotificationWindow; +export default NotificationWindow; diff --git a/lib/ReactViews/Preview/DataPreview.jsx b/lib/ReactViews/Preview/DataPreview.jsx index 7923df63d69..0ba39179b90 100644 --- a/lib/ReactViews/Preview/DataPreview.jsx +++ b/lib/ReactViews/Preview/DataPreview.jsx @@ -1,4 +1,3 @@ -"use strict"; // import Chart from "../Custom/Chart/Chart"; import { runInAction } from "mobx"; import { observer } from "mobx-react"; @@ -173,4 +172,4 @@ class DataPreview extends React.Component { } } -module.exports = withTranslation()(DataPreview); +export default withTranslation()(DataPreview); diff --git a/lib/ReactViews/Preview/ExportData.tsx b/lib/ReactViews/Preview/ExportData.tsx index 334992b5259..cf3e290b9a0 100644 --- a/lib/ReactViews/Preview/ExportData.tsx +++ b/lib/ReactViews/Preview/ExportData.tsx @@ -7,7 +7,7 @@ import { observer } from "mobx-react"; import isDefined from "../../Core/isDefined"; import ExportableMixin from "../../ModelMixins/ExportableMixin"; -const FileSaver = require("file-saver"); +import FileSaver from "file-saver"; interface PropsType extends WithTranslation { item: ExportableMixin.Instance; diff --git a/lib/ReactViews/RelatedMaps/RelatedMaps.tsx b/lib/ReactViews/RelatedMaps/RelatedMaps.tsx index 3b917f229c1..2de330e2ea2 100644 --- a/lib/ReactViews/RelatedMaps/RelatedMaps.tsx +++ b/lib/ReactViews/RelatedMaps/RelatedMaps.tsx @@ -8,9 +8,7 @@ import { ExternalLinkIcon } from "../Custom/ExternalLink"; import parseCustomMarkdownToReact from "../Custom/parseCustomMarkdownToReact"; import { withViewState, WithViewState } from "../Context"; import Styles from "./related-maps.scss"; - -const MenuPanel = - require("../StandardUserInterface/customizable/MenuPanel").default; +import MenuPanel from "../StandardUserInterface/customizable/MenuPanel"; type PropTypes = WithViewState & WithTranslation & { @@ -30,6 +28,7 @@ class RelatedMaps extends React.Component { const smallScreen = this.props.viewState.useSmallScreenInterface; return ( + //@ts-expect-error - not yet ready to tackle tsfying MenuPanel ` top: 0; diff --git a/lib/ReactViews/Tour/TourExplanationBox.jsx b/lib/ReactViews/Tour/TourExplanationBox.tsx similarity index 85% rename from lib/ReactViews/Tour/TourExplanationBox.jsx rename to lib/ReactViews/Tour/TourExplanationBox.tsx index c788a61b8a0..3d199141d60 100644 --- a/lib/ReactViews/Tour/TourExplanationBox.jsx +++ b/lib/ReactViews/Tour/TourExplanationBox.tsx @@ -1,10 +1,10 @@ import styled from "styled-components"; import Box from "../../Styled/Box"; -import { TOUR_WIDTH } from "./tour-helpers.ts"; +import { TOUR_WIDTH } from "./tour-helpers"; // TODO: make relative to app z-index export const TourExplanationBoxZIndex = 10000; -export const TourExplanationBox = styled(Box)` +export const TourExplanationBox = styled(Box)<{ longer?: boolean }>` position: absolute; width: ${(p) => (p.longer ? `${TOUR_WIDTH + 55}` : `${TOUR_WIDTH}`)}px; // background-color: $modal-bg; @@ -31,7 +31,7 @@ export const TourExplanationBox = styled(Box)` h1, h2, h3 { - margin-bottom: ${(p) => p.theme.spacing * 3}px; + margin-bottom: ${(p) => (p.theme.spacing as any) * 3}px; font-size: 16px; font-weight: bold; } diff --git a/lib/ReactViews/Tour/TourOverlay.jsx b/lib/ReactViews/Tour/TourOverlay.jsx index d0ab5347938..3bbe7eb1cd4 100644 --- a/lib/ReactViews/Tour/TourOverlay.jsx +++ b/lib/ReactViews/Tour/TourOverlay.jsx @@ -1,5 +1,3 @@ -"use strict"; - import React from "react"; import PropTypes from "prop-types"; import Styles from "../HelpScreens/obscure-overlay.scss"; @@ -103,4 +101,4 @@ TourOverlay.propTypes = { onCancel: PropTypes.func.isRequired }; -module.exports = TourOverlay; +export default TourOverlay; diff --git a/lib/ReactViews/Tour/TourPortal.jsx b/lib/ReactViews/Tour/TourPortal.jsx index 83734c87fd4..44294b28692 100644 --- a/lib/ReactViews/Tour/TourPortal.jsx +++ b/lib/ReactViews/Tour/TourPortal.jsx @@ -32,10 +32,10 @@ import { } from "./tour-helpers.ts"; import TourExplanationBox, { TourExplanationBoxZIndex -} from "./TourExplanationBox.jsx"; +} from "./TourExplanationBox"; import TourIndicator from "./TourIndicator.jsx"; import TourOverlay from "./TourOverlay.jsx"; -import TourPrefaceBox from "./TourPrefaceBox.jsx"; +import TourPrefaceBox from "./TourPrefaceBox"; import TourProgressDot from "./TourProgressDot.jsx"; /** diff --git a/lib/ReactViews/Tour/TourPrefaceBox.jsx b/lib/ReactViews/Tour/TourPrefaceBox.tsx similarity index 81% rename from lib/ReactViews/Tour/TourPrefaceBox.jsx rename to lib/ReactViews/Tour/TourPrefaceBox.tsx index 71497e6310a..f5dd580a99c 100644 --- a/lib/ReactViews/Tour/TourPrefaceBox.jsx +++ b/lib/ReactViews/Tour/TourPrefaceBox.tsx @@ -1,7 +1,7 @@ import styled from "styled-components"; import Box from "../../Styled/Box"; -export const TourPrefaceBox = styled(Box)` +export const TourPrefaceBox = styled(Box)<{ pseudoBg?: boolean }>` position: fixed; width: 100%; height: 100%; diff --git a/lib/ReactViews/Workbench/Controls/Legend.tsx b/lib/ReactViews/Workbench/Controls/Legend.tsx index 29f0f1c49a6..42751bab931 100644 --- a/lib/ReactViews/Workbench/Controls/Legend.tsx +++ b/lib/ReactViews/Workbench/Controls/Legend.tsx @@ -1,5 +1,3 @@ -"use strict"; - import { observer } from "mobx-react"; import React, { SyntheticEvent } from "react"; import defined from "terriajs-cesium/Source/Core/defined"; diff --git a/lib/ReactViews/Workbench/Controls/OpacitySection.tsx b/lib/ReactViews/Workbench/Controls/OpacitySection.tsx index bd38879816d..8347e075000 100644 --- a/lib/ReactViews/Workbench/Controls/OpacitySection.tsx +++ b/lib/ReactViews/Workbench/Controls/OpacitySection.tsx @@ -1,5 +1,3 @@ -"use strict"; - import { TFunction } from "i18next"; import { runInAction } from "mobx"; import { observer } from "mobx-react"; diff --git a/lib/ReactViews/Workbench/Controls/TimerSection.jsx b/lib/ReactViews/Workbench/Controls/TimerSection.jsx index bc0c2c06156..de6a52f6da3 100644 --- a/lib/ReactViews/Workbench/Controls/TimerSection.jsx +++ b/lib/ReactViews/Workbench/Controls/TimerSection.jsx @@ -4,7 +4,6 @@ import { observer } from "mobx-react"; import defined from "terriajs-cesium/Source/Core/defined"; import Timer from "../../Generic/Timer/Timer"; import { withTranslation } from "react-i18next"; - import Styles from "./timer-section.scss"; @observer diff --git a/lib/ReactViews/Workbench/WorkbenchButton.tsx b/lib/ReactViews/Workbench/WorkbenchButton.tsx index cb147cf885e..fbc424f1fea 100644 --- a/lib/ReactViews/Workbench/WorkbenchButton.tsx +++ b/lib/ReactViews/Workbench/WorkbenchButton.tsx @@ -1,4 +1,3 @@ -"use strict"; import React from "react"; import styled from "styled-components"; import Box from "../../Styled/Box"; diff --git a/lib/Table/TableColumn.ts b/lib/Table/TableColumn.ts index 191401d4a37..be523262363 100644 --- a/lib/Table/TableColumn.ts +++ b/lib/Table/TableColumn.ts @@ -13,8 +13,6 @@ import TableColumnTraits, { THIS_COLUMN_EXPRESSION_TOKEN } from "../Traits/TraitsClasses/Table/ColumnTraits"; import TableColumnType, { stringToTableColumnType } from "./TableColumnType"; -const naturalSort = require("javascript-natural-sort"); -naturalSort.insensitive = true; type TypeHintSet = { /** RegEx to match column name */ diff --git a/lib/ThirdParty/@mapbox/togeojson/index.d.ts b/lib/ThirdParty/@mapbox/togeojson/index.d.ts new file mode 100644 index 00000000000..d0c44021894 --- /dev/null +++ b/lib/ThirdParty/@mapbox/togeojson/index.d.ts @@ -0,0 +1 @@ +declare module "@mapbox/togeojson"; diff --git a/lib/ThirdParty/geojson-vt/index.d.ts b/lib/ThirdParty/geojson-vt/index.d.ts new file mode 100644 index 00000000000..5cbf1214c5d --- /dev/null +++ b/lib/ThirdParty/geojson-vt/index.d.ts @@ -0,0 +1 @@ +declare module "geojson-vt"; diff --git a/lib/ThirdParty/html-to-react/index.d.ts b/lib/ThirdParty/html-to-react/index.d.ts new file mode 100644 index 00000000000..3511ef9983d --- /dev/null +++ b/lib/ThirdParty/html-to-react/index.d.ts @@ -0,0 +1,2 @@ +declare module "html-to-react"; +declare module "html-to-react/lib/utils"; diff --git a/lib/ThirdParty/javascript-natural-sort/index.d.ts b/lib/ThirdParty/javascript-natural-sort/index.d.ts new file mode 100644 index 00000000000..1a72419b918 --- /dev/null +++ b/lib/ThirdParty/javascript-natural-sort/index.d.ts @@ -0,0 +1 @@ +declare module "javascript-natural-sort"; diff --git a/lib/ThirdParty/point-in-polygon/index.d.ts b/lib/ThirdParty/point-in-polygon/index.d.ts new file mode 100644 index 00000000000..7f3aee477ac --- /dev/null +++ b/lib/ThirdParty/point-in-polygon/index.d.ts @@ -0,0 +1 @@ +declare module "point-in-polygon"; diff --git a/lib/ThirdParty/react-datepicker/index.d.ts b/lib/ThirdParty/react-datepicker/index.d.ts new file mode 100644 index 00000000000..78535d005d5 --- /dev/null +++ b/lib/ThirdParty/react-datepicker/index.d.ts @@ -0,0 +1 @@ +declare module "react-datepicker"; diff --git a/lib/ThirdParty/terriajs-cesium-extra/index.d.ts b/lib/ThirdParty/terriajs-cesium-extra/index.d.ts index 3b3c21e18ed..8be9ab50cfe 100644 --- a/lib/ThirdParty/terriajs-cesium-extra/index.d.ts +++ b/lib/ThirdParty/terriajs-cesium-extra/index.d.ts @@ -45,6 +45,8 @@ declare module "terriajs-cesium/Source/Core/PolygonGeometryLibrary"; declare module "terriajs-cesium/Source/DataSources/getElement"; +declare module "terriajs-cesium/Source/Scene/CameraFlightPath"; + // This is a workaround for Cesium's incorrect type declaration for raiseEvent. declare module "terriajs-cesium" { export interface Event { diff --git a/lib/ViewModels/UploadDataTypes.ts b/lib/ViewModels/UploadDataTypes.ts index b419f8b2001..dfcf8253edb 100644 --- a/lib/ViewModels/UploadDataTypes.ts +++ b/lib/ViewModels/UploadDataTypes.ts @@ -2,7 +2,7 @@ export { default as getDataTypes, addOrReplaceLocalFileUploadType, addOrReplaceRemoteFileUploadType, - LocalDataType, - RemoteDataType + type LocalDataType, + type RemoteDataType } from "../Core/getDataType"; export { registerUrlHandlerForCatalogMemberType } from "../Models/Catalog/CatalogReferences/UrlReference"; diff --git a/lib/ViewModels/updateApplicationOnHashChange.ts b/lib/ViewModels/updateApplicationOnHashChange.ts index 6cf0fe59992..50cb8f0d0bc 100644 --- a/lib/ViewModels/updateApplicationOnHashChange.ts +++ b/lib/ViewModels/updateApplicationOnHashChange.ts @@ -1,5 +1,3 @@ -"use strict"; - import Terria from "../Models/Terria"; /** diff --git a/lib/ViewModels/updateApplicationOnMessageFromParentWindow.js b/lib/ViewModels/updateApplicationOnMessageFromParentWindow.js index d298c215199..073b4132ea8 100644 --- a/lib/ViewModels/updateApplicationOnMessageFromParentWindow.js +++ b/lib/ViewModels/updateApplicationOnMessageFromParentWindow.js @@ -1,9 +1,7 @@ -"use strict"; +import { TerriaErrorSeverity } from "../Core/TerriaError"; +import defined from "terriajs-cesium/Source/Core/defined"; -const { TerriaErrorSeverity } = require("../Core/TerriaError"); - -var defined = require("terriajs-cesium/Source/Core/defined").default; -var updateApplicationOnMessageFromParentWindow = function (terria, window) { +const updateApplicationOnMessageFromParentWindow = function (terria, window) { var allowOrigin; window.addEventListener( @@ -58,4 +56,4 @@ var updateApplicationOnMessageFromParentWindow = function (terria, window) { } }; -module.exports = updateApplicationOnMessageFromParentWindow; +export default updateApplicationOnMessageFromParentWindow; diff --git a/package.json b/package.json index 1b1d4a88d50..7ce75ace58f 100644 --- a/package.json +++ b/package.json @@ -111,7 +111,7 @@ "dateformat": "^5.0.3", "dompurify": "^2.5.7", "file-loader": "^3.0.1", - "file-saver": "^1.3.8", + "file-saver": "^2.0.5", "flexsearch": "0.7.21", "fs-extra": "^7.0.1", "geojson-vt": "^3.2.1", @@ -157,7 +157,7 @@ "react-dom": "^16.14.0", "react-ga4": "^2.1.0", "react-i18next": "^11.18.0", - "react-responsive": "^5.0.0", + "react-responsive": "^10.0.0", "react-select": "^3.1.1", "react-swipeable": "^5.1.0", "react-transition-group": "^4.3.0", @@ -189,6 +189,7 @@ "@babel/eslint-parser": "^7.23.3", "@babel/plugin-syntax-dynamic-import": "^7.8.3", "@types/node": "^18.15.11", + "@types/proj4": "^2.5.5", "@types/webpack": "4.41.33", "@typescript-eslint/eslint-plugin": "^6.12.0", "@typescript-eslint/parser": "^6.12.0", diff --git a/test/Core/arrayProductSpec.js b/test/Core/arrayProductSpec.js deleted file mode 100644 index 41ba075604a..00000000000 --- a/test/Core/arrayProductSpec.js +++ /dev/null @@ -1,80 +0,0 @@ -"use strict"; - -var arrayProduct = require("../../lib/Core/arrayProduct"); - -describe("arrayProduct", function () { - it("works with one array of one", function () { - var test = [[1]]; - var target = [[1]]; - expect(arrayProduct(test)).toEqual(target); - }); - - it("works with several arrays of one", function () { - var test = [[1], [2], [3], [4]]; - var target = [[1, 2, 3, 4]]; - expect(arrayProduct(test)).toEqual(target); - }); - - it("works with one array of two", function () { - var test = [[1, 10]]; - var target = [[1], [10]]; - expect(arrayProduct(test)).toEqual(target); - }); - - it("works with an array of two in first place", function () { - var test = [[1, 10], [2], [3], [4]]; - var target = [ - [1, 2, 3, 4], - [10, 2, 3, 4] - ]; - expect(arrayProduct(test)).toEqual(target); - }); - - it("works with arrays of two in the first two places", function () { - var test = [[1, 10], [2, 20], [3], [4]]; - // Actually the order of the subarrays is not important. - var target = [ - [1, 2, 3, 4], - [1, 20, 3, 4], - [10, 2, 3, 4], - [10, 20, 3, 4] - ]; - expect(arrayProduct(test)).toEqual(target); - }); - - it("works with arrays of two in the first three places", function () { - var test = [[1, 10], [2, 20], [3, 30], [4]]; - // Actually the order of the subarrays is not important. - var target = [ - [1, 2, 3, 4], - [1, 2, 30, 4], - [1, 20, 3, 4], - [1, 20, 30, 4], - [10, 2, 3, 4], - [10, 2, 30, 4], - [10, 20, 3, 4], - [10, 20, 30, 4] - ]; - expect(arrayProduct(test)).toEqual(target); - }); - - it("works with an array of two in the final place", function () { - var test = [[1], [2], [3], [4, 40]]; - var target = [ - [1, 2, 3, 4], - [1, 2, 3, 40] - ]; - expect(arrayProduct(test)).toEqual(target); - }); - - it("works with an array of two in the final two places", function () { - var test = [[1], [2], [3, 30], [4, 40]]; - var target = [ - [1, 2, 3, 4], - [1, 2, 3, 40], - [1, 2, 30, 4], - [1, 2, 30, 40] - ]; - expect(arrayProduct(test)).toEqual(target); - }); -}); diff --git a/test/Core/combineDataSpec.js b/test/Core/combineDataSpec.js deleted file mode 100644 index 6c995a680ba..00000000000 --- a/test/Core/combineDataSpec.js +++ /dev/null @@ -1,120 +0,0 @@ -"use strict"; - -var combineData = require("../../lib/Core/combineData"); - -describe("combineData", function () { - it("works with one array", function () { - var data1 = [ - [1, 5], - [3, 7], - [6, 10], - [9, -3] - ]; - var combined = combineData([data1]); - expect(combined).toEqual(data1); - }); - - it("works with two sorted numerical arrays", function () { - var data1 = [ - [1, 5], - [3, 7], - [6, 10], - [9, -3] - ]; - var data2 = [ - [2, 12], - [4, 8], - [6, 5], - [8, 7] - ]; - var target = [ - [1, 5, null], - [2, null, 12], - [3, 7, null], - [4, null, 8], - [6, 10, 5], - [8, null, 7], - [9, -3, null] - ]; - var combined = combineData([data1, data2]); - expect(combined).toEqual(target); - }); - - it("works with two unsorted numerical arrays", function () { - var data1 = [ - [1, 5], - [6, 10], - [3, 7], - [9, -3] - ]; - var data2 = [ - [6, 5], - [4, 8], - [8, 7], - [2, 12] - ]; - var target = [ - [1, 5, null], - [2, null, 12], - [3, 7, null], - [4, null, 8], - [6, 10, 5], - [8, null, 7], - [9, -3, null] - ]; - var combined = combineData([data1, data2]); - expect(combined).toEqual(target); - }); - - it("works with two date arrays", function () { - var data1 = [ - [new Date("2015-03-01"), 5], - [new Date("2015-03-02"), 7], - [new Date("2015-03-04"), 10] - ]; - var data2 = [ - [new Date("2015-02-28"), 12], - [new Date("2015-03-02"), 8] - ]; - var target = [ - [new Date("2015-02-28"), null, 12], - [new Date("2015-03-01"), 5, null], - [new Date("2015-03-02"), 7, 8], - [new Date("2015-03-04"), 10, null] - ]; - var combined = combineData([data1, data2]); - expect(combined).toEqual(target); - }); - - it("works with three sorted numerical arrays", function () { - var data1 = [ - [1, 5], - [3, 7], - [6, 10], - [9, -3] - ]; - var data2 = [ - [2, 12], - [4, 8], - [6, 5], - [8, 7] - ]; - var data3 = [ - [3, 18], - [5, 19], - [6, 16] - ]; - var target = [ - [1, 5, null, null], - [2, null, 12, null], - [3, 7, null, 18], - [4, null, 8, null], - [5, null, null, 19], - [6, 10, 5, 16], - [8, null, 7, null], - [9, -3, null, null] - ]; - var combined = combineData([data1, data2, data3]); - expect(combined).toEqual(target); - }); -}); diff --git a/test/Core/combineFiltersSpec.js b/test/Core/combineFiltersSpec.js deleted file mode 100644 index 8636b59a947..00000000000 --- a/test/Core/combineFiltersSpec.js +++ /dev/null @@ -1,109 +0,0 @@ -"use strict"; - -var combineFilters = require("../../lib/Core/combineFilters"); - -describe("combineFilters", function () { - describe("basic tests:", function () { - it("returns true when all filters true", function () { - expect( - combineFilters([ - function () { - return true; - }, - function () { - return true; - }, - function () { - return true; - } - ])() - ).toBe(true); - }); - - it("returns false when all functions false", function () { - expect( - combineFilters([ - function () { - return false; - }, - function () { - return false; - }, - function () { - return false; - } - ])() - ).toBe(false); - }); - - it("returns false when one functions false", function () { - expect( - combineFilters([ - function () { - return false; - }, - function () { - return true; - }, - function () { - return false; - } - ])() - ).toBe(false); - }); - }); - - it("passes arguments through to all filters", function () { - var filters = [ - jasmine.createSpy("spy1").and.returnValue(true), - jasmine.createSpy("spy2").and.returnValue(true), - jasmine.createSpy("spy3").and.returnValue(true) - ]; - - combineFilters(filters)("I", "am", "an", "elephant"); - - filters.forEach(function (filterSpy) { - expect(filterSpy).toHaveBeenCalledWith("I", "am", "an", "elephant"); - }); - }); - - it("stops on first false result", function () { - var filters = [ - jasmine.createSpy("spy1").and.returnValue(true), - jasmine.createSpy("spy2").and.returnValue(false), - jasmine.createSpy("spy3").and.returnValue(true) - ]; - - combineFilters(filters)(); - - expect(filters[0]).toHaveBeenCalled(); - expect(filters[1]).toHaveBeenCalled(); - expect(filters[2]).not.toHaveBeenCalled(); - }); - - describe("only calls a function once", function () { - it("if it's specified multiple times", function () { - var spy1 = jasmine.createSpy("spy1").and.returnValue(true); - - var filters = [ - spy1, - jasmine.createSpy("spy2").and.returnValue(true), - spy1 - ]; - - combineFilters(filters)(); - - expect(spy1.calls.count()).toBe(1); - }); - - it("if combineFilters() is called on the result of another combineFilters() call", function () { - var spy1 = jasmine.createSpy("spy1").and.returnValue(true); - - var combined = combineFilters([spy1, spy1]); - - combineFilters([combined, spy1])(); - - expect(spy1.calls.count()).toBe(1); - }); - }); -}); diff --git a/test/Map/featureDataToGeoJsonSpec.ts b/test/Map/featureDataToGeoJsonSpec.ts index aad9d2b296b..de98f0c0adc 100644 --- a/test/Map/featureDataToGeoJsonSpec.ts +++ b/test/Map/featureDataToGeoJsonSpec.ts @@ -1,5 +1,3 @@ -"use strict"; - import featureDataToGeoJson from "../../lib/Map/PickedFeatures/featureDataToGeoJson"; describe("featureDataToGeoJson", function () { diff --git a/test/Map/unionRectanglesSpec.js b/test/Map/unionRectanglesSpec.js deleted file mode 100644 index bda7c0188a8..00000000000 --- a/test/Map/unionRectanglesSpec.js +++ /dev/null @@ -1,37 +0,0 @@ -"use strict"; - -var Rectangle = require("terriajs-cesium/Source/Core/Rectangle").default; - -var unionRectangles = require("../../lib/Map/Vector/unionRectangles"); - -describe("unionRectangles", function () { - it("throws when first is not provided", function () { - expect(function () { - unionRectangles(undefined, Rectangle.MAX_VALUE); - }).toThrow(); - }); - - it("throws when second is not provided", function () { - expect(function () { - unionRectangles(Rectangle.MAX_VALUE, undefined); - }).toThrow(); - }); - - it("correctly computes a union", function () { - var rectangle1 = new Rectangle(1.0, 1.1, 1.2, 1.3); - var rectangle2 = new Rectangle(-1.0, 0.9, 1.3, 1.4); - expect(unionRectangles(rectangle1, rectangle2)).toEqual( - new Rectangle(-1.0, 0.9, 1.3, 1.4) - ); - }); - - it("uses the result parameter if provided", function () { - var rectangle1 = new Rectangle(1.0, 1.1, 1.2, 1.3); - var rectangle2 = new Rectangle(-1.0, 0.9, 1.3, 1.4); - var output = new Rectangle(); - - var result = unionRectangles(rectangle1, rectangle2, output); - expect(result).toBe(output); - expect(result).toEqual(new Rectangle(-1.0, 0.9, 1.3, 1.4)); - }); -}); diff --git a/test/Models/Catalog/CatalogGroupSpec.js b/test/Models/Catalog/CatalogGroupSpec.js deleted file mode 100644 index e8247a635ab..00000000000 --- a/test/Models/Catalog/CatalogGroupSpec.js +++ /dev/null @@ -1,674 +0,0 @@ -"use strict"; - -var CatalogGroup = require("../../lib/Models/CatalogGroup"); -var CatalogItem = require("../../lib/Models/CatalogItem"); -var createCatalogMemberFromType = require("../../lib/Models/createCatalogMemberFromType"); -var Terria = require("../../../lib/Models/Terria"); - -describe("CatalogGroup", function () { - var terria; - var group; - beforeEach(function () { - terria = new Terria({ - baseUrl: "./" - }); - group = terria.catalog.group; - group.preserveOrder = false; - createCatalogMemberFromType.register("group", CatalogGroup); - createCatalogMemberFromType.register("item", CatalogItem); - }); - - it("sorts on load by default", function (done) { - group - .updateFromJson({ - type: "group", - items: [ - { - name: "B", - type: "group", - url: "http://not.valid" - }, - { - name: "A", - type: "group", - url: "http://not.valid.either" - } - ] - }) - .then(function () { - expect(group.items.length).toBe(2); - expect(group.items[0].name).toBe("A"); - expect(group.items[1].name).toBe("B"); - done(); - }); - }); - - it("sorts correctly when there is a number at the beginning", function (done) { - group - .updateFromJson({ - type: "group", - items: [ - { - name: "10 Thing", - type: "group", - url: "http://not.valid" - }, - { - name: "2 Thing", - type: "group", - url: "http://not.valid.either" - }, - { - name: "1 Thing", - type: "group", - url: "http://not.valid.either" - } - ] - }) - .then(function () { - expect(group.items.length).toBe(3); - expect(group.items[0].name).toBe("1 Thing"); - expect(group.items[1].name).toBe("2 Thing"); - expect(group.items[2].name).toBe("10 Thing"); - }) - .then(done) - .catch(done.fail); - }); - - it("sorts correctly when there is a number at the end", function (done) { - group - .updateFromJson({ - type: "group", - items: [ - { - name: "Thing 10", - type: "group", - url: "http://not.valid" - }, - { - name: "Thing 2", - type: "group", - url: "http://not.valid.either" - }, - { - name: "Thing 1", - type: "group", - url: "http://not.valid.either" - } - ] - }) - .then(function () { - expect(group.items.length).toBe(3); - expect(group.items[0].name).toBe("Thing 1"); - expect(group.items[1].name).toBe("Thing 2"); - expect(group.items[2].name).toBe("Thing 10"); - }) - .then(done) - .catch(done.fail); - }); - - it("sorts correctly when nameInCatalog is provided", function (done) { - group - .updateFromJson({ - type: "group", - items: [ - { - name: "1", - type: "group", - url: "http://not.valid" - }, - { - name: "2", - type: "group", - nameInCatalog: "4", - url: "http://not.valid.either" - }, - { - name: "3", - type: "group", - url: "http://not.valid.either" - } - ] - }) - .then(function () { - expect(group.items.length).toBe(3); - expect(group.items[0].name).toBe("1"); - expect(group.items[1].name).toBe("3"); - expect(group.items[2].name).toBe("2"); - }) - .then(done) - .catch(done.fail); - }); - - it("sorts items correctly when there is a number in the middle", function (done) { - group - .updateFromJson({ - type: "group", - items: [ - { - name: "Thing 10 Yay", - type: "group", - url: "http://not.valid" - }, - { - name: "Thing 2 Yay", - type: "group", - url: "http://not.valid.either" - }, - { - name: "Thing 1 Yay", - type: "group", - url: "http://not.valid.either" - } - ] - }) - .then(function () { - expect(group.items.length).toBe(3); - expect(group.items[0].name).toBe("Thing 1 Yay"); - expect(group.items[1].name).toBe("Thing 2 Yay"); - expect(group.items[2].name).toBe("Thing 10 Yay"); - }) - .then(done) - .catch(done.fail); - }); - - it("sorts numbered items after unnumbered items", function (done) { - group - .updateFromJson({ - type: "group", - items: [ - { - name: "Thing 1", - type: "group", - url: "http://not.valid" - }, - { - name: "Thing", - type: "group", - url: "http://not.valid.either" - } - ] - }) - .then(function () { - expect(group.items.length).toBe(2); - expect(group.items[0].name).toBe("Thing"); - expect(group.items[1].name).toBe("Thing 1"); - }) - .then(done) - .catch(done.fail); - }); - - it("sorts numbers before letters", function (done) { - group - .updateFromJson({ - type: "group", - items: [ - { - name: "A", - type: "group", - url: "http://not.valid" - }, - { - name: "10", - type: "group", - url: "http://not.valid.either" - }, - { - name: "2", - type: "group", - url: "http://not.valid.either" - }, - { - name: "1", - type: "group", - url: "http://not.valid.either" - } - ] - }) - .then(function () { - expect(group.items.length).toBe(4); - expect(group.items[0].name).toBe("1"); - expect(group.items[1].name).toBe("2"); - expect(group.items[2].name).toBe("10"); - expect(group.items[3].name).toBe("A"); - }) - .then(done) - .catch(done.fail); - }); - - it("does not sort on load if preserveOrder is true", function (done) { - group - .updateFromJson({ - type: "group", - preserveOrder: true, - items: [ - { - name: "B", - type: "group", - url: "http://not.valid" - }, - { - name: "A", - type: "group", - url: "http://not.valid.either" - } - ] - }) - .then(function () { - expect(group.items.length).toBe(2); - expect(group.items[0].name).toBe("B"); - expect(group.items[1].name).toBe("A"); - done(); - }); - }); - - it("puts isPromoted items at the top when sorting", function (done) { - group - .updateFromJson({ - type: "group", - items: [ - { - name: "B", - type: "group", - url: "http://not.valid" - }, - { - name: "A", - type: "group", - url: "http://not.valid.either" - }, - { - name: "C", - isPromoted: true, - type: "group", - url: "http://not.valid.either" - } - ] - }) - .then(function () { - expect(group.items.length).toBe(3); - expect(group.items[0].name).toBe("C"); - expect(group.items[1].name).toBe("A"); - expect(group.items[2].name).toBe("B"); - done(); - }); - }); - - it("puts isPromoted items at the top when preserving order", function (done) { - group - .updateFromJson({ - type: "group", - preserveOrder: true, - items: [ - { - name: "B", - type: "group", - url: "http://not.valid" - }, - { - name: "A", - type: "group", - url: "http://not.valid.either" - }, - { - name: "C", - isPromoted: true, - type: "group", - url: "http://not.valid.either" - } - ] - }) - .then(function () { - expect(group.items.length).toBe(3); - expect(group.items[0].name).toBe("C"); - expect(group.items[1].name).toBe("B"); - expect(group.items[2].name).toBe("A"); - done(); - }); - }); - - it("returns the names of its parents separated by / when uniqueId is called if no id present", function (done) { - group - .updateFromJson({ - type: "group", - name: "A", - items: [ - { - name: "B", - type: "group", - items: [ - { - name: "C", - type: "group" - } - ] - } - ] - }) - .then(function () { - expect(group.items[0].items[0].uniqueId).toBe("A/B/C"); - expect(group.items[0].uniqueId).toBe("A/B"); - expect(group.uniqueId).toBe("A"); - done(); - }); - }); - - describe("when updating items", function () { - it("adds new items when onlyUpdateExistingItems isn't specified", function (done) { - group - .updateFromJson({ - type: "group", - items: [ - { - name: "A", - type: "item" - }, - { - name: "B", - type: "item" - }, - { - name: "C", - type: "item" - } - ] - }) - .then(function () { - expect(group.items[0].name).toBe("A"); - expect(group.items[1].name).toBe("B"); - expect(group.items[2].name).toBe("C"); - done(); - }); - }); - - it("updates existing items by id ahead of name", function (done) { - group - .updateFromJson({ - type: "group", - items: [ - { - name: "A", - type: "item" - }, - { - name: "B", - id: "BUniqueId", - type: "item" - } - ] - }) - .then( - group.updateFromJson.bind(group, { - items: [ - { - name: "C", - id: "BUniqueId" - }, - { - name: "A" - } - ] - }) - ) - .then(function () { - expect(group.items[0].name).toBe("A"); - expect(group.items[1].uniqueId).toBe("BUniqueId"); - expect(group.items[1].name).toBe("C"); - expect(group.items.length).toBe(2); - done(); - }); - }); - - it("updates existing items by name", function (done) { - group - .updateFromJson({ - type: "group", - items: [ - { - name: "A", - type: "item", - url: "http://example.com/A" - }, - { - name: "B", - type: "item", - url: "http://example.com/B" - } - ] - }) - .then( - group.updateFromJson.bind(group, { - items: [ - { - name: "A", - url: "http://test.com/A" - }, - { - name: "B", - url: "http://test.com/B" - } - ] - }) - ) - .then(function () { - expect(group.items[0].url).toBe("http://test.com/A"); - expect(group.items[1].url).toBe("http://test.com/B"); - done(); - }); - }); - - it("only updates existing items when onlyUpdateExistingItems === true", function (done) { - group - .updateFromJson({ - type: "group", - items: [ - { - name: "A", - type: "item", - url: "http://example.com/A" - } - ] - }) - .then( - group.updateFromJson.bind( - group, - { - items: [ - { - name: "A", - url: "http://test.com/A" - }, - { - name: "B", - url: "http://test.com/B" - } - ] - }, - { - onlyUpdateExistingItems: true - } - ) - ) - .then(function () { - expect(group.items[0].url).toBe("http://test.com/A"); - expect(group.items.length).toBe(1); - done(); - }); - }); - }); - - it("adds new children to the catalog index", function () { - var item1 = new CatalogItem(terria); - item1.id = "blah"; - - group.add(item1); - - expect(terria.catalog.shareKeyIndex["blah"]).toBe(item1); - }); - - describe("removes removed children from the catalog index", function () { - it("when child has a specific id", function () { - var item1 = new CatalogItem(terria); - item1.id = "blah"; - - group.add(item1); - group.remove(item1); - - expect(terria.catalog.shareKeyIndex["blah"]).toBeUndefined(); - }); - - it("when child has no id", function () { - var item1 = new CatalogItem(terria); - item1.name = "blah"; - group.name = "foo"; - - group.add(item1); - - expect(terria.catalog.shareKeyIndex["foo/blah"]).toBe(item1); - - group.remove(item1); - - expect(terria.catalog.shareKeyIndex["foo/blah"]).toBeUndefined(); - }); - }); - - describe("for key clashes", function () { - it("inserts items under an altered key if their shareKeys clash with existing keys", function (done) { - group - .updateFromJson({ - type: "group", - items: [ - { - name: "A", - type: "item" - }, - { - name: "B", - id: "uniqueId", - type: "item" - } - ] - }) - .then(function () { - var noIdCatalogItem = new CatalogItem(terria); - noIdCatalogItem.name = "A"; - - var idCatalogItem = new CatalogItem(terria); - idCatalogItem.id = "uniqueId"; - - // When a call is specifically made to .add(), there is no effort to update existing items with the same id. - group.add(noIdCatalogItem); - group.add(idCatalogItem); - - expect(terria.catalog.shareKeyIndex["Root Group/A"]).not.toBe( - noIdCatalogItem - ); - expect(terria.catalog.shareKeyIndex["Root Group/A"]).toBeDefined(); - expect(terria.catalog.shareKeyIndex["Root Group/A (1)"]).toBe( - noIdCatalogItem - ); - - expect(terria.catalog.shareKeyIndex["uniqueId"]).not.toBe( - idCatalogItem - ); - expect(terria.catalog.shareKeyIndex["uniqueId"]).toBeDefined(); - expect(terria.catalog.shareKeyIndex["uniqueId (1)"]).toBe( - idCatalogItem - ); - - // Add again, this time the keys will clash again but should be added under the key + '(2)' - var noIdCatalogItem2 = new CatalogItem(terria); - noIdCatalogItem2.name = "A"; - - var idCatalogItem2 = new CatalogItem(terria); - idCatalogItem2.id = "uniqueId"; - - group.add(noIdCatalogItem2); - group.add(idCatalogItem2); - - expect(terria.catalog.shareKeyIndex["Root Group/A"]).not.toBe( - noIdCatalogItem2 - ); - expect(terria.catalog.shareKeyIndex["uniqueId"]).not.toBe( - idCatalogItem2 - ); - - expect(terria.catalog.shareKeyIndex["uniqueId (1)"]).toBe( - idCatalogItem - ); - expect(terria.catalog.shareKeyIndex["Root Group/A (1)"]).toBe( - noIdCatalogItem - ); - - expect(terria.catalog.shareKeyIndex["Root Group/A (2)"]).toBe( - noIdCatalogItem2 - ); - expect(terria.catalog.shareKeyIndex["uniqueId (2)"]).toBe( - idCatalogItem2 - ); - }) - .catch(fail) - .then(done); - }); - - it("alters the id of clashing items", function (done) { - group - .updateFromJson({ - type: "group", - items: [ - { - name: "A", - type: "item" - }, - { - name: "B", - id: "uniqueId", - type: "item" - } - ] - }) - .then(function () { - var noIdCatalogItem = new CatalogItem(terria); - noIdCatalogItem.name = "A"; - - var idCatalogItem = new CatalogItem(terria); - idCatalogItem.id = "uniqueId"; - - group.add(noIdCatalogItem); - group.add(idCatalogItem); - - expect(noIdCatalogItem.uniqueId).toBe("Root Group/A (1)"); - expect(idCatalogItem.uniqueId).toBe("uniqueId (1)"); - }) - .catch(fail) - .then(done); - }); - }); - - describe("setting isOpen", function () { - beforeEach(function () { - spyOn(terria, "disclaimerListener"); - }); - - describe("to true when group has a disclaimer", function () { - beforeEach(function () { - group.initialMessage = {}; - group.isOpen = true; - }); - - it("triggers a disclaimerEvent", function () { - expect(terria.disclaimerListener.calls.argsFor(0)[0]).toBe(group); - }); - }); - - describe("to true when group has no disclaimer", function () { - beforeEach(function () { - group.isOpen = true; - }); - - it("triggers no disclaimerEvent", function () { - expect(terria.disclaimerListener).not.toHaveBeenCalled(); - }); - }); - }); -}); diff --git a/test/Models/Catalog/CatalogItemSpec.js b/test/Models/Catalog/CatalogItemSpec.js deleted file mode 100644 index 6ceba6da21e..00000000000 --- a/test/Models/Catalog/CatalogItemSpec.js +++ /dev/null @@ -1,419 +0,0 @@ -"use strict"; - -var Rectangle = require("terriajs-cesium/Source/Core/Rectangle").default; - -var CatalogItem = require("../../lib/Models/CatalogItem"); -var CatalogGroup = require("../../lib/Models/CatalogGroup"); -var Catalog = require("../../lib/Models/Catalog"); -var DataSourceClock = - require("terriajs-cesium/Source/DataSources/DataSourceClock").default; -var JulianDate = require("terriajs-cesium/Source/Core/JulianDate").default; -var Terria = require("../../../lib/Models/Terria"); -var createCatalogMemberFromType = require("../../../lib/Models/Catalog/createCatalogMemberFromType"); - -describe("CatalogItem", function () { - var terria; - var item; - beforeEach(function () { - terria = new Terria({ - baseUrl: "./" - }); - item = new CatalogItem(terria); - createCatalogMemberFromType.register("group", CatalogGroup); - createCatalogMemberFromType.register("item", CatalogItem); - }); - - it("uses the url as the direct dataUrl", function () { - item.url = "http://foo.bar"; - - expect(item.dataUrlType).toBe("direct"); - expect(item.dataUrl).toBe("http://foo.bar"); - - item.url = "http://something.else"; - expect(item.dataUrlType).toBe("direct"); - expect(item.dataUrl).toBe("http://something.else"); - }); - - it("explicit dataUrl and dataUrlType overrides using url", function () { - item.url = "http://foo.bar"; - item.dataUrl = "http://something.else"; - item.dataUrlType = "wfs"; - - expect(item.dataUrl).toBe("http://something.else"); - expect(item.dataUrlType).toBe("wfs"); - - // Make sure setting the url again doesn't override the explicitly-set dataUrl. - item.url = "http://hello.there"; - expect(item.dataUrl).toBe("http://something.else"); - expect(item.dataUrlType).toBe("wfs"); - }); - - it("can zoom to only if rectangle is defined", function () { - expect(item.disableZoomTo).toBeTruthy(); - // When a rectangle is defined, it can be zoomed-to. - item.rectangle = Rectangle.fromDegrees(1, 2, 3, 4); - expect(item.disableZoomTo).toBeFalsy(); - }); - - it("keeps its .clock.currentTime and .currentTime in sync with terria.clock.currentTime when .useOwnClock is false", function () { - item.useOwnClock = false; - item.clock = new DataSourceClock(); - item.clock.currentTime = JulianDate.fromIso8601("2019-07-03"); - item.isEnabled = true; - // These are sanity checks to make sure this test cases is established correctly. - expect(item.clock.currentTime).toEqual( - JulianDate.fromIso8601("2019-07-03") - ); - expect(item.currentTime).toEqual(JulianDate.fromIso8601("2019-07-03")); - - // Update the terria.clock and make sure that the all clocks show the update time. - terria.clock.currentTime = JulianDate.fromIso8601("2021-05-11"); - // Force the time to propogate from the terria.clock to the catalogItems.clock. - terria.clock.tick(); - expect(item.clock.currentTime).toEqual( - JulianDate.fromIso8601("2021-05-11") - ); - expect(item.currentTime).toEqual(JulianDate.fromIso8601("2021-05-11")); - expect(terria.clock.currentTime).toEqual( - JulianDate.fromIso8601("2021-05-11") - ); - - // Again update the terria.clock and make sure that the all clocks show the update time. - terria.clock.currentTime = JulianDate.fromIso8601("2023-02-17"); - // Force the time to propogate from the terria.clock to the catalogItems.clock. - terria.clock.tick(); - expect(item.clock.currentTime).toEqual( - JulianDate.fromIso8601("2023-02-17") - ); - expect(item.currentTime).toEqual(JulianDate.fromIso8601("2023-02-17")); - expect(terria.clock.currentTime).toEqual( - JulianDate.fromIso8601("2023-02-17") - ); - }); - - it("does not change .clock.currentTime or .currentTime when terria.clock is updated when .useOwnClock is true", function () { - item.useOwnClock = true; - item.clock = new DataSourceClock(); - item.clock.currentTime = JulianDate.fromIso8601("2019-07-03"); - item.isEnabled = true; - // These are sanity checks to make sure this test cases is established correctly. - expect(item.clock.currentTime).toEqual( - JulianDate.fromIso8601("2019-07-03") - ); - expect(item.currentTime).toEqual(JulianDate.fromIso8601("2019-07-03")); - - // Update the terria.clock and make sure that only the terria.clock is effected. - terria.clock.currentTime = JulianDate.fromIso8601("2021-05-11"); - // Force the time to propogate from the terria.clock to the catalogItems.clock (this should have no effect but we want to be sure). - terria.clock.tick(); - expect(item.clock.currentTime).toEqual( - JulianDate.fromIso8601("2019-07-03") - ); - expect(item.currentTime).toEqual(JulianDate.fromIso8601("2019-07-03")); - expect(terria.clock.currentTime).toEqual( - JulianDate.fromIso8601("2021-05-11") - ); - - // Again update the terria.clock and make sure that only the terria.clock is effected. - terria.clock.currentTime = JulianDate.fromIso8601("2023-02-17"); - // Force the time to propogate from the terria.clock to the catalogItems.clock (this should have no effect but we want to be sure). - terria.clock.tick(); - expect(item.clock.currentTime).toEqual( - JulianDate.fromIso8601("2019-07-03") - ); - expect(item.currentTime).toEqual(JulianDate.fromIso8601("2019-07-03")); - expect(terria.clock.currentTime).toEqual( - JulianDate.fromIso8601("2023-02-17") - ); - }); - - it("correctly updates .clock.currentTime and .currentTime when .useOwnClock true -> false", function () { - item.useOwnClock = true; - item.clock = new DataSourceClock(); - item.clock.currentTime = JulianDate.fromIso8601("2019-07-03"); - terria.clock.currentTime = JulianDate.fromIso8601("2021-05-11"); - item.isEnabled = true; - // These are sanity checks to make sure this test cases is established correctly. - expect(item.clock.currentTime).toEqual( - JulianDate.fromIso8601("2019-07-03") - ); - expect(item.currentTime).toEqual(JulianDate.fromIso8601("2019-07-03")); - expect(terria.clock.currentTime).toEqual( - JulianDate.fromIso8601("2021-05-11") - ); - - item.useOwnClock = false; - // Don't need to explicitly propogate the value (using .tick() ) as it should be copied when useOwnClock is changed. - expect(item.clock.currentTime).toEqual( - JulianDate.fromIso8601("2019-07-03") - ); - expect(item.currentTime).toEqual(JulianDate.fromIso8601("2019-07-03")); - expect(terria.clock.currentTime).toEqual( - JulianDate.fromIso8601("2019-07-03") - ); - }); - - it("correctly updates .clock.currentTime and .currentTime when .useOwnClock false -> true", function () { - item.useOwnClock = false; - item.clock = new DataSourceClock(); - item.clock.currentTime = JulianDate.fromIso8601("2019-07-03"); - terria.clock.currentTime = JulianDate.fromIso8601("2021-05-11"); - item.isEnabled = true; - // Force the time to propogate from the terria.clock to the catalogItems.clock. - terria.clock.tick(); - // These are sanity checks to make sure this test cases is established correctly. - expect(item.clock.currentTime).toEqual( - JulianDate.fromIso8601("2021-05-11") - ); - expect(item.currentTime).toEqual(JulianDate.fromIso8601("2021-05-11")); - expect(terria.clock.currentTime).toEqual( - JulianDate.fromIso8601("2021-05-11") - ); - - terria.clock.currentTime = JulianDate.fromIso8601("2023-11-29"); - // Don't need to explicitly propogate the value as it should be copied when useOwnClock is changed. - item.useOwnClock = true; - expect(item.clock.currentTime).toEqual( - JulianDate.fromIso8601("2023-11-29") - ); - expect(item.currentTime).toEqual(JulianDate.fromIso8601("2023-11-29")); - expect(terria.clock.currentTime).toEqual( - JulianDate.fromIso8601("2023-11-29") - ); - }); - - it("setting .currentTime correctly updates .clock.currentTime, .currentTime and terria.clock.currentTime when .useOwnClock is true", function () { - item.useOwnClock = true; - item.clock = new DataSourceClock(); - item.clock.currentTime = JulianDate.fromIso8601("2019-07-03"); - terria.clock.currentTime = JulianDate.fromIso8601("2021-05-11"); - item.isEnabled = true; - // Force the time to propogate from the terria.clock to the catalogItems.clock. - terria.clock.tick(); - // These are sanity checks to make sure this test cases is established correctly. - expect(item.clock.currentTime).toEqual( - JulianDate.fromIso8601("2019-07-03") - ); - expect(item.currentTime).toEqual(JulianDate.fromIso8601("2019-07-03")); - expect(terria.clock.currentTime).toEqual( - JulianDate.fromIso8601("2021-05-11") - ); - - item.currentTime = JulianDate.fromIso8601("2031-03-23"); - expect(item.clock.currentTime).toEqual( - JulianDate.fromIso8601("2031-03-23") - ); - expect(item.currentTime).toEqual(JulianDate.fromIso8601("2031-03-23")); - expect(terria.clock.currentTime).toEqual( - JulianDate.fromIso8601("2021-05-11") - ); - }); - - it("setting .currentTime correctly updates .clock.currentTime, .currentTime and terria.clock.currentTime when .useOwnClock is false", function () { - item.useOwnClock = false; - item.clock = new DataSourceClock(); - item.clock.currentTime = JulianDate.fromIso8601("2019-07-03"); - terria.clock.currentTime = JulianDate.fromIso8601("2021-05-11"); - item.isEnabled = true; - // Force the time to propogate from the terria.clock to the catalogItems.clock. - terria.clock.tick(); - // These are sanity checks to make sure this test cases is established correctly. - expect(item.clock.currentTime).toEqual( - JulianDate.fromIso8601("2021-05-11") - ); - expect(item.currentTime).toEqual(JulianDate.fromIso8601("2021-05-11")); - expect(terria.clock.currentTime).toEqual( - JulianDate.fromIso8601("2021-05-11") - ); - - item.currentTime = JulianDate.fromIso8601("2031-03-23"); - // Force the time to propogate from the terria.clock to the catalogItems.clock. - terria.clock.tick(); - expect(item.clock.currentTime).toEqual( - JulianDate.fromIso8601("2031-03-23") - ); - expect(item.currentTime).toEqual(JulianDate.fromIso8601("2031-03-23")); - expect(terria.clock.currentTime).toEqual( - JulianDate.fromIso8601("2031-03-23") - ); - }); - - describe("time series data: ", function () { - beforeEach(function () { - spyOn(terria.timelineStack, "addToTop"); - spyOn(terria.timelineStack, "remove"); - }); - - describe("when item has clock", function () { - beforeEach(function () { - item.clock = { - getValue: jasmine.createSpy("getValue"), - definitionChanged: { - addEventListener: jasmine.createSpy("addEventListener") - } - }; - }); - - it("item should be added to top of timelineStack when enabled", function (done) { - item.isEnabled = true; - - item._loadForEnablePromise.then(function () { - expect(terria.timelineStack.addToTop).toHaveBeenCalledWith(item); - done(); - }); - }); - - it("should be removed from timelineStack when disabled", function (done) { - item.isEnabled = true; - - item._loadForEnablePromise.then(function () { - item.isEnabled = false; - expect(terria.timelineStack.removeLayer).toHaveBeenCalledWith(item); - done(); - }); - }); - }); - - describe("when item has no clock", function () { - it("should not call timelineStack", function (done) { - item.isEnabled = true; - - item._loadForEnablePromise.then(function () { - expect(terria.timelineStack.addToTop).not.toHaveBeenCalled(); - done(); - }); - }); - }); - }); - - describe("ids", function () { - var catalog; - - beforeEach(function (done) { - catalog = new Catalog(terria); - - catalog - .updateFromJson([ - { - name: "Group", - type: "group", - items: [ - { - name: "A", - type: "item" - }, - { - name: "B", - id: "thisIsAnId", - type: "item" - }, - { - name: "C", - type: "item", - shareKeys: ["Another/Path"] - }, - { - name: "D", - id: "thisIsAnotherId", - shareKeys: ["This/Is/A/Path", "aPreviousId"], - type: "item" - } - ] - } - ]) - .then(done); - }); - - describe("uniqueId", function () { - it("should return path if no id is specified", function () { - expect(catalog.group.items[0].items[0].uniqueId).toBe( - "Root Group/Group/A" - ); - }); - - it("should return id field if one is specified", function () { - expect(catalog.group.items[0].items[1].uniqueId).toBe("thisIsAnId"); - }); - }); - - describe("allShareKeys", function () { - it("should return just the path if no id or shareKeys are specified", function () { - expect(catalog.group.items[0].items[0].allShareKeys).toEqual([ - "Root Group/Group/A" - ]); - }); - - it("should return just the id if id but no shareKeys are specified", function () { - expect(catalog.group.items[0].items[1].allShareKeys).toEqual([ - "thisIsAnId" - ]); - }); - - it("should return the path and shareKeys if no id specified", function () { - expect(catalog.group.items[0].items[2].allShareKeys).toEqual([ - "Root Group/Group/C", - "Another/Path" - ]); - }); - - it("should return the id and shareKeys if id specified", function () { - expect(catalog.group.items[0].items[3].allShareKeys).toEqual([ - "thisIsAnotherId", - "This/Is/A/Path", - "aPreviousId" - ]); - }); - }); - }); - - describe("setting isEnabled", function () { - beforeEach(function () { - item.nowViewingCatalogItem = {}; - spyOn(terria, "disclaimerListener"); - }); - - describe("to true when item has a disclaimer", function () { - beforeEach(function () { - item.initialMessage = {}; - item.isEnabled = true; - }); - - it("triggers a disclaimerEvent", function () { - expect(terria.disclaimerListener.calls.argsFor(0)[0]).toBe(item); - }); - - it("doesn't immediately finish enabling the view", function () { - expect(item.nowViewingCatalogItem.isEnabled).not.toBe(true); - }); - - it("finishes enabling the view after the callback passed to disclaimerEvent is executed", function (done) { - terria.disclaimerListener.calls.argsFor(0)[1](); - item._loadForEnablePromise - .then(function () { - expect(item.nowViewingCatalogItem.isEnabled).toBe(true); - }) - .then(done) - .catch(fail); - }); - }); - - describe("to true when item has no disclaimer", function () { - beforeEach(function () { - item.isEnabled = true; - }); - - it("triggers no disclaimerEvent", function () { - expect(terria.disclaimerListener).not.toHaveBeenCalled(); - }); - - it("finishes enabling the view", function (done) { - item._loadForEnablePromise - .then(function () { - expect(item.nowViewingCatalogItem.isEnabled).toBe(true); - }) - .then(done) - .catch(fail); - }); - }); - }); -}); diff --git a/test/Models/Catalog/CatalogItems/CsvCatalogItemSpec.js b/test/Models/Catalog/CatalogItems/CsvCatalogItemSpec.js deleted file mode 100644 index 4d824bfa70c..00000000000 --- a/test/Models/Catalog/CatalogItems/CsvCatalogItemSpec.js +++ /dev/null @@ -1,2564 +0,0 @@ -"use strict"; - -var clone = require("terriajs-cesium/Source/Core/clone").default; -var Color = require("terriajs-cesium/Source/Core/Color").default; -var JulianDate = require("terriajs-cesium/Source/Core/JulianDate").default; -var Rectangle = require("terriajs-cesium/Source/Core/Rectangle").default; - -var CatalogItem = require("../../lib/Models/CatalogItem"); -var CsvCatalogItem = require("../../../../lib/Models/Catalog/CatalogItems/CsvCatalogItem"); -var SensorObservationServiceCatalogItem = require("../../../../lib/Models/Catalog/Ows/SensorObservationServiceCatalogItem"); -var ImageryLayerCatalogItem = require("../../lib/Models/ImageryLayerCatalogItem"); -var ImageryProviderHooks = require("../../../../lib/Map/ImageryProviderHooks"); -var loadAndStubTextResources = require("../../../Utility/loadAndStubTextResources"); -var TableStyle = require("../../lib/Models/TableStyle"); -var Terria = require("../../../../lib/Models/Terria"); -var TimeInterval = require("terriajs-cesium/Source/Core/TimeInterval").default; -var VarType = require("../../../../lib/Map/VarType"); -var TableStructure = require("../../lib/Map/TableStructure"); - -var greenTableStyle = new TableStyle({ - colorMap: [ - { - offset: 0, - color: "rgba(0, 64, 0, 1.00)" - }, - { - offset: 1, - color: "rgba(0, 255, 0, 1.00)" - } - ] -}); - -function featureColor(csvItem, i) { - return csvItem.dataSource.entities.values[i]._point._color._value; -} - -describe("CsvCatalogItem with lat and lon", function () { - var terria; - var csvItem; - - beforeEach(function () { - terria = new Terria({ - baseUrl: "./" - }); - csvItem = new CsvCatalogItem(terria); - }); - - it("has sensible type and typeName", function () { - expect(csvItem.type).toBe("csv"); - expect(csvItem.typeName).toBe("Comma-Separated Values (CSV)"); - }); - - it("throws if constructed without a Terria instance", function () { - expect(function () { - var viewModel = new CsvCatalogItem(); // eslint-disable-line no-unused-vars - }).toThrow(); - }); - - it("can be constructed", function () { - expect(csvItem).toBeDefined(); - }); - - it("is derived from CatalogItem", function () { - expect(csvItem instanceof CatalogItem).toBe(true); - }); - - it("can update from json", function () { - var dataStr = "col1, col2\ntest, 0"; - csvItem.updateFromJson({ - name: "Name", - description: "Description", - rectangle: [-10, 10, -20, 20], - url: "http://my.csv.com/test.csv", - data: dataStr, - dataSourceUrl: "none", - dataCustodian: "Data Custodian" - }); - - expect(csvItem.name).toBe("Name"); - expect(csvItem.description).toBe("Description"); - expect(csvItem.rectangle).toEqual(Rectangle.fromDegrees(-10, 10, -20, 20)); - expect(csvItem.type).toBe("csv"); - expect(csvItem.url.indexOf("http://my.csv.com/test.csv")).toBe(0); - expect(csvItem.data.indexOf(dataStr)).toBe(0); - expect(csvItem.dataCustodian).toBe("Data Custodian"); - expect(csvItem.dataSourceUrl).toBe("none"); - }); - - it("uses reasonable defaults for updateFromJson", function () { - csvItem.updateFromJson({}); - - expect(csvItem.name).toBe("Unnamed Item"); - expect(csvItem.description).toBe(""); - expect(csvItem.rectangle).toBeUndefined(); - expect(csvItem.type).toBe("csv"); - expect(csvItem.url).toBeUndefined(); - expect(csvItem.data).toBeUndefined(); - expect(csvItem.dataSourceUrl).toBeUndefined(); - expect(csvItem.dataCustodian).toBeUndefined(); - }); - - it("can be round-tripped with serializeToJson and updateFromJson", function () { - var dataStr = "col1, col2\ntest, 0"; - csvItem.updateFromJson({ - name: "Name", - id: "Id", - description: "Description", - rectangle: [-10, 10, -20, 20], - url: "http://my.csv.com/test.csv", - data: dataStr, - dataSourceUrl: "none", - dataCustodian: "Data Custodian", - dataUrl: "http://my.csv.com/test.csv", - dataUrlType: "direct" - }); - - var json = csvItem.serializeToJson(); - - var reconstructed = new CsvCatalogItem(terria); - reconstructed.updateFromJson(json); - - expect(reconstructed.name).toEqual(csvItem.name); - expect(reconstructed.id).toEqual(csvItem.id); - expect(reconstructed.description).toEqual(csvItem.description); - expect(reconstructed.rectangle).toEqual(csvItem.rectangle); - expect(reconstructed.url).toEqual(csvItem.url); - expect(reconstructed.data).toEqual(csvItem.data); - expect(reconstructed.dataSourceUrl).toEqual(csvItem.dataSourceUrl); - expect(reconstructed.dataCustodian).toEqual(csvItem.dataCustodian); - expect(reconstructed.dataUrl).toEqual(csvItem.dataUrl); - expect(reconstructed.dataUrlType).toEqual(csvItem.dataUrlType); - }); - - it("is correctly loading csv data from a file", function (done) { - csvItem.url = "test/csv/minimal.csv"; - csvItem - .load() - .then(function () { - expect(csvItem.dataSource).toBeDefined(); - expect(csvItem.dataSource.tableStructure).toBeDefined(); - expect(csvItem.dataSource.tableStructure.columns.length).toEqual(5); - }) - .catch(fail) - .then(done); - }); - - it("is able to generate a Legend", function (done) { - csvItem.url = "test/csv/minimal.csv"; - csvItem - .load() - .then(function () { - expect(csvItem.legendUrl).toBeDefined(); - expect(csvItem.legendUrl.mimeType).toBeDefined(); - expect(csvItem.legendUrl.url).toBeDefined(); - }) - .catch(fail) - .then(done); - }); - - it('identifies "lat" and "lon" fields', function (done) { - csvItem.updateFromJson({ data: "lat,lon,value\n-37,145,10" }); - csvItem - .load() - .then(function () { - expect(csvItem.dataSource.tableStructure.hasLatitudeAndLongitude).toBe( - true - ); - }) - .catch(fail) - .then(done); - }); - - it('identifies "latitude" and "longitude" fields', function (done) { - csvItem.updateFromJson({ data: "latitude,longitude,value\n-37,145,10" }); - csvItem - .load() - .then(function () { - expect(csvItem.dataSource.tableStructure.hasLatitudeAndLongitude).toBe( - true - ); - }) - .catch(fail) - .then(done); - }); - - it('does not mistakenly identify "latvian" and "lone_person" fields', function (done) { - csvItem.updateFromJson({ - data: "latvian,lone_person,lat,lon,value\n-37,145,-37,145,10" - }); - csvItem - .load() - .then(function () { - expect( - csvItem.dataSource.tableStructure.columnsByType[VarType.LON][0].name - ).toEqual("lon"); - expect( - csvItem.dataSource.tableStructure.columnsByType[VarType.LAT][0].name - ).toEqual("lat"); - }) - .catch(fail) - .then(done); - }); - - it("handles one line with enum", function (done) { - csvItem.updateFromJson({ data: "lat,lon,org\n-37,145,test" }); - csvItem - .load() - .then(function () { - expect(csvItem.dataSource.tableStructure.hasLatitudeAndLongitude).toBe( - true - ); - expect(csvItem.legendUrl).toBeDefined(); - }) - .catch(fail) - .then(done); - }); - - it("handles numeric fields containing (quoted) thousands commas", function (done) { - csvItem.updateFromJson({ - data: 'lat,lon,value\n-37,145,"1,000"\n-38,145,"234,567.89"' - }); - csvItem - .load() - .then(function () { - var tableStructure = csvItem.dataSource.tableStructure; - expect(tableStructure.hasLatitudeAndLongitude).toBe(true); - expect(tableStructure.columns[2].values[0]).toEqual(1000); - expect(tableStructure.columns[2].values[1]).toBeCloseTo(234567.89, 2); - }) - .catch(fail) - .then(done); - }); - - it("handles missing lines", function (done) { - csvItem.url = "test/csv/blank_line.csv"; - csvItem - .load() - .then(function () { - var tableStructure = csvItem.dataSource.tableStructure; - var latColumn = tableStructure.columnsByType[VarType.LAT][0]; - var lonColumn = tableStructure.columnsByType[VarType.LON][0]; - // There are 7 lines after the header, but only 4 are non-blank. - expect(tableStructure.columns[0].values.length).toBe(4); - expect(latColumn.minimumValue).toBeLessThan(-30); - expect(lonColumn.minimumValue).toBeGreaterThan(150); - }) - .catch(fail) - .then(done); - }); - - it("handles enum fields", function (done) { - csvItem.url = "test/csv/lat_lon_enum.csv"; - csvItem - .load() - .then(function () { - expect(csvItem.dataSource.tableStructure.activeItems[0].name).toBe( - "enum" - ); - }) - .catch(fail) - .then(done); - }); - - it("sets active variable to dataVariable if provided", function (done) { - csvItem.url = "test/csv/lat_lon_enum_val.csv"; - csvItem._tableStyle = new TableStyle({ - dataVariable: "val" - }); - csvItem - .load() - .then(function () { - expect(csvItem.dataSource.tableStructure.activeItems[0].name).toBe( - "val" - ); - }) - .catch(fail) - .then(done); - }); - - it("does not set an active variable to dataVariable if null", function (done) { - csvItem.url = "test/csv/lat_lon_enum_val.csv"; - csvItem._tableStyle = new TableStyle({ - dataVariable: null - }); - csvItem - .load() - .then(function () { - expect(csvItem.dataSource.tableStructure.activeItems.length).toEqual(0); - }) - .catch(fail) - .then(done); - }); - - it("colors enum fields the same (only) when the value is the same", function (done) { - csvItem.url = "test/csv/lat_lon_enum.csv"; - csvItem - .load() - .then(function () { - expect(featureColor(csvItem, 0)).not.toEqual(featureColor(csvItem, 1)); - expect(featureColor(csvItem, 0)).not.toEqual(featureColor(csvItem, 2)); - expect(featureColor(csvItem, 0)).not.toEqual(featureColor(csvItem, 3)); - expect(featureColor(csvItem, 0)).toEqual(featureColor(csvItem, 4)); - expect(featureColor(csvItem, 1)).toEqual(featureColor(csvItem, 3)); - }) - .catch(fail) - .then(done); - }); - - it("handles no data variable", function (done) { - csvItem.url = "test/csv/lat_lon_novals.csv"; - csvItem - .load() - .then(function () { - expect(csvItem.dataSource.tableStructure.activeItems.length).toEqual(0); - expect(csvItem.dataSource.tableStructure.columns.length).toEqual(2); - expect( - csvItem.dataSource.tableStructure.columns[0].values.length - ).toEqual(5); - }) - .catch(fail) - .then(done); - }); - - it("supports dates", function (done) { - csvItem.url = "test/csv/lat_long_enum_moving_date.csv"; - csvItem - .load() - .then(function () { - var source = csvItem.dataSource; - expect(source.tableStructure.activeTimeColumn.name).toEqual("date"); - expect(source.tableStructure.columns[0].values.length).toEqual(13); - expect( - source.tableStructure.columnsByType[VarType.TIME].length - ).toEqual(1); - expect( - source.tableStructure.columnsByType[VarType.TIME][0].julianDates[0] - ).toEqual(JulianDate.fromIso8601("2015-08-01")); - // Test that an entity exists at the expected dates. - var features = source.entities.values; - var featureDates = features.map(getPropertiesDate); - expect(featureDates.indexOf("2015-07-31")).toBe(-1); // no such dates in the input file - expect(featureDates.indexOf("2015-08-07")).toBe(-1); - var earlyFeature = features[featureDates.indexOf("2015-08-01")]; - // The date '2015-08-01' appears to be interpreted as starting at midnight in the local time zone (at least on Chrome). - // Eg. in Sydney summer, JulianDate.toIso8601(earlyFeature.availability.start) returns "2015-07-31T14:00:00Z". - expect( - TimeInterval.contains( - earlyFeature.availability, - JulianDate.fromIso8601("2015-08-01") - ) - ).toBe(true); - // Also test the duration of the interval is one day (the time between input rows). - var durationInSeconds = JulianDate.secondsDifference( - earlyFeature.availability.stop, - earlyFeature.availability.start - ); - expect(durationInSeconds).toBe(24 * 3600); // 24 hours - }) - .catch(fail) - .then(done); - }); - - it("supports dates and very long displayDuration", function (done) { - var sevenDaysInMinutes = 60 * 24 * 7; - csvItem.url = "test/csv/lat_long_enum_moving_date.csv"; - csvItem._tableStyle = new TableStyle({ - displayDuration: sevenDaysInMinutes - }); - csvItem - .load() - .then(function () { - // Now, the features' availabilities should persist for 7 days, not just under 1 day. - var features = csvItem.dataSource.entities.values; - var featureDates = features.map(getPropertiesDate); - var earlyFeature = features[featureDates.indexOf("2015-08-01")]; - expect( - TimeInterval.contains( - earlyFeature.availability, - JulianDate.fromIso8601("2015-08-01T12:00:00Z") - ) - ).toBe(true); - var durationInSeconds = JulianDate.secondsDifference( - earlyFeature.availability.stop, - earlyFeature.availability.start - ); - expect(durationInSeconds).toEqual(sevenDaysInMinutes * 60); - }) - .catch(fail) - .then(done); - }); - - it("supports dates sorted randomly", function (done) { - // Now that we use availability to establish when entities exist, this is not much of a test. - // Could delete, or change it to test something more useful. - csvItem.url = "test/csv/lat_lon_enum_moving_date_unsorted.csv"; - csvItem - .load() - .then(function () { - var source = csvItem.dataSource; - expect(source.tableStructure.columns[0].values.length).toEqual(13); - expect( - source.tableStructure.columnsByType[VarType.TIME].length - ).toEqual(1); - // expect(source.tableStructure.columnsByType[VarType.TIME][0].julianDates[0]).toEqual(JulianDate.fromIso8601('2015-08-05')); - // Test that an entity exists at the expected dates. - var features = source.entities.values; - var featureDates = features.map(getPropertiesDate); - expect(featureDates.indexOf("2015-07-31")).toBe(-1); // no such dates in the input file - expect(featureDates.indexOf("2015-08-07")).toBe(-1); - var earlyFeature = features[featureDates.indexOf("2015-08-01")]; - // The date '2015-08-01' appears to be interpreted as starting at midnight in the local time zone (at least on Chrome). - // Eg. in Sydney summer, JulianDate.toIso8601(earlyFeature.availability.start) returns "2015-07-31T14:00:00Z". - expect( - TimeInterval.contains( - earlyFeature.availability, - JulianDate.fromIso8601("2015-08-01") - ) - ).toBe(true); - // Also test the duration of the interval is one day (the time between input rows). - var durationInSeconds = JulianDate.secondsDifference( - earlyFeature.availability.stop, - earlyFeature.availability.start - ); - expect(durationInSeconds).toBe(24 * 3600); // 24 hours - }) - .catch(fail) - .then(done); - }); - - it("supports moving-point csvs with id column by default", function (done) { - csvItem.url = "test/csv/lat_lon_enum_date_id.csv"; - csvItem - .load() - .then(function () { - var features = csvItem.dataSource.entities.values; - expect(features.length).toEqual(4); // There are 4 features A, B, C and D; does not equal the 13 rows in the file. - var featureA = features.filter(function (feature) { - return feature.name === "feature A"; - })[0]; - // FeatureA has rows for 1,2,4,5,6th of August. But it should still be available on the 3rd. - expect( - TimeInterval.contains( - featureA.availability, - JulianDate.fromIso8601("2015-08-02") - ) - ).toBe(true); - expect( - TimeInterval.contains( - featureA.availability, - JulianDate.fromIso8601("2015-08-03") - ) - ).toBe(true); - expect( - TimeInterval.contains( - featureA.availability, - JulianDate.fromIso8601("2015-08-04") - ) - ).toBe(true); - expect( - TimeInterval.contains( - featureA.availability, - JulianDate.fromIso8601("2015-08-08") - ) - ).toBe(false); - // Check there is no animation gap at the end of moving point csv - expect( - JulianDate.equalsEpsilon( - csvItem.clock.stopTime, - JulianDate.fromIso8601("2015-08-06"), - 1 - ) - ).toBe(true); - }) - .catch(fail) - .then(done); - }); - - it("supports overriding moving-point csvs with id column using null", function (done) { - csvItem.url = "test/csv/lat_lon_enum_date_id.csv"; - csvItem.idColumns = null; - csvItem - .load() - .then(function () { - var features = csvItem.dataSource.entities.values; - expect(features.length).toEqual(13); // There are 13 rows in the file. - }) - .catch(fail) - .then(done); - }); - - it("supports overriding moving-point csvs with id column using []", function (done) { - csvItem.url = "test/csv/lat_lon_enum_date_id.csv"; - csvItem.idColumns = []; - csvItem - .load() - .then(function () { - var features = csvItem.dataSource.entities.values; - expect(features.length).toEqual(13); // There are 13 rows in the file. - }) - .catch(fail) - .then(done); - }); - - it("ignores dates if tableStyle.timeColumn is null", function (done) { - csvItem.url = "test/csv/lat_long_enum_moving_date.csv"; - csvItem._tableStyle = new TableStyle({ timeColumn: null }); - csvItem - .load() - .then(function () { - var source = csvItem.dataSource; - expect(source.tableStructure.activeTimeColumn).toBeUndefined(); - expect(csvItem.clock).toBeUndefined(); - expect(source.clock).toBeUndefined(); - }) - .catch(fail) - .then(done); - }); - - it("ignores dates if tableStyle.timeColumn is set to null from json", function (done) { - // The test above did not pick up a problem in updateFromJson when the meaning of Cesium's defined was changed to also mean notNull (Cesium 1.19). - csvItem.url = "test/csv/lat_long_enum_moving_date.csv"; - csvItem._tableStyle = new TableStyle(); - csvItem._tableStyle.updateFromJson({ timeColumn: null }); - csvItem - .load() - .then(function () { - var source = csvItem.dataSource; - expect(source.tableStructure.activeTimeColumn).toBeUndefined(); - expect(csvItem.clock).toBeUndefined(); - expect(source.clock).toBeUndefined(); - }) - .catch(fail) - .then(done); - }); - - it("uses a second date column with tableStyle.timeColumn name", function (done) { - csvItem.url = "test/csv/lat_lon_enum_date_year.csv"; - csvItem._tableStyle = new TableStyle({ timeColumn: "year" }); - csvItem - .load() - .then(function () { - var source = csvItem.dataSource; - expect(source.tableStructure.activeTimeColumn.name).toEqual("year"); - }) - .catch(fail) - .then(done); - }); - - it("uses a second date column with tableStyle.timeColumn index", function (done) { - csvItem.url = "test/csv/lat_lon_enum_date_year.csv"; - csvItem._tableStyle = new TableStyle({ timeColumn: 4 }); - csvItem - .load() - .then(function () { - var source = csvItem.dataSource; - expect(source.tableStructure.activeTimeColumn.name).toEqual("year"); - }) - .catch(fail) - .then(done); - }); - - it("returns valid values for intervals", function (done) { - csvItem.url = "test/csv/lat_long_enum_moving_date.csv"; - csvItem._tableStyle = new TableStyle({ displayDuration: 60 }); - csvItem - .load() - .then(function () { - var intervals = csvItem.intervals; - - expect(intervals.length).toBe(6); // 13 rows over 6 days - - // interval length is 1 hour - expect(intervals.get(0).start).toEqual( - JulianDate.fromIso8601("2015-08-01") - ); - expect(intervals.get(0).stop).toEqual( - JulianDate.fromIso8601("2015-08-01T01:00Z") - ); - - expect(intervals.start).toEqual(JulianDate.fromIso8601("2015-08-01")); - expect(intervals.stop).toEqual( - JulianDate.fromIso8601("2015-08-06T01:00Z") - ); - }) - .catch(fail) - .then(done); - }); - - it("has the right values in descriptions for feature picking", function (done) { - csvItem.url = "test/csv/lat_lon_enum.csv"; - csvItem - .load() - .then(function () { - function desc(i) { - return csvItem.dataSource.entities.values[i].description._value; - } - expect(desc(0)).toContain("hello"); - expect(desc(1)).toContain("boots"); - }) - .catch(fail) - .then(done); - }); - - it("has a blank in the description table for a missing number", function (done) { - csvItem.url = "test/csv/missingNumberFormatting.csv"; - return csvItem - .load() - .then(function () { - var entities = csvItem.dataSource.entities.values; - expect(entities.length).toBe(2); - expect(entities[0].description.getValue()).toMatch( - "Vals]*>10" - ); - expect(entities[1].description.getValue()).toMatch( - "Vals]*>-" - ); - }) - .catch(fail) - .then(done); - }); - - it("scales points to a size ratio of 300% if scaleByValue true and respects scale value", function (done) { - csvItem.url = "test/csv/lat_lon_val.csv"; - csvItem._tableStyle = new TableStyle({ scale: 5, scaleByValue: true }); - return csvItem - .load() - .then(function () { - var pixelSizes = csvItem.dataSource.entities.values.map(function (e) { - return e.point._pixelSize._value; - }); - csvItem._minPix = Math.min.apply(null, pixelSizes); - csvItem._maxPix = Math.max.apply(null, pixelSizes); - // we don't want to be too prescriptive, but by default the largest object should be 150% normal, smallest is 50%, so 3x difference. - expect(csvItem._maxPix).toEqual(csvItem._minPix * 3); - }) - .then(function () { - var csvItem2 = new CsvCatalogItem(terria); - csvItem2._tableStyle = new TableStyle({ - scale: 10, - scaleByValue: true - }); - csvItem2.url = "test/csv/lat_lon_val.csv"; - return csvItem2.load().yield(csvItem2); - }) - .then(function (csvItem2) { - var pixelSizes = csvItem2.dataSource.entities.values.map(function (e) { - return e.point._pixelSize._value; - }); - var minPix = Math.min.apply(null, pixelSizes); - var maxPix = Math.max.apply(null, pixelSizes); - // again, we don't specify the base size, but x10 things should be twice as big as x5 things. - expect(maxPix).toEqual(csvItem._maxPix * 2); - expect(minPix).toEqual(csvItem._minPix * 2); - }) - .catch(fail) - .then(done); - }); - - it("does not make a feature if it is missing longitude", function (done) { - csvItem.url = "test/csv/lat_lon-missing_val.csv"; - return csvItem - .load() - .then(function () { - expect(csvItem.tableStructure.columns[0].values.length).toEqual(5); - expect(csvItem.dataSource.entities.values.length).toEqual(4); // one line is missing longitude. - }) - .catch(fail) - .then(done); - }); - - it("makes features even if no value column", function (done) { - csvItem.url = "test/csv/lat_lon.csv"; - return csvItem - .load() - .then(function () { - expect(csvItem.dataSource.entities.values.length).toBeGreaterThan(1); - }) - .catch(fail) - .then(done); - }); - - it("supports replaceWithNullValues", function (done) { - csvItem.url = "test/csv/lat_lon_badvalue.csv"; - csvItem._tableStyle = new TableStyle({ replaceWithNullValues: ["bad"] }); - csvItem - .load() - .then(function () { - var valueColumn = csvItem.tableStructure.columns[2]; - expect(valueColumn.values[0]).toEqual(5); - expect(valueColumn.values[1]).toEqual(null); - expect(valueColumn.values[2]).toEqual(0); - }) - .catch(fail) - .then(done); - }); - - it("supports replaceWithZeroValues", function (done) { - csvItem.url = "test/csv/lat_lon_badvalue.csv"; - csvItem._tableStyle = new TableStyle({ replaceWithZeroValues: ["bad"] }); - csvItem - .load() - .then(function () { - var valueColumn = csvItem.tableStructure.columns[2]; - expect(valueColumn.values[0]).toEqual(5); - expect(valueColumn.values[1]).toEqual(0); - expect(valueColumn.values[2]).toEqual(0); - }) - .catch(fail) - .then(done); - }); - - it("defaults to blanks in numeric columns being null", function (done) { - csvItem.url = "test/csv/lat_lon_blankvalue.csv"; - csvItem - .load() - .then(function () { - var valueColumn = csvItem.tableStructure.columns[2]; - expect(valueColumn.values[0]).toEqual(5); - expect(valueColumn.values[1]).toEqual(null); - expect(valueColumn.values[2]).toEqual(0); - }) - .catch(fail) - .then(done); - }); - - it("does not color null the same as zero", function (done) { - csvItem.url = "test/csv/lat_lon_badvalue.csv"; - csvItem._tableStyle = new TableStyle({ replaceWithNullValues: ["bad"] }); - csvItem - .load() - .then(function () { - expect(featureColor(csvItem, 1)).not.toEqual(featureColor(csvItem, 2)); - }) - .catch(fail) - .then(done); - }); - - it("supports nullColor", function (done) { - csvItem.url = "test/csv/lat_lon_badvalue.csv"; - csvItem._tableStyle = new TableStyle({ - replaceWithNullValues: ["bad"], - nullColor: "#A0B0C0" - }); - var nullColor = new Color(160 / 255, 176 / 255, 192 / 255, 1); - csvItem - .load() - .then(function () { - expect(featureColor(csvItem, 1)).toEqual(nullColor); - // This next expectation checks that zeros and null values are differently colored, and that - // null values do not lead to coloring getting out of sync with values. - expect(featureColor(csvItem, 2)).not.toEqual(nullColor); - }) - .catch(fail) - .then(done); - }); - - it("when no column selected, colors with non-null color", function (done) { - csvItem.url = "test/csv/lat_lon_enum_val.csv"; - csvItem._tableStyle = new TableStyle({ - dataVariable: null, - nullColor: "#000000" - }); - var nullColor = new Color(0, 0, 0, 1); - csvItem - .load() - .then(function () { - expect(featureColor(csvItem, 1)).not.toEqual(nullColor); - }) - .catch(fail) - .then(done); - }); - - it('replaces enum tail with "X other values" in the legend', function (done) { - csvItem.url = "test/csv/lat_lon_enum_lots.csv"; - csvItem._tableStyle = new TableStyle({ colorBins: 9 }); - csvItem - .load() - .then(function () { - expect(csvItem.legendUrl).toBeDefined(); - var url = csvItem.legendUrl.url; - expect(url).toContain("2 other values"); - expect(url).not.toContain("unicorns"); - expect(url).toContain("guinea pigs"); - }) - .catch(fail) - .then(done); - }); - - it('does not replace enum tail with "other values" if it fits', function (done) { - csvItem.url = "test/csv/lat_lon_enum_lots2.csv"; - csvItem._tableStyle = new TableStyle({ colorBins: 9 }); - csvItem - .load() - .then(function () { - expect(csvItem.legendUrl).toBeDefined(); - expect(csvItem.legendUrl.url).not.toContain("other values"); - expect(csvItem.legendUrl.url).toContain("turtles"); - }) - .catch(fail) - .then(done); - }); - - it("honors colorBins property when it is less than the number of colors in the palette", function (done) { - csvItem.url = "test/csv/lat_lon_enum_lots.csv"; - csvItem._tableStyle = new TableStyle({ colorBins: 3 }); - csvItem - .load() - .then(function () { - expect(csvItem.legendUrl).toBeDefined(); - var url = csvItem.legendUrl.url; - expect(url).toContain("8 other values"); - expect(url).toContain("cats"); - expect(url).toContain("dogs"); - }) - .catch(fail) - .then(done); - }); - - it('displays a "XX values" legend when colorBinMethod=cycle and there are more unique values than color bins', function (done) { - csvItem.url = "test/csv/lat_lon_enum_lots.csv"; - csvItem._tableStyle = new TableStyle({ - colorBins: 9, - colorBinMethod: "cycle" - }); - csvItem - .load() - .then(function () { - expect(csvItem.legendUrl).toBeDefined(); - var url = csvItem.legendUrl.url; - expect(url).toContain("10 values"); - expect(url).not.toContain("dogs"); - }) - .catch(fail) - .then(done); - }); - - it("displays a normal legend when colorBinMethod=cycle but there are less unique values than color bins", function (done) { - csvItem.url = "test/csv/lat_lon_enum_lots.csv"; - csvItem._tableStyle = new TableStyle({ - colorBins: 15, - colorBinMethod: "cycle" - }); - csvItem - .load() - .then(function () { - expect(csvItem.legendUrl).toBeDefined(); - var url = csvItem.legendUrl.url; - expect(url).not.toContain("values"); - expect(url).toContain("dogs"); - }) - .catch(fail) - .then(done); - }); - - describe("and per-column tableStyle", function () { - it("scales by value", function (done) { - csvItem.url = "test/csv/lat_lon_val.csv"; - csvItem._tableStyle = new TableStyle({ - columns: { - value: { - // only scale the 'value' column - scale: 5, - scaleByValue: true - } - } - }); - return csvItem - .load() - .then(function () { - var pixelSizes = csvItem.dataSource.entities.values.map(function (e) { - return e.point._pixelSize._value; - }); - csvItem._minPix = Math.min.apply(null, pixelSizes); - csvItem._maxPix = Math.max.apply(null, pixelSizes); - // we don't want to be too prescriptive, but by default the largest object should be 150% normal, smallest is 50%, so 3x difference. - expect(csvItem._maxPix).toEqual(csvItem._minPix * 3); - }) - .then(function () { - var csvItem2 = new CsvCatalogItem(terria); - csvItem2._tableStyle = new TableStyle({ - scale: 10, - scaleByValue: true - }); // this time, apply it to all columns - csvItem2.url = "test/csv/lat_lon_val.csv"; - return csvItem2.load().yield(csvItem2); - }) - .then(function (csvItem2) { - var pixelSizes = csvItem2.dataSource.entities.values.map(function ( - e - ) { - return e.point._pixelSize._value; - }); - var minPix = Math.min.apply(null, pixelSizes); - var maxPix = Math.max.apply(null, pixelSizes); - // again, we don't specify the base size, but x10 things should be twice as big as x5 things. - expect(maxPix).toEqual(csvItem._maxPix * 2); - expect(minPix).toEqual(csvItem._minPix * 2); - }) - .catch(fail) - .then(done); - }); - - it("uses correct defaults", function (done) { - // nullColor is passed through to the columns as well, if not overridden explicitly. - csvItem.url = "test/csv/lat_lon_badvalue.csv"; - csvItem._tableStyle = new TableStyle({ - nullColor: "#A0B0C0", - columns: { - value: { - replaceWithNullValues: ["bad"] - } - } - }); - var nullColor = new Color(160 / 255, 176 / 255, 192 / 255, 1); - csvItem - .load() - .then(function () { - expect(featureColor(csvItem, 1)).toEqual(nullColor); - }) - .catch(fail) - .then(done); - }); - - it("supports name and nullColor with column ref by name", function (done) { - csvItem.url = "test/csv/lat_lon_badvalue.csv"; - csvItem._tableStyle = new TableStyle({ - nullColor: "#123456", - columns: { - value: { - replaceWithNullValues: ["bad"], - nullColor: "#A0B0C0", - name: "Temperature" - } - } - }); - var nullColor = new Color(160 / 255, 176 / 255, 192 / 255, 1); - csvItem - .load() - .then(function () { - expect(csvItem.tableStructure.columns[2].name).toEqual("Temperature"); - expect(featureColor(csvItem, 1)).toEqual(nullColor); - }) - .catch(fail) - .then(done); - }); - - it("supports nullColor with column ref by number", function (done) { - csvItem.url = "test/csv/lat_lon_badvalue.csv"; - csvItem._tableStyle = new TableStyle({ - columns: { - 2: { - replaceWithNullValues: ["bad"], - nullColor: "#A0B0C0" - } - } - }); - var nullColor = new Color(160 / 255, 176 / 255, 192 / 255, 1); - csvItem - .load() - .then(function () { - expect(featureColor(csvItem, 1)).toEqual(nullColor); - }) - .catch(fail) - .then(done); - }); - - it("supports type", function (done) { - csvItem.url = "test/csv/lat_lon_badvalue.csv"; - csvItem._tableStyle = new TableStyle({ - columns: { - value: { - replaceWithNullValues: ["bad"], - type: "enum" - } - } - }); - csvItem - .load() - .then(function () { - expect(csvItem.tableStructure.columns[2].type).toEqual(VarType.ENUM); - }) - .catch(fail) - .then(done); - }); - }); -}); - -// eg. use as entities.map(getPropertiesDate) to just get the dates of the entities. -function getPropertiesDate(obj) { - return obj.properties.date.getValue(); -} - -// eg. use as regions.map(getId) to just get the ids of the regions. -function getId(obj) { - return obj.id; -} - -describe("CsvCatalogItem with region mapping", function () { - var terria; - var csvItem; - beforeEach(function () { - terria = new Terria({ - baseUrl: "./" - }); - terria.configParameters.regionMappingDefinitionsUrl = - "test/csv/regionMapping.json"; - csvItem = new CsvCatalogItem(terria); - - // Instead of directly inspecting the recoloring function (which is a private and inaccessible variable), - // get it from this function call. - // This unfortunately makes the test depend on an implementation detail. - spyOn(ImageryProviderHooks, "addRecolorFunc"); - - // Also, for feature detection, spy on this call; the second argument is the regionImageryProvider. - // This unfortunately makes the test depend on an implementation detail. - spyOn(ImageryLayerCatalogItem, "enableLayer"); - - // loadAndStubTextResources(done, [ - // terria.configParameters.regionMappingDefinitionsUrl - // ]).then(done).catch(done.fail); - }); - - it("does not think a lat-lon csv has regions", function (done) { - csvItem.url = "test/csv/lat_long_enum_moving_date.csv"; - csvItem - .load() - .then(function () { - expect(csvItem.regionMapping).toBeUndefined(); - }) - .catch(fail) - .then(done); - }); - - it("does not use region mapping when regions present with lat and lon", function (done) { - csvItem.url = "test/csv/lat_lon_enum_postcode.csv"; - csvItem - .load() - .then(function () { - expect(csvItem.regionMapping).toBeUndefined(); - }) - .catch(fail) - .then(done); - }); - - it("detects LGAs by code", function (done) { - csvItem.updateFromJson({ data: "lga_code,value\n31000,1" }); - csvItem - .load() - .then(function () { - var regionDetails = csvItem.regionMapping.regionDetails; - expect(regionDetails).toBeDefined(); - var regionDetail = regionDetails[0]; - expect(regionDetail.columnName).toEqual("lga_code"); - expect(regionDetail.regionProvider.regionType).toEqual("LGA"); - expect(csvItem.legendUrl).toBeDefined(); - }) - .catch(fail) - .then(done); - }); - - it("matches LGAs by code", function (done) { - csvItem.updateFromJson({ data: "lga_code,value\n31000,1" }); - csvItem - .load() - .then(function () { - csvItem.isEnabled = true; // The recolorFunction call is only made once the layer is enabled. - var regionDetails = csvItem.regionMapping.regionDetails; - expect(regionDetails).toBeDefined(); - var regionDetail = regionDetails[0]; - var recolorFunction = - ImageryProviderHooks.addRecolorFunc.calls.argsFor(0)[1]; - var indexOfThisRegion = regionDetail.regionProvider.regions - .map(getId) - .indexOf(31000); - expect(recolorFunction(indexOfThisRegion)[0]).toBeDefined(); // Test that at least one rgba component is defined. - expect(recolorFunction(indexOfThisRegion)).not.toEqual([0, 0, 0, 0]); // And that the color is not all zeros. - }) - .catch(fail) - .then(done); - }); - - it("matches LGAs by names in various formats", function (done) { - // City of Melbourne is not actually a region, but melbourne is. Same with Sydney (S) and sydney. But test they work anyway. - csvItem.updateFromJson({ - data: "lga_name,value\nCity of Melbourne,1\nGreater Geelong,2\nSydney (S),3" - }); - csvItem - .load() - .then(function () { - csvItem.isEnabled = true; - var regionDetails = csvItem.regionMapping.regionDetails; - expect(regionDetails).toBeDefined(); - var regionDetail = regionDetails[0]; - var recolorFunction = - ImageryProviderHooks.addRecolorFunc.calls.argsFor(0)[1]; - var regionNames = regionDetail.regionProvider.regions.map(getId); - expect(recolorFunction(regionNames.indexOf("bogan"))).not.toBeDefined(); // Test that we didn't try to recolor other regions. - expect( - recolorFunction(regionNames.indexOf("melbourne"))[0] - ).toBeDefined(); // Test that at least one rgba component is defined. - expect(recolorFunction(regionNames.indexOf("melbourne"))).not.toEqual([ - 0, 0, 0, 0 - ]); // And that the color is not all zeros. - expect( - recolorFunction(regionNames.indexOf("greater geelong"))[0] - ).toBeDefined(); // Test that at least one rgba component is defined. - expect( - recolorFunction(regionNames.indexOf("greater geelong")) - ).not.toEqual([0, 0, 0, 0]); // And that the color is not all zeros. - expect(recolorFunction(regionNames.indexOf("sydney"))[0]).toBeDefined(); // Test that at least one rgba component is defined. - expect(recolorFunction(regionNames.indexOf("sydney"))).not.toEqual([ - 0, 0, 0, 0 - ]); // And that the color is not all zeros. - }) - .catch(fail) - .then(done); - }); - - it("matches mapped region column names", function (done) { - csvItem.updateFromJson({ - data: "nothing,value\n31000,1", - tableStyle: { - columns: { - nothing: { - name: "lga_code" - } - } - } - }); - csvItem - .load() - .then(function () { - expect(csvItem.regionMapping.regionDetails).toBeDefined(); - }) - .catch(fail) - .then(done); - }); - - it("does not match original name of mapped region column names", function (done) { - csvItem.updateFromJson({ - data: "lga_code,value\n31000,1", - tableStyle: { - columns: { - lga_code: { - name: "something else" - } - } - } - }); - csvItem - .load() - .then(function () { - expect(csvItem.regionMapping).not.toBeDefined(); - }) - .catch(fail) - .then(done); - }); - - // TODO: What is this testing? - xit("matches numeric state IDs with regexes", function (done) { - csvItem.updateFromJson({ - data: "state,value\n3,30\n4,40\n5,50,\n8,80\n9,90" - }); - csvItem - .load() - .then(function () { - csvItem.isEnabled = true; - var regionDetails = csvItem.regionMapping.regionDetails; - expect(regionDetails).toBeDefined(); - var regionDetail = regionDetails[0]; - var regionNames = regionDetail.regionProvider.regions.map(getId); - // TODO: This is the old test, which doesn't really have an equivalent in the new csv refactor: - // expect(csvItem.dataSource.dataset.variables.state.regionCodes).toEqual(["queensland", "south australia", "western australia", "other territories"]); - // Possibly something like this? However, this fails - it includes tasmania and not queensland. - var names = csvItem.dataSource.tableStructure.columns[0].values.map( - function (id) { - return regionNames[id]; - } - ); - expect(names).toEqual([ - "queensland", - "south australia", - "western australia", - "other territories" - ]); - }) - .catch(fail) - .then(done); - }); - - // I think this would be better as a test of RegionProvider? - // it('matches SA4s', function(done) { - // csvItem.updateFromJson({data: 'sa4,value\n209,correct'}); - // csvItem.load().then(function() { - // csvItem.isEnabled = true; - // return csvItem.dataSource.regionPromise.then(function(regionDetails) { - // expect(regionDetails).toBeDefined(); - // // There is no "rowPropertiesByCode" method any more. - // expect(csvItem.rowPropertiesByCode(209).value).toBe('correct'); - // }).catch(fail); - // }).catch(fail).then(done); - // }); - - it("respects tableStyle color ramping for regions", function (done) { - csvItem.updateFromJson({ - data: "lga_name,value\nmelbourne,0\ngreater geelong,5\nsydney,10", - tableStyle: greenTableStyle - }); - csvItem - .load() - .then(function () { - csvItem.isEnabled = true; - var regionDetails = csvItem.regionMapping.regionDetails; - expect(regionDetails).toBeDefined(); - var regionDetail = regionDetails[0]; - var recolorFunction = - ImageryProviderHooks.addRecolorFunc.calls.argsFor(0)[1]; - var regionNames = regionDetail.regionProvider.regions.map(getId); - // Require the green value to range from 64 to 255, but do not require a linear mapping. - expect(recolorFunction(regionNames.indexOf("melbourne"))).toEqual([ - 0, 64, 0, 255 - ]); - expect( - recolorFunction(regionNames.indexOf("greater geelong"))[1] - ).toBeGreaterThan(64); - expect( - recolorFunction(regionNames.indexOf("greater geelong"))[1] - ).toBeLessThan(255); - expect(recolorFunction(regionNames.indexOf("sydney"))).toEqual([ - 0, 255, 0, 255 - ]); - expect(csvItem.legendUrl).toBeDefined(); - }) - .catch(fail) - .then(done); - }); - - it("uses the requested region mapping column, not just the first one", function (done) { - // The column names in postcode_lga_val_enum.csv are: lga_name, val1, enum, postcode. - var revisedGreenTableStyle = clone(greenTableStyle); - revisedGreenTableStyle.regionType = "poa"; - revisedGreenTableStyle.regionVariable = "postcode"; - csvItem.updateFromJson({ - url: "test/csv/postcode_lga_val_enum.csv", - tableStyle: revisedGreenTableStyle - }); - csvItem - .load() - .then(function () { - var regionDetails = csvItem.regionMapping.regionDetails; - expect(regionDetails).toBeDefined(); - expect( - csvItem.tableStructure.columnsByType[VarType.REGION][0].name - ).toBe("postcode"); - }) - .catch(fail) - .then(done); - }); - - it("can default to an enum field", function (done) { - csvItem.url = "test/csv/postcode_enum.csv"; - csvItem - .load() - .then(function () { - var regionDetails = csvItem.regionMapping.regionDetails; - expect(regionDetails).toBeDefined(); - expect(csvItem.tableStructure.activeItems[0].name).toBe("enum"); - expect(csvItem.legendUrl).toBeDefined(); - }) - .catch(fail) - .then(done); - }); - - it("handles one line with enum", function (done) { - csvItem.updateFromJson({ data: "state,org\nNSW,test" }); - csvItem - .load() - .then(function () { - var regionDetails = csvItem.regionMapping.regionDetails; - expect(regionDetails).toBeDefined(); - expect(csvItem.legendUrl).toBeDefined(); - }) - .catch(fail) - .then(done); - }); - - it("handles no data variable", function (done) { - csvItem.url = "test/csv/postcode_novals.csv"; - csvItem - .load() - .then(function () { - var regionDetails = csvItem.regionMapping.regionDetails; - expect(regionDetails).toBeDefined(); - expect(csvItem.tableStructure.activeItems.length).toEqual(0); - expect(csvItem.tableStructure.columns[0].values.length).toBeGreaterThan( - 1 - ); - csvItem.isEnabled = true; - expect(csvItem.legendUrl).toBeDefined(); - }) - .catch(fail) - .then(done); - }); - - it("chooses the leftmost data column when none specified", function (done) { - csvItem.url = "test/csv/val_enum_postcode.csv"; - csvItem - .load() - .then(function () { - var regionDetails = csvItem.regionMapping.regionDetails; - expect(regionDetails).toBeDefined(); - expect(csvItem.tableStructure.activeItems[0].name).toEqual("val1"); - }) - .catch(fail) - .then(done); - }); - - it("handles LGA names with states for disambiguation", function (done) { - csvItem.updateFromJson({ - url: "test/csv/lga_state_disambig.csv", - tableStyle: new TableStyle({ dataVariable: "StateCapital" }) - }); - csvItem - .load() - .then(function () { - var regionDetails = csvItem.regionMapping.regionDetails; - expect(regionDetails).toBeDefined(); - var regionDetail = regionDetails[0]; - expect(regionDetail.disambigColumnName).toEqual("State"); - // The following test is much more rigorous. - }) - .catch(fail) - .then(done); - }); - - it("supports region-mapped files with dates", function (done) { - csvItem.updateFromJson({ - url: "test/csv/postcode_date_value.csv" - }); - csvItem - .load() - .then(function () { - var regionMapping = csvItem.regionMapping; - var j = JulianDate.fromIso8601; - regionMapping._catalogItem.clock.currentTime = j("2015-08-08"); - csvItem.isEnabled = true; - var regionDetails = regionMapping.regionDetails; - expect(regionDetails).toBeDefined(); - var regionDetail = regionDetails[0]; - expect(csvItem.tableStructure.columns[0].values.length).toEqual(10); - expect( - csvItem.tableStructure.columnsByType[VarType.TIME].length - ).toEqual(1); - expect( - csvItem.tableStructure.columnsByType[VarType.TIME][0].julianDates[0] - ).toEqual(j("2015-08-07")); - // Test that the right regions have been colored (since the datasource doesn't expose the entities). - // On 2015-08-08, only postcodes 3121 and 3122 have values. On neighboring dates, so do 3123 and 3124. - var recolorFunction = - ImageryProviderHooks.addRecolorFunc.calls.argsFor(0)[1]; - var regionNames = regionDetail.regionProvider.regions.map(getId); - - expect(recolorFunction(regionNames.indexOf("3121"))).toBeDefined(); - expect(recolorFunction(regionNames.indexOf("3122"))).toBeDefined(); - expect(recolorFunction(regionNames.indexOf("3123"))).not.toBeDefined(); - expect(recolorFunction(regionNames.indexOf("3124"))).not.toBeDefined(); - expect(csvItem.legendUrl).toBeDefined(); - }) - .catch(fail) - .then(done); - }); - - it("supports region-mapped files with missing dates", function (done) { - csvItem.updateFromJson({ - url: "test/csv/postcode_date_value_missing_date.csv" - }); - csvItem - .load() - .then(function () { - var regionMapping = csvItem.regionMapping; - var j = JulianDate.fromIso8601; - regionMapping._catalogItem.clock.currentTime = j("2015-08-08"); - csvItem.isEnabled = true; - var regionDetails = regionMapping.regionDetails; - expect(regionDetails).toBeDefined(); - var regionDetail = regionDetails[0]; - expect(csvItem.tableStructure.columns[0].values.length).toEqual(10); - expect( - csvItem.tableStructure.columnsByType[VarType.TIME].length - ).toEqual(1); - expect( - csvItem.tableStructure.columnsByType[VarType.TIME][0].julianDates[0] - ).toEqual(j("2015-08-07")); - // Test that the right regions have been colored (since the datasource doesn't expose the entities). - // On 2015-08-08, only postcodes 3121 and 3122 have values. On neighboring dates, so do 3123 and 3124. - var recolorFunction = - ImageryProviderHooks.addRecolorFunc.calls.argsFor(0)[1]; - var regionNames = regionDetail.regionProvider.regions.map(getId); - - expect(recolorFunction(regionNames.indexOf("3121"))).toBeDefined(); - expect(recolorFunction(regionNames.indexOf("3122"))).not.toBeDefined(); // This one was eliminated. - expect(recolorFunction(regionNames.indexOf("3123"))).not.toBeDefined(); - expect(recolorFunction(regionNames.indexOf("3124"))).not.toBeDefined(); - expect(csvItem.legendUrl).toBeDefined(); - }) - .catch(fail) - .then(done); - }); - - it("supports region-mapped files with displayDuration and dates", function (done) { - csvItem.updateFromJson({ - url: "test/csv/postcode_date_value.csv", - tableStyle: new TableStyle({ displayDuration: 60 * 6 }) // 6 hours - }); - csvItem - .load() - .then(function () { - var regionMapping = csvItem.regionMapping; - var j = JulianDate.fromIso8601; - var nineOclock = j("2015-08-08"); // midnight local time - JulianDate.addHours(nineOclock, 9, nineOclock); - regionMapping._catalogItem.clock.currentTime = nineOclock; - csvItem.isEnabled = true; - var regionDetails = regionMapping.regionDetails; - expect(regionDetails).toBeDefined(); - var regionDetail = regionDetails[0]; - expect(csvItem.tableStructure.columns[0].values.length).toEqual(10); - expect( - csvItem.tableStructure.columnsByType[VarType.TIME].length - ).toEqual(1); - expect( - csvItem.tableStructure.columnsByType[VarType.TIME][0].julianDates[0] - ).toEqual(j("2015-08-07")); - // Test that no regions have been colored, since at 9am we are more than 6 hours past the start date of any row. - var recolorFunction = - ImageryProviderHooks.addRecolorFunc.calls.argsFor(0)[1]; - var regionNames = regionDetail.regionProvider.regions.map(getId); - - expect(recolorFunction(regionNames.indexOf("3121"))).not.toBeDefined(); - expect(recolorFunction(regionNames.indexOf("3122"))).not.toBeDefined(); - expect(recolorFunction(regionNames.indexOf("3123"))).not.toBeDefined(); - expect(recolorFunction(regionNames.indexOf("3124"))).not.toBeDefined(); - }) - .catch(fail) - .then(done); - }); - - it('replaces enum tail with "X other values" in the legend', function (done) { - csvItem.url = "test/csv/postcode_enum_lots.csv"; - csvItem._tableStyle = new TableStyle({ colorBins: 9 }); - csvItem - .load() - .then(function () { - expect(csvItem.legendUrl).toBeDefined(); - var url = csvItem.legendUrl.url; - expect(url).toContain("2 other values"); - expect(url).not.toContain("unicorns"); - expect(url).toContain("guinea pigs"); - }) - .catch(fail) - .then(done); - }); - - it("honors colorBins property when it is less than the number of colors in the palette", function (done) { - csvItem.url = "test/csv/postcode_enum_lots.csv"; - csvItem._tableStyle = new TableStyle({ colorBins: 3 }); - csvItem - .load() - .then(function () { - expect(csvItem.legendUrl).toBeDefined(); - var url = csvItem.legendUrl.url; - expect(url).toContain("8 other values"); - expect(url).toContain("cats"); - expect(url).toContain("dogs"); - }) - .catch(fail) - .then(done); - }); - - it('displays a "XX values" legend when colorBinMethod=cycle and there are more unique values than color bins', function (done) { - csvItem.url = "test/csv/postcode_enum_lots.csv"; - csvItem._tableStyle = new TableStyle({ - colorBins: 9, - colorBinMethod: "cycle" - }); - csvItem - .load() - .then(function () { - expect(csvItem.legendUrl).toBeDefined(); - var url = csvItem.legendUrl.url; - expect(url).toContain("10 values"); - expect(url).not.toContain("dogs"); - }) - .catch(fail) - .then(done); - }); - - it("displays a normal legend when colorBinMethod=cycle but there are less unique values than color bins", function (done) { - csvItem.url = "test/csv/postcode_enum_lots.csv"; - csvItem._tableStyle = new TableStyle({ - colorBins: 15, - colorBinMethod: "cycle" - }); - csvItem - .load() - .then(function () { - expect(csvItem.legendUrl).toBeDefined(); - var url = csvItem.legendUrl.url; - expect(url).not.toContain("values"); - expect(url).toContain("dogs"); - }) - .catch(fail) - .then(done); - }); - - it("is less than 2000 characters when serialised to JSON then URLEncoded", function (done) { - csvItem.url = "test/csv/postcode_enum.csv"; - csvItem - .load() - .then(function () { - var url = encodeURIComponent(JSON.stringify(csvItem.serializeToJson())); - expect(url.length).toBeLessThan(2000); - }) - .catch(fail) - .then(done); - }); - - //describe('when data is partially unmatchable', function() { - // beforeEach(function(done) { - // spyOn(terria.error, 'raiseEvent'); - // csvItem.updateFromJson({data: 'Postcode,value\n2000,1\n9999,2'}).catch(fail); - // csvItem.load().then(done); - // }); - // - // xit('emits an error event', function() { - // csvItem.isEnabled = true; - // expect(terria.raiseErrorToUser).toHaveBeenCalled(); - // }); - // - // xit('and showWarnings is false, it emits no error event or JS Error', function() { - // csvItem.showWarnings = false; - // csvItem.isEnabled = true; - // expect(terria.raiseErrorToUser).not.toHaveBeenCalled(); - // }); - //}); - - describe("and feature picking", function () { - var postcode3124 = { - type: "FeatureCollection", - features: [ - { - type: "Feature", - id: "FID_POA_2011_AUST.766", - geometry: { - type: "MultiPolygon", - coordinates: [] - }, - geometry_name: "the_geom", - properties: { - FID: 765, - POA_CODE: "3124", - POA_NAME: "3124", - SQKM: 7.29156648352383 - } - } - ], - crs: { - type: "name", - properties: { - name: "urn:ogc:def:crs:EPSG::4326" - } - } - }; - - it("works", function (done) { - var csvFile = "test/csv/postcode_val_enum.csv"; - - loadAndStubTextResources(done, [ - csvFile, - terria.configParameters.regionMappingDefinitionsUrl, - "data/regionids/region_map-FID_POA_2011_AUST_POA_CODE.json" - ]).then(function (resources) { - jasmine.Ajax.stubRequest( - "http://regionmap-dev.nationalmap.nicta.com.au/region_map/ows?transparent=true&format=image%2Fpng&exceptions=application%2Fvnd.ogc.se_xml&styles=&tiled=true&service=WMS&version=1.1.1&request=GetFeatureInfo&layers=region_map%3AFID_POA_2011_AUST&srs=EPSG%3A3857&bbox=16143500.373829227%2C-4559315.8631541915%2C16153284.31344973%2C-4549531.923533689&width=256&height=256&query_layers=region_map%3AFID_POA_2011_AUST&x=217&y=199&info_format=application%2Fjson" - ).andReturn({ - responseText: JSON.stringify(postcode3124) - }); - - csvItem.url = csvFile; - csvItem - .load() - .then(function () { - csvItem.isEnabled = true; // Required to create an imagery layer. - var regionDetails = csvItem.regionMapping.regionDetails; - expect(regionDetails).toBeDefined(); - // We are spying on calls to ImageryLayerCatalogItem.enableLayer; the argument[1] is the regionImageryProvider. - // This unfortunately makes the test depend on an implementation detail. - var regionImageryProvider = - ImageryLayerCatalogItem.enableLayer.calls.argsFor(0)[1]; - expect(regionImageryProvider).toBeDefined(); - return regionImageryProvider.pickFeatures( - 3698, - 2513, - 12, - 2.5323739090365693, - -0.6604719122857645 - ); - }) - .then(function (r) { - expect(r[0].name).toEqual("3124"); - var description = r[0].description; //.getValue(terria.clock.currentTime); - expect(description).toContain("42.42"); - expect(description).toContain("the universe"); - }) - .catch(fail) - .then(done); - }); - }); - - it("works with fuzzy matching", function (done) { - var csvFile = "test/csv/lga_fuzzy_val.csv"; - - loadAndStubTextResources(done, [ - csvFile, - terria.configParameters.regionMappingDefinitionsUrl, - "data/regionids/region_map-FID_LGA_2011_AUST_LGA_NAME11.json", - "data/regionids/region_map-FID_LGA_2011_AUST_STE_NAME11.json" - ]).then(function (resources) { - jasmine.Ajax.stubRequest( - "http://regionmap-dev.nationalmap.nicta.com.au/region_map/ows?transparent=true&format=image%2Fpng&exceptions=application%2Fvnd.ogc.se_xml&styles=&tiled=true&service=WMS&version=1.1.1&request=GetFeatureInfo&layers=region_map%3AFID_LGA_2011_AUST&srs=EPSG%3A3857&bbox=16143500.373829227%2C-4559315.8631541915%2C16153284.31344973%2C-4549531.923533689&width=256&height=256&query_layers=region_map%3AFID_LGA_2011_AUST&x=217&y=199&info_format=application%2Fjson" - ).andReturn({ - responseText: JSON.stringify({ - type: "FeatureCollection", - features: [ - { - type: "Feature", - id: "FID_LGA_2011_AUST.163", - geometry: { - type: "MultiPolygon", - coordinates: [] - }, - geometry_name: "the_geom", - properties: { - FID: 162, - LGA_CODE11: "21110", - LGA_NAME11: "Boroondara (C)", - STE_CODE11: "2", - STE_NAME11: "Victoria", - AREA_SQKM: 60.1808559111785 - } - } - ], - crs: { - type: "name", - properties: { - name: "urn:ogc:def:crs:EPSG::4326" - } - } - }) - }); - - csvItem.url = csvFile; - csvItem - .load() - .then(function () { - csvItem.isEnabled = true; // Required to create an imagery layer. - var regionDetails = csvItem.regionMapping.regionDetails; - expect(regionDetails).toBeDefined(); - // We are spying on calls to ImageryLayerCatalogItem.enableLayer; the argument[1] is the regionImageryProvider. - // This unfortunately makes the test depend on an implementation detail. - var regionImageryProvider = - ImageryLayerCatalogItem.enableLayer.calls.argsFor(0)[1]; - expect(regionImageryProvider).toBeDefined(); - return regionImageryProvider.pickFeatures( - 3698, - 2513, - 12, - 2.5323739090365693, - -0.6604719122857645 - ); - }) - .then(function (r) { - expect(r[0].name).toEqual("Boroondara (C)"); - var description = r[0].description; //.getValue(terria.clock.currentTime); - expect(description).toContain("42.42"); - expect(description).toContain("the universe"); - }) - .catch(fail) - .then(done); - }); - }); - - it("works with disambiguated LGA names like Wellington, VIC", function (done) { - var csvFile = "test/csv/lga_state_disambig.csv"; - loadAndStubTextResources(done, [ - csvFile, - terria.configParameters.regionMappingDefinitionsUrl, - "data/regionids/region_map-FID_LGA_2011_AUST_LGA_NAME11.json", - "data/regionids/region_map-FID_LGA_2011_AUST_STE_NAME11.json", - "data/regionids/region_map-FID_STE_2011_AUST_STE_NAME11.json" - ]).then(function (resources) { - jasmine.Ajax.stubRequest( - "http://regionmap-dev.nationalmap.nicta.com.au/region_map/ows?transparent=true&format=image%2Fpng&exceptions=application%2Fvnd.ogc.se_xml&styles=&tiled=true&service=WMS&version=1.1.1&request=GetFeatureInfo&layers=region_map%3AFID_LGA_2011_AUST&bbox=16437018.562444303%2C-3913575.8482010253%2C16593561.59637234%2C-3757032.814272985&width=256&height=256&srs=EPSG%3A3857&query_layers=region_map%3AFID_LGA_2011_AUST&x=249&y=135&info_format=application%2Fjson" - ).andReturn({ - responseText: JSON.stringify({ - type: "FeatureCollection", - features: [ - { - type: "Feature", - id: "FID_LGA_2011_AUST.143", - geometry: { - type: "MultiPolygon", - coordinates: [] - }, - geometry_name: "the_geom", - properties: { - FID: 142, - LGA_CODE11: "18150", - LGA_NAME11: "Wellington (A)", - STE_CODE11: "1", - STE_NAME11: "New South Wales", - AREA_SQKM: 4110.08848071889 - } - } - ], - crs: { - type: "name", - properties: { - name: "urn:ogc:def:crs:EPSG::4326" - } - } - }) - }); - // Use a regular expression for this URL because IE9 has ~1e-10 differences in the bbox parameter. - jasmine.Ajax.stubRequest( - new RegExp( - "http://regionmap-dev\\.nationalmap\\.nicta\\.com\\.au/region_map/ows\\?transparent=true&format=image%2Fpng&exceptions=application%2Fvnd\\.ogc\\.se_xml&styles=&tiled=true&service=WMS&version=1\\.1\\.1&request=GetFeatureInfo&layers=region_map%3AFID_LGA_2011_AUST&bbox=16280475\\.5285162\\d\\d%2C-4618019\\.5008772\\d\\d%2C16358747\\.0454802\\d\\d%2C-4539747\\.9839131\\d\\d&width=256&height=256&srs=EPSG%3A3857&query_layers=region_map%3AFID_LGA_2011_AUST&x=126&y=58&info_format=application%2Fjson" - ) - ).andReturn({ - responseText: JSON.stringify({ - type: "FeatureCollection", - features: [ - { - type: "Feature", - id: "FID_LGA_2011_AUST.225", - geometry: { - type: "MultiPolygon", - coordinates: [] - }, - geometry_name: "the_geom", - properties: { - FID: 224, - LGA_CODE11: "26810", - LGA_NAME11: "Wellington (S)", - STE_CODE11: "2", - STE_NAME11: "Victoria", - AREA_SQKM: 10817.3680807268 - } - } - ], - crs: { - type: "name", - properties: { - name: "urn:ogc:def:crs:EPSG::4326" - } - } - }) - }); - csvItem.url = csvFile; - csvItem - .load() - .then(function () { - csvItem.isEnabled = true; // Required to create an imagery provider. - var regionDetails = csvItem.regionMapping.regionDetails; - expect(regionDetails).toBeDefined(); - // We are spying on calls to ImageryLayerCatalogItem.enableLayer; the second argument is the regionImageryProvider. - // This unfortunately makes the test depend on an implementation detail. - var regionImageryProvider = - ImageryLayerCatalogItem.enableLayer.calls.argsFor(0)[1]; - expect(regionImageryProvider).toBeDefined(); - return regionImageryProvider.pickFeatures( - 464, - 314, - 9, - 2.558613543017636, - -0.6605448031188106 - ); - }) - .then(function (r) { - expect(r[0].name).toEqual("Wellington (S)"); - var description = r[0].description; //.getValue(terria.clock.currentTime); - expect(description).toContain("Wellington"); // leaving it open whether it should show server-side ID or provided value - expect(description).toContain("Melbourne"); - }) - .then(function () { - var regionImageryProvider = - ImageryLayerCatalogItem.enableLayer.calls.argsFor(0)[1]; - return regionImageryProvider.pickFeatures( - 233, - 152, - 8, - 2.600997237149669, - -0.5686381345023742 - ); - }) - .then(function (r) { - expect(r[0].name).toEqual("Wellington (A)"); - var description = r[0].description; //.getValue(terria.clock.currentTime); - expect(description).toContain("Wellington"); - expect(description).toContain("Sydney"); - }) - .catch(fail) - .then(done); - }); - }); - - it("time-varying features update with time", function (done) { - var csvFile = "test/csv/postcode_val_enum_time.csv"; - - loadAndStubTextResources(done, [ - csvFile, - terria.configParameters.regionMappingDefinitionsUrl, - "data/regionids/region_map-FID_POA_2011_AUST_POA_CODE.json" - ]).then(function (resources) { - jasmine.Ajax.stubRequest( - "http://regionmap-dev.nationalmap.nicta.com.au/region_map/ows?transparent=true&format=image%2Fpng&exceptions=application%2Fvnd.ogc.se_xml&styles=&tiled=true&service=WMS&version=1.1.1&request=GetFeatureInfo&layers=region_map%3AFID_POA_2011_AUST&srs=EPSG%3A3857&bbox=16143500.373829227%2C-4559315.8631541915%2C16153284.31344973%2C-4549531.923533689&width=256&height=256&query_layers=region_map%3AFID_POA_2011_AUST&x=217&y=199&info_format=application%2Fjson" - ).andReturn({ - responseText: JSON.stringify(postcode3124) - }); - - csvItem.url = csvFile; - csvItem - .load() - .then(function () { - csvItem.isEnabled = true; // Required to create an imagery layer. - var regionDetails = csvItem.regionMapping.regionDetails; - expect(regionDetails).toBeDefined(); - // We are spying on calls to ImageryLayerCatalogItem.enableLayer; the argument[1] is the regionImageryProvider. - // This unfortunately makes the test depend on an implementation detail. - var regionImageryProvider = - ImageryLayerCatalogItem.enableLayer.calls.argsFor(0)[1]; - expect(regionImageryProvider).toBeDefined(); - return regionImageryProvider.pickFeatures( - 3698, - 2513, - 12, - 2.5323739090365693, - -0.6604719122857645 - ); - }) - .then(function (r) { - expect(r[0].name).toEqual("3124"); - var description = r[0].description.getValue( - JulianDate.fromIso8601("2016-01-01T15:00:00Z") - ); - expect(description).toContain("alpha"); - expect(description).not.toContain("beta"); - expect(description).not.toContain("gamma"); - expect(description).not.toContain("omega"); - description = r[0].description.getValue( - JulianDate.fromIso8601("2016-01-02T15:00:00Z") - ); - expect(description).toContain("gamma"); - expect(description).not.toContain("delta"); - expect(description).not.toContain("alpha"); - expect(description).not.toContain("omega"); - description = r[0].description.getValue( - JulianDate.fromIso8601("2016-01-03T15:00:00Z") - ); - expect(description).toContain("omega"); - expect(description).not.toContain("zeta"); - expect(description).not.toContain("alpha"); - expect(description).not.toContain("beta"); - }) - .catch(fail) - .then(done); - }); - }); - }); -}); - -describe("CsvCatalogItem with no geo using default bundled regionMapping", function () { - var terria; - var csvItem; - beforeEach(function () { - terria = new Terria({ - baseUrl: "./" - }); - terria.configParameters.regionMappingDefinitionsUrl = - "data/regionMapping.json"; - - csvItem = new CsvCatalogItem(terria); - }); - - it("is not mappable", function (done) { - csvItem.url = "test/csv_nongeo/xy.csv"; - csvItem - .load() - .then(function () { - expect(csvItem.isMappable).toEqual(false); - expect(csvItem.regionMapping).toBeUndefined(); - expect(csvItem.tableStructure.name).toBe(""); - expect(csvItem.tableStructure.allowMultiple).toBe(true); - expect(csvItem.tableStructure.items.length).toBe(2); - }) - .catch(fail) - .then(done); - }); - - it("does not automatically enable a column if a table style is loaded in without a dataVariable", function (done) { - csvItem.url = "test/csv_nongeo/xy.csv"; - csvItem - .updateFromJson({ - tableStyle: { - dataVariable: "y" - } - }) - .then(function () { - return csvItem.load(); - }) - .then(function () { - expect(csvItem.tableStructure.activeItems.length).toEqual(1); - expect(csvItem.tableStructure.items.length).toEqual(2); - expect(csvItem.tableStructure.activeItems[0].name).toEqual("y"); - expect(csvItem.tableStructure.name).toBe(""); - expect(csvItem.tableStructure.allowMultiple).toBe(true); - }) - .then(function () { - csvItem.updateFromJson({ - tableStyle: { - allVariablesUnactive: true, - dataVariable: undefined - } - }); - }) - .then(function () { - expect(csvItem.isMappable).toEqual(false); - expect(csvItem.tableStructure.items.length).toEqual(2); - expect(csvItem.tableStructure.activeItems.length).toEqual(0); - }) - .catch(fail) - .then(done); - }); - - it("does not automatically enable a column if a table style is loaded in with columns all unactive", function (done) { - csvItem.url = "test/csv_nongeo/xy.csv"; - csvItem - .updateFromJson({ - tableStyle: { - allVariablesUnactive: true, - columns: { - 0: { - active: false - }, - 1: { - active: false - }, - 2: { - active: false - } - } - } - }) - .then(function () { - return csvItem.load(); - }) - .then(function () { - expect(csvItem.tableStructure.activeItems.length).toEqual(0); - expect(csvItem.tableStructure.items.length).toEqual(2); - expect(csvItem.tableStructure.name).toBe(""); - }) - .catch(fail) - .then(done); - }); - - it("interprets height column as non-geo", function (done) { - csvItem.url = "test/csv_nongeo/x_height.csv"; - csvItem - .load() - .then(function () { - expect(csvItem.isMappable).toBe(false); - expect( - csvItem.tableStructure.columnsByType[VarType.ALT].length - ).toEqual(0); - expect(csvItem.tableStructure.items.length).toBe(3); - }) - .catch(fail) - .then(done); - }); -}); - -describe("CsvCatalogItem & chart sharing", function () { - var terria; - var csvItem; - var columns; - - beforeEach(function () { - terria = new Terria({ - baseUrl: "./" - }); - csvItem = new CsvCatalogItem(terria); - }); - describe("disableIncompatibleTableColumn interaction", function () { - describe("should not disable other charted columns if there are no active columns in use", function () { - it("activates time series columns when loading the time series last", function (done) { - const xyCsv = new CsvCatalogItem(terria); - const timeSeriesCsv = new CsvCatalogItem(terria); - xyCsv - .updateFromJson({ - type: "csv", - url: "test/csv_nongeo/xy.csv", - isEnabled: true, - isShown: true - }) - .then(xyCsv.load.bind(xyCsv)) - .then(function () { - timeSeriesCsv.updateFromJson({ - type: "csv", - url: "test/csv_nongeo/time_series.csv", - isEnabled: true, - isShown: true - }); - }) - .then(timeSeriesCsv.load.bind(timeSeriesCsv)) - .then(function () { - expect(timeSeriesCsv.tableStructure.allowMultiple).toBe(true); - expect(xyCsv.tableStructure.allowMultiple).toBe(true); - expect(terria.catalog.chartableItems.length).toBe(2); - expect(timeSeriesCsv.tableStructure.activeItems.length).toBe(1); - expect(xyCsv.tableStructure.activeItems.length).toBe(0); - expect(timeSeriesCsv.xAxis.type).not.toBe(xyCsv.xAxis.type); - done(); - }); - }); - it("activates scalar columns when loading the time series first", function (done) { - const xyCsv = new CsvCatalogItem(terria); - const timeSeriesCsv = new CsvCatalogItem(terria); - timeSeriesCsv - .updateFromJson({ - type: "csv", - url: "test/csv_nongeo/time_series.csv", - isEnabled: true, - isShown: true - }) - .then(timeSeriesCsv.load.bind(timeSeriesCsv)) - .then(function () { - xyCsv.updateFromJson({ - type: "csv", - url: "test/csv_nongeo/xy.csv", - isEnabled: true, - isShown: true - }); - }) - .then(xyCsv.load.bind(xyCsv)) - .then(function () { - expect(timeSeriesCsv.tableStructure.allowMultiple).toBe(true); - expect(xyCsv.tableStructure.allowMultiple).toBe(true); - expect(terria.catalog.chartableItems.length).toBe(2); - expect(timeSeriesCsv.tableStructure.activeItems.length).toBe(0); - expect(xyCsv.tableStructure.activeItems.length).toBe(1); - expect(timeSeriesCsv.xAxis.type).not.toBe(xyCsv.xAxis.type); - // Do an update from json that triggers a 'toggleActiveCallback' - xyCsv.updateFromJson({ - tableStyle: { - dataVariable: "y" - } - }); - expect(timeSeriesCsv.tableStructure.activeItems.length).toBe(0); - expect(xyCsv.tableStructure.activeItems.length).toBe(1); - - // if we enable columns on timeSeries, then go ahead and - // tell the xyCsv to make sure it's disabled, the toggleActive callback - // shouldn't go ahead and disable the other charted items - timeSeriesCsv.updateFromJson({ - tableStyle: { - columns: { - 0: { - active: false - }, - 1: { - active: true - }, - 2: { - active: true - } - } - } - }); - xyCsv.updateFromJson({ - tableStyle: { - allVariablesUnactive: true - } - }); - - expect(timeSeriesCsv.tableStructure.activeItems.length).toBe(2); - expect(xyCsv.tableStructure.activeItems.length).toBe(0); - done(); - }); - }); - }); - // Catalog items get shown and hidden through traversing stories, ensure they're initialised correctly - describe("should not read an out of date state of tableStructure.activeItems when show is toggled", function () { - it("with time series csvs", function (done) { - const timeSeriesCsv = new CsvCatalogItem(terria); - timeSeriesCsv - .updateFromJson({ - type: "csv", - url: "test/csv_nongeo/time_series.csv", - isEnabled: true, - isShown: true - }) - .then(timeSeriesCsv.load.bind(timeSeriesCsv)) - .then(function () { - expect( - timeSeriesCsv.tableStyle.allVariablesUnactive - ).toBeUndefined(); - expect(timeSeriesCsv.tableStructure.items[1].isActive).toBe(true); - timeSeriesCsv.tableStyle.allVariablesUnactive = true; - expect(timeSeriesCsv.tableStructure.items[1].isActive).toBe(true); - timeSeriesCsv._show(); - expect(timeSeriesCsv.tableStructure.items[1].isActive).toBe(false); - - done(); - }); - }); - it("with scalar csvs", function (done) { - const xyCsv = new CsvCatalogItem(terria); - xyCsv - .updateFromJson({ - type: "csv", - url: "test/csv_nongeo/xy.csv", - isEnabled: true, - isShown: true - }) - .then(xyCsv.load.bind(xyCsv)) - .then(function () { - expect(xyCsv.tableStyle.allVariablesUnactive).toBeUndefined(); - expect(xyCsv.tableStructure.items[1].isActive).toBe(true); - xyCsv.tableStyle.allVariablesUnactive = true; - expect(xyCsv.tableStructure.items[1].isActive).toBe(true); - xyCsv._show(); - expect(xyCsv.tableStructure.items[1].isActive).toBe(false); - - done(); - }); - }); - }); - }); - describe("serialization around tableStyle & tableStructures for geo csvs", function () { - it("does not generate columns when allowMultiple is false", function (done) { - csvItem - .updateFromJson({ - type: "csv", - url: "test/csv/lat_lon_name_value.csv", - isEnabled: true, - isShown: true, - isvForCharting: false - }) - .then(csvItem.load.bind(csvItem)) - .then(function () { - expect(csvItem.tableStructure.allowMultiple).toBe(false); - expect(csvItem.isMappable).toBe(true); - var json = csvItem.serializeToJson(); - expect(json.columns).toBeUndefined(); - }) - .then(done) - .catch(done.fail); - }); - it("toggles the selected dataVariable in tablestructure from updateFromJson (e.g. story-transitions)", function (done) { - csvItem - .updateFromJson({ - type: "csv", - url: "test/csv/lat_lon_name_value.csv", - isEnabled: true, - isShown: true, - isCsvForCharting: false - }) - .then(csvItem.load.bind(csvItem)) - .then(function () { - expect(csvItem.isMappable).toEqual(true); - expect(csvItem.concepts[0].activeItems.length).toEqual(1); - expect(csvItem.concepts[0].activeItems[0].name).toEqual("value"); - }) - .then(function () { - csvItem.updateFromJson({ - tableStyle: { - dataVariable: "name" - } - }); - }) - .then(function () { - expect(csvItem.isMappable).toEqual(true); - expect(csvItem.concepts[0].activeItems.length).toEqual(1); - expect(csvItem.concepts[0].activeItems[0].name).toEqual("name"); - }) - .then(done) - .catch(done.fail); - }); - }); - describe("serialization around tableStyle & tableStructures for non-geo time series csvs", function () { - it("can be round-tripped with serializeToJson and updateFromJson", function () { - columns = { - 0: { - active: false - }, - 1: { - active: false - }, - 2: { - active: false - } - }; - csvItem.updateFromJson({ - type: "csv", - url: "test/csv_nongeo/time_series.csv", - isEnabled: true, - isShown: true, - isCsvForCharting: true, - tableStyle: { - columns: columns - } - }); - - var json = csvItem.serializeToJson(); - - var reconstructed = new CsvCatalogItem(terria); - reconstructed.updateFromJson(json); - - expect(reconstructed.type).toEqual(csvItem.type); - expect(reconstructed.url).toEqual(csvItem.url); - expect(reconstructed.isEnabled).toEqual(csvItem.isEnabled); - expect(reconstructed.isShown).toEqual(csvItem.isShown); - expect(reconstructed.isCsvForCharting).toEqual(csvItem.isCsvForCharting); - - expect(reconstructed.tableStyle.columns[0].active).toBe( - columns[0].active - ); - expect(reconstructed.tableStyle.columns[1].active).toBe( - columns[1].active - ); - expect(reconstructed.tableStyle.columns[2].active).toBe( - columns[2].active - ); - }); - it("serializes the dataurl for sharing if url does not exist", function () { - columns = { - 0: { - active: false - }, - 1: { - active: false - }, - 2: { - active: false - } - }; - const dataUrl = - "data:attachment/csv,Time%2CCapacity%2CPower%0A2015-10-19T00%3A10%3A00%2B1000%2C0.1%2C0.085%0A2015-10-19T01%3A15%3A00%2B1000%2C0.2%2C0.14%0A2015-10-19T02%3A20%3A00%2B1000%2C0.3%2C0.3%0A2015-10-19T03%3A25%3A00%2B1000%2C0%2C0%0A2015-10-19T04%3A30%3A00%2B1000%2C0.1%2C0%0A2015-10-19T05%3A35%3A00%2B1000%2C-0.4%2C0%0A2015-10-19T06%3A40%3A00%2B1000%2C0.4%2C0.3%0A2015-10-19T07%3A45%3A00%2B1000%2C0.1%2C0.1"; - csvItem.updateFromJson({ - type: "csv", - dataUrl: dataUrl, - isEnabled: true, - isShown: true, - isCsvForCharting: true, - tableStyle: { - columns: columns - } - }); - - var json = csvItem.serializeToJson(); - expect(json.dataUrl).toEqual(dataUrl); - - var reconstructed = new CsvCatalogItem(terria); - reconstructed.updateFromJson(json); - - expect(reconstructed.type).toEqual(csvItem.type); - expect(reconstructed.url).toBeUndefined(); - expect(reconstructed.dataUrl).toEqual(dataUrl); - expect(reconstructed.isEnabled).toEqual(csvItem.isEnabled); - expect(reconstructed.isShown).toEqual(csvItem.isShown); - expect(reconstructed.isCsvForCharting).toEqual(csvItem.isCsvForCharting); - expect(reconstructed.tableStyle.columns[0].active).toBe( - columns[0].active - ); - expect(reconstructed.tableStyle.columns[1].active).toBe( - columns[1].active - ); - expect(reconstructed.tableStyle.columns[2].active).toBe( - columns[2].active - ); - }); - it("generates columns on a table style on serialization for chartable items, when a CsvCatalogItem is created without them", function (done) { - columns = { - 0: { - active: false - }, - 1: { - active: false - }, - 2: { - active: true - } - }; - - csvItem.updateFromJson({ - type: "csv", - url: "test/csv_nongeo/time_series.csv", - isEnabled: true, - isShown: true, - isCsvForCharting: false - }); - - expect(csvItem.tableStyle.columns).toBeUndefined(); - - csvItem - .load() - .then(function () { - // loaded in with 1 active item, - expect(csvItem.isMappable).toBe(false); - expect(csvItem.concepts[0].allowMultiple).toEqual(true); - expect(csvItem.concepts[0].activeItems.length).toEqual(1); - expect(csvItem.concepts[0].items.length).toEqual(3); - expect(csvItem.concepts[0].items[0].isActive).toEqual(false); - expect(csvItem.concepts[0].items[1].isActive).toEqual(true); - expect(csvItem.concepts[0].items[2].isActive).toEqual(false); - - // deselect first and choose the second item - csvItem.concepts[0].items[1].toggleActive(); - csvItem.concepts[0].items[2].toggleActive(); - expect(csvItem.concepts[0].items[1].isActive).toEqual(false); - expect(csvItem.concepts[0].items[2].isActive).toEqual(true); - - var json = csvItem.serializeToJson(); - - var reconstructed = new CsvCatalogItem(terria); - reconstructed.updateFromJson(json); - expect(reconstructed.tableStyle.columns[0].active).toBe( - columns[0].active - ); - expect(reconstructed.tableStyle.columns[1].active).toBe( - columns[1].active - ); - expect(reconstructed.tableStyle.columns[2].active).toBe( - columns[2].active - ); - expect(reconstructed.tableStyle.columns[1].chartLineColor).toBe( - reconstructed.colors[0] - ); - expect(reconstructed.tableStyle.columns[2].chartLineColor).toBe( - reconstructed.colors[1] - ); - - // try with 2 active item selected - csvItem.concepts[0].items[1].toggleActive(); - expect(csvItem.concepts[0].items[1].isActive).toEqual(true); - expect(csvItem.concepts[0].items[2].isActive).toEqual(true); - var json2 = csvItem.serializeToJson(); - var reconstructed2 = new CsvCatalogItem(terria); - reconstructed2.updateFromJson(json2); - expect(reconstructed2.tableStyle.columns[0].active).toBe(false); - expect(reconstructed2.tableStyle.columns[1].active).toBe(true); - expect(reconstructed2.tableStyle.columns[2].active).toBe(true); - expect(reconstructed2.tableStyle.columns[1].chartLineColor).toBe( - reconstructed2.colors[0] - ); - expect(reconstructed2.tableStyle.columns[2].chartLineColor).toBe( - reconstructed2.colors[1] - ); - }) - .then(done) - .catch(done.fail); - }); - - it("initialises and shares the correct 'no variables selected' state", function (done) { - columns = { - 0: { - active: false - }, - 1: { - active: false - }, - 2: { - active: false - } - }; - // the flow for shared csv items is that the tableStyle is serialised - csvItem - .updateFromJson({ - type: "csv", - url: "test/csv_nongeo/time_series.csv", - isEnabled: true, - isShown: true, - isCsvForCharting: true, - tableStyle: { - columns: columns - } - }) - .then(function () { - expect(csvItem.tableStyle.columns[0].active).toBe(columns[0].active); - expect(csvItem.tableStyle.columns[1].active).toBe(columns[1].active); - expect(csvItem.tableStyle.columns[2].active).toBe(columns[2].active); - }) - .then(csvItem.load.bind(csvItem)) - .then(function () { - const tableStructure = csvItem.concepts[0]; - expect(tableStructure.items[0].isActive).toBe(false); - expect(tableStructure.items[1].isActive).toBe(true); - expect(tableStructure.items[2].isActive).toBe(false); - - // we apply table style columns to structure when loading from a shared (chart) catalog item - csvItem.applyTableStyleColumnsToStructure( - { columns: columns }, - csvItem.tableStructure - ); - - // Check that the table structure now overrode and reflects the columnstyle provided - expect(tableStructure.items[0].isActive).toBe(false); - expect(tableStructure.items[1].isActive).toBe(false); - expect(tableStructure.items[2].isActive).toBe(false); - expect(tableStructure.activeItems.length).toBe(0); - }) - .then(function () { - const serialized = csvItem.serializeToJson(); - expect(serialized.tableStyle.allVariablesUnactive).toBe(true); - expect(serialized.tableStyle.columns[0].active).toBe(false); - expect(serialized.tableStyle.columns[1].active).toBe(false); - expect(serialized.tableStyle.columns[2].active).toBe(false); - }) - .then(done) - .catch(done.fail); - }); - it("initialises the correct 'second variable is selected' state & shares newly toggled state", function (done) { - columns = { - 0: { - active: false - }, - 1: { - active: false - }, - 2: { - active: true - } - }; - // the flow for shared csv items is that the tableStyle is serialised - csvItem - .updateFromJson({ - type: "csv", - url: "test/csv_nongeo/time_series.csv", - isEnabled: true, - isShown: true, - isCsvForCharting: true, - tableStyle: { - columns: columns - } - }) - .then(function () { - expect(csvItem.tableStyle.columns[0].active).toBe(columns[0].active); - expect(csvItem.tableStyle.columns[1].active).toBe(columns[1].active); - expect(csvItem.tableStyle.columns[2].active).toBe(columns[2].active); - }) - .then(csvItem.load.bind(csvItem)) - .then(function () { - // because we load in non-geospatial data, and there are activeItems - // ensureActiveColumnForNonSpatial() shouldn't change active columns - const tableStructure = csvItem.concepts[0]; - expect(tableStructure.items[0].isActive).toBe(false); - expect(tableStructure.items[1].isActive).toBe(false); - expect(tableStructure.items[2].isActive).toBe(true); - - // toggleActive on tableStructure items do not reflect back into table styles - tableStructure.items[1].toggleActive(); - expect(tableStructure.items[1].isActive).toBe(true); - - // should have two active items on tableStructure now - expect(tableStructure.items[0].isActive).toBe(false); - expect(tableStructure.items[1].isActive).toBe(true); - expect(tableStructure.items[2].isActive).toBe(true); - - // however active should still be false on !tableStyle! until we sync changes - expect(csvItem.tableStyle.columns[0].active).toBe(false); - expect(csvItem.tableStyle.columns[1].active).toBe(false); - expect(csvItem.tableStyle.columns[2].active).toBe(true); - - // trigger a syncActiveColumns through serialization - const serialized = csvItem.serializeToJson(); - expect(csvItem.tableStyle.columns[0].active).toBe(false); - expect(csvItem.tableStyle.columns[1].active).toBe(true); - expect(csvItem.tableStyle.columns[2].active).toBe(true); - expect(serialized.tableStyle.allVariablesUnactive).toBe(undefined); - expect(serialized.tableStyle.columns[0].active).toBe(false); - expect(serialized.tableStyle.columns[1].active).toBe(true); - expect(serialized.tableStyle.columns[2].active).toBe(true); - }) - .then(done) - .catch(done.fail); - }); - }); - describe("load behaviour around SensorObservationServiceCatalogItem generated csvs", function () { - var sosItem; - var tableStructure; - beforeEach(function () { - terria = new Terria({ - baseUrl: "./" - }); - csvItem = new CsvCatalogItem(terria); - tableStructure = new TableStructure(); - sosItem = new SensorObservationServiceCatalogItem(terria); - sosItem.id = "SosItem"; - terria.catalog.group.add(sosItem); - }); - it("attempts a load when `data` property is not undefined", function (done) { - csvItem - .updateFromJson({ - type: "csv", - url: "test/data/service/at/SOMEIDENTIFIER101", // this url shouldn't be utilised at all - sourceCatalogItemId: "SosItem", - regenerationOptions: { - // also does nothing for the test but required for sos chart sharing - procedure: { - identifier: - "http://test.domain/test/data/service/tstypes/YearlyMean", - title: "Annual+average", - defaultDuration: "40y" - } - }, - isEnabled: true, - isShown: true, - isCsvForCharting: true, - tableStyle: { - columns: {} - } - }) - .then(function () { - csvItem.data = Promise.resolve(tableStructure); - }) - .then(csvItem.load.bind(csvItem)) - .then(function () { - expect(csvItem.tableStructure).toEqual(tableStructure); - }) - .then(done) - .catch(done.fail); - }); - it("does not load when we haven't defined how to load it via the csv's `data` property", function (done) { - csvItem - .updateFromJson({ - type: "csv", - url: "test/data/service/at/SOMEIDENTIFIER101", // this url shouldn't be utilised at all - sourceCatalogItemId: "SosItem", - isEnabled: true, - isShown: true, - isCsvForCharting: true, - tableStyle: { - columns: {} - } - }) - .then(csvItem.load.bind(csvItem)) - .then(function () { - expect(csvItem.tableStructure).toBeUndefined(); - }) - .then(done) - .catch(done.fail); - }); - }); -}); diff --git a/test/Models/Catalog/CatalogSpec.js b/test/Models/Catalog/CatalogSpec.js deleted file mode 100644 index d2fcb43d8eb..00000000000 --- a/test/Models/Catalog/CatalogSpec.js +++ /dev/null @@ -1,336 +0,0 @@ -"use strict"; - -var Terria = require("../../../lib/Models/Terria"); -var loadJson = require("../../../lib/Core/loadJson").default; -var CHART_DATA_CATEGORY_NAME = - require("../../../lib/Core/addedForCharts").CHART_DATA_CATEGORY_NAME; - -var Catalog = require("../../lib/Models/Catalog"); -var CatalogItem = require("../../lib/Models/CatalogItem"); -var createCatalogMemberFromType = require("../../../lib/Models/Catalog/createCatalogMemberFromType"); -var CatalogGroup = require("../../lib/Models/CatalogGroup"); -var GeoJsonCatalogItem = require("../../../lib/Models/Catalog/CatalogItems/GeoJsonCatalogItem"); -var ImageryLayerCatalogItem = require("../../lib/Models/ImageryLayerCatalogItem"); -var WebMapServiceCatalogItem = require("../../../lib/Models/Catalog/Ows/WebMapServiceCatalogItem"); - -describe("Catalog", function () { - var terria; - var catalog; - - beforeEach(function () { - terria = new Terria({ - baseUrl: "./" - }); - createCatalogMemberFromType.register("group", CatalogGroup); - createCatalogMemberFromType.register("item", CatalogItem); - createCatalogMemberFromType.register( - "imageryLayerCatalogItem", - ImageryLayerCatalogItem - ); - createCatalogMemberFromType.register("wms", WebMapServiceCatalogItem); - catalog = terria.catalog; - }); - - it("can register group and geojson, and update from json", function (done) { - createCatalogMemberFromType.register("geojson", GeoJsonCatalogItem); - - loadJson("test/init/geojson-with-template.json") - .then(function (json) { - var catalog = new Catalog(terria); - catalog - .updateFromJson(json.catalog) - .then(function () { - expect(catalog.group.constructor).toEqual(CatalogGroup); - expect(catalog.group.items[0].constructor).toEqual(CatalogGroup); - expect(catalog.group.items[0].items[0].constructor).toEqual( - GeoJsonCatalogItem - ); - done(); - }) - .catch(done.fail); - }) - .catch(done.fail); - }); - - describe("chartDataGroup", function () { - it("returns the group used for chart data when retrieved via chartDataGroup", function () { - const group = catalog.chartDataGroup; - expect(group.name).toBe(CHART_DATA_CATEGORY_NAME); - expect(group.type).toBe("group"); - expect(group.description).toBe("A group for chart data."); - expect(group.isUserSupplied).toBe(true); - }); - }); - - describe("updateByShareKeys", function () { - it("works when resolving by id", function (done) { - catalog - .updateFromJson([ - { - name: "A", - type: "group", - items: [ - { - id: "C", - name: "C", - type: "item", - isEnabled: false - } - ] - }, - { - name: "B", - type: "group" - } - ]) - .then(function () { - expect(catalog.group.items[0].items[0].isEnabled).toBe(false); - expect(catalog.group.items[0].isOpen).toBeFalsy(); - expect(catalog.group.isOpen).toBeFalsy(); - - return catalog.updateByShareKeys({ C: {} }); - }) - .then(function () { - expect(catalog.group.items[0].items[0].isEnabled).toBe(true); - expect(catalog.group.items[0].isOpen).toBeTruthy(); - expect(catalog.group.isOpen).toBeTruthy(); - done(); - }) - .catch(fail); - }); - - it("works when resolving by shareKeys", function (done) { - catalog - .updateFromJson([ - { - name: "A", - type: "group", - items: [ - { - id: "blah", - shareKeys: ["C"], - name: "C", - type: "item", - isEnabled: false - } - ] - }, - { - name: "B", - type: "group" - } - ]) - .then(function () { - expect(catalog.group.items[0].items[0].isEnabled).toBe(false); - expect(catalog.group.items[0].isOpen).toBeFalsy(); - expect(catalog.group.isOpen).toBeFalsy(); - - return catalog.updateByShareKeys({ C: {} }); - }) - .then(function () { - expect(catalog.group.items[0].items[0].isEnabled).toBe(true); - expect(catalog.group.items[0].isOpen).toBeTruthy(); - expect(catalog.group.isOpen).toBeTruthy(); - done(); - }) - .catch(fail); - }); - - it("opens parent groups", function (done) { - catalog - .updateFromJson([ - { - name: "A", - type: "group", - items: [ - { - id: "C", - name: "C", - type: "item" - } - ] - }, - { - name: "B", - type: "group" - } - ]) - .then(function () { - return catalog.updateByShareKeys({ C: {} }); - }) - .then(function () { - expect(catalog.group.items[0].isOpen).toBe(true); - expect(catalog.group.isOpen).toBe(true); - done(); - }) - .catch(fail); - }); - - it("works for multiple share keys", function (done) { - catalog - .updateFromJson([ - { - name: "A", - type: "group", - items: [ - { - id: "C", - name: "C", - type: "item" - } - ] - }, - { - name: "B", - type: "group", - items: [ - { - id: "D", - name: "D", - type: "item" - } - ] - } - ]) - .then(function () { - return catalog.updateByShareKeys({ C: {}, D: {} }); - }) - .then(function () { - expect(catalog.group.items[0].items[0].isEnabled).toBe(true); - expect(catalog.group.items[1].items[0].isEnabled).toBe(true); - done(); - }) - .catch(fail); - }); - - it("only enabled a catalog member after all those before it have finished loading", function (done) { - catalog - .updateFromJson([ - { - name: "A", - type: "group" - } - ]) - .then(function () { - expect(catalog.group.items[0].items.length).toBe(0); - - spyOn(catalog.group.items[0], "load").and.returnValue( - catalog.group.items[0].updateFromJson({ - items: [ - { - id: "C", - name: "C", - type: "item" - } - ] - }) - ); - - return catalog.updateByShareKeys({ "Root Group/A": {}, C: {} }); - }) - .then(function () { - expect(catalog.group.items[0].items[0].isEnabled).toBe(true); - done(); - }) - .catch(fail); - }); - - it("updates associated shared data like opacity", function (done) { - catalog - .updateFromJson([ - { - name: "A", - type: "imageryLayerCatalogItem" - } - ]) - .then(function () { - expect(catalog.group.items[0].opacity).not.toBe(0.3); - - return catalog.updateByShareKeys({ - "Root Group/A": { - opacity: 0.3 - } - }); - }) - .then(function () { - expect(catalog.group.items[0].opacity).toBe(0.3); - done(); - }) - .catch(fail); - }); - }); - - describe("serializeToJson", function () { - beforeEach(function (done) { - catalog - .updateFromJson([ - { - name: "A", - type: "group", - items: [ - { - id: "C", - name: "C", - type: "wms" - } - ] - }, - { - name: "B", - type: "group", - items: [ - { - id: "D", - name: "D", - type: "wms" - } - ] - } - ]) - .then(done); - }); - - it("serializes the catalog recursively", function () { - var serialized = catalog.serializeToJson(); - - expect(serialized.length).toBe(2); - expect(serialized[0].name).toBe("A"); - expect(serialized[1].items.length).toBe(1); - expect(serialized[1].items[0].name).toBe("D"); - }); - - it("can round-trip a basic catalog", function (done) { - var serialized = catalog.serializeToJson(); - var newCatalog = new Catalog(terria); - newCatalog - .updateFromJson(serialized) - .then(function () { - expect(newCatalog.items).toEqual(catalog.items); - done(); - }) - .catch(fail); - }); - - it("ignores properties filtered out by propertyFilter", function () { - var serialized = catalog.serializeToJson({ - propertyFilter: function (property, item) { - return property !== "name"; - } - }); - - expect(serialized[0].name).toBeUndefined(); - expect(serialized[0].id).toBe("Root Group/A"); - }); - - it("ignores items filtered out by itemFilter", function () { - var serialized = catalog.serializeToJson({ - itemFilter: function (item) { - return item.name !== "C"; - } - }); - - expect(serialized[0].items.length).toBe(0); - expect(serialized[1].items.length).toBe(1); - }); - }); -}); diff --git a/test/Models/Catalog/Ows/CswCatalogGroupSpec.ts b/test/Models/Catalog/Ows/CswCatalogGroupSpec.ts index ae4910984c2..ca7b25a63e8 100644 --- a/test/Models/Catalog/Ows/CswCatalogGroupSpec.ts +++ b/test/Models/Catalog/Ows/CswCatalogGroupSpec.ts @@ -1,5 +1,3 @@ -"use strict"; - import Terria from "../../../../lib/Models/Terria"; import CswCatalogGroup from "../../../../lib/Models/Catalog/Ows/CswCatalogGroup"; diff --git a/test/Models/CesiumSpec.ts b/test/Models/CesiumSpec.ts index 21b535143a1..a73249ebffc 100644 --- a/test/Models/CesiumSpec.ts +++ b/test/Models/CesiumSpec.ts @@ -24,8 +24,7 @@ import MappableTraits, { RectangleTraits } from "../../lib/Traits/TraitsClasses/MappableTraits"; import TerriaViewer from "../../lib/ViewModels/TerriaViewer"; - -const supportsWebGL = require("../../lib/Core/supportsWebGL"); +import supportsWebGL from "../../lib/Core/supportsWebGL"; const describeIfSupported = supportsWebGL() ? describe : xdescribe; diff --git a/test/Models/NowViewingSpec.js b/test/Models/NowViewingSpec.js deleted file mode 100644 index 993377a3972..00000000000 --- a/test/Models/NowViewingSpec.js +++ /dev/null @@ -1,134 +0,0 @@ -"use strict"; - -var NowViewing = require("../../lib/Models/NowViewing"); -var Terria = require("../../lib/Models/Terria"); -var Cesium = require("../../lib/Models/Cesium"); -var CesiumWidget = - require("terriajs-cesium/Source/Widgets/CesiumWidget/CesiumWidget").default; -var Leaflet = require("../../lib/Models/Leaflet"); -var L = require("leaflet"); -var CatalogItem = require("../../lib/Models/CatalogItem"); -var supportsWebGL = require("../../lib/Core/supportsWebGL"); -var TileCoordinatesImageryProvider = - require("terriajs-cesium/Source/Scene/TileCoordinatesImageryProvider").default; - -describe("NowViewing without a viewer", function () { - var terria; - var nowViewing; - - beforeEach(function () { - terria = new Terria({ - baseUrl: "./" - }); - nowViewing = new NowViewing(terria); - }); - - it("can add an item", function () { - var item = new CatalogItem(terria); - expect(nowViewing.items.length).toEqual(0); - nowViewing.add(item); - expect(nowViewing.items.length).toEqual(1); - }); -}); - -var describeIfSupported = supportsWebGL() ? describe : xdescribe; - -// only run these tests if the browser supports WebGL -// the browser may still not show WebGL properly - see TerriaViewer.js for a more precise test if needed - -describeIfSupported("NowViewing with a minimal Cesium viewer", function () { - var container; - var widget; - var cesium; - var terria; - var nowViewing; - - beforeEach(function () { - container = document.createElement("div"); - document.body.appendChild(container); - - widget = new CesiumWidget(container, { - imageryProvider: new TileCoordinatesImageryProvider() - }); - terria = new Terria({ - baseUrl: "./" - }); - cesium = new Cesium(terria, widget); - terria.currentViewer = cesium; - terria.cesium = cesium; - nowViewing = terria.nowViewing; - }); - - afterEach(function () { - if (widget && !widget.isDestroyed()) { - widget = widget.destroy(); - } - document.body.removeChild(container); - }); - - it("can raise an item", function () { - var item1 = new CatalogItem(terria); - var item2 = new CatalogItem(terria); - nowViewing.add(item1); - nowViewing.add(item2); - expect(nowViewing.items.indexOf(item1)).toEqual(1); - nowViewing.raise(item1); - expect(nowViewing.items.indexOf(item1)).toEqual(0); - }); - - it("can lower an item", function () { - var item1 = new CatalogItem(terria); - var item2 = new CatalogItem(terria); - nowViewing.add(item1); - nowViewing.add(item2); - expect(nowViewing.items.indexOf(item1)).toEqual(1); - nowViewing.lower(item2); - expect(nowViewing.items.indexOf(item1)).toEqual(0); - }); -}); - -describe("NowViewing with a minimal Leaflet viewer", function () { - var container; - var leaflet; - var terria; - var nowViewing; - - beforeEach(function () { - terria = new Terria({ - baseUrl: "./" - }); - container = document.createElement("div"); - container.id = "container"; - document.body.appendChild(container); - var map = L.map("container").setView([-28.5, 135], 5); - - leaflet = new Leaflet(terria, map); - terria.currentViewer = leaflet; - terria.leaflet = leaflet; - nowViewing = terria.nowViewing; - }); - - afterEach(function () { - document.body.removeChild(container); - }); - - it("can raise an item", function () { - var item1 = new CatalogItem(terria); - var item2 = new CatalogItem(terria); - nowViewing.add(item1); - nowViewing.add(item2); - expect(nowViewing.items.indexOf(item1)).toEqual(1); - nowViewing.raise(item1); - expect(nowViewing.items.indexOf(item1)).toEqual(0); - }); - - it("can lower an item", function () { - var item1 = new CatalogItem(terria); - var item2 = new CatalogItem(terria); - nowViewing.add(item1); - nowViewing.add(item2); - expect(nowViewing.items.indexOf(item1)).toEqual(1); - nowViewing.lower(item2); - expect(nowViewing.items.indexOf(item1)).toEqual(0); - }); -}); diff --git a/test/ReactViews/FeatureInfoPanelSpec.tsx b/test/ReactViews/FeatureInfoPanelSpec.tsx index f41c6deeb2f..a4a61e9b2e2 100644 --- a/test/ReactViews/FeatureInfoPanelSpec.tsx +++ b/test/ReactViews/FeatureInfoPanelSpec.tsx @@ -1,5 +1,3 @@ -"use strict"; - // import knockout from 'terriajs-cesium/Source/ThirdParty/knockout'; import React from "react"; import { findWithType } from "react-shallow-testutils"; diff --git a/test/ViewModels/updateApplicationOnMessageFromParentWindowSpec.js b/test/ViewModels/updateApplicationOnMessageFromParentWindowSpec.js deleted file mode 100644 index 8ad1f3b06f1..00000000000 --- a/test/ViewModels/updateApplicationOnMessageFromParentWindowSpec.js +++ /dev/null @@ -1,118 +0,0 @@ -"use strict"; - -var CatalogGroup = require("../../lib/Models/CatalogGroup"); -var createCatalogMemberFromType = require("../../lib/Models/Catalog/createCatalogMemberFromType"); -var Terria = require("../../lib/Models/Terria"); -var updateApplicationOnMessageFromParentWindow = require("../../lib/ViewModels/updateApplicationOnMessageFromParentWindow"); - -describe("updateApplicationOnMessageFromParentWindow", function () { - var terria; - var fakeWindow; - - beforeEach(function () { - terria = new Terria({ - baseUrl: "./" - }); - createCatalogMemberFromType.register("group", CatalogGroup); - - fakeWindow = jasmine.createSpyObj("window", ["addEventListener"]); - fakeWindow.parent = jasmine.createSpyObj("parentWindow", ["postMessage"]); - }); - - it("subscribes to messages", function () { - updateApplicationOnMessageFromParentWindow(terria, fakeWindow); - expect(fakeWindow.addEventListener.calls.count()).toBe(1); - expect(fakeWindow.addEventListener.calls.first().args[0]).toBe("message"); - }); - - it("posts a message to its parent when ready", function () { - updateApplicationOnMessageFromParentWindow(terria, fakeWindow); - expect(fakeWindow.parent.postMessage.calls.count()).toBe(1); - expect(fakeWindow.parent.postMessage.calls.first().args).toEqual([ - "ready", - "*" - ]); - }); - - it("updates the model when it receives a message from the parent", function () { - var messageEventHandler; - fakeWindow.addEventListener.and.callFake(function (eventName, callback) { - messageEventHandler = callback; - }); - updateApplicationOnMessageFromParentWindow(terria, fakeWindow); - - messageEventHandler({ - source: fakeWindow.parent, - data: { - initSources: [ - { - catalog: [ - { - name: "Foo", - type: "group" - } - ] - } - ] - } - }); - - var fooGroup = terria.catalog.group.findFirstItemByName("Foo"); - expect(fooGroup).toBeDefined(); - expect(fooGroup.type).toBe("group"); - }); - - it("updates the model when it receives a message from the opener", function () { - var messageEventHandler; - fakeWindow.addEventListener.and.callFake(function (eventName, callback) { - messageEventHandler = callback; - }); - updateApplicationOnMessageFromParentWindow(terria, fakeWindow); - - messageEventHandler({ - opener: fakeWindow.parent, - data: { - initSources: [ - { - catalog: [ - { - name: "Foo", - type: "group" - } - ] - } - ] - } - }); - - var fooGroup = terria.catalog.group.findFirstItemByName("Foo"); - expect(fooGroup).toBeDefined(); - expect(fooGroup.type).toBe("group"); - }); - - it("ignores messages that are not from its parent or opener window", function () { - var messageEventHandler; - fakeWindow.addEventListener.and.callFake(function (eventName, callback) { - messageEventHandler = callback; - }); - updateApplicationOnMessageFromParentWindow(terria, fakeWindow); - - messageEventHandler({ - source: {}, - data: { - initSources: [ - { - catalog: [ - { - name: "Foo", - type: "group" - } - ] - } - ] - } - }); - - expect(terria.catalog.group.findFirstItemByName("Foo")).not.toBeDefined(); - }); -});