@cocreate/utils 1.21.16 → 1.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/utils.js DELETED
@@ -1,606 +0,0 @@
1
- (function (root, factory) {
2
- if (typeof define === 'function' && define.amd) {
3
- define([], function () {
4
- return factory(true)
5
- });
6
- } else if (typeof module === 'object' && module.exports) {
7
- module.exports = factory(false);
8
- } else {
9
- root.returnExports = factory(true);
10
- }
11
- }(typeof self !== 'undefined' ? self : this, function (isBrowser) {
12
-
13
- /*globals DOMParser*/
14
- function clickedElement() {
15
- document.addEventListener('click', e => {
16
- document.clickedElement = e.target;
17
- });
18
-
19
- try {
20
- let frameDocuments = window.top.frameDocuments;
21
- if (!frameDocuments) {
22
- window.top.frameDocuments = new Map();
23
- frameDocuments = window.top.frameDocuments;
24
- }
25
- let frames = document.querySelectorAll('iframe');
26
- for (let frame of frames) {
27
- let frameDocument = frame.contentDocument;
28
- if (!frameDocuments.has(frameDocument)) {
29
- frameDocuments.set(frameDocument, '')
30
- frameDocument.addEventListener('click', e => {
31
- frameDocument.clickedElement = e.target;
32
- });
33
- }
34
- }
35
-
36
- } catch (e) {
37
- console.log('cross-origin failed')
38
- }
39
-
40
- }
41
-
42
- const ObjectId = (rnd = r16 => Math.floor(r16).toString(16)) =>
43
- rnd(Date.now() / 1000) + ' '.repeat(16).replace(/./g, () => rnd(Math.random() * 16));
44
-
45
- function checkValue(value) {
46
- if (/{{\s*([\w\W]+)\s*}}/g.test(value))
47
- return false;
48
- else
49
- return true
50
- }
51
-
52
- function dotNotationToObject(data, obj = {}) {
53
- try {
54
- for (const key of Object.keys(data)) {
55
- let value = data[key]
56
- let newObject = obj
57
- let oldObject = new Object(obj)
58
- let keys = key.split('.');
59
- let length = keys.length - 1
60
- for (let i = 0; i < keys.length; i++) {
61
- if (/\[([0-9]*)\]/g.test(keys[i])) {
62
- let [k, index] = keys[i].split('[');
63
- index = index.slice(0, -1)
64
- if (length == i) {
65
- if (value === undefined)
66
- newObject[k].splice(index, 1);
67
- else
68
- newObject[k][index] = value;
69
- } else {
70
- newObject[k] = oldObject[k] || [];
71
- newObject[k][index] = oldObject[k][index] || {};
72
- newObject = newObject[k][index]
73
- oldObject = oldObject[k][index]
74
- }
75
- } else {
76
- if (length == i) {
77
- if (value === undefined)
78
- delete newObject[keys[i]]
79
- else
80
- newObject[keys[i]] = value;
81
- } else {
82
- newObject[keys[i]] = oldObject[keys[i]] || {};
83
- newObject = newObject[keys[i]]
84
- oldObject = oldObject[keys[i]]
85
- }
86
- }
87
- }
88
- }
89
- return obj
90
- } catch (error) {
91
- console.log("Error converting dot notation to object", error);
92
- return false;
93
- }
94
- }
95
-
96
- function getValueFromObject(json, path) {
97
- try {
98
- if (typeof json == 'undefined' || !path)
99
- return;
100
-
101
- path = path.replace(/\[(\d+)\]/g, '.$1');
102
-
103
- let jsonData = json, subpath = path.split('.');
104
-
105
- for (let i = 0; i < subpath.length; i++) {
106
- jsonData = jsonData[subpath[i]];
107
- if (!jsonData)
108
- return jsonData;
109
- }
110
- return jsonData;
111
- } catch (error) {
112
- console.log("Error in getValueFromObject", error);
113
- return;
114
- }
115
- }
116
-
117
- function domParser(str) {
118
- try {
119
- var mainTag = str.match(/\<(?<tag>[a-z0-9]+)(.*?)?\>/).groups.tag;
120
- } catch (e) {
121
- // console.log(e, 'find position: can not find the main tag');
122
- }
123
- let doc;
124
- switch (mainTag) {
125
- case 'html':
126
- doc = new DOMParser().parseFromString(str, "text/html");
127
- return doc.documentElement;
128
- case 'body':
129
- doc = new DOMParser().parseFromString(str, "text/html");
130
- return doc.body;
131
- case 'head':
132
- doc = new DOMParser().parseFromString(str, "text/html");
133
- return doc.head;
134
-
135
- default:
136
- let con = document.createElement('dom-parser');
137
- con.innerHTML = str;
138
- return con;
139
- }
140
- }
141
-
142
- function parseTextToHtml(text) {
143
- let doc = new DOMParser().parseFromString(text, "text/html");
144
- if (doc.head.children[0]) return doc.head.children[0];
145
- else return doc.body.children[0];
146
- }
147
-
148
- function escapeHtml(html) {
149
- return html.replaceAll('&', '&amp').replaceAll('<', '&lt').replaceAll('>', '&gt;').replaceAll("'", '&#39;').replaceAll('"', '&quot;');
150
- }
151
-
152
- function cssPath(node, container) {
153
- let pathSplits = [];
154
- do {
155
- if (!node || !node.tagName) return false;
156
- let pathSplit = node.tagName.toLowerCase();
157
- // if (node.tagName == "DOM-PARSER" || node.hasAttribute('contenteditable')){
158
- // pathSplit = "[contenteditable]";
159
- // node = '';
160
- // }
161
- if (node.id) {
162
- pathSplit += "#" + node.id;
163
- node = '';
164
- }
165
- else {
166
- // let eid = node.getAttribute('eid');
167
- // if (/{{\s*([\w\W]+)\s*}}/g.test(eid)) {
168
- // eid = false;
169
- // }
170
- // if (eid) {
171
- // pathSplit += `[eid="${eid}"]`;
172
- // node = '';
173
- // }
174
- // else {
175
- // if (node.classList.length) {
176
- // node.classList.forEach((item) => {
177
- // if (item.indexOf(":") === -1) pathSplit += "." + item;
178
- // });
179
- // }
180
-
181
- if (node.parentNode && node.parentNode.children.length > 1) {
182
- // TODO: improve array logic so ignores javascript generated html??
183
- let children = []
184
- for (let child of node.parentNode.children) {
185
- // if (!child.matches('.mirror'))
186
- // children.push(child);
187
- if (child.tagName == node.tagName)
188
- children.push(child);
189
- }
190
- let index = Array.prototype.indexOf.call(
191
- children,
192
- node
193
- );
194
- // if (children.length > 1)
195
- // pathSplit += `:nth-child(${index + 1})`;
196
- pathSplit += `:nth-of-type(${index + 1})`;
197
- }
198
-
199
- // pathSplits.unshift(pathSplit);
200
- node = node.parentNode;
201
- if (node == null || node.tagName == "HTML" || node.tagName == "DOM-PARSER" || node.nodeName == "#document" || node.hasAttribute('contenteditable'))
202
- node = '';
203
- }
204
- // }
205
- pathSplits.unshift(pathSplit);
206
- } while (node);
207
- let path = pathSplits.join(" > ")
208
- if (path && path.includes('<')) {
209
- let index = path.lastIndexOf(' >')
210
- if (index != -1)
211
- path = path.slice(0, index)
212
- else {
213
- index = path.lastIndexOf('<')
214
- path = path.slice(0, index)
215
- }
216
- }
217
-
218
- return path;
219
- }
220
-
221
- function queryDocumentSelectorAll(selector) {
222
- let elements = [];
223
-
224
- if (selector) {
225
- let selectors = [selector];
226
- if (selector.indexOf(',') !== -1) {
227
- selectors = selector.split(',');
228
- }
229
- for (let selector of selectors) {
230
- let els;
231
- if (selector.indexOf(';') !== -1) {
232
- let targetDocument;
233
- let [documentSelector, targetSelector] = selector.split(';');
234
- if (['parent', 'parentDocument'].includes(documentSelector))
235
- targetDocument = window.parent.document;
236
- else {
237
- let frame = document.querySelector(documentSelector);
238
- if (frame)
239
- targetDocument = frame.contentDocument;
240
- }
241
- if (targetDocument) {
242
- if (targetSelector)
243
- els = targetDocument.querySelectorAll(targetSelector);
244
- else
245
- if (targetDocument.clickedElement)
246
- els = [targetDocument.clickedElement];
247
- }
248
- }
249
- else
250
- els = document.querySelectorAll(selector);
251
- if (els) {
252
- els = Array.prototype.slice.call(els);
253
- elements = elements.concat(els);
254
- }
255
- }
256
- }
257
- return elements;
258
- }
259
-
260
- function queryDocumentSelector(selector) {
261
- if (selector) {
262
- let selectors = [selector];
263
- if (selector.indexOf(',') !== -1) {
264
- selectors = selector.split(',');
265
- }
266
- for (let selector of selectors) {
267
- let el;
268
- if (selector.indexOf(';') !== -1) {
269
- let targetDocument;
270
- let [documentSelector, targetSelector] = selector.split(';');
271
- if (['parent', 'parentDocument'].includes(documentSelector))
272
- targetDocument = window.parent.document;
273
- else {
274
- let frame = document.querySelector(documentSelector);
275
- if (frame)
276
- targetDocument = frame.contentDocument;
277
- }
278
- if (targetDocument) {
279
- if (targetSelector)
280
- el = targetDocument.querySelector(targetSelector);
281
- else
282
- if (targetDocument.clickedElement)
283
- el = [targetDocument.clickedElement];
284
- }
285
- }
286
- else
287
- el = document.querySelector(selector);
288
- if (el)
289
- return el
290
- }
291
- }
292
- return;
293
- }
294
-
295
- function queryData(data, query) {
296
- if (!data)
297
- return false;
298
-
299
- if (!Array.isArray(data))
300
- data = [data]
301
-
302
- if (!query)
303
- return true
304
-
305
- if (!Array.isArray(query))
306
- query = [query]
307
- if (!query.length)
308
- return true
309
-
310
- let queryResult = false
311
- for (let n = 0; n < data.length; n++) {
312
- for (let i = 0; i < query.length; i++) {
313
- let dataValue
314
- if (query[i].name.includes('.') || /\[([0-9]*)\]/g.test(query[i].name))
315
- dataValue = getValueFromObject(data[n], query[i].name)
316
- else
317
- dataValue = data[n][query[i].name]
318
- if (dataValue == undefined)
319
- dataValue = ''
320
- let logicalOperator = query[i].logicalOperator || 'and'
321
- let queryValues = query[i].value
322
- if (!Array.isArray(queryValues))
323
- queryValues = [queryValues]
324
-
325
- let queryStatus = false
326
- for (let queryValue of queryValues) {
327
- if (query[i].caseSensitive != 'true' || query[i].caseSensitive != true) {
328
- if (typeof dataValue == 'string')
329
- dataValue = dataValue.toLowerCase()
330
- if (typeof queryValue == 'string')
331
- queryValue = queryValue.toLowerCase()
332
- }
333
-
334
- switch (query[i].operator) {
335
- case '$includes':
336
- case 'includes':
337
- if (dataValue.includes(queryValue))
338
- queryStatus = true
339
- // if (queryValue === "" && logicalOperator === 'and') {
340
- // if (dataValue !== "")
341
- // queryStatus = false
342
- // }
343
- break;
344
- case '$eq':
345
- if (dataValue == queryValue)
346
- queryStatus = true
347
- break;
348
- case '$ne':
349
- if (dataValue != queryValue)
350
- queryStatus = true
351
- break;
352
- case '$lt':
353
- if (dataValue > queryValue)
354
- queryStatus = true
355
- break;
356
- case '$lte':
357
- if (dataValue >= queryValue)
358
- queryStatus = true
359
- break;
360
- case '$gt':
361
- if (dataValue < queryValue)
362
- queryStatus = true
363
- break;
364
- case '$gte':
365
- if (dataValue <= queryValue)
366
- queryStatus = true
367
- break;
368
- case '$in':
369
- if (Array.isArray(dataValue) && dataValue.some(x => queryValue.includes(x)))
370
- queryStatus = true
371
- break;
372
- case '$nin':
373
- if (!Array.isArray(dataValue) || !dataValue.some(x => queryValue.includes(x)))
374
- queryStatus = true
375
- break;
376
- case '$range':
377
- if (queryValue[0] !== null && queryValue[1] !== null) {
378
- if (dataValue >= queryValue[0] && dataValue <= queryValue[1])
379
- queryStatus = true
380
- } else if (queryValue[0] == null && dataValue <= queryValue[1]) {
381
- queryStatus = true
382
- } else if (queryValue[1] == null && dataValue >= queryValue[0]) {
383
- queryStatus = true
384
- }
385
- break;
386
-
387
- default:
388
- if (dataValue.includes(queryValue))
389
- queryStatus = true
390
- break;
391
- }
392
- if (queryStatus == true) {
393
- queryResult = true
394
- break;
395
- }
396
-
397
- }
398
- switch (logicalOperator) {
399
- case 'and':
400
- if (queryStatus == false)
401
- return false
402
- break;
403
- }
404
- // if (logicalOperator == 'and' && queryStatus == false)
405
- // return false
406
- }
407
- }
408
-
409
- return queryResult;
410
- }
411
-
412
- function searchData(data, search) {
413
- if (!search)
414
- return true
415
- if (!Array.isArray(search))
416
- search = [search]
417
- for (let i = 0; i < search.length; i++) {
418
- let searchValue = search[i].value
419
- if (!Array.isArray(searchValue))
420
- searchValue = [searchValue]
421
- for (let key in data) {
422
- let value = data[key];
423
- let status = false;
424
- switch (typeof value) {
425
- case 'number':
426
- value = value.toString();
427
- break;
428
- case 'object':
429
- value = JSON.stringify(value)
430
- break;
431
- case 'function':
432
- value = value.toString();
433
- break;
434
- }
435
- if (search[i].caseSensitive != 'true' || search[i].caseSensitive != true)
436
- value = value.toLowerCase()
437
-
438
- for (let i = 0; i < searchValue.length; i++) {
439
- let searchString = searchValue[i]
440
- if (search[i].caseSensitive != 'true' || search[i].caseSensitive != true)
441
- searchString = searchString.toLowerCase()
442
-
443
- if (searchString === "" && search[i].operator === 'and') {
444
- if (value !== "")
445
- return false
446
- }
447
-
448
- if (value.indexOf(searchString) > -1)
449
- status = true;
450
-
451
- if (status)
452
- return true;
453
- else if (search[i].operator == 'and')
454
- return false;
455
-
456
-
457
- }
458
- }
459
- if (search[i].value.length && search[i].operator == 'or')
460
- return false
461
-
462
- }
463
- return true
464
- }
465
-
466
- function sortData(data, sort) {
467
- if (!Array.isArray(sort))
468
- sort = [sort]
469
- for (let i = 0; i < sort.length; i++) {
470
- let name = sort[i].name
471
- if (name) {
472
- try {
473
- data.sort((a, b) => {
474
- if (sort[i].direction == 'desc') {
475
- switch (typeof b[name]) {
476
- case 'string':
477
- if (!b[name])
478
- b[name] = ""
479
- return b[name].localeCompare(a[name])
480
- case 'number':
481
- if (!b[name])
482
- b[name] = 0
483
- return b[name] - a[name]
484
- case 'array':
485
- case 'object':
486
- break;
487
- }
488
- } else {
489
- switch (typeof a[name]) {
490
- case 'string':
491
- if (!a[name])
492
- a[name] = ""
493
- return a[name].localeCompare(b[name])
494
- case 'number':
495
- if (!a[name])
496
- a[name] = 0
497
- return a[name] - b[name]
498
- case 'array':
499
- case 'object':
500
- break;
501
- }
502
- }
503
- });
504
- } catch (error) {
505
- console.log(error)
506
- }
507
- }
508
- }
509
- return data;
510
- }
511
-
512
- function getAttributes(el) {
513
- if (!el) return;
514
-
515
- let attributes = window.CoCreateConfig.attributes;
516
- let object = {};
517
-
518
- for (let attribute of el.attributes) {
519
- let variable = attributes[attribute.name]
520
- if (variable) {
521
- object[variable] = attribute.value
522
- }
523
- }
524
-
525
- return object
526
- }
527
-
528
- function getAttributeNames(variables) {
529
- let reversedObject = {}
530
- for (const key of Object.keys(CoCreateConfig.attributes)) {
531
- reversedObject[CoCreateConfig.attributes[key]] = key
532
- }
533
-
534
- let attributes = [];
535
- for (const variable of variables) {
536
- let attribute = reversedObject[variable]
537
- if (attribute)
538
- attributes.push(attribute)
539
- }
540
- return attributes
541
- }
542
-
543
- function setAttributeNames(attributes, overWrite) {
544
- let reversedObject = {}
545
- for (const key of Object.keys(CoCreateConfig.attributes)) {
546
- reversedObject[CoCreateConfig.attributes[key]] = key
547
- }
548
-
549
- for (const attribute of Object.keys(attributes)) {
550
- const variable = attributes[attribute]
551
- if (!reversedObject[variable] || overWrite != false)
552
- reversedObject[variable] = attribute
553
- }
554
-
555
- let revertObject = {}
556
- for (const key of Object.keys(reversedObject)) {
557
- revertObject[reversedObject[key]] = key
558
- }
559
- CoCreateConfig.attributes = revertObject
560
- }
561
-
562
-
563
- // function computeStyles(el, properties) {
564
- // let computed = window.getComputedStyle(el);
565
- // let result = {};
566
- // properties.forEach((property) => {
567
- // result[property] = parseInt(computed[property]);
568
- // });
569
- // return result;
570
- // }
571
-
572
- // function checkParent(element, selectors){
573
- // let parentElement;
574
- // do {
575
- // parentElement = element.parentElement.closest(selectors);
576
- // if (parentElement) {
577
- // element = parentElement;
578
- // } else {
579
- // return element;
580
- // }
581
- // } while (parentElement);
582
- // }
583
-
584
- if (isBrowser)
585
- clickedElement();
586
-
587
- return {
588
- ObjectId,
589
- checkValue,
590
- dotNotationToObject,
591
- getValueFromObject,
592
- domParser,
593
- parseTextToHtml,
594
- escapeHtml,
595
- cssPath,
596
- queryDocumentSelector,
597
- queryDocumentSelectorAll,
598
- queryData,
599
- searchData,
600
- sortData,
601
- getAttributes,
602
- setAttributeNames,
603
- getAttributeNames
604
- }
605
-
606
- }));