-
Notifications
You must be signed in to change notification settings - Fork 0
/
EZboot - Copy.js
4056 lines (3688 loc) · 132 KB
/
EZboot - Copy.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
/*--------------------------------------------------------------------------------------------------
Dreamweaver LINT global references and definitions not used here {
--------------------------------------------------------------------------------------------------*/
/*global
EZ:true, EZ$:true, EZ_:true,
EZgetEl, EZgetValue, EZsetValue, EZnone, EZdisplayCaller,
DWfile, dw:true, e:true, f:true, g:true
*/
var e; //global used for try/catch
(function() {[ //global variables and functions defined but not used
EZgetEl, EZgetValue, EZsetValue, EZnone, EZdisplayCaller,
DWfile, dw, e, f, g ]});
//. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .}
(function(ez)
{
var defaultFormatOptions = {
formatter: 'toString',
formatOpts: {
tostring: {
timestamp: false,
format: 'string', //"string", "html" or "collapse"
collapse: { //ignored unless format="html"
depth: 3, //depth minlines used - maxlines not
minlines: 3, //no collapse if less items than value
maxlines: 10 //collapse if more items than value
},
//TODO: support "stringify"
htmlFormatter: 'EZ.format.Element',
htmlFormatterOpts: {
extract: 'brief'
}, //...if htmlFormatter not defined...
html: { //toString() internal html format options
maxdepth: 3,
maxchildren: 1,
maxchars: 99,
attributes: 'id className tagName parent'.split(' '),
input: [ //currently html_tagtype_keys and hardcoding
{
type: 'text textarea password hidden button',
attributes: 'value'
},{
type: 'radio checkbox',
attributes: 'checked'
},{
type: 'image',
attributes: 'src'
}
]
}
},
stringify: {
spaces:4,
legacy: '*',
plus: 'ignore="constructor script" unquoteKeys escapeAll'
}
},
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
htmlFormatter: {
format: 'html', //"html" "json" or "object"
formatter: 'EZ.stringify', //json formatter
formatOpts: {spaces: 4},
sort: false,
maxdepth: 4,
maxchildren: 1,
maxchars: 0,
maxlinechars: 0,
// removeQuotes: false,
noAttributeQuotes: false,
quote: '"',
tagValue: 'style src href',
tagAttributes: ('title checked autocomplete translate spellcheck readOnly disabled required'
+ ' value size multiple').split(/\+/),
extract: 'basic',
extractGroups: {
brief: ['tagName', 'type', 'name', 'id', 'className'],
basic: 'tagName type id name className checked value src href'.split(/\s+/),
plus: ['basic', 'attributes'], //basic plus defined tag attributes
children: ['basic', 'children'], //basic plus children
all:'plus checked value selected'.split(/\s+/), //innerText ??
//TODO: ...
outer: ['all', 'children'],
currentStyle: '',
offsets: ('clientWidth clientHeight clientLeft clientTop '
+ 'offsetWidth offsetHeight offsetLeft offsetTop offsetParent '
+ 'clientWidth clientHeight clientLeft clientTop').split(/\s+/),
elements: 'parentElement nextElementSibling previousElementSibling'.split(/\s+/),
//or nodes
most: 'events sibblings offsets'.split(/\s+/),
verbose: 'parent children'.split(/\s+/),
//verbose: []
defined: [],
},
defaults: {String:'extract', Array:'extract'},
},
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
version: '02-18-2017'
};
//===============================================================================================
/**
* EZ(), EZ$(), EZ_(), EZ.context(), EZ.get(), EZ.getEl(), EZ.set(), EZ.val() and tubs
**/
(function _____EZ_EZget_EZset_related_____() {
/*-----------------------------------------------------------------------------------------------
EZ(el,options) -- primary EZ Object defined as Function
returns single element or Array of elements if el is Array of selectors.
TODO:
when called as tag handler e.g. onclick="EZ(...)" -- tag passed as this if tag has EZ() bind.
allow defaultFormatOptions changes by onLoad functions() including <body onLoad="...">
------------------------------------------------------------------------------------------------*/
window.EZ = function EZ(sel, options)
{
if (this instanceof arguments.callee) return //called as constructor
void(options); //DW lint -- debugger convenience
EZ.tags = [];
var el = sel;
var type = EZ.getType(el);
if (type == 'Element')
return EZ.el = EZ.tags[0] = el;
//-----------------------------------\\
while (false && typeof(el) == 'string') // TODO: cache?? -- could have changed \\
{ //---------------------------------------\\
EZ.cache = EZ.cache || [];
var idx = EZ.cache.indexOf(sel)
el = EZ[idx];
if (el !== undefined || !(el instanceof Element))
break; //nogo if not cache or not still Element
EZ.cache.splice(idx,1)
EZ.cache.unshift(el);
EZ.cache = EZ.cache.slice(0,50);
return EZ.el = EZ.tags[0] = el;
}
var args = [].slice.call(arguments);
var defaults = {defaults:{legacy:false}}
args.push(defaults);
return EZgetEl.apply(this, args);
}
//-------------------------------\\
if (ez instanceof Object) // restore any prior EZ properties \\
{ //-----------------------------------\\
for (var key in ez) if (EZ[key] === undefined) EZ[key] = ez[key];
}
//NOTE: Chrome seems to load below script before executing this statement ??
// Does this mean functions can be referenced before they are defined
// as IE has always allowed but not historically allowed by Mozilla ??
EZ.defaultFormatOptions = defaultFormatOptions;
/*--------------------------------------------------------------------------------------------------
return current global options with defaults appended
--------------------------------------------------------------------------------------------------*/
EZ.defaultOptions = function EZdefaultOptions(name)
{
var defaultOpts = 'EZ.defaultOptions.'.concat(name).ov();
var options = 'EZ.'.concat(name,'.options').ov() || defaultOpts;
if (options != defaultOpts)
{
Object.keys(defaultOpts).forEach(function(key)
{
if (key in options) return;
options[key] = defaultOpts[key];
});
}
return EZ[name].options = options;
}
/*--------------------------------------------------------------------------------------------------
EZ variants and related
--------------------------------------------------------------------------------------------------*/
/**
* EZ$: return all elements matching all selector(s)
*/
EZ.$ = EZ$ = function()
{
var args = [].slice.call(arguments).concat([ {defaults:{all:true}} ]);
return EZgetEl.apply(this, args);
}
/**
* EZ_: return null if no el matches selector
*/
EZ_ = function()
{
var args = ([].slice.call(arguments)).concat([ {defaults:{all:false}} ]);
return EZgetEl.apply(this, args);
}
EZ._ = EZ_;
/**
* EZ.nul: return all elements matching selector(s) or null
*/
EZ.nul = function()
{
var args = [].slice.call(arguments).concat([ {defaults:{notFound:null}} ]);
return EZgetEl.apply(this, args);
}
//_____________________________________________________________________________________________
EZ.test = function()
{
EZ.test.run('#myid', {EZ: {ex:'', note:'' }})
EZ.test.run('<div>', '<div', {EZ: {ex:'', note:'' }})
EZ.test.run('.myclass', {EZ: {ex:'', note:'' }})
EZ.test.run('myid', 'div', 'myclass', {EZ: {ex:'', note:'' }})
// form fields
EZ.test.run('notifyForm:notifySelected', {EZ: {ex:'', note:'' }})
EZ.test.run('@notifyForm:notifySelected', {EZ: {ex:'', note:'' }})
EZ.test.run('@notifyForm:notifySelecte', {EZ: {ex:'', note:'bad name' }})
EZ.test.run('notifySelected', {EZ: {ex:'', note:'' }})
EZ.test.run('@notifySelected', {EZ: {ex:'', note:'' }})
//. . . . . . . . . . . . . . . . . . . . . . . .
}
//__________________________________________________________________________________
/**
* if element context, get chain selection element if callers 1st arg is array
* otherwise prepend context elements to callers args.
* if not element context return caller args as is.
*/
EZ.context = function EZcontext(ctx)
{
var args = [].slice.call(arguments.callee.caller.arguments);
if (ctx != window && typeof(ctx) != 'function')
{
if (!EZ.isArray(args[0]))
args.unshift(ctx); //prepend context element(s)
else
{ //update 1st arg with selected elements
var tags = EZgetEl.call(ctx, args[0], true);
args[0] = tags.length > 1 ? tags : tags[0];
}
}
return args;
}
//__________________________________________________________________________________
/**
* calls EZ.get_basic until and if EZ.getValue loaded
*/
EZ.get = function EZget(el, defaultValue)
{
if (EZ.getConstructorName(el) == 'EZfield')
el = el.el;
var rtnValue = (window.EZgetValue)
? EZgetValue.apply(this,[].slice.call(arguments)) //full functionality if loaded
: EZ.get_basic(el, defaultValue); //otherwise basic function
EZ.tags = EZ.get.tags = EZ.tags;
EZ.el = EZ.get.el = EZ.tags instanceof Object ? EZ.tags[0] : EZ.none();
return rtnValue;
}
//__________________________________________________________________________________
/**
* stub with min functionality -- until full version loaded
* if el not element, try as id or name -- returns 1st element for html collection
*/
EZ.getEl = function EZgetEl(el, allTags /* true for all tags */)
{
var name = el + '';
if (!EZ.isEl(el)) el = document.getElementById(el);
if (!el) el = document.getElementsByName(name);
if (!allTags && EZ.isArray(el)) el = EZ.collapse(el);
return el;
}
//__________________________________________________________________________________
/**
* calls EZ.set_basic -OR- EZ.setValue if loaded
*/
EZ.set = function EZset(el, value)
{
if (EZ.getConstructorName(el) == 'EZfield')
el = el.el;
var rtnValue = (window.EZsetValue) //use full functionality if loaded
? EZsetValue.apply(this,EZ.context(this))
: EZ.set_basic(el, value);
EZ.tags = EZ.set.tags = EZ.tags;
EZ.el = EZ.set.el = EZ.tags instanceof Object ? EZ.tags[0] : EZ.none();
return rtnValue;
}
//__________________________________________________________________________________
/**
* calls EZ.get() or EZ.set()
*/
EZ.val = function EZval(el,value)
{
/* jshint: doc only */ e = [el,value];
return !arguments.length ? '' //if no args, return blank
: arguments.length == 1 ? EZgetValue(el) //if single arg, call getValue()
: EZsetValue.apply(this,[].slice.call(arguments)); //otherwise call setValue()
}
//_____________________________________________________________________________________________
/**
* unit test stubs -- redefined when EZunit_tests.html loaded
*/
EZ.test.data = {}; //???
EZ.test.running = 'no capture';
EZ.test.run = function EZtestRun() {return false}
EZ.test.isTestFunction = EZ.isTest = function EZisTest()
{
return EZ.test.isTest && EZ.test.isTest(arguments.callee.caller);
}
EZ.test.getTestrun = EZ.test.setTestValue = function() {}
EZ.test.debug = function EZtestDebug() {return false}
if (!EZ.debug) EZ.debug = EZ.test.debug;
/**
* capture stubs -- redefined by EZcapture,js
*/
EZ.test.capture = function EZtestCapture() {return false}
EZ.test.capture.mode = false;
EZ.capture = function() {return false}
//_____________________________________________________________________________________________
/**
* More stubs for functions with full script in other files
*/
EZ.json = {}; //uses JSON.stringify/parse if EZ.stringify.js not loaded
EZ.util = {};
EZ.popup = function EZpopup__NA() {return EZ.oops('EZadvanced.js required but not loaded')}
EZ.trace = function EZtrace_NA() { return '' }
EZ.getPref = function EZgetPref(key, defaultValue) {return defaultValue};
EZ.toString = function(obj)
{ //stub until EZ.toString.js loaded
var ctx = (obj != null) ? obj : this;
if (typeof(ctx) == 'function') //presumably ctx is EZ()
return Function.prototype.toString.call(ctx);
else if (typeof(ctx) == 'object')
{
var text = 'EZ.toString() not loaded...';
for (var p in ctx)
text += p + ': ' + ctx[p];
}
}
//_________________________________________________________________________________________________
EZ.cookie = {
get:function EZcookieGet() {return ''},
set:function EZcookieSet() {return ''}
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
})();
return EZ;
})(window.EZ)
//__________________________________________________________________________________________________
EZ.toArrayBoot = function EZtoArray_boot(arg, delimiter) {
//__________________________________________________________________________________________________
/**
* most functionality of full EZ.toArray() -- does not supports delimiter =false, or Object
* TODO: not well tested BUT VERY LIMITED use
**/
if (delimiter === true)
delimiter = ','
if (typeof(delimiter) == 'string')
delimiter = RegExp('\\s*?[' + delimiter + ']\\s*');
if ( !(delimiter instanceof RegExp) )
delimiter = '';
var a = (arg === '' || arg == null || typeof(arg) == 'function') ? []
: (arg instanceof Array) ? arg
: (arg instanceof Object && 'length' in arg) ? [].slice.call(arg)
: (typeof(arg) == 'string') ? []
: (delimiter) ? arg.split(delimiter)
: [arg];
return a;
}
//__________________________________________________________________________________________________
EZ.getCaller = function _____EZgetCaller(caller, exclude) {
//__________________________________________________________________________________________________
/**
* Error.prototype.stackTrace() does all the work -- just identify ourself as "this"
**/
"use strict";
EZ.getCaller.format = EZ.getCaller.format || 'callerName';
return Error.prototype.stackTrace.call(EZ.getCaller, caller, exclude);
}
/*--------------------------------------------------------------------------------------------------
EZ.getCallerName([fn])
ARGUMENTS:
fn (optional) fn to find caller name (default is immediate caller)
TODO: if true find immediate caller before anonymous
RETURNS:
name of the calling function's caller -OR- fn caller if specified.
var caller = arguments.callee.caller;
var callerName = caller.displayName || caller.name || '';
--------------------------------------------------------------------------------------------------*/
EZ.getCallerName = function EZcallerName(fn, exclude)
{
var isBefore = (fn === true);
if (isBefore)
fn = '';
fn = fn || arguments.callee.caller;
exclude = exclude || [];
for (var i=0; i<50; i++)
{
var caller = '.arguments.callee.caller'.ov(fn);
if (exclude.includes(caller))
continue;
var callerName = !caller ? '' //'NA'
: caller.name || caller.displayName || 'anonymous';
if (!callerName)
return '';
else if (!isBefore || callerName != 'anonymous')
return callerName;
}
EZ.oops('over 50 callers');
return '';
}
/*__________________________________________________________________________________________________
global constants {
__________________________________________________________________________________________________*/
EZ.EOL = String.fromCharCode(172); //used to show end of non-object value
EZ.DASH = '‑'; //non-breaking dash
EZ.DOT = String.fromCharCode(8226); //base marker -- used to create compound marker
EZ.DOTS = (' .').dup(3);
EZ.MORE = (EZ.DOT).dup(3);
EZ.LINE = '—'
EZ.SPACE = String.fromCharCode(160);
EZ.SPACES = ' '.dup(120);
EZ.TRUE = 'true'.wrap();
EZ.FALSE = 'false'.wrap();
EZ.BLANK = 'blank'.wrap()
EZ.EMPTY = 'empty string'.wrap()
EZ.NULL = 'null'.wrap();
EZ.NONE = 'none'.wrap();
EZ.NAN = 'NaN'.wrap();
EZ.UNDEFINED = 'undefined'.wrap();
EZ.NA = 'not loaded'.wrap();
//__________________________________________________________________________________________________
EZ.global = (function(ez)
{
var global = {
legacy: { //EZ.isLegacy() returns true when legacy key not defined
na:undefined, n:null, //test data??
EZmatchPlus: true,
EZisEmpty: false,
EZbindElements: false,
EZisCaller: false,
EZeventAdd: true, //required for regex assistant
EZshowHide: true, // ''
EZclassAction: true, EZhasClass:true, // ''
EZgetEl:false, EZgetEl_notFoundnull:true,
EZgetStyle:false,
EZtechSupport: true
},
messages: { //EZ.init() copies to EZ.messages
exception: 'Unexpected Server Response Try Again Later',
techSupport: 'Technical Difficulty Displaying Page -- Try Later or Contact Tech Support',
jsonBad: 'Unrecognized Data Returned from Server',
debugOptionsLost: 'saved debug options invalid',
noTagsFound: 'no html tags found',
argRequired: '{1} argument required',
argMissing: '{1} arguments required', //prefix wih # args required
argsNotFound: 'arguments not found: ', //append arg names
stringRequired: 'armument must be string: ', // '' '' ''
functionArgReq: 'armument must be function: ',
requiresOneArg: 'at least on argument required',
maxdepth: 'exceeded maxdepth: ',
noArgs: 'no arguments',
noArrayArg: 'no array argument',
singleArrayArg: 'single array argument',
multipleArrayArgs: 'multiple array arguments',
arrayLikeRequired: 'array or array-like argument required',
arrayFill: 'array fill',
rootNotFound: 'specified root invalid',
noStyleFound: 'no style found: ',
unknownEventName: 'unknown event name',
dropdownModuleRequired: 'EZdropdown RZ.editmodule required',
review: 'review scenario',
safety: 'unexpected scenario',
notdone: 'coding not completed',
untested: 'untested scenario',
unexpected: 'unexpected scenario', //oops default?
moretesting: 'more testing required: {1}',
oops: 'Technical Difficulty: {0}'
},
scripts: {}, //loaded scripts -- set but not yet used
}
if (ez.global) //preserve any defined EZ.global properties
{
var _merge = function(global, value)
{
if (value instanceof Object)
{
if ( !(global instanceof Object) )
global = {};
for (var key in value)
global[key] = _merge(global[key], value[key]);
}
else global = value
return global;
}
global = _merge(global, ez.global);
}
return global;
})(EZ)
//} end of EZ.global / constants
//__________________________________________________________________________________________________
EZ.dotName = function EZdotName_boot(key) {
/*{-------------------------------------------------------------------------------------------------
simple dotName until full version loaded -- returns Array() with overridden toString()
non-functional exclude related functions to avoid js error if called.
------------------------------------------------------------------------------------------------}*/
var dotName = key ? [key] : [];
dotName.toString = function(key)
{
var value = this.slice();
if (key)
value.push(key);
return value.join('.');
}
dotName.isExcluded = function() { return false };
dotName.getSkipList = function() { return [] };
return dotName;
}
//__________________________________________________________________________________________________
EZ.log = function EZlog_boot() {
/*{-------------------------------------------------------------------------------------------------
save log messages until EZ.log pseudo class loaded and initialized
------------------------------------------------------------------------------------------------}*/
"use strict";
if (EZ.log.queue === null)
return
if (EZ.log.queue === undefined) //create for log arguments until full EZ.log loads
{ //...but stop logging if full EZ.log never loaded
EZ.log.queue = {};
window.addEventListener('load', function()
{
if (EZ.log.name.includes('boot'))
EZ.log.queue = null;
}, false);
}
var caller = EZ.getCaller();
var name = this ? this.name || this.toString()
: (caller.name || '-na-');
EZ.log.queue[name] = EZ.log.queue[name] || [];
var args = [].slice.call(arguments);
args.caller = caller; //verbose but safe
EZ.log.queue[name].push(args);
}
//__________________________________________________________________________________________________
/**
* TODO: pondering... minimal w/o options ??
**/
EZ.dotName = function EZdotName_minimal()
{
};
//__________________________________________________________________________________________________
(function _____EZformat_limited_____() {
/**
* EZ.format() -- limited functionality until EZformat.js loads
**/
EZ.format = {
//_________________________________________________________________________________________
toStringElement: { //Element.toString default argument: if blank or
defaultValue: 'brief', //undefined native: e.g. "[object HTMLSpanElement]"
defaultAttributes: 'className id name tagName type'
},
//_________________________________________________________________________________________
seconds: function format_seconds(ms) //full functionality
{
var seconds = (ms / 1000) + '';
var formatted = seconds.match(/^(.*\.\d{0,3})?/)[0]
|| seconds.match(/^(.*\.\d{0,4})?/)[0]
|| '0.000';
return formatted.concat('0000').substr(0,5);
},
//_________________________________________________________________________________________
/**
* when called with element from right click context menu...
* formats and displays selected elememt in popup window with additional actions / options
*
* https://www.mattzeunert.com/2016/02/19/custom-chrome-devtools-object-formatters.html
//_________________________________________________________________________________________
**/
tag: function ___format_tag(el)
{
return Element.toString.prototype.apply(el, [].slice.call(arguments));
},
//__________________________________________________________________________________________
/**
* Super flexible and robust value formating -- blends full functonality from EZ.toString()
* and JSON.plus.stringify() with powerful html Element format capibility and ability to
* include, exclude or extract one or more specified Object and/or Element properties.
*
* Collapsably html -and- console.log formats available.
*
* See EZ.format.Element() for html element details -- Element.prototype.toString() linked
* with ability to extract html as String, json or Object representation of live html tags.
*__________________________________________________________________________________________
**/
value: function ___format_value(value, maxchars, callback, options)
{
if (this.isTest)
void(0);
var args = [].slice.call(arguments);
var maxchars = options;
if (!isNaN(options))
options = {maxchars: maxchars};
if (options instanceof Object)
maxchars = options.maxchars;
else maxchars = 0;
var type = __getType(value);
if (type.endsWith('()')) //native fn: Array(), Object(), trim()
return type;
// . . . . . . . . . . . . . . . . .
switch (type)
{
case 'null': return EZ.NULL;
case 'undefined': return EZ.UNDEFINED;
case 'Boolean': return (value) ? EZ.TRUE : EZ.FALSE;
case 'Number': return isNaN(value) ? EZ.NAN : __formatNumber();
case 'String': return (value === '') ? EZ.BLANK : __formatString();
case 'Date': return __formatDate();
case 'RegExp': return __formatRegExp();
case 'Element': return __formatElement();
case 'Function': return __formatFunction();
default: return __formatObject();
}
// . . . . . . . . . . . . . . . . .
//_________________________________________________________________________________________
function __getType()
{
var toStr = Object.prototype.toString.call(value);
type = toStr.substring(8,toStr.length-1);
if (/(Null|Undefined)/.test(type))
return type.toLowerCase();
if (type.toLowerCase() == type) //got "global" for value=window
type = value.constructor.name; //...at one time
while (value instanceof Object)
{
if (typeof(value) == 'function')
value = value.constructor;
if (typeof(value) != 'function') break;
var script = Function.prototype.toString.call(value);
if (!/\{\s*\[native code\]\s*\}/.test(script)) break;
return value.name + '()';
}
return type;
}
//_________________________________________________________________________________________
/**
* calls EZ.format.formatObject() when loaded otherwise use native toString() for value
* type -- avoid value.toString() to prevent loop if it contains any EZ.format() call.
**/
function __formatObject()
{ //full functionality
//-------------------------------------------------------------------------------------
if (EZ.format.formatObject) return EZ.format.formatObject.apply(this, args);
//-------------------------------------------------------------------------------------
var str = value.constructor.prototype.toString.call(value) //limited functionality
if (maxchars && str > maxchars)
return (value instanceof Array) ? '[]' : '{}';
}
//_________________________________________________________________________________________
function __formatElement()
{
if (!EZ.format.Element
|| args.length == 1
|| Object.keys(options).length === 0
|| (Object.keys(options).length === 1 && options.extract == this.toStringDefault.defaultValue))
return Element.prototype.toString.call(value); //limited functionality
return EZ.format.Element.apply(this, args); //full functionality
}
//_________________________________________________________________________________________
function __formatString() //full functionality
{
var str = '';
var isClipped = false;
value = value.replace(/\r\n/g, '\n').replace(/\r/g, '\n').replace(/\n/g, EZ.EOL);
value = value.trimPlus(EZ.EOL); //EOL = String.fromCharCode(172); __ end of line
// |
value = value.substr(0,maxchars || value.length).replace(/(.)/g, function(ch)
{
if (!maxchars || str.length <= maxchars)
{
var code = ch.charCodeAt(0);
if (code < 32 || code > 255)
ch = '0x' + code.toString(16);
str += ch;
}
else
isClipped = true;
});
if (!str)
str = EZ.EMPTY;
else if (isClipped)
str += EZ.MORE;
else if (maxchars && str.length > maxchars)
str = '"' + EZ.MORE + '"';
else if (!str.startsWith('"'))
str = '"' + str.wrap('"') + '"';
return str;
}
//_________________________________________________________________________________________
function __formatNumber() //full functionality
{
var str = value.toString();
if (maxchars && str.length > maxchars)
str = str.substr(0, maxchars-1) + '...';
return str;
}
//_________________________________________________________________________________________
function __formatRegExp() //full functionality
{
var lastIndex = (value.lastIndex ? ':' + value.lastIndex : '');
var str = '/' + value.source + '/' + value.flags + lastIndex;
// + (value.lastIndex ? ':' + value.lastIndex : '');
if (maxchars && str.length > maxchars)
{
//str = '/' + str.substr(0, Math.min(0, maxchars-5)) + '/...';
//if (maxchars && str.length > maxchars)
str = '/.../' + lastIndex;
}
return str;
}
//_________________________________________________________________________________________
/** legacy EZ.dateTime()
* used for EZ.format.value(date) even after EZ.format.js loaded
*/
function __formatDate()
{
if (value.valueOf().toString() == 'NaN')
return 'Invalid Date';
var str = ('0'+(value.getMonth()+1).toString()).substr(-2) + '-'
+ ('0'+value.getDate()).substr(-2) + '-'
+ value.getFullYear()
var hours = value.getHours() % 12
var minutes = value.getMinutes();
var seconds = value.getSeconds();
var ms = value.getMilliseconds();
if (hours > 0 || minutes > 0 || seconds > 0 || ms > 0)
{
if (maxchars && str.length > (maxchars-10))
str += '...'
else
{
if (hours === 0) hours = 12
str += ' '
+ ('00'+hours.toString()).substr(-2) + ':'
+ ('00'+minutes).substr(-2);
if (seconds > 0)
str += ':' + ('00'+seconds).substr(-2);
if (ms > 0)
str += '.' + ('000'+ms).substr(-3);
str += (value.getHours() < 12 ? ' AM' : ' PM');
}
}
if (maxchars && str.length > maxchars)
str = 'Date()';
return str;
}
//______________________________________________________________________________________________
function __formatFunction() //full functionality
{
var pattern = /function\s*(\w*)\s*\(([\s\S]*?)\)[^{]*{\s*([\s\S]*)}/;
var results = Function.prototype.toString.call(value).match(pattern);
if (!results)
return 'function ' + (value.name || '') + '...';
var name = value.name || results[1] || options.key || '';
if (name.startsWith('bound '))
return value.name.substr(6) + '()'
var args = (results[2] || '').replace(/\s*\/\*[\s\S]*?\*\/\s*/g, '');
var lines = EZ.getLineCount(results[3] || '');
lines = (lines) ? (lines + ' lines').wrap('{}')
: (results[3].includes('native')) ? ''
: '...'.wrap('{}');
var str = ('function ' + name).trim() + '(' + args + ') ' + lines;
//var str = 'function ' + name + '(' + args + ')\n'
// + '{ lines: ' + (lines.concat('\n').match(/\n/).length-1) + ' }'
if (maxchars)
{
if (str.length > maxchars)
str = name + '(' + args + ')'
if (str.length > maxchars)
str = name + '(...)' + lines;
if (str.length > maxchars)
str = name + '(...)';
}
return str.trim();
}
},
//______________________________________________________________________________________________
$:"last key DW collapse hack"
}
//_____________________________________________________________________________________________
// EZ.formatDate is defined for backward compatibilty and EZ.format.value() convenience
// niether is currently updated when EZformat.js is subsequently loaded.
EZ.formatDate = function(date) { return EZ.format.value(date) }
EZ.format.date = EZ.formatDate;
EZ.format.dateTime = EZ.formatDate;
EZ.format.time = EZ.formatDate;
//. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
})();//...end of EZ.format()
EZ.date = function EZdate_boot() { return new Date([].slice.call(arguments)) }
//__________________________________________________________________________________________________
EZ.sync = function ___sync(value, defaultValues, name, maxdepth) {
/*-------------------------------------------------------------------------------------------------{
* EZ.sync(obj, defaultValues)
*
* TODO:
* use EZ.merge.deep if options ??
*_________________________________________________________________________________________________
}*/
if ( !(value instanceof Object) || !(defaultValues instanceof Object) ) return;
var logging = (name !== null);
name = name || '';
if (!isNaN(name))
{
maxdepth = name;
name = '';
}
var actions = ''; //get actions from name prefix
name = (name+'').replace(/^([+-@*?^]*)/, function(all, p)
{
actions = p;
return '';
});
var logKey = ''; //if name starts with [...]
name.replace(/^(\[(.*)\])?/, function(all, wrapped, key)
{
logKey = key || '';
return '';
});
if (!/[+-]/.test(actions))
actions += '+-';
var msg = [(name || 'Object name NA') + ' \t\t @ ' + EZ.format.time('ms') + '\t'];
var formatOpts = maxdepth;
if (!isNaN(formatOpts))
formatOpts = {maxdepth: maxdepth};
else
formatOpts = EZ.options.call(formatOpts);
maxdepth = formatOpts.maxdepth || 9;
formatOpts.maxchars = formatOpts.maxchars || 100;
var dotName = //(actions.includes('?')) ? new EZ.dotNameDev()
(EZ.dotName) ? new EZ.dotName()
: [];
//______________________________________________________________________________________________
/**
*
**/
var _format = function(action,obj,key)
{
formatOpts.key = key;
var fmt = (dotName instanceof Array) ? dotName.concat([key]).join('.')
: dotName.toString(key);
fmt = ' ' + fmt + ' \t '
+ '\t *' + action + '* \t ... '
+ obj[key]
// + EZ.format.value(obj[key], formatOpts)
msg.push(fmt)
}
//______________________________________________________________________________________________
/**
* for nested Objects at this depth
**/
var _syncDepth = function(obj, defaultValues, dotName, depth)
{
if (depth > maxdepth || EZ.getType(defaultValues) != 'Object')
return;
var keysActs = obj.$sync || actions; //sync actions for this property
if (/[+=]/.test(keysActs))
{ //for add or replace...
Object.keys(defaultValues).forEach(function(key) //add missing properties
{
if (key in obj || key == '$sync')
return;
obj[key] = obj[key] || defaultValues[key];
_format('added',obj,key);
});
/*
Object.keys(defaultValues).forEach(function(key)
{
if (key == '$sync')
return;
if (obj[key] === defaultValues[key])
return;
if (key in obj && !(key in defaultValues))
return;
if (key in obj && !keysActs.includes('='))
if (keysActs.includes('='))
delete obj[key];
var act = key in obj ? 'replaced' : 'added';
_format(act , obj, key);
obj[key] = obj[key] || defaultValues[key];
});
*/
}
if (keysActs.includes('-')) //for delete...
{
var deleteKeys = Object.keys(obj).remove( Object.keys(defaultValues) );
deleteKeys.forEach(function(key)
{
if (!isNaN(key)) return; //ignore numeric keys -- assume ArrayLike
_format('deleted',obj,key);
delete obj[key];
});
}
if (!keysActs.includes('$')) //delete $sync control unless it contains $
delete obj.$sync;
Object.keys(obj).forEach(function(key) //for nested Object properties
{
if (obj[key] instanceof Object)
_syncDepth(obj[key], defaultValues[key], dotName.concat([key]), depth+1);
});
}
//==============================================================================================
_syncDepth(value, defaultValues, dotName, 0);
//==============================================================================================
if (msg.length == 1)
{
if (actions.includes('^')) return ''; //no changes not logged
msg[0] += '... no changes\t\t';
}
msg = msg.format();
if (logging)
// EZ.logPlus(msg, logKey);
return msg;
}
//__________________________________________________________________________________________________
EZ.sync.getSet = function(obj, dotName){
/*{-------------------------------------------------------------------------------------------------
. . .
-------------------------------------------------------------------------------------------------}*/
var bindList = {
get: function _get(key, defaultValue)
{
if (key == null || key in this === false)
return EZ.oops(this.errmsg(key, 'invalid key')) || defaultValue;
return (key in this && this[key] !== undefined) ? this[key]