-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathutils.html
342 lines (292 loc) · 11 KB
/
utils.html
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
<link rel="import" href="patch-polymer.html">
<script>
var Utils = {}
Utils.parse_splices = function(splices, give_moved){
// I really don't understand what you get from an array.splices observer.
// Here we takes the "splices" object provided, and guarantee to return
// an object with two arrays of items called added and removed.
// if give_moodified is truthy, then we provide a third array, modified
// giving an array of objects which had their index changed
var added_keys, removed_keys, moved_keys;
// Firstly, get the list of added and removed *keys*
if(!splices || !splices.keySplices || splices.keySplices.length === 0){
// nothing
added_keys = [];
removed_keys = [];
} else if (splices.keySplices.length === 1){
// assume that if there's only one element in the array then it's already properly de-deduped
added_keys = splices.keySplices[0].added;
removed_keys = splices.keySplices[0].removed;
} else {
// multiple splices..I'm not sure how to interpret the indexSplices,
// but the keySplices is easier.
added_keys = new Set(), removed_keys = new Set();
for (let s of splices.keySplices) {
for (let key of s.removed) {
if(added_keys.has(key)){
added_keys.delete(key);
} else {
removed_keys.add(key);
}
}
for (let key of s.added) {
if(removed_keys.has(key)){
removed_keys.delete(key);
} else {
added_keys.add(key);
}
}
}
}
// Now convert the keys to objects...
var added = [], removed = [], moved = [];
if(added_keys.length || added_keys.size){
let coll = Polymer.Collection.get(splices.indexSplices[0].object);
for(let key of added_keys){
let item = coll.getItem(key);
(item !== undefined) && added.push(item);
}
}
if(removed_keys.length || removed_keys.size){
// we can't use getItem for removed items, because they're no longer in the
// collection.
// note that this bit depends on the polymer patch which sets _pkey
let discarded_items = new Map();
for(let s of splices.indexSplices){
for(let item of s.removed)if(item){
discarded_items.set(item._pkey, item);
}
}
for(let key of removed_keys){
let item = discarded_items.get(key);
(item !== undefined) && removed.push(item);
}
}
if(give_moved && splices && splices.indexSplices && splices.indexSplices.length){
// Not sure what the right way to do this is...
// I think the API needs to improve, at least the docs do.
let new_array = splices.indexSplices[0].object; // all indexSplices refer to the actual object, i.e. as it currently exists
// firstly, work out how long the array originally was
let original_len = new_array.length;
for(let s of splices.indexSplices){
original_len -= s.addedCount;
original_len += s.removed.length;
}
// now we construct a map from new_idx to old idx
// note that added things are inserted as undefined, because we don't care about them here..yet..
let old_from_new = [];
for(let ii=0; ii<original_len; ii++){
old_from_new.push(ii);
}
for(let s of splices.indexSplices){
old_from_new.splice.apply(old_from_new, [s.index, s.removed.length].concat(Array(s.addedCount)));
}
// and then we can iterate over it to see which things have moved
moved = [];
for(let [ii, item] of new_array.entries()) if(old_from_new[ii] !== undefined && old_from_new[ii] !== ii) {
moved.push(item);
}
// ahh, but it turns out we do care about things that were removed and then reinserted
// to find them, we collect a list of all the items that have been removed and check
// if any of them are still in the array (given that they were inserted they will be "undefined"
// in the old_from_new mapping).
let all_removed_items = new Set();
for(let s of splices.indexSplices){
for(let item of s.removed){
all_removed_items.add(item);
}
}
for(let [ii, item] of new_array.entries()) if(old_from_new[ii] === undefined && all_removed_items.has(item)){
moved.push(item);
}
}
return {
added: added,
removed: removed,
moved: moved
};
}
Utils.deep_clone = function(obj){
// this doesn't bother realing with self-referential things, but it
// does tolerate things that wouldn't work with JSON.parse(JSON.stringify)
// in particular typed arrays (which are *not* cloned, but end up in both
// src and dest), files, and dom elements likewise.
if (!obj) {
return obj;
} else if(obj.constructor === Object || obj.constructor === Array){
let dest = new obj.constructor();
for(let key in obj)if(Object.hasOwnProperty.call(obj, key)){
dest[key] = Utils.deep_clone(obj[key]);
}
return dest;
} else {
return obj; // string, numbers, and other strange things
}
}
Utils.get_key = function(arr, item){
// don't use this in a tight loop..lift the get(arr) out of the loop.
return Polymer.Collection.get(arr).getKey(item);
}
Utils.is_equal_simple = function(a, b){
// very simple....
if((a && !b) || (!a && b)){
return false;
}
for(let aa in a){
if(b[aa] !== a[aa]){
return false;
}
}
for(let bb in b){
if(b[bb] !== a[bb]){
return false;
}
}
return true;
};
//Escape a user specified string for use in regex search.
// Taken from http://stackoverflow.com/a/3561711
Utils.regex_escape= function(s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
};
//Takes an Array of strings and returns a regex which can be used for finding items in the set given in the list
// with the longest possible match returned. e.g.
// regex_from_list(["hello","world","hello world"]).exec("this hello world life") will match on "hello world".
Utils.regex_from_list = function(a){
if(!a.length)
return null;
return RegExp(a.sort(function(a,b){
return b.length-a.length;
}).map(Utils.regex_escape).join("|"));
};
// setImmediate (on main thread), but we just the same impementation as worker-builder
// taken/adapted from https://github.com/YuzuJS/setImmediate/blob/master/setImmediate.js
(function(){
// exports window.setImmediate and window.clearImmediate
var last_task_h=0;
var tasks = {};
window._immediate_channel = new MessageChannel();
_immediate_channel.port1.onmessage = function(e) {
var h = e.data;
try {
tasks[h] && tasks[h]();
} finally {
clearImmediate(h);
}
}
window.setImmediate = function(cb) {
tasks[++last_task_h] = cb;
_immediate_channel.port2.postMessage(last_task_h);
return last_task_h;
}
window.clearImmediate = function(h){
delete tasks[h];
}
})();
Utils.typed_array_manager = (function(){
return {
to_akey: function(arr){
return {array: arr};
},
get_array_clone: function(akey){
// note that the clone is not put in the store. It is
// inteded to be used when dealing with workers, and needing to
// transfer an array in its intereity to another thread.
return akey && akey.array && new akey.array.constructor(akey.array);
}
};
})();
Utils.file_manager = (function(){
let counter = 0;
return {
to_fkey: function(file){
return {
file: file,
id: ++counter // useful when disscussing things with workers
};
},
};
})();
Utils.clone_canvas = function(old_canv){
if(!old_canv){
return;
}
let new_canv = document.createElement("canvas");
new_canv.width = old_canv.width;
new_canv.height = old_canv.height;
new_canv.getContext('2d').drawImage(old_canv, 0, 0);
new_canv.style.cssText = old_canv.style.cssText;
return new_canv;
}
Utils.ckey_to_data_url = function(ckey, height, width){
if(!ckey){
return "";
}
let canv_el;
if(ckey.canvas){
// ckey is an actual canvas
canv_el = ckey.canvas;
let computed_width, computed_height;
if(!height || !width){
try{
let s = getComputedStyle(canv_el);
width = width || parseInt(s.width);
height = height || parseInt(s.height);
}catch(e){
// TODO: might want the (width && !height) thing, as below
width = width || canv_el.width;
height = height || canv_el.height;
};
}
} else {
// ckey is just buffer and dims, so put data into a new canvas
canv_el = document.createElement('canvas');
canv_el.width = ckey.dims[0];
canv_el.height = ckey.dims[1];
ctx = canv_el.getContext('2d');
let im_data = ctx.createImageData(ckey.dims[0], ckey.dims[1]);
im_data.data.set(new Uint8ClampedArray(ckey.buffer));
ctx.putImageData(im_data, 0, 0);
if(width && !height){
height = ckey.dims[1] * width/ckey.dims[0];
} else if(height && !width){
width = ckey.dims[0] * height/ckey.dims[1];
} else {
height = ckey.dims[1];
width = ckey.dims[0];
}
}
if(width !== canv_el.width || height !== canv_el.height){
// resize to new canvas, so there's no room for recieving
// application to screw it up
let original_canv = canv_el;
canv_el = document.createElement('canvas');
canv_el.width = width;
canv_el.height = height;
canv_el.getContext('2d').drawImage(original_canv, 0, 0, original_canv.width,
original_canv.height, 0, 0, width, height);
}
let url = canv_el.toDataURL();
return `<img src='${url}' width='${width}' height='${height}' />`;
}
Utils.array_to_csv = function(array, cols, title){
"use strict";
let text;
if(cols){
text = [];
for(let ii=0; ii<array.length; ii+=cols){
text.push(Array.prototype.join.call(array.slice(ii, ii+cols), ", "));
}
text = text.join("\n");
} else {
text = Array.prototype.join.call(array, "\n");
}
let a = document.createElement('a');
document.body.appendChild(a);
a.download = (title || "data") + ".csv";
a.href = "data:text/plain;base64," + btoa(text);
a.click();
document.body.removeChild(a);
console.log("(you may need to give permission for the document to be saved)");
};
</script>