@cocreate/utils 1.21.15 → 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/webpack.config.js CHANGED
@@ -1,84 +1,90 @@
1
1
  const path = require("path")
2
2
  const TerserPlugin = require("terser-webpack-plugin")
3
3
  const MiniCssExtractPlugin = require("mini-css-extract-plugin")
4
- let isProduction = process.env.NODE_ENV === "production"
5
4
  const { CleanWebpackPlugin } = require("clean-webpack-plugin")
6
5
 
7
- module.exports = {
8
- entry: {
9
- "CoCreate-utils": "./src/index.js",
10
- },
11
- output: {
12
- path: path.resolve(__dirname, "dist"),
13
- filename: isProduction ? "[name].min.js" : "[name].js",
14
- libraryTarget: "umd",
15
- libraryExport: "default",
16
- library: ["CoCreate", "utils"],
17
- globalObject: "this",
18
- },
6
+ module.exports = (env, argv) => {
7
+ let isProduction = false
8
+ if (argv.mode === 'production')
9
+ isProduction = true
19
10
 
20
- plugins: [
21
- new CleanWebpackPlugin(),
22
- new MiniCssExtractPlugin({
23
- filename: "[name].css",
24
- }),
25
- ],
26
- // Default mode for Webpack is production.
27
- // Depending on mode Webpack will apply different things
28
- // on final bundle. For now we don't need production's JavaScript
29
- // minifying and other thing so let's set mode to development
30
- mode: isProduction ? "production" : "development",
31
- module: {
32
- rules: [
33
- {
34
- test: /.js$/,
35
- exclude: /(node_modules)/,
36
- use: {
37
- loader: "babel-loader",
38
- options: {
39
- plugins: ["@babel/plugin-transform-modules-commonjs"],
40
- },
11
+ const config = {
12
+ entry: {
13
+ "CoCreate-utils": "./src/index.js",
41
14
  },
42
- },
43
- {
44
- test: /.css$/i,
45
- use: [
46
- { loader: "style-loader", options: { injectType: "linkTag" } },
47
- "file-loader",
15
+ output: {
16
+ path: path.resolve(__dirname, "dist"),
17
+ filename: isProduction ? "[name].min.js" : "[name].js",
18
+ libraryTarget: "umd",
19
+ libraryExport: "default",
20
+ library: ["CoCreate", "utils"],
21
+ globalObject: "this",
22
+ },
23
+
24
+ plugins: [
25
+ new CleanWebpackPlugin(),
26
+ new MiniCssExtractPlugin({
27
+ filename: "[name].css",
28
+ }),
48
29
  ],
49
- },
50
- ],
51
- },
30
+ // Default mode for Webpack is production.
31
+ // Depending on mode Webpack will apply different things
32
+ // on final bundle. For now we don't need production's JavaScript
33
+ // minifying and other thing so let's set mode to development
34
+ mode: isProduction ? "production" : "development",
35
+ module: {
36
+ rules: [
37
+ {
38
+ test: /.js$/,
39
+ exclude: /(node_modules)/,
40
+ use: {
41
+ loader: "babel-loader",
42
+ options: {
43
+ plugins: ["@babel/plugin-transform-modules-commonjs"],
44
+ },
45
+ },
46
+ },
47
+ {
48
+ test: /.css$/i,
49
+ use: [
50
+ { loader: "style-loader", options: { injectType: "linkTag" } },
51
+ "file-loader",
52
+ ],
53
+ },
54
+ ],
55
+ },
52
56
 
53
- // add source map
54
- ...(isProduction ? {} : { devtool: "eval-source-map" }),
57
+ // add source map
58
+ ...(isProduction ? {} : { devtool: "eval-source-map" }),
55
59
 
56
- optimization: {
57
- minimize: true,
58
- minimizer: [
59
- new TerserPlugin({
60
- extractComments: true,
61
- // cache: true,
62
- parallel: true,
63
- // sourceMap: true, // Must be set to true if using source-maps in production
64
- terserOptions: {
65
- // https://github.com/webpack-contrib/terser-webpack-plugin#terseroptions
66
- // extractComments: 'all',
67
- compress: {
68
- drop_console: true,
69
- },
70
- },
71
- }),
72
- ],
73
- splitChunks: {
74
- chunks: "all",
75
- minSize: 200,
76
- // maxSize: 99999,
77
- //minChunks: 1,
60
+ optimization: {
61
+ minimize: true,
62
+ minimizer: [
63
+ new TerserPlugin({
64
+ extractComments: true,
65
+ // cache: true,
66
+ parallel: true,
67
+ // sourceMap: true, // Must be set to true if using source-maps in production
68
+ terserOptions: {
69
+ // https://github.com/webpack-contrib/terser-webpack-plugin#terseroptions
70
+ // extractComments: 'all',
71
+ compress: {
72
+ drop_console: true,
73
+ },
74
+ },
75
+ }),
76
+ ],
77
+ splitChunks: {
78
+ chunks: "all",
79
+ minSize: 200,
80
+ // maxSize: 99999,
81
+ //minChunks: 1,
78
82
 
79
- cacheGroups: {
80
- defaultVendors: false,
81
- },
82
- },
83
- },
84
- }
83
+ cacheGroups: {
84
+ defaultVendors: false,
85
+ },
86
+ },
87
+ },
88
+ }
89
+ return config
90
+ }
package/src/archive.js DELETED
@@ -1,495 +0,0 @@
1
- export function getParentFromElement(element, parent_class, attributes) {
2
- if (parent_class) {
3
- if (element.classList.contains(parent_class)) {
4
- return element;
5
- }
6
-
7
- let node = element.parentNode;
8
- while (node != null && node.classList) {
9
- if (node.classList.contains(parent_class)) {
10
- return node;
11
- }
12
- node = node.parentNode;
13
- }
14
- }
15
- else if (attributes) {
16
- if (attributes.every((attr) => element.attributes.hasOwnProperty(attr))) {
17
- return element;
18
- }
19
-
20
- let node = element.parentNode;
21
- while (node != null && node.attributes) {
22
- if (attributes.every((attr) => node.attributes.hasOwnProperty(attr))) {
23
- return node;
24
- }
25
- node = node.parentNode;
26
- }
27
- }
28
-
29
- return false;
30
- }
31
-
32
-
33
- export function isJsonString(str_data) {
34
- try {
35
- let json_data = JSON.parse(str_data);
36
- if (typeof json_data === "object" && json_data != null) {
37
- return true;
38
- }
39
- else {
40
- return false;
41
- }
42
- }
43
- catch (e) {
44
- return false;
45
- }
46
- }
47
-
48
- export function getAttributes(element) {
49
- return element.getAttributeNames().reduce((attrMap, name) => {
50
- attrMap[name] = element.getAttribute(name);
51
- return attrMap;
52
- }, {});
53
- }
54
-
55
- // TODO: duplicate it is in crud.utils
56
- export function checkValue(value) {
57
- if (!value) return false;
58
- if (/{{\s*([\w\W]+)\s*}}/g.test(value)) {
59
- return false;
60
- }
61
-
62
- return true;
63
- }
64
-
65
- // TODO: Maybe can be deprciated
66
- export function getValueFromJonDeep(json, path) {
67
- try {
68
- if (typeof json == 'undefined')
69
- return false;
70
- let subpath = path.split('.');
71
- let find = subpath.shift();
72
- if (subpath.length > 0) {
73
- return this.__getValueFromJonDeep(json[find], subpath.join('.'))
74
- }
75
- return json[find];
76
- }
77
- catch (error) {
78
- console.log(error)
79
- return false;
80
- }
81
- }
82
-
83
- // hosseins utills
84
-
85
- // function to go through all frames
86
- export function allFrame(callback) {
87
- let allFrames = [{ document, window }];
88
- for (let frame of document.querySelectorAll("iframe")) {
89
- let frameDocument = frame.contentDocument || frame.contentWindow.document;
90
- let frameWindow = frame.contentWindow;
91
- allFrames.push({
92
- document: frameDocument,
93
- window: frameWindow,
94
- frameElement: frame,
95
- });
96
- }
97
- let result = new Set();
98
- for (let frame of allFrames) {
99
- let callbackResult = callback(frame);
100
- if (
101
- callbackResult &&
102
- typeof callbackResult[Symbol.iterator] === "function"
103
- )
104
- callbackResult.forEach((el) => result.add(el));
105
- else if (callbackResult) result.add(callbackResult);
106
- }
107
-
108
- return Array.from(result);
109
- }
110
-
111
- export function cssPath(node) {
112
- let pathSplits = [];
113
- do {
114
- if (!node || !node.tagName) return false;
115
- let pathSplit = node.tagName.toLowerCase();
116
- if (node.id && node.tagName !== "BODY") pathSplit += "#" + node.id;
117
-
118
- if (node.classList.length && node.tagName !== "BODY") {
119
- node.classList.forEach((item) => {
120
- if (item.indexOf(":") === -1) pathSplit += "." + item;
121
- });
122
- }
123
-
124
- if (node.tagName !== "BODY" && node.parentNode) {
125
- let index = Array.prototype.indexOf.call(
126
- node.parentNode.children,
127
- node
128
- );
129
- pathSplit += `:nth-child(${index + 1})`;
130
- }
131
-
132
- pathSplits.unshift(pathSplit);
133
- node = node.parentNode;
134
- } while (node.tagName !== "HTML");
135
-
136
- return pathSplits.join(" > ");
137
- }
138
-
139
- export function getTopMostWindow() {
140
- let parentWindow = window;
141
- while (parentWindow !== window.parent) parentWindow = window.parent;
142
- return parentWindow;
143
- }
144
-
145
- export function findIframeFromElement(windowObject, element) {
146
- let frameElement;
147
- allFrame((frame) => {
148
- if (frame.document.contains(element)) frameElement = frame.frameElement;
149
- // window.cc.findIframeFromElement(frame.window, element);
150
- });
151
- return frameElement;
152
- }
153
-
154
- export function getIframeFromPath(path) {
155
- let topWindow = getTopMostWindow;
156
-
157
- path.forEach((selector) => {
158
- if (topWindow) topWindow = topWindow.querySelector(selector);
159
- });
160
- return topWindow;
161
- }
162
- // DO NOT REMOVE
163
-
164
- export function* configMatch(elementConfig, element) {
165
- for (let config of elementConfig) {
166
- // if (!Array.isArray(config.selector))
167
- // config.selector = [config.selector];
168
-
169
- if (config.selector && element.matches(config.selector)) yield config;
170
- }
171
- return;
172
- }
173
-
174
-
175
- // export function configMatch2(elementConfig, element) {
176
- // let result = [];
177
- // for (let config of elementConfig) {
178
- // if (config.selector && element.matches(config.selector)) result.push(config);
179
- // }
180
- // return result;
181
- // }
182
-
183
- // DO NOT REMOVE
184
-
185
- // an opiniated function uses configMatch2 to read configs
186
- // WARNING: the config iterated from top to bottom. for deseired effect elementConfig should be reveresed
187
- // typeof elementConfig: array of objects and every objects containing keys as false, true or a selector
188
- // element: the element to read attributes
189
- // key: the key in which is in elementConfig and on match onSuccess callback will be called
190
- export function configExecuter(element, key, onSuccess, elementConfig) {
191
- for (let config of configMatch(elementConfig || window.elementConfig, element))
192
- if (config[key] === true) return onSuccess(element, config);
193
- else if (config[key] === false) return false;
194
- else if (config[key] === undefined) continue;
195
- else if (isValidSelector(config[key]))
196
- return onSuccess(element, config, true);
197
- else console.warn("builder: wrong element config ", config);
198
-
199
- return false;
200
- }
201
-
202
-
203
- export function parseTextToHtml(text) {
204
- let doc = new DOMParser().parseFromString(text, "text/html");
205
- if (doc.head.children[0]) return doc.head.children[0];
206
- else return doc.body.children[0];
207
- }
208
-
209
- export function splitBydelimiter(str, delimiter) {
210
- return str.split(delimiter).map((s) => s.trim());
211
- }
212
-
213
- export function joinBydelimiter(str, delimiter) {
214
- return str.map((s) => s.trim()).join(delimiter);
215
- }
216
-
217
- export function isValidSelector(selector) {
218
- try {
219
- document.createDocumentFragment().querySelector(selector);
220
- }
221
- catch (error) {
222
- return false;
223
- }
224
- return true;
225
- }
226
-
227
- export function getElementPath(element, returnContext) {
228
- let path = [];
229
-
230
- let topWindow = window;
231
- let iframeElement = findIframeFromElement(topWindow, element);
232
- let p = cssPath(iframeElement);
233
- if (p) path.unshift(p);
234
-
235
- return returnContext ? { path, document: iframeElement || document } : path;
236
- //TODO: support for nested iframe
237
- // while(iframeElement !== findIframeFromElement(topWindow,iframeElement))
238
- // {
239
- // iframeElement = findIframeFromElement(topWindow,iframeElement);
240
- // path.unshift(cssPath(iframeElement))
241
- // }
242
- }
243
-
244
- export function logger(level = "all") {
245
- if (!['all', 'error', 'warn', 'log', 'off'].includes(level))
246
- throw new Error('level must be one of all, error, warn, log or off')
247
- return {
248
- error: function(msg) {
249
- // if (compoentToLoad.includes(comName))
250
- if (['all', 'error'].includes(level))
251
- console.error.apply(console, arguments)
252
- },
253
- warn: function(msg) {
254
- // if (compoentToLoad.includes(comName))
255
- if (['all', 'error', 'warn'].includes(level))
256
- console.warn.apply(console, arguments)
257
- },
258
- log: function() {
259
- // if (compoentToLoad.includes(comName))
260
- if (['all', 'error', 'warn', 'log'].includes(level))
261
- console.log.apply(console, arguments)
262
- },
263
- }
264
-
265
- }
266
-
267
- export async function waitForLoad(doc) {
268
-
269
- if (doc.contentDocument.readyState === 'loading') {
270
- try {
271
- await new Promise((resolve, reject) => {
272
- doc.contentWindow.addEventListener('load', (e) => resolve())
273
- });
274
- }
275
- catch (err) {
276
- console.error('iframe can not be loaded')
277
- }
278
- // this.observerElements(doc.contentWindow)
279
- // doc.contentWindow.observedByCCAttributes = true;
280
- }
281
- }
282
-
283
- //export function frameQuerySelector(comSelector) {
284
- // let [canvasSelector, selector] = comSelector.split(';');
285
- // let canvas = this.querySelector(canvasSelector);
286
- // if (!canvas)
287
- // return null;
288
-
289
-
290
- // return canvas.contentWindow.document.querySelector(selector);
291
- // }
292
-
293
- export function getComplexSelector(node, comSelector) {
294
- let selectors = comSelector.split(';');
295
- let canvas = node;
296
- for (let i = 0; i < selectors.length - 1; i++) {
297
- canvas = canvas.querySelector(selectors[i]);
298
- if (!canvas)
299
- return [];
300
-
301
- }
302
- return [this, [selectors.length - 1]]
303
- }
304
-
305
- export function frameQuerySelector(comSelector) {
306
- let [canvas, selector] = getComplexSelector(this, comSelector)
307
- if (canvas)
308
- return canvas.contentWindow.document.querySelector(selector);
309
- return null;
310
-
311
- }
312
-
313
- export function frameQuerySelectorAll(comSelector) {
314
- let [canvas, selector] = getComplexSelector(this, comSelector)
315
- if (canvas)
316
- return canvas.contentWindow.document.querySelectorAll(selector);
317
- return [];
318
-
319
-
320
- }
321
-
322
- async function complexSelector(comSelector, callback) {
323
- let [canvasSelector, selector] = comSelector.split(';');
324
- let canvas = document.querySelector(canvasSelector);
325
- if (!canvas) {
326
- console.warn('complex selector canvas now found for', comSelector);
327
- return;
328
- }
329
-
330
- if (canvas.contentDocument.readyState === 'loading') {
331
- try {
332
- await new Promise((resolve, reject) => {
333
- canvas.contentWindow.addEventListener('load', (e) => resolve());
334
- });
335
- }
336
- catch(err) {
337
- console.error('iframe can not be loaded');
338
- }
339
- }
340
-
341
- if (canvas.contentWindow.parent.CoCreate.observer && !observerInit.has(canvas.contentWindow)) {
342
- observerElements(canvas.contentWindow);
343
- }
344
-
345
- return callback(canvas.contentWindow.document, selector);
346
- }
347
-
348
- // function eid(html){
349
- // let dom = domParser(html);
350
- // let elements = dom.querySelectorAll('*');
351
- // for (let element of elements){
352
- // if (!element.getAttribute('eid')){
353
- // element.setAttribute(eid, uuid(8))
354
- // }
355
- // }
356
- // return dom.outterHTML
357
- // }
358
-
359
-
360
- // export function computeStyles(el, properties) {
361
- // let computed = window.getComputedStyle(el);
362
- // let result = {};
363
- // properties.forEach((property) => {
364
- // result[property] = parseInt(computed[property]);
365
- // });
366
- // return result;
367
- // }
368
-
369
- function isObjectEmpty(obj) {
370
- for (var x in obj) { return false; }
371
- return true;
372
- }
373
-
374
- export function getFrameSelector(selector) {
375
- let selectorArray = [];
376
- if (selector) {
377
- let selectors = [selector];
378
- if (selector.indexOf(',') !== -1){
379
- selectors = selector.split(',');
380
- }
381
- for (let selector of selectors){
382
- let els;
383
- if (selector.indexOf(';') !== -1) {
384
- let [documentSelector, targetSelector] = selector.split(';');
385
- let frame = document.querySelector(documentSelector);
386
- if (frame)
387
- selectorArray.push({Document: frame.contentDocument, selector: targetSelector});
388
- }
389
- else
390
- selectorArray.push({Document: document, selector: selector});
391
- }
392
- return selectorArray;
393
- }
394
- }
395
- export function queryFrameSelectorAll(selector) {
396
- let elements = [];
397
-
398
- if (selector) {
399
- let selectors = [selector];
400
- if (selector.indexOf(',') !== -1){
401
- selectors = selector.split(',');
402
- }
403
- for (let selector of selectors){
404
- let els;
405
- if (selector.indexOf(';') !== -1) {
406
- let [documentSelector, targetSelector] = selector.split(';');
407
- let frame = document.querySelector(documentSelector);
408
- if (frame) {
409
- let targetDocument = frame.contentDocument;
410
- if (targetSelector)
411
- els = targetDocument.querySelectorAll(targetSelector);
412
- else
413
- if (targetDocument.clickedElement)
414
- els = [targetDocument.clickedElement];
415
- }
416
- }
417
- else
418
- els = document.querySelectorAll(selector);
419
- if (els){
420
- els = Array.prototype.slice.call(els);
421
- elements = elements.concat(els);
422
- }
423
- }
424
- return elements;
425
- }
426
- }
427
-
428
- function decodeArray(data) {
429
- let keys = Object.keys(data);
430
- let objectData = {};
431
-
432
- keys.forEach((k) => {
433
- let nk = k
434
- if (/\[([0-9]*)\]/g.test(k)) {
435
- nk = nk.replace(/\[/g, '.');
436
- if (nk.endsWith(']'))
437
- nk = nk.slice(0, -1)
438
- nk = nk.replace(/\]./g, '.');
439
- nk = nk.replace(/\]/g, '.');
440
- }
441
- objectData[nk] = data[k];
442
- });
443
- return objectData;
444
- }
445
-
446
- function valueTypes(data) {
447
- let object = {}
448
- if ( typeof data === 'object' ) {
449
- // update['$set'] = {}
450
- for (let key of Object.keys(data)) {
451
- let value = data[key]
452
- let val;
453
- let valueType = typeof value;
454
- switch(valueType) {
455
- case 'string':
456
- val = value
457
- break;
458
- case 'number':
459
- val = Number(value)
460
- break;
461
- case 'object':
462
- if (Array.isArray(value))
463
- val = new Array(...value)
464
- else
465
- val = new Object(value)
466
- break;
467
- default:
468
- val = value
469
- }
470
- object[key] = val
471
- }
472
- return object;
473
- }
474
- }
475
-
476
-
477
- export default {
478
- getElementPath,
479
- isValidSelector,
480
- joinBydelimiter,
481
- splitBydelimiter,
482
- parseTextToHtml,
483
- configExecuter,
484
- configMatch,
485
- getIframeFromPath,
486
- findIframeFromElement,
487
- getTopMostWindow,
488
- cssPath,
489
- allFrame,
490
- checkAttrValue,
491
- getAttributes,
492
- isJsonString,
493
- getParentFromElement,
494
- logger
495
- }