-
-
Notifications
You must be signed in to change notification settings - Fork 309
/
util.js
executable file
·1589 lines (1379 loc) · 60.5 KB
/
util.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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* wysiwyg web editor
*
* suneditor.js
* Copyright 2017 JiHong Lee.
* MIT license.
*/
'use strict';
/**
* @description utility function
*/
const util = {
_d: document,
_w: window,
isIE: window.navigator.userAgent.match(/(MSIE|Trident.*rv[ :])([0-9]+)/) !== null,
isIE_Edge: (window.navigator.userAgent.match(/(MSIE|Trident.*rv[ :])([0-9]+)/) !== null) || (window.navigator.appVersion.indexOf('Edge') > -1),
/**
* @description Removes attribute values such as style and converts tags that do not conform to the "html5" standard.
* @param {String} text
* @returns {String} HTML string
* @private
*/
_tagConvertor: function (text) {
const ec = {'b': 'strong', 'i': 'em', 'ins': 'u', 'strike': 'del', 's': 'del'};
return text.replace(/(<\/?)(b|strong|i|em|ins|u|s|strike|del)\b\s*(?:[^>^<]+)?\s*(?=>)/ig, function (m, t, n) {
return t + ((typeof ec[n] === 'string') ? ec[n] : n);
});
},
/**
* @description HTML Reserved Word Converter.
* @param {String} contents
* @returns {String} HTML string
* @private
*/
_HTMLConvertor: function (contents) {
const ec = {'&': '&', '\u00A0': ' ', '\'': '"', '<': '<', '>': '>'};
return contents.replace(/&|\u00A0|'|<|>/g, function (m) {
return (typeof ec[m] === 'string') ? ec[m] : m;
});
},
/**
* @description Unicode Character 'ZERO WIDTH SPACE' (\u200B)
*/
zeroWidthSpace: '\u200B',
/**
* @description Regular expression to find 'zero width space' (/\u200B/g)
*/
zeroWidthRegExp: new RegExp(String.fromCharCode(8203), 'g'),
/**
* @description Regular expression to find only 'zero width space' (/^\u200B+$/)
*/
onlyZeroWidthRegExp: new RegExp('^' + String.fromCharCode(8203) + '+$'),
/**
* @description A method that checks If the text is blank or to see if it contains 'ZERO WIDTH SPACE' or empty (util.zeroWidthSpace)
* @param {String|Node} text String value or Node
* @returns {Boolean}
*/
onlyZeroWidthSpace: function (text) {
if (typeof text !== 'string') text = text.textContent;
return text === '' || this.onlyZeroWidthRegExp.test(text);
},
/**
* @description Gets XMLHttpRequest object
* @returns {XMLHttpRequest|ActiveXObject}
*/
getXMLHttpRequest: function () {
/** IE */
if (this._w.ActiveXObject) {
try {
return new ActiveXObject('Msxml2.XMLHTTP');
} catch (e) {
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch (e1) {
return null;
}
}
}
/** netscape */
else if (this._w.XMLHttpRequest) {
return new XMLHttpRequest();
}
/** fail */
else {
return null;
}
},
/**
* @description Create Element node
* @param {String} elementName Element name
* @returns {Element}
*/
createElement: function (elementName) {
return this._d.createElement(elementName);
},
/**
* @description Create text node
* @param {String} text text contents
* @returns {Node}
*/
createTextNode: function (text) {
return this._d.createTextNode(text || '');
},
/**
* @description Get the the tag path of the arguments value
* If not found, return the first found value
* @param {Array} nameArray File name array
* @param {String} extension js, css
* @returns {String}
*/
getIncludePath: function (nameArray, extension) {
let path = '';
const pathList = [];
const tagName = extension === 'js' ? 'script' : 'link';
const src = extension === 'js' ? 'src' : 'href';
let fileName = '(?:';
for (let i = 0, len = nameArray.length; i < len; i++) {
fileName += nameArray[i] + (i < len - 1 ? '|' : ')');
}
const regExp = new this._w.RegExp('(^|.*[\\/])' + fileName + '(\\.[^\\/]+)?\.' + extension + '(?:\\?.*|;.*)?$', 'i');
const extRegExp = new this._w.RegExp('.+\\.' + extension + '(?:\\?.*|;.*)?$', 'i');
for (let c = this._d.getElementsByTagName(tagName), i = 0; i < c.length; i++) {
if (extRegExp.test(c[i][src])) {
pathList.push(c[i]);
}
}
for (let i = 0; i < pathList.length; i++) {
let editorTag = pathList[i][src].match(regExp);
if (editorTag) {
path = editorTag[0];
break;
}
}
if (path === '') path = pathList.length > 0 ? pathList[0][src] : '';
-1 === path.indexOf(':/') && '//' !== path.slice(0, 2) && (path = 0 === path.indexOf('/') ? location.href.match(/^.*?:\/\/[^\/]*/)[0] + path : location.href.match(/^[^\?]*\/(?:)/)[0] + path);
if (!path) throw '[SUNEDITOR.util.getIncludePath.fail] The SUNEDITOR installation path could not be automatically detected. (name: +' + name + ', extension: ' + extension + ')';
return path;
},
/**
* @description Returns the CSS text that has been applied to the current page.
* @param {Document|null} doc To get the CSS text of an document(core._wd). If null get the current document.
* @returns {String} Styles string
*/
getPageStyle: function (doc) {
let cssText = '';
const sheets = (doc || this._d).styleSheets;
for (let i = 0, len = sheets.length, rules; i < len; i++) {
try {
rules = sheets[i].cssRules;
} catch (e) {
continue;
}
for (let c = 0, cLen = rules.length; c < cLen; c++) {
cssText += rules[c].cssText;
}
}
return cssText;
},
/**
* @description Get the argument iframe's document object
* @param {Element} iframe Iframe element (context.element.wysiwygFrame)
* @returns {Document}
*/
getIframeDocument: function (iframe) {
let wDocument = iframe.contentWindow || iframe.contentDocument;
if (wDocument.document) wDocument = wDocument.document;
return wDocument;
},
/**
* @description Get attributes of argument element to string ('class="---" name="---" ')
* @param {Element} element Element object
* @param {Array|null} exceptAttrs Array of attribute names to exclude from the result
* @returns {String}
*/
getAttributesToString: function (element, exceptAttrs) {
if (!element.attributes) return '';
const attrs = element.attributes;
let attrString = '';
for (let i = 0, len = attrs.length; i < len; i++) {
if (exceptAttrs && exceptAttrs.indexOf(attrs[i].name) > -1) continue;
attrString += attrs[i].name + '="' + attrs[i].value + '" ';
}
return attrString;
},
/**
* @descriptionGets Get the length in bytes of a string.
* referencing code: "https://github.com/shaan1974/myrdin/blob/master/expressions/string.js#L11"
* @param {String} text String text
* @returns {Number}
*/
getByteLength: function(text) {
const encoder = this._w.encodeURIComponent;
let cr, cl;
if (this.isIE_Edge) {
cl = this._w.unescape(encoder(text.toString())).length;
cr = 0;
if (encoder(text.toString()).match(/(%0A|%0D)/gi) !== null) {
cr = encoder(text.toString()).match(/(%0A|%0D)/gi).length;
}
return cl + cr;
} else {
cl = (new this._w.TextEncoder('utf-8').encode(text.toString())).length;
cr = 0;
if (encoder(text.toString()).match(/(%0A|%0D)/gi) !== null) {
cr = encoder(text.toString()).match(/(%0A|%0D)/gi).length;
}
return cl + cr;
}
},
/**
* @description It is judged whether it is the edit region top div element or iframe's body tag.
* @param {Node} element The node to check
* @returns {Boolean}
*/
isWysiwygDiv: function (element) {
if (element && element.nodeType === 1 && (this.hasClass(element, 'se-wrapper-wysiwyg') || /^BODY$/i.test(element.nodeName))) return true;
return false;
},
/**
* @description It is judged whether it is a node related to the text style.
* (strong|span|font|b|var|i|em|u|ins|s|strike|del|sub|sup|mark|a|label)
* @param {Node} element The node to check
* @returns {Boolean}
*/
isTextStyleElement: function (element) {
return element && element.nodeType !== 3 && /^(strong|span|font|b|var|i|em|u|ins|s|strike|del|sub|sup|mark|a|label)$/i.test(element.nodeName);
},
/**
* @description It is judged whether it is the format element (P, DIV, H[1-6], PRE, LI)
* Format element also contain "free format Element"
* @param {Node} element The node to check
* @returns {Boolean}
*/
isFormatElement: function (element) {
return (element && element.nodeType === 1 && (/^(P|DIV|H[1-6]|PRE|LI|TD|TH)$/i.test(element.nodeName) || this.hasClass(element, '(\\s|^)__se__format__replace_.+(\\s|$)|(\\s|^)__se__format__free_.+(\\s|$)')) && !this.isComponent(element) && !this.isWysiwygDiv(element));
},
/**
* @description It is judged whether it is the range format element. (BLOCKQUOTE, OL, UL, FIGCAPTION, TABLE, THEAD, TBODY, TR, TH, TD)
* * Range format element is wrap the format element (util.isFormatElement)
* @param {Node} element The node to check
* @returns {Boolean}
*/
isRangeFormatElement: function (element) {
return (element && element.nodeType === 1 && (/^(BLOCKQUOTE|OL|UL|FIGCAPTION|TABLE|THEAD|TBODY|TR|TH|TD)$/i.test(element.nodeName) || this.hasClass(element, '(\\s|^)__se__format__range_.+(\\s|$)')));
},
/**
* @description It is judged whether it is the free format element. (PRE)
* Free format elements's line break is "BR" tag.
* Free format elements is included in the format element.
* @param {Node} element The node to check
* @returns {Boolean}
*/
isFreeFormatElement: function (element) {
return (element && element.nodeType === 1 && (/^PRE$/i.test(element.nodeName) || this.hasClass(element, '(\\s|^)__se__format__free_.+(\\s|$)')) && !this.isComponent(element) && !this.isWysiwygDiv(element));
},
/**
* @description It is judged whether it is the component [img, iframe] cover(element className - ".se-component") and table, hr
* @param {Node} element The node to check
* @returns {Boolean}
*/
isComponent: function (element) {
return element && (/se-component/.test(element.className) || /^(TABLE|HR)$/.test(element.nodeName));
},
/**
* @description It is judged whether it is the component [img, iframe] cover(element className - ".se-component")
* @param {Node} element The node to check
* @returns {Boolean}
*/
isMediaComponent: function (element) {
return element && /se-component/.test(element.className);
},
/**
* @description If a parent node that contains an argument node finds a format node (util.isFormatElement), it returns that node.
* @param {Node} element Reference node.
* @param {Function|null} validation Additional validation function.
* @returns {Element|null}
*/
getFormatElement: function (element, validation) {
if (!element) return null;
if (!validation) {
validation = function () { return true; };
}
while (element) {
if (this.isWysiwygDiv(element)) return null;
if (this.isRangeFormatElement(element)) element.firstElementChild;
if (this.isFormatElement(element) && validation(element)) return element;
element = element.parentNode;
}
return null;
},
/**
* @description If a parent node that contains an argument node finds a format node (util.isRangeFormatElement), it returns that node.
* @param {Node} element Reference node.
* @param {Function|null} validation Additional validation function.
* @returns {Element|null}
*/
getRangeFormatElement: function (element, validation) {
if (!element) return null;
if (!validation) {
validation = function () { return true; };
}
while (element) {
if (this.isWysiwygDiv(element)) return null;
if (this.isRangeFormatElement(element) && !/^(THEAD|TBODY|TR)$/i.test(element.nodeName) && validation(element)) return element;
element = element.parentNode;
}
return null;
},
/**
* @description If a parent node that contains an argument node finds a free format node (util.isFreeFormatElement), it returns that node.
* @param {Node} element Reference node.
* @param {Function|null} validation Additional validation function.
* @returns {Element|null}
*/
getFreeFormatElement: function (element, validation) {
if (!element) return null;
if (!validation) {
validation = function () { return true; };
}
while (element) {
if (this.isWysiwygDiv(element)) return null;
if (this.isFreeFormatElement(element) && validation(element)) return element;
element = element.parentNode;
}
return null;
},
/**
* @description Add style and className of copyEl to originEl
* @param {Element} originEl Origin element
* @param {Element} copyEl Element to copy
*/
copyTagAttributes: function (originEl, copyEl) {
if (copyEl.style.cssText) {
originEl.style.cssText += copyEl.style.cssText;
}
const classes = copyEl.classList;
for (let i = 0, len = classes.length; i < len; i++) {
this.addClass(originEl, classes[i]);
}
if (!originEl.style.cssText) originEl.removeAttribute('style');
if (!originEl.className.trim()) originEl.removeAttribute('class');
},
/**
* @description Copy and apply attributes of format tag that should be maintained. (style, class) Ignore "__se__format__" class
* @param {Element} originEl Origin element
* @param {Element} copyEl Element to copy
*/
copyFormatAttributes: function (originEl, copyEl) {
copyEl = copyEl.cloneNode(false);
copyEl.className = copyEl.className.replace(/(\s|^)__se__format__[^\s]+/g, '');
this.copyTagAttributes(originEl, copyEl);
},
/**
* @description Get the item from the array that matches the condition.
* @param {Array|HTMLCollection|NodeList} array Array to get item
* @param {Function|null} validation Conditional function
* @param {Boolean} multi If true, returns all items that meet the criteria otherwise, returns an empty array.
* If false, returns only one item that meet the criteria otherwise return null.
* @returns {Array|Object}
*/
getArrayItem: function (array, validation, multi) {
if (!array || array.length === 0) return null;
validation = validation || function () { return true; };
const arr = [];
for (let i = 0, len = array.length, a; i < len; i++) {
a = array[i];
if (validation(a)) {
if (!multi) return a;
else arr.push(a);
}
}
return !multi ? null : arr;
},
/**
* @description Get the index of the argument value in the element array
* @param {Array|HTMLCollection|NodeList} array element array
* @param {Node} element The element to find index
* @returns {Number}
*/
getArrayIndex: function (array, element) {
let idx = -1;
for (let i = 0, len = array.length; i < len; i++) {
if (array[i] === element) {
idx = i;
break;
}
}
return idx;
},
/**
* @description Get the next index of the argument value in the element array
* @param {Array|HTMLCollection|NodeList} array element array
* @param {Node} item The element to find index
* @returns {Number}
*/
nextIdx: function (array, item) {
let idx = this.getArrayIndex(array, item);
if (idx === -1) return -1;
return idx + 1;
},
/**
* @description Get the previous index of the argument value in the element array
* @param {Array|HTMLCollection|NodeList} array Element array
* @param {Node} item The element to find index
* @returns {Number}
*/
prevIdx: function (array, item) {
let idx = this.getArrayIndex(array, item);
if (idx === -1) return -1;
return idx - 1;
},
/**
* @description Returns the index compared to other sibling nodes.
* @param {Node} node The Node to find index
* @returns {Number}
*/
getPositionIndex: function (node) {
let idx = 0;
while ((node = node.previousSibling)) {
idx += 1;
}
return idx;
},
/**
* @description Returns the position of the "node" in the "parentNode" in a numerical array.
* ex) <p><span>aa</span><span>bb</span></p> : getNodePath(node: "bb", parentNode: "<P>") -> [1, 0]
* @param {Node} node The Node to find position path
* @param {Node|null} parentNode Parent node. If null, wysiwyg div area
* @param {Object|null} _newOffsets If you send an object of the form "{s: 0, e: 0}", the text nodes that are attached together are merged into one, centered on the "node" argument.
* "_newOffsets.s" stores the length of the combined characters after "node" and "_newOffsets.e" stores the length of the combined characters before "node".
* Do not use unless absolutely necessary.
* @returns {Array}
*/
getNodePath: function (node, parentNode, _newOffsets) {
const path = [];
let finds = true;
this.getParentElement(node, function (el) {
if (el === parentNode) finds = false;
if (finds && !this.isWysiwygDiv(el)) {
// merge text nodes
if (_newOffsets && el.nodeType === 3) {
let temp = null, tempText = null;
_newOffsets.s = _newOffsets.e = 0;
let previous = el.previousSibling;
while (previous && previous.nodeType === 3) {
tempText = previous.textContent.replace(this.zeroWidthRegExp, '');
_newOffsets.s += tempText.length;
el.textContent = tempText + el.textContent;
temp = previous;
previous = previous.previousSibling;
this.removeItem(temp);
}
let next = el.nextSibling;
while (next && next.nodeType === 3) {
tempText = next.textContent.replace(this.zeroWidthRegExp, '');
_newOffsets.e += tempText.length;
el.textContent += tempText;
temp = next;
next = next.nextSibling;
this.removeItem(temp);
}
}
// index push
path.push(el);
}
return false;
}.bind(this));
return path.map(this.getPositionIndex).reverse();
},
/**
* @description Returns the node in the location of the path array obtained from "util.getNodePath".
* @param {Array} offsets Position array, array obtained from "util.getNodePath"
* @param {Node} parentNode Base parent element
* @returns {Node}
*/
getNodeFromPath: function (offsets, parentNode) {
let current = parentNode;
let nodes;
for (let i = 0, len = offsets.length; i < len; i++) {
nodes = current.childNodes;
if (nodes.length === 0) break;
if (nodes.length <= offsets[i]) {
current = nodes[nodes.length - 1];
} else {
current = nodes[offsets[i]];
}
}
return current;
},
/**
* @description Compares the style and class for equal values.
* Returns true if both are text nodes.
* @param {Node} a Node to compare
* @param {Node} b Node to compare
* @returns {Boolean}
*/
isSameAttributes: function (a, b) {
if (a.nodeType === 3 && b.nodeType === 3) return true;
if (a.nodeType === 3 || b.nodeType === 3) return false;
const style_a = a.style;
const style_b = b.style;
let compStyle = 0;
for (let i = 0, len = style_a.length; i < len; i++) {
if (style_a[style_a[i]] === style_b[style_a[i]]) compStyle++;
}
const class_a = a.classList;
const class_b = b.classList;
const reg = this._w.RegExp;
let compClass = 0;
for (let i = 0, len = class_a.length; i < len; i++) {
if (reg('(\s|^)' + class_a[i] + '(\s|$)').test(class_b.value)) compClass++;
}
return (compStyle === style_b.length && compStyle === style_a.length) && (compClass === class_b.length && compClass === class_a.length);
},
/**
* @description Check the node is a list (ol, ul)
* @param {Node|String} node The element or element name to check
* @returns {Boolean}
*/
isList: function (node) {
return node && /^(OL|UL)$/i.test(typeof node === 'string' ? node : node.nodeName);
},
/**
* @description Check the node is a list cell (li)
* @param {Node|String} node The element or element name to check
* @returns {Boolean}
*/
isListCell: function (node) {
return node && /^LI$/i.test(typeof node === 'string' ? node : node.nodeName);
},
/**
* @description Check the node is a table (table, thead, tbody, tr, th, td)
* @param {Node|String} node The element or element name to check
* @returns {Boolean}
*/
isTable: function (node) {
return node && /^(TABLE|THEAD|TBODY|TR|TH|TD)$/i.test(typeof node === 'string' ? node : node.nodeName);
},
/**
* @description Check the node is a table cell (td, th)
* @param {Node|String} node The element or element name to check
* @returns {Boolean}
*/
isCell: function (node) {
return node && /^(TD|TH)$/i.test(typeof node === 'string' ? node : node.nodeName);
},
/**
* @description Check the node is a break node (BR)
* @param {Node|String} node The element or element name to check
* @returns {Boolean}
*/
isBreak: function (node) {
return node && /^BR$/i.test(typeof node === 'string' ? node : node.nodeName);
},
/**
* @description Check the node is a anchor node (A)
* @param {Node|String} node The element or element name to check
* @returns {Boolean}
*/
isAnchor: function (node) {
return node && /^A$/i.test(typeof node === 'string' ? node : node.nodeName);
},
/**
* @description Check the node is a media node (img, iframe, audio, video, canvas)
* @param {Node|String} node The element or element name to check
* @returns {Boolean}
*/
isMedia: function (node) {
return node && /^(IMG|IFRAME|AUDIO|VIDEO|CANVAS)$/i.test(typeof node === 'string' ? node : node.nodeName);
},
/**
* @description Checks for numeric (with decimal point).
* @param {String|Number} text Text string or number
* @returns {Boolean}
*/
isNumber: function (text) {
return !!text && /^-?\d+(\.\d+)?$/.test(text + '');
},
/**
* @description Get a number.
* @param {String|Number} text Text string or number
* @param {Number} maxDec Maximum number of decimal places (-1 : Infinity)
* @returns {Number}
*/
getNumber: function (text, maxDec) {
if (!text) return null;
let number = (text + '').match(/-?\d+(\.\d+)?/);
if (!number || !number[0]) return null;
number = number[0];
return maxDec < 0 ? number * 1 : maxDec === 0 ? this._w.Math.round(number * 1) : (number * 1).toFixed(maxDec) * 1;
},
/**
* @description Get all "children" of the argument value element (Without text nodes)
* @param {Element} element element to get child node
* @param {Function|null} validation Conditional function
* @returns {Array}
*/
getListChildren: function (element, validation) {
const children = [];
if (!element || !element.children || element.children.length === 0) return children;
validation = validation || function () { return true; };
(function recursionFunc(current) {
if (element !== current && validation(current)) {
children.push(current);
}
for (let i = 0, len = current.children.length; i < len; i++) {
recursionFunc(current.children[i]);
}
})(element);
return children;
},
/**
* @description Get all "childNodes" of the argument value element (Include text nodes)
* @param {Node} element element to get child node
* @param {Function|null} validation Conditional function
* @returns {Array}
*/
getListChildNodes: function (element, validation) {
const children = [];
if (!element || element.childNodes.length === 0) return children;
validation = validation || function () { return true; };
(function recursionFunc(current) {
if (element !== current && validation(current)) {
children.push(current);
}
for (let i = 0, len = current.childNodes.length; i < len; i++) {
recursionFunc(current.childNodes[i]);
}
})(element);
return children;
},
/**
* @description Returns the number of parents nodes.
* "0" when the parent node is the WYSIWYG area.
* "-1" when the element argument is the WYSIWYG area.
* @param {Node} element The element to check
* @returns {Number}
*/
getElementDepth: function (element) {
if (!element || this.isWysiwygDiv(element)) return -1;
let depth = 0;
element = element.parentNode;
while (element && !this.isWysiwygDiv(element)) {
depth += 1;
element = element.parentNode;
}
return depth;
},
/**
* @description Get the parent element of the argument value.
* A tag that satisfies the query condition is imported.
* Returns null if not found.
* @param {Node} element Reference element
* @param {String|Function} query Query String (nodeName, .className, #ID, :name) or validation function.
* Not use it like jquery.
* Only one condition can be entered at a time.
* @returns {Element|null}
*/
getParentElement: function (element, query) {
let check;
if (typeof query === 'function') {
check = query;
} else {
let attr;
if (/^\./.test(query)) {
attr = 'className';
query = query.split('.')[1];
} else if (/^#/.test(query)) {
attr = 'id';
query = '^' + query.split('#')[1] + '$';
} else if (/^:/.test(query)) {
attr = 'name';
query = '^' + query.split(':')[1] + '$';
} else {
attr = 'nodeName';
query = '^' + query + '$';
}
const regExp = new this._w.RegExp(query, 'i');
check = function (el) {
return regExp.test(el[attr]);
};
}
while (element && !check(element)) {
if (this.isWysiwygDiv(element)) {
return null;
}
element = element.parentNode;
}
return element;
},
/**
* @description Get the child element of the argument value.
* A tag that satisfies the query condition is imported.
* Returns null if not found.
* @param {Node} element Reference element
* @param {String|Function} query Query String (nodeName, .className, #ID, :name) or validation function.
* @param {Boolean} last If true returns the last node among the found child nodes. (default: first node)
* Not use it like jquery.
* Only one condition can be entered at a time.
* @returns {Element|null}
*/
getChildElement: function (element, query, last) {
let check;
if (typeof query === 'function') {
check = query;
} else {
let attr;
if (/^\./.test(query)) {
attr = 'className';
query = query.split('.')[1];
} else if (/^#/.test(query)) {
attr = 'id';
query = '^' + query.split('#')[1] + '$';
} else if (/^:/.test(query)) {
attr = 'name';
query = '^' + query.split(':')[1] + '$';
} else {
attr = 'nodeName';
query = '^' + (query === 'text' ? '#' + query : query) + '$';
}
const regExp = new this._w.RegExp(query, 'i');
check = function (el) {
return regExp.test(el[attr]);
};
}
const childList = this.getListChildNodes(element, function (current) {
return check(current);
});
return childList[last ? childList.length - 1 : 0];
},
/**
* @description 1. The first node of all the child nodes of the "first" element is returned.
* 2. The last node of all the child nodes of the "last" element is returned.
* 3. When there is no "last" element, the first and last nodes of all the children of the "first" element are returned.
* { sc: "first", ec: "last" }
* @param {Node} first First element
* @param {Node|null} last Last element
* @returns {Object}
*/
getEdgeChildNodes: function (first, last) {
if (!first) return;
if (!last) last = first;
while (first && first.nodeType === 1 && first.childNodes.length > 0 && !this.isBreak(first)) first = first.firstChild;
while (last && last.nodeType === 1 && last.childNodes.length > 0 && !this.isBreak(last)) last = last.lastChild;
return {
sc: first,
ec: last || first
};
},
/**
* @description Returns the position of the left and top of argument. {left:0, top:0}
* @param {Node} element Target node
* @param {Element|null} wysiwygFrame When use iframe option, iframe object should be sent (context.element.wysiwygFrame)
* @returns {Object}
*/
getOffset: function (element, wysiwygFrame) {
let offsetLeft = 0;
let offsetTop = 0;
let offsetElement = element.nodeType === 3 ? element.parentElement : element;
const wysiwyg = this.getParentElement(element, this.isWysiwygDiv.bind(this));
while (offsetElement && !this.hasClass(offsetElement, 'se-container') && offsetElement !== wysiwyg) {
offsetLeft += offsetElement.offsetLeft;
offsetTop += offsetElement.offsetTop;
offsetElement = offsetElement.offsetParent;
}
const iframe = wysiwygFrame && /iframe/i.test(wysiwygFrame.nodeName);
return {
left: offsetLeft + (iframe ? wysiwygFrame.parentElement.offsetLeft : 0),
top: (offsetTop - wysiwyg.scrollTop) + (iframe ? wysiwygFrame.parentElement.offsetTop : 0)
};
},
/**
* @description It compares the start and end indexes of "a" and "b" and returns the number of overlapping indexes in the range.
* ex) 1, 5, 4, 6 => "2" (4 ~ 5)
* @param {Number} aStart Start index of "a"
* @param {Number} aEnd End index of "a"
* @param {Number} bStart Start index of "b"
* @param {Number} bEnd Start index of "b"
* @returns {Number}
*/
getOverlapRangeAtIndex: function (aStart, aEnd, bStart, bEnd) {
if (aStart <= bEnd ? aEnd < bStart : aEnd > bStart) return 0;
const overlap = (aStart > bStart ? aStart : bStart) - (aEnd < bEnd ? aEnd : bEnd);
return (overlap < 0 ? overlap * -1 : overlap) + 1;
},
/**
* @description Set the text content value of the argument value element
* @param {Node} element Element to replace text content
* @param {String} txt Text to be applied
*/
changeTxt: function (element, txt) {
if (!element || !txt) return;
element.textContent = txt;
},
/**
* @description Replace element
* @param {Element} element Target element
* @param {String|Element} newElement String or element of the new element to apply
*/
changeElement: function (element, newElement) {
if (typeof newElement === 'string') {
if (element.outerHTML) {
element.outerHTML = newElement;
} else {
const doc = this.createElement('DIV');
doc.innerHTML = newElement;
newElement = doc.firstChild;
element.parentNode.replaceChild(newElement, element);
}
} else if (newElement.nodeType === 1) {
element.parentNode.replaceChild(newElement, element);
}
},
/**
* @description Set style, if all styles are deleted, the style properties are deleted.
* @param {Element} element Element to set style
* @param {String} styleName Style attribute name (marginLeft, textAlign...)
* @param {String|Number} value Style value
*/
setStyle: function (element, styleName, value) {
element.style[styleName] = value;
if (!value && !element.style.cssText) {
element.removeAttribute('style');
}
},
/**
* @description Determine whether any of the matched elements are assigned the given class
* @param {Element} element Elements to search class name
* @param {String} className Class name to search for
* @returns {Boolean}
*/
hasClass: function (element, className) {
if (!element) return;
return (new this._w.RegExp(className)).test(element.className);
},
/**
* @description Append the className value of the argument value element
* @param {Element} element Elements to add class name
* @param {String} className Class name to be add
*/
addClass: function (element, className) {
if (!element) return;
const check = new this._w.RegExp('(\\s|^)' + className + '(\\s|$)');
if (check.test(element.className)) return;
element.className += (element.className.length > 0 ? ' ' : '') + className;
},
/**
* @description Delete the className value of the argument value element
* @param {Element} element Elements to remove class name
* @param {String} className Class name to be remove
*/
removeClass: function (element, className) {
if (!element) return;
const check = new this._w.RegExp('(\\s|^)' + className + '(\\s|$)');
element.className = element.className.replace(check, ' ').trim();
if (!element.className.trim()) element.removeAttribute('class');
},
/**
* @description Argument value If there is no class name, insert it and delete the class name if it exists
* @param {Element} element Elements to replace class name
* @param {String} className Class name to be change
*/
toggleClass: function (element, className) {