-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathutils.js
More file actions
414 lines (369 loc) · 12.4 KB
/
utils.js
File metadata and controls
414 lines (369 loc) · 12.4 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
/******************************************************************************
*
* Copyright (c) 2017, the Perspective Authors.
*
* This file is part of the Perspective library, distributed under the terms of
* the Apache License 2.0. The full license can be found in the LICENSE file.
*
*/
/**
* Instantiate a Template DOM object from an HTML text string.
*
* Params
* ------
* template : An HTML string representing a template.
*
* Returns
* -------
* A Template DOM object.
*/
function importTemplate(template) {
const div = document.createElement("div");
div.innerHTML = template;
return Array.prototype.slice.call(div.children)[0];
}
function setTemplateContent(template) {
// return early in browsers that have template tag support
if (template.content) {
return;
}
template.content = document.createDocumentFragment();
let child;
while ((child = template.firstChild)) {
Node.prototype.appendChild.call(template.content, child);
}
}
/**
* A simple tool for creating Web Components v0.
*
* Params
* ------
* template : An HTML string representing a template. Should have an 'id'
* attribute which will become the new Web Component's tag name.
* proto : The new Web Component's prototype object, as per spec.
*/
export function registerElement(templateString, styleString, proto) {
const template = importTemplate(templateString);
setTemplateContent(template);
if (styleString) {
template.innerHTML = `<style>${styleString.toString()}</style>` + template.innerHTML;
}
template.innerHTML = `<style id="psp_styles" scope="${template.getAttribute("id")}">test{}</style>` + template.innerHTML;
let is_locked = 0;
const _perspective_element = class extends proto {
attributeChangedCallback(name, old, value) {
if (is_locked > 0) {
return;
}
if (value === null) {
value = "null";
}
if (name[0] !== "_" && old != value && !!Object.getOwnPropertyDescriptor(proto.prototype, name).set) {
this[name] = value;
}
}
_setAttributeSafe(key, val) {
is_locked++;
try {
this.setAttribute(key, val);
} finally {
is_locked--;
}
}
connectedCallback() {
if (this._initialized) {
return;
}
this._initializing = true;
var node = document.importNode(template.content, true);
this.attachShadow({mode: "open"});
if (this._vieux) {
this._vieux.appendChild(node);
node = this._vieux;
}
this.shadowRoot.appendChild(node);
if (super.connectedCallback) {
super.connectedCallback();
}
// Call all attributes bound to setters on the proto
for (let key of Object.getOwnPropertyNames(proto.prototype)) {
if (key !== "connectedCallback") {
if (this.hasAttribute(key) && key[0] !== "_" && !!Object.getOwnPropertyDescriptor(proto.prototype, key).set) {
this[key] = this.getAttribute(key);
}
}
}
this._initializing = false;
this._initialized = true;
}
static get observedAttributes() {
return Object.getOwnPropertyNames(proto.prototype);
}
};
for (let key of Object.getOwnPropertyNames(proto.prototype)) {
let descriptor = Object.getOwnPropertyDescriptor(proto.prototype, key);
if (descriptor && descriptor.set) {
let old = descriptor.set;
descriptor.set = function(val) {
if (!this.hasAttribute(key) || this.getAttribute(key) !== val) {
this.setAttribute(key, val);
return;
}
if (!this._initializing && !this._initialized) {
return;
}
old.call(this, val);
};
Object.defineProperty(proto.prototype, key, descriptor);
}
}
let name = template.getAttribute("id");
console.log(`Registered ${name}`);
window.customElements.define(name, _perspective_element);
}
export function bindTemplate(template, ...styleStrings) {
const style = styleStrings.map(x => x.toString()).join("\n");
return function(cls) {
return registerElement(template, {toString: () => style}, cls);
};
}
/**
* A decorator for declaring a setter property of an HTMLElement descendent
* class as serialized JSON. Handles converting these types before invoking
* the underlying function/
*
* @param {object} _default the default value to supply the setter when
* undefined, removed or invalid.
*/
function _attribute(_default) {
return function(cls, name, desc) {
const old_set = desc.value;
desc.set = function(x) {
let attr = this.getAttribute(name);
try {
if (x === null || x === undefined || x === "") {
x = _default();
}
if (typeof x !== "string") {
x = JSON.stringify(x);
}
if (x !== attr) {
attr = x;
}
attr = JSON.parse(attr);
} catch (e) {
console.warn(`Invalid value for attribute "${name}": ${x}`);
attr = _default();
}
old_set.call(this, attr);
};
desc.get = function() {
if (this.hasAttribute(name)) {
return JSON.parse(this.getAttribute(name));
} else {
return _default();
}
};
delete desc["value"];
delete desc["writable"];
return desc;
};
}
/**
* Just like `setTimeout` except it returns a promise which resolves after the
* callback has (also resolved).
*
* @param {func} cb
* @param {*} timeout
*/
export async function setPromise(cb = async () => {}, timeout = 0) {
await new Promise(x => setTimeout(x, timeout));
return await cb();
}
export const invertPromise = () => {
let _resolve;
const promise = new Promise(resolve => {
_resolve = resolve;
});
promise.resolve = _resolve;
return promise;
};
export function throttlePromise(target, property, descriptor, clear = false) {
if (typeof target === "boolean") {
return function(target, property, descriptor) {
return throttlePromise(target, property, descriptor, true);
};
}
// Each call to `throttlePromise` has a unique `lock`
const lock = Symbol("private lock");
const _super = descriptor.value;
async function throttleOnce(id) {
if (id !== this[lock].gen) {
// This invocation got de-duped with a later one, but it will
// wake up first, so if there is not a lock acquired here, push
// it to the back of the event queue.
if (!this[lock].lock) {
await new Promise(requestAnimationFrame);
}
// Now await the currently-processing invocation (which
// occurred after than this one) and return.
await this[lock].lock;
return true;
}
}
// Wrap the underlying function
descriptor.value = async function(...args) {
// Initialize the lock for this Object instance, if it has never been
// initialized.
this[lock] = this[lock] || {gen: 0};
// Assign this invocation a unique ID.
let id = ++this[lock].gen;
if (clear) {
await new Promise(requestAnimationFrame);
}
// If the `lock` property is defined, a previous invocation is still
// processing.
if (this[lock].lock) {
// `await` the previous call; afterwards, the drawn state will be
// updated but we need to draw again to incorporate this
// invocation's state changes.
await this[lock].lock;
// We only want to execute the _last_ invocation, since each call
// precludes the previous ones if they are still queue-ed.
if (await throttleOnce.call(this, id)) {
return;
}
} else if (clear) {
// Even if the lock is clear, we need to debounce the queue-ed.
const debounced = await throttleOnce.call(this, id);
if (debounced) {
return;
}
}
// This invocation has made it to the render process, so "acquire" the
// lock.
this[lock].lock = invertPromise();
// Call the decorated function itself
let result;
try {
result = await _super.call(this, ...args);
} finally {
// Errors can leave promises which depend on this behavior
// dangling.
const l = this[lock].lock;
delete this[lock]["lock"];
// If this invocation is still the latest, clear the attribute
// state.
// TODO this is likely not he behavior we want for this event ..
if (id === this[lock].gen && clear) {
this.removeAttribute("updating");
this.dispatchEvent(new Event("perspective-update-complete"));
}
l.resolve();
}
return result;
};
// A function which clears the lock just like the main wrapper, but then
// does nothing.
descriptor.value.flush = async function(obj) {
if (obj[lock]?.lock) {
await obj[lock].lock;
await new Promise(requestAnimationFrame);
if (obj[lock]?.lock) {
await obj[lock].lock;
}
}
};
return descriptor;
}
/**
* Swap 2 HTMLElements in a container.
* @param {HTMLElement} container
* @param {HTMLElement} elem1
* @param {HTMLElement} elem2
*/
export function swap(container, ...elems) {
if (elems[0] === elems[1]) return;
if (elems.every(x => x.classList.contains("null-column"))) return;
let [i, j] = elems.map(x => Array.prototype.slice.call(container.children).indexOf(x));
if (j < i) {
[i, j] = [j, i];
elems = elems.reverse();
}
container.insertBefore(elems[1], elems[0]);
if (j + 1 === container.children.length) {
container.appendChild(elems[0]);
} else {
container.insertBefore(elems[0], container.children[j + 1]);
}
}
export const json_attribute = _attribute(() => ({}));
export const array_attribute = _attribute(() => []);
export const registerPlugin = (name, plugin) => {
if (global.registerPlugin) {
global.registerPlugin(name, plugin);
} else {
global.__perspective_plugins__ = global.__perspective_plugins__ || [];
global.__perspective_plugins__.push([name, plugin]);
}
};
/**
* Given an expression, return its alias.
*
* @param {*} expression
* @returns String
*/
export function getExpressionAlias(expression) {
const matches = expression.match(/\/\/(.+?)$/m);
let alias;
// Has an alias - use that to type check.
if (matches && matches.length == 2) {
alias = matches[1].trim();
return alias;
} else {
return expression;
}
}
/**
* Adds an alias to the given expression and returns it.
*
* @param {*} expression
* @returns String
*/
// export function addExpressionAlias(expression) {
// let alias;
// expression.length > 20
// ? (alias =
// expression
// .replace("\n", " ")
// .substr(0, 20)
// .trim() + "...")
// : (alias = expression);
// return `//${alias}\n${expression}`;
// }
/**
* Given an alias and an array of string expressions, find the alias inside
* the expressions array. This is important so we can map aliases back to
* expressions inside _new_row.
*
* @param {String} alias
* @param {Array<String>} expressions
* @returns String
*/
export function findExpressionByAlias(alias, expressions) {
for (const expr of expressions) {
const expr_alias = getExpressionAlias(expr);
if (alias === expr_alias) {
return expr;
}
}
}
/**
* Given an expression, strips the alias and returns the expression.
*
* @param {String} expression
* @returns String
*/
export function getRawExpression(expression) {
return expression.replace(/\/\/(.+)\n/, "");
}