-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.js
474 lines (429 loc) · 12.8 KB
/
utils.js
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
import { Utils as CommonUtils, ProcessSchema } from '@openeo/js-commons';
import Loading from './components/internal/Loading.vue';
import Errored from './components/internal/Errored.vue';
const SEARCH_SPLITCHARS = /[\s\.,;:"'!&\(\{\[\)\}\]]+/g;
const SEARCH_SERIALIZER = (_, value) => {
if (value === null) {
return "";
}
else if (typeof value === 'string') {
return value.replace(/\s+/g, ' ');
}
return value;
};
class Utils extends CommonUtils {
static kebabToCamelCase(str) {
return str.replace(/-(\w)/g, (_, c) => c ? c.toUpperCase() : '');
}
static enableHtmlProps(vm) {
// Don't execute if not in web-component mode (i.e. check for the shadow root)
if (!Utils.isObject(vm.$root) || !vm.$root.$options.shadowRoot) {
return;
}
// Read the HTML props once the page is completely loaded and all props are completely available
if(document.readyState === 'complete') {
Utils.readHtmlProps(vm);
}
else {
document.addEventListener('readystatechange', () => Utils.enableHtmlProps(vm), {once: true});
}
}
static readHtmlProps(vm) {
if (!Utils.isObject(vm) || !Utils.isObject(vm.$slots) || !Array.isArray(vm.$slots.default)) {
return;
}
// Read script tags
let slots = vm.$slots.default.filter(slot => typeof slot.tag === 'string' && slot.tag.toUpperCase() === 'SCRIPT' && typeof slot.data.attrs.type === 'string' && slot.data.attrs.type.includes('application/json'));
// We are using `includes` here as for some strange reasons in Jupyter Notebooks subsequent re-renders of the cell
// result in the attribute value being prefixed by a "true/", i.e.the value in slot.data.attrs.type is "true/application/json".
for(let slot of slots) {
let prop = null;
try {
if (typeof slot.data.attrs.prop === 'string' && slot.data.attrs.prop.length > 0) {
prop = Utils.kebabToCamelCase(slot.data.attrs.prop);
}
let value = JSON.parse(slot.data.domProps.innerHTML);
if (prop) {
Utils.setProp(vm, prop, value); // Set a single prop
}
else if (Utils.isObject(value)) {
for(let key in value) { // Set all props
Utils.setProp(vm, key, value[key]);
}
}
else {
console.error(`Props passed via script tag must be contained in an object.`);
}
}
catch (error) {
if (prop) {
console.error(`Prop '${prop}' passed via script tag is invalid: ${error.message}`);
}
else {
console.error(`Props passed via script tag are invalid: ${error.message}`);
}
}
}
}
static loadFontAwesome(vm) {
let webComponent = Utils.isObject(vm.$root) && vm.$root.$options.shadowRoot;
let stylesheets = Array.from((webComponent || document).styleSheets);
for(let css of stylesheets) {
if (typeof css.href === 'string' && css.href.includes('fontawesome')) {
return;
}
}
// Don't execute if not in web-component mode (browsers don't support loading fonts in shadowroot)
if (!webComponent) {
let font = document.createElement('link');
font.as = "font";
font.type = "font/woff2";
font.crossOrigin = true;
font.href = "https://use.fontawesome.com/releases/v5.13.0/webfonts/fa-solid-900.woff2";
document.head.appendChild(font);
}
let css = document.createElement('link');
css.rel = "stylesheet";
css.type = "text/css";
css.media = "all";
css.href = "https://use.fontawesome.com/releases/v5.13.0/css/all.css";
(webComponent || document.head).appendChild(css);
}
static setProp(vm, prop, value) {
// Depending on when during the page load this is executed, we
// need either to populate propsData (initially available) or
// $props (available after propsData has been read).
let propsRef = Utils.isObject(vm.$props) ? vm.$props : vm.$options.propsData;
vm.$set(propsRef, Utils.kebabToCamelCase(prop), value);
}
static loadAsyncComponent(importer) {
return {
component: importer,
loading: Loading,
error: Errored,
delay: 0,
timeout: 10000
};
}
static dataType(schema, signature = false, similarAllowed = 2, level = 0) {
let schemaObj = new ProcessSchema(schema);
var types = new Set();
for(let i in schemaObj.schemas) {
let dt = schemaObj.schemas[i];
let native = dt.nativeDataType();
let type = dt.dataType();
// Make the data types that we can submit via JSON (e.g. raster-cube, labeled-array) native
if (!dt.isEditable()) {
native = type;
}
else if (signature && schemaObj.schemas.filter(other => other.nativeDataType() === native).length > similarAllowed) {
// For signatures only: Check whether another similar type is available, then show only native type
types.add(native);
continue;
}
let formatted = native === type ? type : `${type}:${native}`;
if (native === 'array' && Utils.isObject(dt.schema.items)) {
let arrayItems = Utils.dataType(dt.schema.items, signature, similarAllowed, level + 1);
if (arrayItems !== 'any') {
formatted += `<${arrayItems}>`;
}
}
types.add(formatted);
}
if (types.has('any')) {
return 'any';
}
return Array.from(types).join(signature || level > 0 ? '|' : ', ');
}
static htmlentities_decode(str) {
if (typeof str !== 'string') {
str = String(str);
}
return str.replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"').replace(/'/g, "'");
}
static htmlentities(str) {
if (typeof str !== 'string') {
str = String(str);
}
return str.replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, ''');
}
static countObjectKeys(data) {
var count = {};
for(var i in data) {
var obj = data[i];
if (typeof obj !== 'object' || obj === null || Array.isArray(obj)) {
return null;
}
for(var key in obj) {
if (typeof count[key] === 'undefined') {
count[key] = 1;
}
else {
count[key]++;
}
}
}
return count;
}
static isTableLike(data, force = false) {
if (typeof data !== 'object' || data === null) {
return [];
}
var countedKeys = Utils.countObjectKeys(data);
if (countedKeys !== null) {
if (force === true) {
return Object.keys(countedKeys);
}
var num = 0;
var sum = 0;
for (var i in countedKeys) {
num++;
sum += countedKeys[i];
}
var avg = sum / num;
var dataSize = Array.isArray(dataSize) ? data.length : Object.keys(data).length;
if (avg > dataSize/2) {
return Object.keys(countedKeys);
}
}
return [];
}
static isUrl(value, onlyHttp = true) {
if (!Utils.hasText(value)) {
return false;
}
try {
let url = new URL(value);
if (onlyHttp && !url.protocol.match(/^https?:$/i)) {
return false;
}
return true;
} catch (error) {
return false;
}
}
static prettifyAbbreviation(str) {
if (typeof str === 'string' && str.match(/[A-Z]+/) === null) {
return str.toUpperCase();
}
return str;
}
static ensurePoint(pt, fallback = null) {
if (typeof fallback !== 'function') {
fallback = () => [0,0];
}
if (!Array.isArray(pt)) {
return fallback();
}
if (typeof pt[0] !== 'number') {
pt[0] = fallback()[0] || 0;
}
if (typeof pt[1] !== 'number') {
pt[1] = fallback()[1] || 0;
}
return pt;
}
static formatRef(value) {
if (this.isRef(value)) {
if (value.from_node) {
return "#" + value.from_node;
}
else if (value.from_parameter) {
return "$" + value.from_parameter;
}
}
return value;
}
static isRef(obj) {
return (Utils.isObject(obj) && (obj.from_parameter || obj.from_node));
}
static isRefEqual(ref1, ref2) {
if (!Utils.isRef(ref1) || !Utils.isRef(ref2)) {
return false;
}
else if (ref1.from_parameter && ref1.from_parameter === ref2.from_parameter) {
return true;
}
else if (ref1.from_node && ref1.from_node === ref2.from_node) {
return true;
}
return false;
}
// A very rough GeoJSON detection, if no GeoJSON schema is available.
static detectGeoJson(data) {
if (!Utils.isObject(data)) {
return false;
}
else if (typeof data.type !== 'string') {
return false;
}
switch(data.type) {
case "Point":
case "MultiPoint":
case "LineString":
case "MultiLineString":
case "Polygon":
case "MultiPolygon":
if (!Array.isArray(data.coordinates)) {
return false;
}
return true;
case "GeometryCollection":
if (!Array.isArray(data.geometries)) {
return false;
}
return true;
case "Feature":
if (data.geometry !== null && !Utils.isObject(data.geometry)) {
return false;
}
if (data.properties !== null && !Utils.isObject(data.properties)) {
return false;
}
return true;
case "FeatureCollection":
if (!Array.isArray(data.features)) {
return false;
}
return true;
default:
return false;
}
}
static toProcessParameters(parameters) {
if (Utils.isObject(parameters)) {
let processParameters = [];
for(let name in parameters) {
let param = parameters[name];
let schema = Utils.omitFromObject(param, ['description', 'required', 'default', 'federation:backends']);
processParameters.push({
name,
description: param.description,
optional: !param.required,
default: param.default,
'federation:backends': param['federation:backends'],
schema
});
}
return processParameters.sort((a,b) => Utils.compareStringCaseInsensitive(a.name, b.name));
}
else {
return [];
}
}
static formatCurrency(amount, currency, fallback = '') {
if (typeof amount !== 'number') {
return fallback;
}
try {
return amount.toLocaleString(undefined, { style: 'currency', currency: currency });
} catch(error) {
let str = amount.toLocaleString(undefined, {maximumFractionDigits: 2});
if (typeof currency === 'string') {
str += ' ';
str += currency;
}
return str.trim();
}
}
static formatBudget(budget, currency, unlimited = "Unlimited") {
if (budget === null) {
return unlimited;
}
else {
return Utils.formatCurrency(budget, currency);
}
}
static formatTimestamp(value, fallback = 'n/a') {
if (typeof value === 'string') {
try {
return new Date(value).toLocaleString(undefined, {
timeZone: "UTC",
timeZoneName: "short"
});
} catch (error) {}
}
return fallback;
}
static formatFileSize(value, fallback = 'n/a') {
let units = ['B', 'kB', 'MB', 'GB', 'TB', 'PB'];
if (typeof value !== 'number') {
return fallback;
}
let i = value == 0 ? 0 : Math.floor( Math.log(value) / Math.log(1024) );
let size = value / Math.pow(1024, i);
let sizeStr = size.toLocaleString(undefined, {maximumFractionDigits: 1});
return `${sizeStr} ${units[i]}`;
}
static formatProcessSignature(process, html = true) {
let params = [];
if (Array.isArray(process.parameters)) {
for(let i in process.parameters) {
let p = process.parameters[i];
let pType = Utils.dataType(p.schema, true, 1);
let req = p.optional ? '?' : '';
let pDefault = '';
if (p.optional && typeof p.default !== 'undefined') {
pDefault = JSON.stringify(p.default);
}
let pStr;
if (html) {
pStr = `<span class="param-optional">${req}</span><span class="data-type">${ Utils.htmlentities(pType) }</span> <span class="param-name">${ Utils.htmlentities(p.name) }</span>`;
if (pDefault) {
if (pDefault.length > 30) {
pDefault = `<span title="${ Utils.htmlentities(pDefault) }">…</span>`;
}
pStr += ` = <span class="param-argument">${pDefault}</span>`;
}
}
else {
pStr = req + pType + " " + p.name + pDefault;
}
params.push(pStr);
}
}
let paramStr = "(" + params.join(", ") + ") : ";
let returnSchema = Utils.isObject(process.returns) && process.returns.schema && typeof process.returns.schema === 'object' ? process.returns.schema : {};
let returns = Utils.dataType(returnSchema, true, 2);
if (html) {
return `<span class="process-name">${ Utils.htmlentities(process.process.id) }</span>${paramStr}<span class="data-type">${ Utils.htmlentities(returns) }</span>`;
}
else {
return process.process.id + paramStr + returns;
}
}
static search(searchterm, target, and = true) {
if (typeof searchterm !== 'string' || searchterm.length === 0) {
return false;
}
if (Utils.isObject(target)) {
target = Object.values(target);
}
else if (typeof target === 'string') {
target = [target];
}
if (!Array.isArray(target)) {
return false;
}
// Prepare search terms
searchterm = searchterm.toLowerCase().split(SEARCH_SPLITCHARS);
// Prepare text to search in
target = target
.map(v => {
if (typeof v === 'string') {
return v;
}
else {
// Convert non-strings to a string (JSON-related chars "': are added to SEARCH_SPLITCHARS)
return JSON.stringify(v, SEARCH_SERIALIZER, 0);
}
})
.join(' ') // Merge into a single string
.replace(SEARCH_SPLITCHARS, ' ') // replace split chars with white spaces
.toLowerCase(); // Lowercase
// Search with "and" or "or"
let fn = and ? 'every' : 'some';
return searchterm[fn](term => target.includes(term));
}
};
export default Utils;