-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDOM.js
More file actions
1083 lines (1039 loc) · 40.4 KB
/
Copy pathDOM.js
File metadata and controls
1083 lines (1039 loc) · 40.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
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
/**
* @module DOM
* @description Document-Object Model stuff
* @version 1.0
* @since 1.1
* @license MIT
* @author Maximilian Berkmann <maxieberkmann@gmail.com>
* @copyright Maximilian Berkmann 2016
* @requires module:essence
* @requires Misc
* @requires Files
* @type {Module}
* @exports DOM
*/
var DOM = new Module("DOM", "DOM stuff", ["Misc", "Files"], 1, function () {
BrowserDetect.init();
});
/* eslint no-undef: 0 */
/**
* @description Print onto something
* @param {*} text Data to be printed
* @param {boolean} [isHTML=false] Has to be formatted as an HTML code or not
* @param {string} [place="body"] Place to print <code>text</code>
* @returns {undefined}
* @see module:DOM~println
* @since 1.0
* @func
*/
function print (text, isHTML, place) {
$e(place || "body").isEmpty()? $e(place || "body").write(text, isHTML): $e(place || "body").after(text, isHTML)
}
/**
* @description Print-line onto something
* @param {*} text Data to be printed
* @param {boolean} [isHTML=false] Has to be formatted as an HTML code or not
* @param {string} [place="body"] Place to print <code>text</code>
* @returns {undefined}
* @see module:DOM~print
* @since 1.0
* @func
*/
function println (text, isHTML, place) {
$e(place || "body").isEmpty()? $e(place || "body").write(text + "<br />", isHTML): $e(place || "body").after(text + "<br />", true)
}
/**
* @description Temporarily add meta-data to the page
* @param {string} n Name
* @param {NumberLike} ctt Content
* @param {boolean} [httpe=false] HTTP Equiv specified ?
* @returns {undefined}
* @see module:DOM~getMetaData
* @since 1.0
* @func
*/
function addMetaData (n, ctt, httpe) {
/* exported addMetaData */
var el = document.createElement("meta");
httpe? el.httpEquiv = n: el.name = n;
el.content = ctt;
document.head.appendChild(el)
}
/**
* @description Get the meta-data of the current page
* @returns {string[]} Name and content results
* @see module:DOM~addMetaData
* @since 1.0
* @func
*/
function getMetaData () {
var md = $n("*meta"), resN = [], resC = [];
for (var i = 0; i < md.length; i++) {
resN[i] = md[i].name || md[i].httpEquiv || md[i].title;
resC[i] = md[i].content || md[i].value;
}
return [resN, resC]
}
/**
* @description Disable right clicks
* @param {boolean} [restore=false] Restore the right click
* @returns {undefined}
* @since 1.0
* @func
*/
function noRightClick (restore) {
if (restore) {
document.oncontextmenu = $G.contextMenu;
} else {
$G.contextMenu = document.oncontextmenu;
document.oncontextmenu = new Function("return false")
}
}
/**
* @description Redirect to somewhere
* @param {string} to Place to be redirected to
* @param {number} [dt=3e3] Time delay (in ms)
* @param {string} divId Id of the element to be used to inform the user about what's going on
* @returns {undefined}
* @since 1.0
* @func
*/
function redirect (to, dt, divId) { //Redirect to #to in #dt ms
if (!dt) dt = 3e3; //If dt hasn't an assign value so it will assign a default one
var s = Math.floor(dt / 1e3); //Convert from ms to start
$e("#" + divId).write("<h2> Redirecting to <ins>" + to + "</ins> ...<br />in <span id = 'timeleft'>" + s +"</span >start</h2>", true); //Write the Redirecting message to the screen
s--; //Countdown
$e("#timeleft").write(s);
setTimeout("location = '" + to + "';", dt); //Set the timeout for the redirection
}
/**
* @description Validity check
* @param {string} txt Text
* @param {string} type Type
* @returns {boolean} Validity check result
* @see module:DOM~validate
* @since 1.0
* @func
*/
function isValid (txt, type) {
var pattern, lenOK = true;
switch (type.toLowerCase()) {
case "email":
pattern = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/; //From SO
lenOK = txt.length >= 9 && txt.length < 64;
break;
case "tel":
pattern = /^\+(?:[0-9]?){6,14}[0-9]$/; //From somewhere
break;
case "username":
pattern = /^[A-Za-z_0-9-]+$/;
lenOK = txt.length > 3 && txt.length <= 16;
break;
case "name":
pattern = /^[A-Za-z-]{2,35}$/;
break;
case "price":
pattern = /^[0-9]*\x2e[0-9]{2}$/;
lenOK = txt.length > 3;
break;
case "number":
pattern = /\d/; // /^(\x2d|)[0-9] * $/ wouldn't accept floats
break;
case "date":
pattern = /(\d{1,2}\/d{1,2}\/d{2,4})/; // /^([0-9]{2}\x2f){2}\x2f([0-9]{2}|[0-9]{4})$/; //Accept d/m/y*
lenOK = txt.split("/")[1] <= 12 && txt.split("/")[0] <= 31;
break;
case "hex":
pattern = /(#|0x)?([A-Fa-f0-9]){3}(([A-Fa-f0-9]){3})?/; //From CheatSheets (iOS)
break;
case "tag": //From CheatSheets (iOS)
pattern = /(<(\/?[^>]+)>)/;
break;
case "password":
pattern = /|^\c]\w{8,}/;
break;
case "file":
pattern = /^[\S]+([A-Za-z0-9_]*\.(jpg|png|gif|ico|bmp))$/;
break;
case "variable":
pattern = /^[A-Za-z_$]+[0-9]*[A-Za-z_$]*$/;
break;
case "colour":
pattern = /^(#([A-Fa-f0-9]{3}|[A-Fa-f0-9]{6}))|(rgb\(([0-9]+,\s){2}([0-9]+)\))|(rgba\(([0-9]+,\s){3}((0|1|)\.[0-9]*)\))|(hsl\(([0-9]+,\s){2}([0-9]+)\))|(hsla\(([0-9]+,\s){3}((0|1|)\.[0-9]*)\))$/;
break;
case "url":
pattern = /^((http(|s):\/\/)|((file|ftp):\/\/\/))(\/[A-Za-z0-9_-]*)|[A-Za-z0-9_-]$/;
break;
case "ip":
pattern = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/; //From http://code.tutsplus.com/tutorials/8-regular-expressions-you-should-know--net-6149
break;
case "time":
pattern = /^[0-5][0-9](\x3a|\.)[0-5][0-9]|([0-5][0-9]\x3a[0-5][0-9]){0,2}(\x3a|\.)[0-5][0-9]$/;
break;
default: pattern = /\w/;
}
return pattern.test(txt) && lenOK
}
/**
* @description Validation check on a form
* @param {node} fm Form
* @param {boolean} [ignoreRequired=false] Ignored the required attribute
* @returns {boolean} Validation check
* @see module:DOM~isValid
* @since 1.0
* @func
*/
function validate (fm, ignoreRequired) { //Check if a form is valid
if (!fm) fm = document.forms[0];
var valid = true;
for (var i = 0; i < fm.length; i++) {
if (ignoreRequired || fm[i].required) {
//Missing: select, datetime, datetime-local, time, month, range, search, week, url
if (fm[i].name === "username" || fm[i].name === "price") valid = valid && isValid(fm[i].value, fm[i].name);
else if (fm[i].type === "password" || fm[i].type === "email" || fm[i].type === "tel" || fm[i].type === "date" || fm[i].type === "hex" || fm[i].type === "variable" || fm[i].type === "file" || fm[i].type === "hidden") valid = valid && isValid(fm[i].value, fm[i].type);
else if (fm[i].name === "price") valid = valid && isValid(fm[i].value, fm[i].name);
else if (fm[i].name.indexOf("name") >= 0) valid = valid && isValid(fm[i].value, "name");
else if (fm[i].type === "checkbox" && fm[i].checked) valid = valid && true;
else valid = valid && !isNon(fm[i].value); //Radio,
}
}
return valid
}
/**
* @description Get the HTML equivalent of the string
* @param {string} str String
* @returns {Code} HTML equivalent
* @see module:DOM~unescapeHTML
* @since 1.0
* @func
*/
function escapeHTML (str) {
var span = document.createElement("span");
span.appendChild(document.createTextNode(str));
return span.innerHTML
}
/**
* @description Get the string equivalent of the HTML code
* @param {string} code HTML code
* @returns {string} String equivalent
* @see module:DOM~escapeHTML
* @since 1.0
* @func
*/
function unescapeHTML (code) {
var span = document.createElement("span");
span.innerHTML = code;
return span.innerText;
}
/**
* @description Get all the resources of a page apart from the in-CSS ones
* @param {boolean} rmEmpty Flag to remove empty resources from the list
* @todo Maybe some specifications to filter up ? And also more info about those resources
* @returns {Array} Resources
* @since 1.0
* @func
*/
function getResources (rmEmpty) {
var links = $n("*link"), scripts = $n("*script"), rsc = [], hypertxt = $n("*a"), img = $n("*img"), btnImg = $n("*input image"),
inCSS = [$n("*div"), $n("*section"), $n("*td"), $n("*th"), $n("*li")];
for (var i = 0; i < links.length; i++) {
if (!isNon(links[i])) rsc[i] = links[i].href;
Essence.say(links[i].href.split("/")[links[i].href.split("/").length - 1] + " has been added to the resources getter.", "info");
}
for (i = 0; i < scripts.length; i++) {
if (!isNon(scripts[i])) rsc.push(scripts[i].src);
Essence.say(scripts[i].src.split("/")[scripts[i].src.split("/").length - 1] + " has been added to the resources getter.", "info")
}
for (i = 0; i < hypertxt.length; i++) {
if (!isNon(hypertxt[i])) rsc.push(hypertxt[i].href);
Essence.say(hypertxt[i].href.split("/")[hypertxt[i].href.split("/").length - 1] + " has been added to the resources getter.", "info")
}
for (i = 0; i < img.length; i++) {
if (!isNon(img[i])) rsc.push(img[i].src);
Essence.say(img[i].src.split("/")[img[i].src.split("/").length - 1] + " has been added to the resources getter.", "info")
}
for (i = 0; i < btnImg.length; i++) {
if (!isNon(btnImg[i])) rsc.push(btnImg[i].src);
Essence.say(btnImg[i].src.split("/")[btnImg[i].src.split("/").length - 1] + " has been added to the resources getter.", "info")
}
for (i = 0; i < inCSS.length; i++) {
for (var j = 0; j < inCSS[i].length; j++) {
rsc.push(inCSS[i][j].style.backgroundImage.slice(4, inCSS[i][j].style.backgroundImage.length - 1));
var x = inCSS[i][j].style.backgroundImage.slice(4, inCSS[i][j].style.backgroundImage.length - 1);
Essence.say(x.split("/")[x.split("/").length - 1] + " has been added to the resources getter.", "info");
}
} //Remove or not unnecessary cells with a double check for one.
Essence.say("Resource list: " + rsc.clean());
return rmEmpty? rsc.clean(): rsc
}
/**
* @description Get the list of scripts
* @param {boolean} [asList=false] Result should be a list or an object
* @returns {*} List/dictionary of scripts
* @see module:DOM~gatherStylesheets
* @since 1.0
* @func
*/
function gatherScripts (asList) { //Sort of getResources() but dedicated to only scripts and easier to use
var $s = $n("*script"), res = asList? []: {};
for (var i = 0; i<$s.length; i++) asList? res.push($s[i].src): res[$s[i].src.split("/")[$s[i].src.split("/").length - 1]] = $s[i].src;
return res
}
//noinspection JSUnusedGlobalSymbols
/**
* @description Gather internal scripts.
* @param {boolean} [format=false] Format to an easy-to-use array
* @returns {Array} Internal scripts
* @since 1.1
* @func
*/
function gatherInternalScripts (format) {
return format? document.scripts.toArray().filter(function (x) {
return x.text != "";
}).map(function (x) {
return x.src;
}): document.scripts.toArray().filter(function (x) {
return x.text != "";
});
}
/**
* @description Gather external scripts.
* @param {boolean} [format=false] Format to an easy-to-use array
* @returns {Array} External scripts
* @since 1.1
* @func
*/
function gatherExternalScripts (format) {
return format? document.scripts.toArray().filter(function (x) {
return x.src != "";
}).map(function (x) {
return x.src;
}): document.scripts.toArray().filter(function (x) {
return x.src != "";
});
}
//noinspection JSUnusedGlobalSymbols
/**
* @description Gather remote resources from the file.
* @param {string} [type] Type (either: "script", "stylesheet" or "" (for both))
* @return {string[]} Remote resources
* @func
* @since 1.1
* @see module:DOM~gatherLocalResources
*/
function gatherRemoteResources (type) {
var $rsc = type === "script"? gatherScripts(true): (type === "stylesheet"? gatherStylesheets(true): gatherStylesheets(true).concat(gatherScripts(true)));
return $rsc.filter(function (x) {
return x.sameFirst(location.href) != getDirectoryPath()
})
}
//noinspection JSUnusedGlobalSymbols
/**
* @description Gather local resources from the file.
* @param {string} [type] Type (either: "script", "stylesheet" or "" (for both))
* @return {string[]} Remote resources
* @func
* @since 1.1
* @see module:DOM~gatherRemoteResources
*/
function gatherLocalResources (type) {
var $rsc = type === "script"? gatherScripts(true): (type === "stylesheet"? gatherStylesheets(true): gatherStylesheets(true).concat(gatherScripts(true)));
return $rsc.filter(function (x) {
return x.sameFirst(location.href) === getDirectoryPath()
})
}
/**
* @description Get the list of stylesheets
* @param {boolean} [asList=false] Result should be a list or an object
* @returns {*} List/dictionary of stylesheets
* @see module:DOM~gatherScripts
* @since 1.0
* @func
*/
function gatherStylesheets (asList) {
var $l = $n("*link"), $s = $n("*style"), res = asList? []: {};
for (var i = 0; i<$l.length; i++) asList? res.push($l[i].href): res[$l[i].href.split("/")[$l[i].href.split("/").length - 1]] = $l[i].href;
for ( i = 0; i<$s.length; i++) asList? res.push($s[i].href): res[$s[i].href.split("/")[$s[i].href.split("/").length - 1]] = $s[i].href;
return res
}
//noinspection JSUnusedGlobalSymbols
/**
* @description Gather internal stylesheets.
* @param {boolean} [format=false] Format to easy-to-use array
* @returns {Array} Internal stylesheets
* @since 1.1
* @func
*/
function gatherInternalStylesheets (format) {
return format? document.styleSheets.toArray().filter(function (x) {
return x.ownerNode.tagName === "STYLE";
}).map(function (x) {
return x.href;
}): document.styleSheets.toArray().filter(function (x) {
return x.ownerNode.tagName === "STYLE";
});
}
//noinspection JSUnusedGlobalSymbols
/**
* @description Gather external stylesheets.
* @param {boolean} [format=false] Format to easy-to-use array
* @returns {Array} External stylesheets
* @since 1.1
* @func
*/
function gatherExternalStylesheets (format) {
return format? document.styleSheets.toArray().filter(function (x) {
return x.ownerNode.tagName === "LINK";
}).map(function (x) {
return x.href;
}): document.styleSheets.toArray().filter(function (x) {
return x.ownerNode.tagName === "LINK";
});
}
/**
* @description A basic HTML table
* @param {NumberLike} [caption=""] Caption
* @param {Array} rows Rows of the table
* @param {string} [id="t"] ID of the table
* @param {string} [style] Style of table
* @param {boolean} [split=false] Split rows into multiple columns
* @param {string[]} [cellIds] Ids of each cells
* @returns {string} HTML code
* @since 1.0
* @func
*/
function simpleTable (caption, rows, id, style, split, cellIds) {
if (isNon(style)) style = "";
if (!id) id = "t";
var tab = "<table id='" + id + "' style='" + style + "' cellspacing=0 cellpadding=2>" + (caption? "<caption>" + caption + "</caption>": "");
for (var i = 0; i < rows.length; i++) {
tab += "<tr>";
if (split) {
for(var j = 0; j < rows[i].length; j++) tab += "<td id='" + id + (isNon(cellIds)? i+"_"+j: cellIds[i][j]) + "'>" + rows[i][j] + "</td>";
} else tab += "<td id='" + id + (isNon(cellIds)? i: cellIds[i]) + "'>" + rows[i] + "</td>";
tab += "</tr>";
}
tab += "</table>";
Essence.addCSS("#" + id + " table{background: #000;}#" + id + " table, #" + id + " td {border: 1px solid #000; color: #000; background: #fff;}#" + id + " tr:nth-child(even) td{background: #ddd;}#"+ id + " tr td:hover{background: #bbb;}");
return tab
}
/**
* @description Row HTML table
* @param {NumberLike} caption Caption
* @param {Array} headerRows Row headers
* @param {Array} rows Rows of the table
* @param {string} id ID of the table
* @param {boolean} [split=false] Split rows into multiple columns
* @param {string} [style] Style of table
* @param {string[]} [cellIds] Ids of each cells
* @returns {string} HTML code
*/
function rowTable (caption, headerRows, rows, id, split, style, cellIds) {
if (isNon(style)) style = "";
if (!id) id = "t";
var tab = "<table id='" + id + "' style='" + style + "' cellspacing=0 cellpadding=2>" + (caption? "<caption>" + caption + "</caption>": "");
//var rowspan = (headerRows.length <= rows.length)? rows.length/headerRows.length: headerRows.length/rows.length;
for (var i = 0; i < rows.length; i++) {
tab += headerRows? "<tr><th>" + headerRows[i] + "</th>": "<tr>";
if (split) {
for (var j = 0; j < rows[i].length; j++) {
tab += "<td id='" + id + (isNon(cellIds)? i+"_"+j: cellIds[i][j]) + "'>" + rows[i][j] + "</td>";
}
} else tab += "<td id='" + id + (isNon(cellIds)? i: cellIds[i]) + "'>" + rows[i] + "</td>";
tab += "</tr>";
}
tab += "</table><style>#" + id + " table{background: #000;}#"+ id + " table, #"+ id + " td, #"+ id + " th{border: 1px solid #000; color: #000; background: #fff;}#"+ id + " tr:nth-child(even) td, #"+ id + " tr:nth-child(even) th{background: #ddd;}#"+ id + " tr td:hover, #"+ id + " tr th:hover{background: #bbb;}</style>";
return tab
}
/**
* @description Column HTML table
* @param {NumberLike} caption Caption
* @param {Array} headerCols Row headers
* @param {Array} cols Cols of the table
* @param {string} id ID of the table
* @param {boolean} [split=false] Split columns into multiple rows
* @param {string} [style] Style of table
* @param {string[]} [cellIds] Ids of each cells
* @returns {string} HTML code
*/
function colTable (caption, headerCols, cols, id, split, style, cellIds) {
if (isNon(style)) style = "";
if (!id) id = "t";
var tab = "<table id='" + id + "' style='" + style + "' cellspacing=0 cellpadding=2>" + (caption? "<caption>" + caption + "</caption>": "");
//var colspan = (headerCols.length <= cols.length)? cols.length/headerCols.length: headerCols.length/cols.length;
//console.log(colspan);
if (headerCols) {
tab += "<tr>";
for (var i = 0; i < headerCols.length; i++) {
tab += "<th>" + headerCols[i] + "</th>";
}
tab += "</tr>";
}
for (i = 0; i < cols.length; i++) {
tab +="<tr>";
if (split) {
for (var j = 0; j < cols[i].length; j++) {
tab += "<td id='" + id + (isNon(cellIds)? i + "_" + j: cellIds[i][j]) + "'>" + cols[i][j] + "</td>";
}
} else tab += "<td id='" + id + (isNon(cellIds)? i: cellIds[i]) + "'>" + cols[i] + "</td>";
tab += "</tr>"
}
tab += "</table>";
Essence.addCSS("#"+ id + " table{background: #000;}#"+ id + " table, #"+ id + " td, #"+ id + " th{border: 1px solid #000; color: #000; background: #fff;}#"+ id + " tr:nth-child(even) td{background: #ddd;}#"+ id + " tr td:hover{background: #bbb;}");
return tab
}
/**
* @description Complex HTML table
* @param {NumberLike} caption Caption
* @param {Array} headerRows Row headers
* @param {Array} rows Rows of the table
* @param {Array} headerCols Columns Headers
* @param {string} id ID of the table
* @param {boolean} [split=false] Split rows into multiple columns
* @param {string} [style] Style of table
* @param {string[]} [cellIds] Ids of each cells
* @returns {string} HTML code
*/
function complexTable (caption, headerRows, rows, headerCols, id, split, style, cellIds) {
if (isNon(style)) style = "";
if (!id) id = "t";
var tab = "<table id='" + id + "' style='" + style + "' cellspacing=0 cellpadding=2>" + (caption? "<caption>" + caption + "</caption><tr><td></td>": "<tr><td></td>");
for(var i = 0; i < headerCols.length; i++) tab += "<th>" + headerCols[i] + "</th>";
tab += "</tr>";
for (i = 0; i < rows.length; i++) {
tab += (headerRows)? "<tr><th>" + headerRows[i] + "</th>": "<tr>";
if (split) {
for (var j = 0; j < rows[i].length; j++) tab += "<td id='" + id + (isNon(cellIds)? i + "_" + j: cellIds[i][j]) + "'>" + rows[i][j] + "</td>";
} else tab += "<td id='" + id + (isNon(cellIds)? i: cellIds[i]) + "'>" + rows[i] + "</td></tr>";
tab += "</tr>";
}
tab += "</table>";
Essence.addCSS("#"+ id + " table{background: #000;}#"+ id + " table, #"+ id + " td, #"+ id + " th{border: 1px solid #000; color: #000; background: #fff;}#"+ id + " tr:nth-child(even) td{background: #ddd;}#"+ id + " tr td:hover{background: #bbb;}");
return tab
}
/**
* @description HTML table with coloured empty cells
* @param {NumberLike} caption Caption
* @param {Array} cols Columns
* @param {string[]} clrs Colours list
* @param {string} id ID of the table
* @param {boolean} [split=false] Split the cells into multiple ones
* @param {string} [style] Style of the table
* @returns {string} Colour HTML table
* @since 1.0
* @func
*/
function colourTable (caption, cols, clrs, id, split, style) {
if (!id) id = "c";
var tab = "<table id='" + id + "' style='" + style + "' cellspacing=0 cellpadding=2>" + (caption? "<caption>" + caption + "</caption>": "");
if (cols) {
tab += "<tr>";
for(var i = 0; i < cols.length; i++) tab += "<th>" + cols[i] + "</th>";
tab += "</tr>";
}
for (i = 0; i < clrs.length; i++) {
tab +="<tr>";
if (split) {
for(var j = 0; j < clrs[i].length; j++) tab += isValid(clrs[i][j], "color")? "<td style='background:" + clrs[i][j] + ";'><br /></td>": "<td>" + clrs[i][j] + "</td>";
} else tab += "<td style='background:" + clrs[i] + ";'><br /></td>";
tab +="</tr>"
}
tab += "</table>";
Essence.addCSS("#"+ id + " table{background: #000;}#"+ id + " table, #"+ id + " td, #"+ id + " th{border: 1px solid #000; color: #000; background: #fff;}#"+ id + " tr:nth-child(even) td{background: #ddd;}#"+ id + " tr td:hover{background: #bbb;}");
return tab
}
/**
* @description Compare two matrices and display a table with all the different elements of $b in regards to $a
* @param {Array} a Matrix a
* @param {Array} b Matrix b
* @param {boolean} [toHTML=false] HTML output
* @returns {*} Comparison table result
* @since 1.0
* @func
* @throws {Error} Uncomparable matrices
*/
function tableCompare (a, b, toHTML) { //Compare two matrices and display a table with all the different elements
if(a.size(true) != b.size(true)) throw new Error("You can't compare two matrices of different sizes");
var res = Copy(a);
for (var i = 0; i < res.length; i++) {
for (var j = 0; j < res[i].length; j++) res[i][j] = (a[i][j] === b[i][j])? "": b[i][j];
}
toHTML? println(simpleTable("Comparison", res)): console.table(res);
return res;
}
/**
* @description (Ask to) bookmark a webpage
* @param {string} url URL of the webpage
* @param {string} title Title
* @param {string} [elmId="body"] Element ID
* @returns {undefined}
* @since 1.0
* @func
*/
function addFav (url, title, elmId) {
var place = elmId? "#" + elmId: "body";
if (navigator.appName.substring(0, 3) === "Mic" && navigator.appVersion.substring(0, 1) >= 4) $e(place).write("<a href=\"#\" onClick=\"window.external.AddFavorite(" + url + ", " + title + ");return false;\">Bookmark this webpage</a><br />", true);
else $e(place).write("Press CTRL + D to add this webpage to your bookmarks!", true)
}
/**
* @description Browser check.<br />
* Source: somewhere
* @returns {checkBrowser} Browser check
* @this checkBrowser
* @since 1.0
* @todo Document the properties
* @constructor
*/
function checkBrowser () {
this.ver = navigator.appVersion;
this.dom = document.getElementById? 1: 0;
this.ie5 = (this.ver.has("MSIE 5") && this.dom)? 1: 0;
this.ie4 = (document.all && !this.dom)? 1: 0;
this.ns5 = (this.dom && parseInt(this.ver) >= 5)? 1: 0;
this.ns4 = (document.layers && !this.dom)? 1: 0;
this.any = (this.ie5 || this.ie4 || this.ns4 || this.ns5);
return this
}
/**
* @description Browser detection system.<br />
* Source: somewhere
* @type {{init: BrowserDetect.init, searchString: BrowserDetect.searchString, searchVersion: BrowserDetect.searchVersion, dataBrowser: Array, dataOS: Array, info: BrowserDetect.info}}
* @since 1.0
* @global
* @property {Function} BrowserDetect.init Initializer
* @property {function(Object): Object} BrowserDetect.searchString String search
* @property {function(string): number} BrowserDetect.searchVersion Version search
* @property {Object[]} BrowserDetect.dataBrowser Browser data
* @property {Object[]} BrowserDetect.dataOS OS data
* @property {function(): string} BrowserDetect.info Information about the browser
*/
var BrowserDetect = { //Browser detection system
init: function () {
this.browser = this.searchString(this.dataBrowser) || "Unknown browser";
this.version = this.searchVersion(navigator.userAgent) || this.searchVersion(navigator.appVersion) || "xx.yy";
this.OS = this.searchString(this.dataOS) || "Unknown OS";
},
searchString: function (data) {
for (var i = 0; i < data.length; i++) {
var dataString = data[i].string, dataProp = data[i].prop;
this.versionSearchString = data[i].versionSearch || data[i].identity;
if (dataString) {
if (dataString.has(data[i].subString)) return data[i].identity
}else if (dataProp) return data[i].identity
}
},
searchVersion: function (dataString) {
var index = dataString.indexOf(this.versionSearchString);
if (index === -1) return;
return parseFloat(dataString.substring(index + this.versionSearchString.length + 1))
},
dataBrowser: [{
string: navigator.userAgent, subString: "Chrome", identity: "Chrome"
}, {
string: navigator.userAgent, subString: "OmniWeb", versionSearch: "OmniWeb/", identity: "OmniWeb"
}, {
string: navigator.vendor, subString: "Apple", identity: "Safari", versionSearch: "Version"
}, {
prop: window.opera, identity: "Opera", versionSearch: "Version"
}, {
string: navigator.vendor, subString: "iCab", identity: "iCab"
}, {
string: navigator.vendor, subString: "KDE", identity: "Konqueror"
}, {
string: navigator.userAgent, subString: "Firefox", identity: "Firefox"
}, {
string: navigator.vendor, subString: "Camino", identity: "Camino"
}, { //For newer Netscapes (6+)
string: navigator.userAgent, subString: "Netscape", identity: "Netscape"
}, {
string: navigator.userAgent, subString: "MSIE", identity: "Explorer", versionSearch: "MSIE"
}, {
string: navigator.userAgent, subString: "Gecko", identity: "Mozilla", versionSearch: "rv"
}, { //For older Netscapes (4-)
string: navigator.userAgent, subString: "Mozilla", identity: "Netscape", versionSearch: "Mozilla"
}],
dataOS: [{
string: navigator.platform, subString: "Win", identity: "Windows"
}, {
string: navigator.platform, subString: "Mac", identity: "Mac"
}, {
string: navigator.userAgent, subString: "iPhone", identity: "iPhone/iPod"
}, {
string: navigator.userAgent, subString: "Android", identity: "HTC/Samsung/LG/Nexus"
}, {
string: navigator.userAgent, subString: "BlackBerry", identity: "BlackBerry"
}, {
string: navigator.platform, subString: "Linux", identity: "Linux"
}],
info: function () {
return this.browser + "/" + this.version + " (" + this.OS + ")";
}
};
/**
* @description Type a message
* @param {string} msg Message
* @param {Element|string} where Place to type the message
* @param {boolean} [HTML=false] HTML flag
* @returns {undefined}
* @see module:DOM~writeMsg2
* @since 1.0
* @func
*/
function writeMsg (msg, where, HTML) {
var txt, pos = 0;
while (pos < msg.length + 10) {
txt = msg.substring(pos, 0);
isCustomType(where, "element")? where.write(txt, HTML): $e(where).write(txt, HTML);
pos++;
}
}
/**
* @description Type a message
* @param {string} msg Message
* @param {string} slc Place to type the message
* @param {boolean} [HTML=false] HTML flag
* @param {number} [delay=150] Inter-character delay
* @param {string} [txt=""] Text
* @param {number} [pos=0] Position
* @returns {undefined}
* @see module:DOM~writeMsg
* @since 1.0
* @func
*/
function writeMsg2 (msg, slc, HTML, delay, txt, pos) {
if(!txt) txt = "";
if(!pos) pos = 0;
if (pos < msg.length + 10) {
txt = msg.substring(pos, 0);
HTML? $n(slc).innerHTML = txt: $n(slc).innerText = txt;
pos++;
setTimeout("writeMsg2('" + msg + "', '" + slc + "', " + HTML + ", " + delay + ", '" + txt + "', " + pos + ")", delay || 150);
}
}
/**
* @description Templating + conversion
* @param {string} [name="Template"] Name
* @param {string} [txt=""] Text/code containing the {{params}}
* @param {string[]} [params=["tab", "date", "time", "timestamp", "br"]] Parameters
* @param {boolean} [consoleSpecial=false] Resulting text formatted to the console
* @constructor
* @this {Template}
* @returns {Template} Template
* @since 1.0
* @func
* @property {string} Template.name Name
* @property {string} Template.path Path (for saving)
* @property {string[]} Template.params Parameters (in {{...}})
* @property {string[]} Template.special Special parameters (predefined parameters)
* @property {string[]} Template.specialEq Special parameters equivalence
* @property {string} Template.text Raw text/code containing the parameters ({{param}})
* @property {function(Object, boolean): (Code)} Template.gen Text/code generator
* @property {function(Object, string, string)} Template.save Save the generated text/code in the specified path
*/
function Template (name, txt, params, consoleSpecial) {
this.name = name || "Template";
this.path = this.name + ".jst";
this.params = params || ["name", "description", "version", "title", "path"];
this.special = ["tab", "date", "time", "timestamp", "br", ""];
this.specialEq = [" ", getDate(), getTime(true), getTimestamp(true), "<br />"];
if (consoleSpecial) {
this.specialEq[0] = "\t";
this.specialEq[4] = "\n";
}
this.text = txt || "";
this.gen = function (obj, unEscape) { //Generate a text/code from the template using the keys of the object
var res = unEscape? unescapeHTML(this.text): this.text, k = keyList(obj, true);
for(var i = 0; i < k.length; i++) res = res.replace(RegExpify("{{" + k[i] + "}}"), obj[k[i]]);
for(i = 0; i < this.special.length; i++) res = res.replace(RegExpify("%" + this.special[i] + "%"), this.specialEq[i], " ");
return res
};
this.save = function (obj, name, ext) { //Save the template into a file or the converted version
if (obj) save(this.gen(obj), (name || this.name) + "." + (ext || ".js"), ext || "javascript");
else save(this.text, this.path, "javascript")
};
return this;
}
/**
* @description Remove (X)HTML tags
* @param {string} str String with potential tags
* @returns {string} Tagless string
* @since 1.0
* @func
*/
function stripTags (str) {
return str.replace(/<[\s\S]+>(.*?)<\/[\s\S]+>/, "$1")
}
/**
* @description Make tabs up
* @param {number} [n=1] Number of tabs
* @returns {string} Tabs
* @func
* @since 1.1
*/
function tabs (n) {
return " ".repeat(n || 1);
}
/**
* @description Get the value of an attribute of a tag with a known attribute selector
* @param {string} tagName Tag name
* @param {string} knownAttrSelector Know attribute selector (in the form: attr='val')
* @param {string} attr Attribute
* @return {*} Value of the attribute in the tag
* @since 1.1
* @func
* @example
* //We want to get the meta description and we know that there's an element such as $n("meta[name='description']") ≠ null
* var docDescription = $t("meta", "name='description'", "content");
* @global
*/
function $t (tagName, knownAttrSelector, attr) {
var tag = $e(tagName + "[" + knownAttrSelector + "]").val(false, true), start;
start = tag.search(attr + "=\"|\'") + attr.length + 2;
return tag.get(start, start + tag.get(start).indexOf(tag.has("'")? "'": "\"") - 1);
}
/**
* @description A Document templating system that will change the DOM with the use of data-* attributes or {{*}}
* @global
* @type {{attrs: string[], assoc: Array, get: DocTemplate.get, getAll: DocTemplate.getAll, getVal: DocTemplate.getVal, getValAll: DocTemplate.getValAll, associate: DocTemplate.associate, associateAll: DocTemplate.associateAll, template: Template, deMustache: DocTemplate.deMustache}}
* @since 1.1
* @this DocTemplate
* @property {string[]} DocTemplate.attrs Attributes (either preceded by data- attributes in HTML elements or between {{ and }})
* @property {Array} DocTemplate.assoc Associations What the templating system is going to use to associate/change the elements with data-[attr] or the {{attr}} strings
* @property {function(Str, *)} DocTemplate.add Add attribute(s)/association(s) pairs
* @property {function(string, boolean): (Array|NodeList)} DocTemplate.get Get the HTML elements with the attribute data-[<code>attrName</code>]
* @property {function(boolean): (Array[]|NodeList[])} DocTemplate.getAll Get All the HTML elements with a data-* attribute
* @property {function(string): Array} DocTemplate.getVal Get the values of the data-[<code>attrName</code>] attributes
* @property {function(): Array} DocTemplate.getVallAll Get all the values of the data-[attr] attributes
* @property {function(string, boolean)} DocTemplate.associate Place the corresponding association (in <code>DocTemplate.assoc</code>) in the HTML element's inner value
* @property {function(boolean)} DocTemplate.associateAll Place the associations (in <code>DocTemplate.assoc</code>) in the HTML element's inner values
* @property {Template} DocTemplate.template Mustache template (<span style='color: red;'>warning: This might mess up some JS generated HTML content</span>)
* @property {Function} DocTemplate.deMustache Change all the mustached variables in the HTML body
*/
var DocTemplate = {
attrs: ["lorem", "greet", "date", "time", "timestamp", "essence", "charset", "author", "title", "dir"],
assoc: [$G["lorem"], "Welcome !", getDate(), getTime(true), getTimestamp(true), "EssenceJS v" + Essence.version, $t("meta", "charset", "charset") || "UTF-8", $t("meta", "name='author'", "content") || "Maximilian Berkmann", document.hasChildNodes("title")? $e("title").val(): getFilename(true), getDirectoryPath()],
add: function (attr, assoc) {
isType(attr, "Array")? this.attrs.append(attr): this.attrs.push(attr);
isType(assoc, "Array")? this.assoc.append(assoc): this.assoc.push(assoc);
},
get: function (attrName, toArr) {
return toArr? $n("*[data-" + attrName + "]").toArray(): $n("*[data-" + attrName + "]");
},
getAll: function (oneDim) {
var nodeLists = this.attrs.map(function (a) {
return $n("*[data-" + a + "]");
});
return oneDim? nodeLists.map(function (nodeList) {
return nodeList.toArray();
}): nodeLists;
},
getVal: function (attrName) {
return this.get(attrName, true).map(function (node) {
return node.getAttribute("data-" + attrName);
})
},
getValAll: function () {
var pos = -1;
return this.getAll(true).map(function (nodeList) {
pos++;
return nodeList.map(function (node) {
return node.getAttribute("data-" + DocTemplate.attrs[pos]);
});
})
},
associate: function (attrName, html) {
var self = this;
this.get(attrName, true).map(function (node) {
html? node.innerHTML = self.assoc[self.attrs.indexOf(attrName)]: node.innerText = self.assoc[self.attrs.indexOf(attrName)];
})
},
associateAll: function (html) {
var self = this;
for (var i = 0; i < this.attrs.length; i++) {
this.get(this.attrs[i], true).map(function (node) {
html? node.innerHTML = self.assoc[i]: node.innerText = self.assoc[i];
})
}
},
template: new Template("DocTemplate", escapeHTML($e("body").val(true)), this.attrs),
deMustache: function () {
$e("body").write(this.template.gen(Objectify(this.attrs, this.assoc), true), true);
},
fullDeMustache: function () {
$e("html").write((new Template("DocTemplate", escapeHTML($e("html").val(true)), this.attrs)).gen(Objectify(this.attrs, this.assoc), true), true);
}
};
//noinspection JSUnusedGlobalSymbols
/**
* @description Turn HTML code into console/alert friendly text.
* @param {Code} code Code
* @returns {string} Console friendly text
* @func
* @since 1.1
* @see module:DOM~text2html
*/
function html2text (code) {
return code.multiReplace([
[/<br \/>/gm, "\n"],
[/\s{2,4}/gm, "\t"]
]);
}
/**
* @description Turn console/alert friendly text into HTML code.
* @param {string} text Console friendly text
* @returns {Code} HTML code
* @func
* @since 1.1
* @see module:DOM~html2text
*/
function text2html (text) {
return text.multiReplace([
[/\n/gm, "<br />"],
[/\t|\s{2}/gm, "  "]
]);
}
/**
* @description A text buffer to allow complex text printing management.
* @type {{log: string, writeToDocument: Buffer.writeToDocument, writeToConsole: Buffer.writeToConsole, add: Buffer.add, show: Buffer.show}}
* @property {Code} Buffer.log Buffer's content
* @property {function(boolean)} Buffer.writeToDocument Write the buffer's content to the page
* @property {Function} Buffer.writeToConsole Write the buffer's content to the console
* @property {function(Code)} Buffer.add Add content to the buffer
* @property {function(string, boolean, boolean)} Buffer.show Show the buffer's content at the desired place in the appropriate format
* @property {Function} Buffer.clear Clear the buffer
* @global
*/
var Buffer = {
log: "",
writeToDocument: function (isHTML) {
print(this.log, isHTML);
},
writeToConsole: function () {
console.log("\t[Buffer]\n" + this.log);
},
add: function (text) {
this.log += text + "\n";
},
show: function (console, withHTML, keepLog) {
if (console) this.writeToConsole();
else {
this.log = text2html(this.log);
this.writeToDocument(withHTML);
}
if (!keepLog) this.log = "";
},
clear: function () {
this.log = "";
console.log("Buffer cleared");
}
};
/**
* @description Dissect a selector and return if it matches some top-level CSS selections (or the matching bits).
* @param {String} selector Selector
* @param {boolean} [booleanOnly=false] Return the result as boolean (so test results)
* @returns {{list: boolean, tag: boolean, id: boolean, class: boolean, pseudoSelector: boolean, multiple: boolean, namespace: boolean}} Dissection
* @since 1.1
* @func
* @TODO make sure it gets the tags and spaces right
*/
function dissect (selector, booleanOnly) {
var hasPart = function (regexp) {
var matches = selector.match(new RegExp(regexp, "g"));
return matches === null? null: matches;
};
return booleanOnly? {
list: /\*\w+/g.test(selector),
tag: /^\w+[^#.|:](\s*?\w*[^#.|:]|$)/g.test(selector), //to improve
id: /#\w+/g.test(selector),
class: /\.\w+/g.test(selector),
pseudoSelector: /:\w+/g.test(selector),
multiple: /\s+/g.test(selector),
namespace: /\w+\|\w+/g.test(selector)
}: {
list: hasPart(/\*\w+/),
tag: hasPart(/^\w+[^#.|:](\s*?\w*[^#.|:]|$)/), //to improve
id: hasPart(/#\w+/),
class: hasPart(/\.\w+/),
pseudoSelector: hasPart(/:\w+/),
multiple: hasPart(/\s+/),
namespace: hasPart(/\w+\|\w+/)
};