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
441 lines (407 loc) · 12.8 KB
/
util.ts
File metadata and controls
441 lines (407 loc) · 12.8 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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
/**
* Copyright 2025 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 axios from "axios";
import _ from "lodash";
import { AutoCompleteResult } from "../components/nl_search_bar/auto_complete_input";
import { Theme } from "../theme/types";
import { stringifyFn } from "../utils/axios";
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",
"enable_feature",
"disable_feature",
"detector",
]);
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, "")
.slice(2, 12);
}
/** 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
* @param contents
* @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];
}
/**
* Processes a source url for display in the UI.
* Sanitizes the url to prevent XSS attacks while also
* prepending https:// if the url is missing a protocol.
*/
export function sanitizeSourceUrl(url: string): string {
if (!url) {
return "";
}
const trimmedUrl = url.trim();
// Ensure we have a protocol for the parser to work
// If the input is missing a valid protocol, we prepend https://
// Prepending https:// blocks unsafe protocols like javascript:// or vbscript://
const urlToParse =
trimmedUrl.startsWith("http://") || trimmedUrl.startsWith("https://")
? trimmedUrl
: "https://" + trimmedUrl;
try {
const parsed = new URL(urlToParse);
return parsed.href;
} catch (e) {
// If the URL does not have a valid URL structure, return empty
// This will block urls with scripts like http://javascript:alert(1)
return "";
}
}
/**
* This function removes the protocol from a url.
*
* Example:
*
* stripProtocol("https://datacommons.org")
* -> "datacommons.org"
*/
export function stripProtocol(url: string): string {
if (!url) {
return "";
}
return url.replace(/^https?:\/\//i, "");
}
/**
* This function truncates a string to `maxLength`, replacing
* the excised fragment with `omission`.
*
* If maxLength is less omission.length or str is already
* short enough, the function returns str unchanged.
*
* Example:
*
* truncateText(
* "datacatalog.worldbank.org/dataset/world-development-indicators",'
* 50, "middle")
* -> "datacatalog.worldbank.org…d-development-indicators"
*
*/
export function truncateText(
str: string,
maxLength: number,
position: "start" | "middle" | "end" = "end",
omission = "…"
): string {
if (maxLength <= omission.length || str.length <= maxLength) {
return str;
}
const charactersToKeep = maxLength - omission.length;
switch (position) {
case "start":
return omission + str.slice(str.length - charactersToKeep);
case "middle": {
const front = Math.ceil(charactersToKeep / 2);
const back = Math.floor(charactersToKeep / 2);
return str.slice(0, front) + omission + str.slice(str.length - back);
}
case "end":
default:
return str.slice(0, charactersToKeep) + omission;
}
}
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 {
// If the query ends with the pattern (case-insensitive), remove it.
if (query.trim().toLowerCase().endsWith(pattern.trim().toLowerCase())) {
return query.substring(0, query.length - pattern.length);
}
// Otherwise, return the original query.
return query;
}
/**
* 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");
}
export function escapeRegExp(string: string): string {
return string.replace(/[.*+?^${}()|[\\]\\]/g, "\\$&");
}
export async function getStatVarInfo(dcids: string[]): Promise<any> {
if (!dcids || dcids.length === 0) {
return Promise.resolve({});
}
const flags = extractFlagsToPropagate(window.location.href);
const params = {
dcids,
...Object.fromEntries(flags.entries()),
};
return axios.get("/api/variable/info", {
params,
paramsSerializer: stringifyFn,
});
}
export function replaceQueryWithSelection(
query: string,
result: AutoCompleteResult,
hasLocation: boolean,
statVarInfo: any
): { query: string; placeDcid: string } {
if (
result.matchType === "stat_var_search" ||
result.matchType === "location_search"
) {
// For stat vars and locations, do a case-insensitive replacement of the last
// occurrence of the matched concept.
const lowerCaseQuery = query.toLowerCase();
const lowerCaseMatchedQuery = result.matchedQuery.toLowerCase();
const lastIndex = lowerCaseQuery.lastIndexOf(lowerCaseMatchedQuery);
if (lastIndex !== -1) {
const prefix = query.substring(0, lastIndex);
if (
!hasLocation &&
result.matchType === "stat_var_search" &&
!result.hasPlace
) {
const placeTypeSummary = statVarInfo?.[result.dcid]?.placeTypeSummary;
if (placeTypeSummary) {
// Check for Earth first.
const earthPlace = placeTypeSummary?.Place?.topPlaces?.find(
(p) => p.dcid === "Earth"
);
if (earthPlace) {
return {
query: `${prefix}${result.name} in the ${earthPlace.name}`,
placeDcid: earthPlace.dcid,
};
}
// Ordered list of other place types.
const placeTypes = [
"Continent",
"Country",
"State",
"AdministrativeArea1",
"EurostatNUTS1",
];
for (const placeType of placeTypes) {
const places = placeTypeSummary?.[placeType]?.topPlaces;
if (places && places.length > 0) {
const randomIndex = Math.floor(Math.random() * places.length);
const randomPlace = places[randomIndex];
return {
query: `${prefix}${result.name} in ${randomPlace.name}`,
placeDcid: randomPlace.dcid,
};
}
}
}
return {
query: prefix + result.name + " on Earth",
placeDcid: "Earth",
};
}
return { query: prefix + result.name, placeDcid: "" };
}
}
// Fallback for any other case.
return {
query: stripPatternFromQuery(query, result.matchedQuery) + result.name,
placeDcid: "",
};
}