-
Notifications
You must be signed in to change notification settings - Fork 114
/
jquerymy.js
4880 lines (4288 loc) · 146 KB
/
jquerymy.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
/*
* jQuery.my 1.3.4
* Requires jQuery 2.0+, SugarJS 1.3.9-1.4.x
*
* — async functions support
* — fixed issues derived from lgtm static analysis
* — unsortable items are no more deleted from bound array
* — $.my.f.tojson generates prettier output, also
* received 3rd arg (obj, tabChars, maxLineLength)
*
* More details at jquerymy.com
*
* (c) @ermouth, thanks @carpogoryanin, @ftescht
* 2024-01-04
*/
;(function ($) {
var _version = '1.3.4';
// Some shortcuts and constants
var TMP, lang = 'en',
wURL = window.URL || window.webkitURL,
ie8 = !document.addEventListener,
Lang = ((window.navigator.language || window.navigator.userLanguage || 'en')+'').split('-')[0].toLowerCase(),
d8 = '{yyyy}-{MM}-{dd}',
h24= '{HH}:{mm}',
Ob = 'object',
Da = 'data',
Ar = 'array',
St = 'string',
Fu = 'function',
Ch = 'change',
rthis = /^this\./,
isA = Object.isArray,
isB = Object.isBoolean,
isS = Object.isString,
isO = Object.isObject,
isN = Object.isNumber,
isR = Object.isRegExp,
isF = Object.isFunction,
isP = function (a) {
// detects promise
return null != a && typeof a == Ob && isF(a.then);
},
forms = _getref($, 'my.f.repo') ? $.my.f.repo() : {_src:{}, _name:'Default manifest cache'},
restyles = _getref($, 'my.f.restyles') ? $.my.f.restyles() : {},
Merge = Object.merge,
Clone = Object.clone,
Keys = Object.keys,
$E = $.extend,
$D = $.Deferred,
T = $.type,
N = null,
n = function (o) {return o !== null && o !== undefined},
// Configurables using $.my[fname](newHandler)
// like $.my.ajax(newGlobalAjaxHandlerFunction)
_ajax = $.ajax,
_cache = _localCache,
_now = Date.now,
_require = _localRequire;
//########################################################
// Storage of rules defined by cascading selectors
// very similar to css. Leafs are processors
// or processing rules for this type of node
var MY = {
//getter and setter functions for different types of nodes
vals: {
'.my-form': function ($o, v) {
//object is jQuery.my instance
if ($o && $o.my ) {
var d = $o.my(Da);
return Object.equal(d,v) ? d : $o.my(Da, v, true);
}
else return v || N;
},
'.hasDatepicker':function ($o,v) {
//object has jQ UI datepicker
if(n(v)) $o.datepicker('setDate', v=='' ? v : Date.create(v));
var date = $o.datepicker('getDate');
return (date ? date.format(d8) : '');
},
'.my-tags': function ($o,v) {
//object is jQ tags control
if (n(v)) {
if (isS(v) || isN(v)) $o.tags(Da,[v + '']);
else if (isA(v)) $o.tags(Da, v);
}
return $o.tags(Da);
},
'.ui-draggable': (function ($o,v) {
//object is jQ UI draggable
if (n(v) && isO(v)) {
var c = {};
if (!isNaN(v.left)) c.left = (+v.left).ceil(2) + 'px';
if (!isNaN(v.top)) c.top = (+v.top).ceil(2) + 'px';
if (c.left || c.top) $o.css(c);
}
var p = $o.position();
return {
left: v && !isNaN(v.left) ? (+v.left).ceil(2) : p.left.ceil(2),
top: v && !isNaN(v.top) ? (+v.top).ceil(2) : p.top.ceil(2)
};
}),
'.my-form-list': (function ($o,list) {
//object is list of forms
var i, old, xold, mod, eq, //ctr = 0,
$n, $drag,
od = $o.data('formlist')||{},
gen = od.generator||{},
itemSel = gen.selector || '>.my-form',
merge = !!gen.merge,
tmpl = gen.template || '<div></div>',
tmplIsVar = /\{/.test(tmpl),
hasher = gen.hash || _sdbm,
ider = gen.id || _sdbm,
extHasher = gen.ext,
delay = gen.delay || 50,
sP = 'ui-sortable',
sPlc= '.'+sP+'-placeholder',
sortable = $o.is('.'+sP),
sorting = !!$o.children(sPlc).length,
result=[],
redraw = [],
now = _now();
// sortable hides unmovable items, so we can’t use option/items. 1.3.3
//var $c = sortable ? $o.find($o.sortable('option', 'items')) : $o.find(itemSel);
var $c = $o.find(itemSel);
if (n(list) && isA(list)) {
//return list passed if dragging taking place
if (sorting) return list;
// first we must estimate
// if putting new data over old
// changes anything
old = [];
xold = {};
$c.each(function (i) {
var $x = $(this), xd = $x.data('my'), dd;
if (xd) {
old.push(xd.data);
if (!merge && (dd = $x.data('formlist'))) xold[dd.oid] = xd.data;
}
});
//fast compare
eq = _aeq(old, list, '==');
if (!eq){
// We possibly have new data, hash it
var hash=[], oid = [], xoid = {}, present={};
redraw = [];
// Build id <-> idx and hashes
for (i=0; i<list.length; i++) {
oid[i] = ider(list[i], i) + '';
xoid[oid[i]] = i;
hash[i] = (ider !== hasher ? hasher(list[i], i) : oid[i]) + '';
}
//clean childs with no match to new data
$c.each(function () {
var $x = $(this),
md = $x.data('formlist') || {},
coid = md.oid;
if (
coid && _has(xoid, coid)
&& (
merge ||
list[xoid[coid]] === xold[coid]
)
) present[coid] = $(this);
else {
if ($x.hasClass('my-form')) $x.my('remove', true);
else $x.remove();
}
});
//iterate list
for (i=0; i<list.length; i++) {
if (_has(present, oid[i])) {
$n = present[oid[i]].detach().appendTo($o);
result.push($n.my('data'));
// decide if we must redraw
if (hash[i]!==($n.data('formlist')||{}).hash) {
if (merge && result.last() !== list[i]) {
// we must merge new data on existing form
gen.merge(result.last(), list[i]);
}
redraw.push($n);
}
} else {
$n = $(tmplIsVar ? tmpl.assign(list[i]) : tmpl).appendTo($o);
$n.data('formlist',{
list: list[i],
index: i,
hash: hash[i],
oid: oid[i]
});
// Init subform
_run.call(
$n,
_manifest (gen.parent, gen.manifest, list[i], i, list, $o),
list[i]
).then(function($n){
$n.on('change.my', _itemChange.debounce(delay/1.3));
}.fill($n));
result.push($n.my('data'));
}
}
// redraw if any
if (redraw.length && extHasher){
for (i=0;i<redraw.length;i++) _draw(redraw[i]);
redraw = [];
}
old=xold=mod=null;
return result;
}
xold=mod=null;
return old;
} else if ($c.length) {
if ((now - gen.stamp > 1.4*delay)
|| now - gen.stamp > 100
|| !gen.stashed
|| (gen.stashed.length !== $c.length-(sorting?1:0))
) {
if (sorting) $drag = $o.find('>.'+sP+'-helper');
var ri = 0;
$c.each(function (idx, elt) {
var $x = $(elt), xd, xf, chash, dirty = false;
if (!sorting || !$x.hasClass(sP+'-helper')) {
if (sorting && $x.hasClass(sP + '-placeholder')) $x = $drag;
xd = $x.data("my");
xf = $x.data("formlist");
if (xd && xf) {
result.push(xd.data);
if (ri != xf.index) {
xf.index = ri;
dirty = !0;
}
if (extHasher) {
chash = hasher(xd.data, ri)+"";
if (chash !== xf.hash) {
xf.hash = chash;
dirty = !0;
}
}
ri += 1;
if (dirty) redraw.push($x);
}
}
});
for (i=0;i<redraw.length;i++) _draw(redraw[i]);
redraw=[];
gen.stamp = now;
gen.stashed = result;
}
else result = gen.stashed.slice(0);
return result;
}
return list||[];
function _itemChange () {
var $this = $(this), df, i,
dd = $this.data('my');
if (dd) {
df = $this.data('formlist');
i = df.index;
df.hash = hasher(dd.data, i) + '';
if (ider !== hasher) df.oid = ider(dd.data, i) + '';
else df.oid =df.hash;
}
$o.trigger('check.my');
}
function _draw($form) {
if ($form.data('my').locktill+delay/1.3<now) $form.my('redraw');
}
}),
'input[type=date]':function ($o,v) {
//object is date input
var d;
if(n(v)) {
d = v!='' ? Date.create(v).format(d8) : '';
if (isS(d) && !/Invalid/.test(d)) $o.val(d);
return d;
}
d = $o.val();
return (d!='' ? Date.create(d).format(d8) : '');
},
'input[type=time]':function ($o,v) {
//object is time input
var d;
if(n(v)) {
d = v!='' ? Date.create(v).format(h24) : '';
if (isS(d) && !/Invalid/.test(d)) $o.val(d);
return d;
}
d = $o.val();
return (d!='' ? Date.create(d).format(h24) : '');
},
'input': ({
"[type='text'],[type='number'],[type='button'],[type='range'],[type='hidden'],:not([type])":{
//nearly all main input types and button
'.ui-slider-input': function ($o,v) {
//input with jQ UI slider() applied
if (n(v)) $o.val(v).slider('refresh');
},
'div.select2-container+input': function ($o, v) {
//select2
if (n(v) && JSON.stringify(v)!== JSON.stringify($o.select2('val')))
$o.select2('val', isA(v) ? v : [v]);
return $o.select2('val');
},
'': function ($o,v) {if(n(v)) $o.val(v+"");}
},
"[type='password'],[type='tel'],[type='email'],[type='search']": function ($o,v) {if(n(v)) $o.val(v + '');},
':radio':function ($o,v) {
//radio buttons
var pos = -1;
if (n(v)) {
$o.each(function (ind) {
var val = $(this).val();
if (v+'' === val+'') pos = ind;
});
var jqcheck = $o.eq(0).checkboxradio;
if (jqcheck) $o.each(function(ind){
var $x = $(this);
if (pos != ind && $x.is(':checked'))
$x.prop('checked', false).checkboxradio('refresh');
});
if (pos>-1) {
var $x = $o.eq(pos);
if (!$x.is(':checked')) {
$x.prop('checked', true);
if (jqcheck) $x.checkboxradio('refresh');
}
} else if (!jqcheck) $o.each(function(){$(this).prop('checked',false)});
}
if (pos==-1) for (var ind=0; ind<$o.length; ind++) {
if ($o.eq(ind).is(':checked')) pos=ind;
}
return pos!=-1 ? $o.eq(pos).val() : '';
},
':checkbox': function ($o, v0) {
//checkbox
var v = v0, a = [];
if (n(v)) {
if (!isA(v)) v = [v0];
var jqcheck = !!$o.eq(0).checkboxradio;
$o.each(function(ind) {
var $x = $(this), val = $x.val(), on = $x.is(":checked");
if (v.indexOf(val)!=-1) {
a.push(val);
if (!on) $x.prop('checked', true);
} else if (on) $x.prop('checked', false);
if (jqcheck) $x.checkboxradio('refresh');
});
} else {
$o.each(function(){
var $x = $(this);
if ($x.is(':checked')) a.push($x.val());
});
}
return a;
}
}),
'select': ({
'.ui-slider-switch': function ($o, v) {
//on-off in jQ Mobile
if (n(v)) {
$o.val(v + '');
$o.slider('refresh');
}
},
'div.select2-container+select':{
'[multiple]': function ($o, v) {
if (n(v)) $o.select2('val', isA(v) ? v : [v]);
return $o.select2('val');
},
'':function ($o, v) {
if (n(v)) $o.select2('val', v + '');
return $o.select2('val');
}
},
'.select2-hidden-accessible':{
// select2 v4
'[multiple]': function ($o, v) {
if (n(v) && JSON.stringify(v) !== JSON.stringify($o.select2('val'))) {
$o.val(isA(v) ? v : [v]).trigger('change.select2');
}
return $o.select2('val');
},
'':function ($o, v) {
if (n(v)) $o.val(v + '').trigger('change.select2');
return $o.val();
}
},
'[multiple]': function ($o, v) {
if (n(v)) {
$o.val(v, []);
if ($o.selectmenu && ($o.data('uiSelectmenu') || $o.data('selectmenu'))) $o.selectmenu('refresh', true);
//the only way to check if we have jQ UI selectmenu() attached
}
return $o.val()||[];
},
'': function ($o, v) {
if (n(v)) {
$o.val(v + '');
if ($o.selectmenu && ($o.data('uiSelectmenu') || $o.data('selectmenu'))) $o.selectmenu('refresh', true);
}
}
}),
'textarea': ({
// textarea or rich editor over
'.my-cleditor':function ($o,v) {
if(n(v)) $o.val(v).cleditor()[0].updateFrame();
return $o.val();
},
'div.redactor_box textarea,.redactor': function ($o,v) {
var r9 = $o.hasClass('my-redactor-9');
if(n(v)) {
if(r9) $o.redactor('set', v);
else $o.setCode(v, false);
return v;
}
return r9 ? $o.redactor('get') : $o.getCode();
},
'.my-codemirror':function ($o,v){
if (n(v)) {
$o[0].nextSibling.CodeMirror.setValue(v);
return v;
}
return $o[0].nextSibling.CodeMirror.getValue();
},
'':function ($o,v) {if(n(v)) $o.val(v + '');}
}),
'fieldset,form,section,footer,aside,.my-container': (function ($o, v) {
//object is class-manageable container,
//value is an array of css rules
var clist = _slice($o[0], 0).sort(),
list = v;
if (n(v)) {
if (isS(v)) list = v.split(/[,\s]+/).compact(true);
if (isA(list)) {
list.sort();
if (list.join(" ")!==clist.join(" ")) {
$o.attr("css", list.join(" "));
clist = list;
}
}
}
return clist;
}),
'div,span': ({
'.ui-slider':function ($o, v){
if(n(v)) $o.slider('option', $o.slider('option', 'values') ? 'values' : 'value', f.clone(v));
return f.clone($o.slider('option', 'values') || $o.slider('option', 'value') || 0);
},
'.ui-buttonset': function ($o, v) {
//jQ UI buttonset ()
if (!n(v)) {
var jor = $o.find(':radio:checked');
if (jor.length && jor.button) return jor.val() || jor.button('option', 'label') ;
} else if (v == '') {
var jon = N;
$o.find(':radio').each(function () {
jon= ($(this).val() || $(this).button('option', 'label'))==v ? $(this) : jon ;
});
if (jon) {
jon.attr('checked', true);
$o.buttonset('refresh');
return v;
}
}
$o.find(':radio:checked').attr('checked',false);
$o.buttonset('refresh');
return '';
},
'.ace_editor':function ($o,v) {
if(n(v)) ace.edit($o[0]).setValue(v);
return ace.edit($o[0]).getValue(v);
},
'': function ($o,v) {
if(n(v)) $o.html(v);
return $o.html();
}
}),
'a,p,li,td,th,h1,h2,h3,h4,h5,h6,pre,code':function ($o,v) {
if(n(v)) $o.html(v);
return $o.html();
},
'img':function ($o,v) {
if (n(v)) $o.attr('src', v);
return $o.attr('src') || '';
},
'':function ($o,v) {
if (n(v)) $o.html(v);
return $o.html() || $o.text() || ($o.val() + '') || '';
}
},
//messages
//########################################################
msg:{
"":{en:"Invalid input", ru:"Неверное значение"},
formError:{en:"Form error",ru:"Ошибка формы"},
initFailed:{
en:'<p class="my-error">Form init failed</p>',
ru:'<p class="my-error">Ошибка инициализации формы</p>'
},
badInput:{en:"Invalid input", ru:"Неверное значение"},
patternMismatch:{en:"Pattern mismatch", ru:"Не соответствует шаблону"},
rangeOverflow:{en:"Over maximum", ru:"Больше максимума"},
rangeUnderflow:{en:"Under minimum", ru:"Меньше минимума"},
stepMismatch:{en:"Step mismatch", ru:"Не кратно шагу"},
tooLong:{en:"Too long", ru:"Слишком длинно"},
typeMismatch:{en:"Invalid type", ru:"Неверный тип"},
valueMissing:{en:"Required", ru:"Обязательное поле"}
},
// Different controls’ events to watch for
// ########################################################
events: {
".hasDatepicker":"change.my check.my",
".my-form,.my-tags":"change.my check.my",
".ui-slider":"slide.my check.my",
"div.redactor_box textarea":"redactor.my check.my",
".my-codemirror":"codemirror.my check.my",
".ace_editor":"ace.my check.my",
".my-form-list":"sortupdate.my check.my",
".ui-sortable":"sortchange.my sortupdate.my check.my",
".ui-draggable":"drag.my dragstop.my check.my",
"a, .pseudolink, input[type=button], button": "click.my",
"img, :radio, :checkbox": "click.my check.my",
"div.select2-container+input,div.select2-container+select,.select2-hidden-accessible":"change.my check.my input.my",
".ui-buttonset,input, select, textarea":
"blur.my change.my check.my"+(navigator.appName.to(5)==="Micro"?" keyup.my":" input.my"),
"":"check.my"
},
// Functions retrieving container for different controls
// ########################################################
containers: {
"*[data-role='fieldcontain'] *":{ //jQuery Mobile
"input,textarea,select,button,:radio": function ($o) {
return $o.parents('[data-role="fieldcontain"]').eq(0);
}
},
"div.redactor_box textarea":function ($o){
return $o.parents('div.redactor_box').eq(0).parent();
},
".my-tags,.hasDatepicker,.ui-widget,input,textarea,select,button" :{
".my-cleditor": function ($o) {
return $o.parents('div.cleditorMain').eq(0).parent();
},
"": function ($o) {
var p = $o[0].parentNode, t = p.nodeName;
if (/^(div|span|a|p|form|fieldset|li|ul|td|th|h\d)$/i.test(t)) return $(p);
else return $o.parents('div,span,a,p,form,fieldset,li,ul,td,th,h1,h2,h3,h4,h5,h6').eq(0);
}
},
"": function ($o) {return $o;}
},
// Disablers and enablers
// ########################################################
offon: {
//if x==true disables control else enables
'.ace_editor': function (x,$o) {ace.edit($o[0]).setReadOnly(x)},
'.ui-selectable': function (x,$o) {_jquix($o,'selectable', x)},
'.ui-slider': function (x,$o) {_jquix($o,'slider', x)},
'.ui-draggable': function (x,$o) {_jquix($o,'draggable', x)},
'.ui-buttonset': function (x,$o) {_jquix($o,'buttonset', x)},
'.hasDatepicker': function (x,$o) {_jquix($o,'datepicker', x)},
'.my-form': function (x,$o) {$o.my('disabled', !!x)},
'div.select2-container+input,div.select2-container+select': function (x,$o) {_jquix($o,'select2', x)},
'.select2-hidden-accessible':function(x,$o){$o.prop('disabled',!!x)},
'.my-cleditor': function (x,$o) { $o.cleditor()[0].disable(!!x)},
'': function (x,$o) {$o.attr('disabled', !!x)}
},
// Destructors
// ########################################################
destroy:{
'.hasDatepicker': function ($o){$o.datepicker('destroy')},
'.ui-slider': function ($o){$o.slider('destroy')},
'.ui-sortable':{
'.my-form-list':function ($o){
$o.find('>.my-form').each(function(){$(this).my('remove')});
$o.removeClass('my-form-list');
$o.sortable('destroy');
},
'':function ($o){$o.sortable('destroy');}
},
'.my-form-list': function ($o){
$o.find('>.my-form').each(function(){$(this).my('remove')});
},
'.ui-draggable':function ($o){$o.draggable('destroy')},
'.my-redactor-8':function ($o){
$o.destroyEditor();
$o.removeClass('my-redactor-8');
},
'div.select2-container+input,div.select2-container+select,.select2-hidden-accessible':function ($o){$o.select2('destroy')},
//'.select2-hidden-accessible': function($o){$o.destroy()},
'.my-form': function ($o) {$o.my('remove')},
'textarea': {
'.my-codemirror': function ($o) {
$o[0].nextSibling.CodeMirror.toTextArea();
$o.removeClass('my-codemirror');
}
}
}
};
// Default values for .params section of manifest
// ########################################################
MY.params = {
container:function ($o) {
return _traverse($o, MY.containers)($o);
},
change:N,
// depth of dependencies resolver tree
recalcDepth: 2,
// default delay of bind invocation
delay: 0,
// if true form assumed unjsonned
strict: false,
// delay of <style> repaint on screen resize, -1 for no repaint
restyle: -1,
// default locale for manifests with .lang
locale: Lang,
// Messages object
messages: Object.map(MY.msg, function (k,v){return v[Lang]||v.en;}),
// selector of err tip containers
errorTip: '.my-error-tip',
// class applied on container on err
errorCss: 'my-error',
// err tips animation duration
animate: 0,
// err tips animation effect
effect: function ($e, onoff, duration) {
if (onoff) return $e.fadeIn(duration); $e.fadeOut(duration);
},
// undo steps to remember
remember: 0,
silent: false,
// form undo history object
history: {},
// min gap in ms between subsequent calls of history(),
historyDelay:100,
// default loader
loader: function (manifestId, parentId) {
var pi = $D(), m = _cache(manifestId + '');
if (m) pi.resolve(m);
else pi.reject(null);
return pi.promise();
},
ajaxTimeout:10000
};
Date.prototype.toJSON = function() {return this.toISOString();};
RegExp.prototype.toJSON = function() {return 'new RegExp(' + this.toString() + ')'};
var f = {
// Helper functions
con: _CON,
clone: function (o) {return o.clone ? o.clone() : o;},
indom: _indom,
jquix: _jquix,
overlap: _overlap,
patch: _patch,
kickoff: _kickoff,
sdbmCode: _sdbm,
tojson: _tojson,
fromjson: function (s) {var obj = JSON.parse(s); _unjson(obj); return obj;},
unjson: function(obj) {_unjson(obj); return obj;},
mask: _mask,
unmask: _unmask,
getref: _getref,
repo: function() {return forms;},
restyles: function() {return restyles;},
blob2base64: function(blob, done, nosplit) {
var reader = new FileReader();
reader.onload = function() {done(nosplit ? reader.result : reader.result.split(',')[1]);};
reader.readAsDataURL(blob);
},
base642blob: function(base64, done, mime) {
var binary = atob(base64),
len = binary.length,
buffer = new ArrayBuffer(len),
view = new Uint8Array(buffer);
for (var i = 0; i < len; i++) view[i] = binary.charCodeAt(i);
var blob = new Blob([view], {type: mime || 'application/octet-stream'});
if (isF(done)) done(blob);
else return blob;
},
base64: function (s0, decode, prefix0) {
// If s0 is not string it's stringified
// If decode is true, decodes base64, else encodes
// If prefix===true, utf-8 BOM is added,
// If prefix is a string, it’s assumed mime,
// and added to encoded data
var r = null,
s = (isS(s0) ? s0 : $.my.tojson(s0)),
prefix = isS(prefix0) ? 'data:'+prefix0+';base64,': '';
if(decode) {
try {r = decodeURIComponent(escape(window.atob(s)));}catch(e) {r=null;}
if (null!==r && /(^".*"$)|(^\[.*\]$)|(^\{.*\}$)/.test(r)) {
try {r = f.fromjson(r);}catch(e) {r=null;}
}
return r;
}
return prefix + window.btoa(
(prefix0===true ? '\xEF\xBB\xBF' : '')
+ unescape(encodeURIComponent(s))
);
},
css2json: function(css){
var acc = '', res = (
(css+'')
.replace(/\/\*[\s\S]+\*\//gm,'')
.replace(/@charset[^;]+;/gim,'')
.replace(/[\n\t\s]+/g,' ')
.replace(/\s*@media[^{]*\{/g,function(e){return e.to(-1).trim() + 'ᴥ'})
.replace(/\}/g,'}ᴥ')
.replace(/^\n+/g, '').replace(/[\n\s]+$/g, '')
.split('ᴥ')
.compact(true)
.reduce(function(a,b){
var t = b.trim(), p, k, v;
if ('}' == t) acc = '';
else if (/^[^{]+\{[^\}]+\}$/.test(t)) {
p = t.to(-1).split("{");
k = ' ' + p[0].trim();
v = p[1].trim();
if (v.last() != ';') v += ';';
if (!acc) a[k] = (a[k] || '')+v;
else a[acc][k] = (a[acc][k] || '') + v;
}
else if (/^@media/.test(t)) {
a[t] = {};
acc = t;
}
return a;
},{})
);
return res;
},
tmpl: function(){},
_s2css: _style,
_normUI: _normalize
};
//######### JQUERY METHODS ##############
var methods = {
container: function ($o) {return _traverse($o, MY.containers)($o);},
data: (function (data, noRecalc) {
var $x = this;
if (isO(data)) {
$x.my().data = _overlap($x.my().data, data);
this.my("redraw", noRecalc);
}
return $x.my().data;
}),
disabled: (function (bool) {
var $d, i, dn,onOff,
$x = this,
d = $x.my();
if (!d) return undefined;
if (bool == N) return d.disabled;
if (!!bool) {
//disable all controls
Keys(d.ui).forEach(function(i){
var $d = _find($x, i),
dn = $d.my();
if (dn) dn.predisabled = dn.disabled;
_css(true, $d, ':disabled');
});
$x.addClass('my-disabled');
}
else {
Keys(d.ui).forEach(function(i){
var $d = _find($x, i),
dn = $d.my();
if (!dn) return;
_css(dn.predisabled, $d, ':disabled');
});
$x.removeClass('my-disabled');
$x.my('redraw');
}
}),
errors: (function () {
var e0 = $(this).my().errors || {},
e = {};
Keys(e0).forEach(function(i){
var t = e0[i];
if ((typeof t == St && t != '') || (isO(t) && Object.size(t))) e[i] = t;
});
return e;
}),
find: function _findUiNode(sel) {
var $x = this, d = $x.my();
if (d && d.root) $x = d.root;
return $x.find(sel);
},
history: function (a,c) {return _history(a, this.my().params, c);},
id: (function (id, obj) {
if (isS(id)) return _cache(id, obj);
else {
var d = this.my();
return (d && d.id)?d.id:N;
}
}),
index: function () {
var o = (this.my().root && !this.my().ddata)?this.my().root:this;
return (o.data('formlist')||{}).index;
},
indom: function(){ return _indom(this); },
init: _run,
insert: (function (where, what) {
var src = this.hasClass("my-form-list")?this:(this.my().root||this),
o = src.hasClass("my-form-list")?src:src.parent(".my-form-list"),
pos = (src.data("formlist")||{}).index,
list,
obj = what,
gen = o.data("formlist").generator,
idx;
if (null==pos) pos=0;
if (rthis.test(gen.bind)) list = _getref(o.my().manifest, gen.bind.replace(rthis,''));
else list = _getref(o.my().data, gen.bind);
if (!isO(obj)) {
if (!isO(gen.manifest)) {
if (o===src) throw "No data to insert, cannot guess when manifest is a function.";
obj = Clone(src.my().manifest.data, true);
}
else obj = Clone(gen.manifest.data,true)||{};
}
if ("before"===where) idx=pos;
else if("after"===where) idx=pos+1;
else if (!isNaN(where)) {
idx=(1*where).clamp(0, list.length);
} else throw "Invalid position for insertion";
list.add(obj, idx);
o.trigger("redraw");
}),
manifest: function (format) {
return format=='json' ? f.tojson(this.my().manifest) : this.my().manifest;
},
promise: function (fn) {if (isF(fn)) this.my().promise.then(fn); return this.my().promise;},
radio: function _emitRadioMessage (channel, msg) {
this.trigger('radio', isS(channel) ? {channel:channel, message:msg} : channel);
},
redraw: (function ( noRecalc, silent) {
// Redraws the form
var $x = this,
d = $x.my(),
depth = 2;
if (d && isO(d.ui)) {
depth = d.params.recalcDepth;
Object.keys(d.ui).forEach(function (key) {
var $n = _find($x, key);
_update($n, noRecalc ? N : undefined , depth);
if (!noRecalc) {
if ($n.hasClass('my-form')) $n.my('redraw');
if ($n.hasClass('my-form-list')) $n.trigger('redraw');
else $n.trigger('check.my');
}
});
if (!silent && noRecalc) $x.trigger(Ch);
}
return $x;
}),
remove: (function (fromDOM){
var $o = this,
$style,
$locstyle, m,
locFiles,
d, ui, cid, mid;
if (!this.my()) return N;
//child elt requests form removal
if (this.my().root && !this.my().ddata) $o = this.my().root;
m = $o.my();
d = m.data;
cid = m.cid;
mid = m.mid;
// stop event listeners
$o.unbind(".my");
// exec done
if (isO(m) && m.manifest && isF(m.manifest.die)) {
try {
m.manifest.die.call(m.manifest, $o, m.manifest);
} catch(e){}
}
// remove stylesheets
if ($style=m.style) {
if ($style.data("count")=="1") {
try{$style.remove();}catch(e){}
}
else $style.data("count", $style.data("count")-1);
}
if ($locstyle=m.localStyle) {
try{
delete restyles[cid];
$locstyle.remove();
}catch(e){}
}
// revoke data urls
if (window.URL && (locFiles = m.locFiles) && locFiles.length) {
for (var i=0;i< locFiles.length; i++) {
try { URL.revokeObjectURL(locFiles[i]); } catch(e) {}
}
}
// remove $.my from ui entries
ui = (m||{}).ui;
if (ui) {
Keys(ui).forEach(function (key){