forked from datacommonsorg/website
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutil.ts
More file actions
259 lines (236 loc) · 7.61 KB
/
util.ts
File metadata and controls
259 lines (236 loc) · 7.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
/**
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import _ from "lodash";
import { URLSearchParams } from "url";
import { Theme } from "../theme/types";
import { MAX_DATE, MAX_YEAR, SOURCE_DISPLAY_NAME } from "./constants";
// This has to be in sync with server/__init__.py
export const placeExplorerCategories = [
"economics",
"health",
"equity",
"crime",
"education",
"demographics",
"housing",
"environment",
"energy",
"health_new",
"energy_new",
"crime_new",
"demographics_new",
"economics_new",
];
const SEARCH_PARAMS_TO_PROPAGATE = new Set(["hl"]);
const NO_DATE_CAP_RCP_STATVARS = [
// This stat var only has data for 2100. while other stat vars along the same
// lines (eg. NumberOfMonths_5CelsiusOrMore_Percentile90AcrossModels_) have
// data for 2030, 2050, and 2100 so we want to cap the date for those at 2050.
"NumberOfMonths_5CelsiusOrMore_Percentile10AcrossModels_",
// These stat vars compare against historical observed data, so we do not want
// to hardcode the default date.
"DifferenceRelativeToObservationalData_",
// These SVs are not a time-series, but a single value across multi-decadal time-horizons.
"ProjectedMax_Until_",
"ProjectedMin_Until_",
// All PDF probability projections should be excluded.
"PctProb_",
];
// used to set fields in an object
export interface Setter<T> {
(value: T): void;
}
export function randDomId(): string {
return Math.random()
.toString(36)
.replace(/[^a-z]+/g, "")
.substr(2, 10);
}
/** Determines if the width corresponds to mobile based on themes. */
export function isMobileByWidth(theme: Theme | null): boolean {
if (theme === null) {
return false;
}
return window.innerWidth <= (theme?.breakpoints?.sm ?? 768);
}
/**
* Downloads a file under a given filename.
* @param filename name to download the file to
* @param file the file to download
*/
export function downloadFile(fileName: string, file: Blob | File): void {
const link = document.createElement("a");
const url = window.URL.createObjectURL(file);
link.setAttribute("href", url);
link.setAttribute("download", fileName);
link.onclick = (): void => {
setTimeout(() => window.URL.revokeObjectURL(url));
};
link.click();
link.remove();
}
/**
* Saves csv to filename.
* @param {filename} string
* @param {contents} string
* @return void
*/
export function saveToFile(filename: string, contents: string): void {
let mimeType = "text/plain";
if (filename.match(/\.csv$/i)) {
mimeType = "text/csv;charset=utf-8";
} else if (filename.match(/\.svg$/i)) {
mimeType = "image/svg+xml;charset=utf-8";
}
const blob = new Blob([contents], { type: mimeType });
downloadFile(filename, blob);
}
/**
* Get display text from a url.
*/
export function urlToDisplayText(url: string): string {
if (!url) {
return "";
}
if (url in SOURCE_DISPLAY_NAME) {
return SOURCE_DISPLAY_NAME[url];
}
// Use domain as the default display name
return url
.replace("http://", "")
.replace("https://", "")
.replace("www.", "")
.split(/[/?#]/)[0];
}
export function isDateTooFar(date: string): boolean {
return date.slice(0, 4) > MAX_YEAR;
}
/**
* Hack for handling stat vars with dates with (predicted) dates in the future.
* If a defaultDate is specified, always return that.
* If variable has future observations, return either MAX_YEAR or MAX_DATE
* Otherwise, return ""
* TODO: Find a better way to accomodate variables with dates in the future
*/
export function getCappedStatVarDate(
statVarDcid: string,
defaultDate = ""
): string {
if (defaultDate) {
return defaultDate;
}
// Only want to cap stat var date for stat vars with RCP or SSP.
if (!statVarDcid.includes("_RCP") && !statVarDcid.includes("_SSP")) {
return "";
}
for (const svSubstring of NO_DATE_CAP_RCP_STATVARS) {
if (statVarDcid.includes(svSubstring)) {
return "";
}
}
// Wet bulb temperature is observed at P1Y, so need to use year for the date.
if (
statVarDcid.includes("WetBulbTemperature") ||
statVarDcid.includes("AggregateMin_Percentile") ||
statVarDcid.includes("AggregateMax_Percentile") ||
statVarDcid.includes("AggregateMin_Median") ||
statVarDcid.includes("AggregateMax_Median") ||
statVarDcid.includes("NumberOfMonths_")
) {
return MAX_YEAR;
}
return MAX_DATE;
}
/**
* Makes the spinner visible if there is one within the specific container with the given id.
* @param containerId the id of the container to show spinner in
*/
export function loadSpinner(containerId: string): void {
const container = document.getElementById(containerId);
if (container) {
const browserScreens = container.getElementsByClassName("screen");
if (!_.isEmpty(browserScreens)) {
browserScreens[0].classList.add("d-block");
}
}
}
/**
* Removes the spinner if there is one within the specific container with the given id.
* @param containerId the id of the container to remove spinner from
*/
export function removeSpinner(containerId: string): void {
const container = document.getElementById(containerId);
if (container) {
const browserScreens = container.getElementsByClassName("screen");
if (!_.isEmpty(browserScreens)) {
browserScreens[0].classList.remove("d-block");
}
}
}
/**
* Removes the pattern parameter from the query if that substring is present at the end.
* @param query the string from which to remove the pattern
* @param pattern a string which we want to find and remove from the query.
* @returns the query with the pattern removed if it was found.
*/
export function stripPatternFromQuery(query: string, pattern: string): string {
const regex = new RegExp("(?:.(?!" + pattern + "))+([,;\\s])?$", "i");
// Returns the query without the pattern parameter.
// E.g.: query: "population of Calif", pattern: "Calif",
// returns "population of "
return query.replace(regex, "");
}
/**
* Extracts all flags to propagate from the URL.
*/
export function extractFlagsToPropagate(url: string): URLSearchParams {
try {
const parsedUrl = new URL(url);
const searchParams = parsedUrl.searchParams;
for (const key of searchParams.keys()) {
if (!SEARCH_PARAMS_TO_PROPAGATE.has(key)) {
searchParams.delete(key);
}
}
return searchParams;
} catch (error) {
console.error("Invalid URL provided:", error);
return new URLSearchParams();
}
}
/**
* Redirects to the destination URL while preserving the URL parameters in the originURL.
*
* @param originUrl Current URL from which to extract URL parameters
* @param destinationUrl Desitnation URL to follow
* @param overrideParams Parameters to override.
*/
export function redirect(
originUrl: string,
destinationUrl: string,
overrideParams: URLSearchParams = new URLSearchParams()
): void {
const originParams = extractFlagsToPropagate(originUrl);
// Override parameters in originParams if necessary.
overrideParams.forEach((value, key) => {
originParams.set(key, value);
});
let finalUrl = destinationUrl;
if (originParams.size > 0) {
finalUrl += "?" + originParams.toString();
}
window.open(finalUrl, "_self");
}