forked from vitmalina/w2ui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathw2fields.js
2677 lines (2606 loc) · 140 KB
/
w2fields.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
/************************************************************************
* Library: Web 2.0 UI for jQuery (using prototypical inheritance)
* - Following objects defined
* - w2field - various field controls
* - $().w2field - jQuery wrapper
* - Dependencies: jQuery, w2utils
*
* == NICE TO HAVE ==
* - upload (regular files)
* - BUG with prefix/postfix and arrows (test in different contexts)
* - prefix and suffix are slow (100ms or so)
* - multiple date selection
* - month selection, year selections
* - arrows no longer work (for int)
* - form to support custom types
* - rewrite suffix and prefix positioning with translateY()
* - MultiSelect - Allow Copy/Paste for single and multi values
* - add routeData to list/enum
* - for type: list -> read value from attr('value')
* - ENUM, LIST: should be able to define which is ID field and which is TEXT
* - ENUM, LIST: same data structure as grid
* - ENUM, LIST: should have same as grid (limit, offset, search, sort)
* - ENUM, LIST: should support wild cars
* - add selection of predefined times (used for appointments)
*
* == 1.5 changes
* - added support decimalSymbol (added options.decimalSymbol)
* - $('#id').w2field() - will return w2field object (same as $('#id').data('w2field'))
* - added resize() function and automatic watching for size
* - bug: if input is hidden and then enum is applied, then when it becomes visible, it will be 110px
* - deprecate placeholder, read it from input
* - added get(), set(), setIndex() for fields
* - added options.compare function for list, combo, enum
* - added options.filter for list, combo, enum
* - added selection for the current date in the calendar
* - added for enum options.onScroll
* - modified clearCache()
* - changed onSearch - happens when search input changes
* - added options.method - for combo/list/enum if url is defined
* - options.items can be a function now
* - options.maxDropWidth
* - options.noMinutes - for time field
* - options.transarent = t/f for color
* - remote data is not compatible with grid
* - options.recId, options.recText - to define custom id and text for remove data, can be string or function
*
************************************************************************/
(function ($) {
var w2field = function (options) {
// public properties
this.el = null;
this.helpers = {}; // object or helper elements
this.type = options.type || 'text';
this.options = $.extend(true, {}, options);
this.onSearch = options.onSearch || null;
this.onRequest = options.onRequest || null;
this.onLoad = options.onLoad || null;
this.onError = options.onError || null;
this.onClick = options.onClick || null;
this.onAdd = options.onAdd || null;
this.onNew = options.onNew || null;
this.onRemove = options.onRemove || null;
this.onMouseOver = options.onMouseOver || null;
this.onMouseOut = options.onMouseOut || null;
this.onIconClick = options.onIconClick || null;
this.onScroll = options.onScroll || null;
this.tmp = {}; // temp object
// clean up some options
delete this.options.type;
delete this.options.onSearch;
delete this.options.onRequest;
delete this.options.onLoad;
delete this.options.onError;
delete this.options.onClick;
delete this.options.onMouseOver;
delete this.options.onMouseOut;
delete this.options.onIconClick;
delete this.options.onScroll;
// extend with defaults
$.extend(true, this, w2obj.field);
};
// ====================================================
// -- Registers as a jQuery plugin
$.fn.w2field = function (method, options) {
// call direct
if (this.length == 0) {
var pr = w2field.prototype;
if (pr[method]) {
return pr[method].apply(pr, Array.prototype.slice.call(arguments, 1));
}
} else {
// if without arguments - return the object
if (arguments.length == 0) {
var obj = $(this).data('w2field');
return obj;
}
if (typeof method == 'string' && typeof options == 'object') {
method = $.extend(true, {}, options, { type: method });
}
if (typeof method == 'string' && options == null) {
method = { type: method };
}
method.type = String(method.type).toLowerCase();
return this.each(function (index, el) {
var obj = $(el).data('w2field');
// if object is not defined, define it
if (obj == null) {
var obj = new w2field(method);
$.extend(obj, { handlers: [] });
if (el) obj.el = $(el)[0];
obj.init();
$(el).data('w2field', obj);
return obj;
} else { // fully re-init
obj.clear();
if (method.type == 'clear') return;
var obj = new w2field(method);
$.extend(obj, { handlers: [] });
if (el) obj.el = $(el)[0];
obj.init();
$(el).data('w2field', obj);
return obj;
}
return null;
});
}
};
// ====================================================
// -- Implementation of core functionality
/* To add custom types
$().w2field('addType', 'myType', function (options) {
$(this.el).on('keypress', function (event) {
if (event.metaKey || event.ctrlKey || event.altKey
|| (event.charCode != event.keyCode && event.keyCode > 0)) return;
var ch = String.fromCharCode(event.charCode);
if (ch != 'a' && ch != 'b' && ch != 'c') {
if (event.stopPropagation) event.stopPropagation(); else event.cancelBubble = true;
return false;
}
});
$(this.el).on('blur', function (event) { // keyCode & charCode differ in FireFox
var ch = this.value;
if (ch != 'a' && ch != 'b' && ch != 'c') {
$(this).w2tag(w2utils.lang("Not a single character from the set of 'abc'"));
}
});
});
*/
w2field.prototype = {
custom: {}, // map of custom types
addType: function (type, handler) {
type = String(type).toLowerCase();
this.custom[type] = handler;
return true;
},
removeType: function (type) {
type = String(type).toLowerCase();
if (!this.custom[type]) return false;
delete this.custom[type];
return true;
},
init: function () {
var obj = this;
var options = this.options;
var defaults;
// Custom Types
if (typeof this.custom[this.type] == 'function') {
this.custom[this.type].call(this, options);
return;
}
// only for INPUT or TEXTAREA
if (['INPUT', 'TEXTAREA'].indexOf(this.el.tagName.toUpperCase()) == -1) {
console.log('ERROR: w2field could only be applied to INPUT or TEXTAREA.', this.el);
return;
}
switch (this.type) {
case 'text':
case 'int':
case 'float':
case 'money':
case 'currency':
case 'percent':
case 'alphanumeric':
case 'bin':
case 'hex':
defaults = {
min : null,
max : null,
step : 1,
autoFormat : true,
currencyPrefix : w2utils.settings.currencyPrefix,
currencySuffix : w2utils.settings.currencySuffix,
currencyPrecision : w2utils.settings.currencyPrecision,
decimalSymbol : w2utils.settings.decimalSymbol,
groupSymbol : w2utils.settings.groupSymbol,
arrows : false,
keyboard : true,
precision : null,
silent : true,
prefix : '',
suffix : ''
};
this.options = $.extend(true, {}, defaults, options);
options = this.options; // since object is re-created, need to re-assign
options.numberRE = new RegExp('['+ options.groupSymbol + ']', 'g');
options.moneyRE = new RegExp('['+ options.currencyPrefix + options.currencySuffix + options.groupSymbol +']', 'g');
options.percentRE = new RegExp('['+ options.groupSymbol + '%]', 'g');
// no keyboard support needed
if (['text', 'alphanumeric', 'hex', 'bin'].indexOf(this.type) != -1) {
options.arrows = false;
options.keyboard = false;
}
this.addPrefix(); // only will add if needed
this.addSuffix();
break;
case 'color':
defaults = {
prefix : '#',
suffix : '<div style="width: '+ (parseInt($(this.el).css('font-size')) || 12) +'px"> </div>',
arrows : false,
keyboard : false,
transparent : true
};
$.extend(options, defaults);
this.addPrefix(); // only will add if needed
this.addSuffix(); // only will add if needed
// additional checks
$(this.el).attr('maxlength', 6);
if ($(this.el).val() != '') setTimeout(function () { obj.change(); }, 1);
break;
case 'date':
defaults = {
format : w2utils.settings.dateFormat, // date format
keyboard : true,
silent : true,
start : '', // string or jquery object
end : '', // string or jquery object
blocked : {}, // { '4/11/2011': 'yes' }
colored : {}, // { '4/11/2011': 'red:white' }
blockWeekDays : null // array of numbers of weekday to block
};
this.options = $.extend(true, {}, defaults, options);
options = this.options; // since object is re-created, need to re-assign
if ($(this.el).attr('placeholder') == null) $(this.el).attr('placeholder', options.format);
break;
case 'time':
defaults = {
format : w2utils.settings.timeFormat,
keyboard : true,
silent : true,
start : '',
end : '',
noMinutes : false
};
this.options = $.extend(true, {}, defaults, options);
options = this.options; // since object is re-created, need to re-assign
if ($(this.el).attr('placeholder') == null) $(this.el).attr('placeholder', options.format);
break;
case 'datetime':
defaults = {
format : w2utils.settings.dateFormat + ' | ' + w2utils.settings.timeFormat,
keyboard : true,
silent : true,
start : '', // string or jquery object or Date object
end : '', // string or jquery object or Date object
blocked : [], // [ '4/11/2011', '4/12/2011' ] or [ new Date(2011, 4, 11), new Date(2011, 4, 12) ]
colored : {}, // { '12/17/2014': 'blue:green', '12/18/2014': 'gray:white' }; // key has be be formatted with w2utils.settings.dateFormat
placeholder : null, // optional. will fall back to this.format if not specified. Only used if this.el has no placeholder attribute.
btn_now : true, // show/hide the use-current-date-and-time button
noMinutes : false
};
this.options = $.extend(true, {}, defaults, options);
options = this.options; // since object is re-created, need to re-assign
if ($(this.el).attr('placeholder') == null) $(this.el).attr('placeholder', options.placeholder || options.format);
break;
case 'list':
case 'combo':
defaults = {
items : [],
selected : {},
url : null, // url to pull data from
recId : null, // map retrieved data from url to id, can be string or function
recText : null, // map retrieved data from url to text, can be string or function
method : null, // default comes from w2utils.settings.dataType
interval : 350, // number of ms to wait before sending server call on search
postData : {},
minLength : 1, // min number of chars when trigger search
cacheMax : 250,
maxDropHeight : 350, // max height for drop down menu
maxDropWidth : null, // if null then auto set
match : 'begins', // ['contains', 'is', 'begins', 'ends']
silent : true,
icon : null,
iconStyle : '',
onSearch : null, // when search needs to be performed
onRequest : null, // when request is submitted
onLoad : null, // when data is received
onError : null, // when data fails to load due to server error or other failure modes
onIconClick : null,
renderDrop : null, // render function for drop down item
compare : null, // compare function for filtering
filter : true, // weather to filter at all
prefix : '',
suffix : '',
openOnFocus : false, // if to show overlay onclick or when typing
markSearch : false
};
options.items = this.normMenu(options.items); // need to be first
if (this.type == 'list') {
// defaults.search = (options.items && options.items.length >= 10 ? true : false);
defaults.openOnFocus = true;
$(this.el).addClass('w2ui-select');
// if simple value - look it up
if (!$.isPlainObject(options.selected) && options.items) {
for (var i = 0; i< options.items.length; i++) {
var item = options.items[i];
if (item && item.id == options.selected) {
options.selected = $.extend(true, {}, item);
break;
}
}
}
this.watchSize();
}
options = $.extend({}, defaults, options, {
align : 'both', // same width as control
altRows : true // alternate row color
});
this.options = options;
if (!$.isPlainObject(options.selected)) options.selected = {};
$(this.el).data('selected', options.selected);
if (options.url) {
options.items = [];
this.request(0);
}
if (this.type == 'list') this.addFocus();
this.addPrefix();
this.addSuffix();
setTimeout(function () { obj.refresh(); }, 10); // need this for icon refresh
$(this.el).attr('autocomplete', 'off');
if (options.selected.text != null) $(this.el).val(options.selected.text);
break;
case 'enum':
defaults = {
items : [],
selected : [],
max : 0, // max number of selected items, 0 - unlim
url : null, // not implemented
recId : null, // map retrieved data from url to id, can be string or function
recText : null, // map retrieved data from url to text, can be string or function
interval : 350, // number of ms to wait before sending server call on search
method : null, // default comes from w2utils.settings.dataType
postData : {},
minLength : 1, // min number of chars when trigger search
cacheMax : 250,
maxWidth : 250, // max width for a single item
maxHeight : 350, // max height for input control to grow
maxDropHeight : 350, // max height for drop down menu
maxDropWidth : null, // if null then auto set
match : 'contains', // ['contains', 'is', 'begins', 'ends']
silent : true,
openOnFocus : false, // if to show overlay onclick or when typing
markSearch : true,
renderDrop : null, // render function for drop down item
renderItem : null, // render selected item
compare : null, // compare function for filtering
filter : true, // alias for compare
style : '', // style for container div
onSearch : null, // when search needs to be performed
onRequest : null, // when request is submitted
onLoad : null, // when data is received
onError : null, // when data fails to load due to server error or other failure modes
onClick : null, // when an item is clicked
onAdd : null, // when an item is added
onNew : null, // when new item should be added
onRemove : null, // when an item is removed
onMouseOver : null, // when an item is mouse over
onMouseOut : null, // when an item is mouse out
onScroll : null // when div with selected items is scrolled
};
options = $.extend({}, defaults, options, {
align : 'both', // same width as control
suffix : '',
altRows : true // alternate row color
});
options.items = this.normMenu(options.items);
options.selected = this.normMenu(options.selected);
this.options = options;
if (!$.isArray(options.selected)) options.selected = [];
$(this.el).data('selected', options.selected);
if (options.url) {
options.items = [];
this.request(0);
}
this.addSuffix();
this.addMulti();
this.watchSize();
break;
case 'file':
defaults = {
selected : [],
max : 0,
maxSize : 0, // max size of all files, 0 - unlim
maxFileSize : 0, // max size of a single file, 0 -unlim
maxWidth : 250, // max width for a single item
maxHeight : 350, // max height for input control to grow
maxDropHeight : 350, // max height for drop down menu
maxDropWidth : null, // if null then auto set
silent : true,
renderItem : null, // render selected item
style : '', // style for container div
onClick : null, // when an item is clicked
onAdd : null, // when an item is added
onRemove : null, // when an item is removed
onMouseOver : null, // when an item is mouse over
onMouseOut : null // when an item is mouse out
};
options = $.extend({}, defaults, options, {
align : 'both', // same width as control
altRows : true // alternate row color
});
this.options = options;
if (!$.isArray(options.selected)) options.selected = [];
$(this.el).data('selected', options.selected);
if ($(this.el).attr('placeholder') == null) {
$(this.el).attr('placeholder', w2utils.lang('Attach files by dragging and dropping or Click to Select'));
}
this.addMulti();
this.watchSize();
break;
}
// attach events
this.tmp = {
onChange : function (event) { obj.change.call(obj, event); },
onClick : function (event) { obj.click.call(obj, event); },
onFocus : function (event) { obj.focus.call(obj, event); },
onBlur : function (event) { obj.blur.call(obj, event); },
onKeydown : function (event) { obj.keyDown.call(obj, event); },
onKeyup : function (event) { obj.keyUp.call(obj, event); },
onKeypress : function (event) { obj.keyPress.call(obj, event); }
};
$(this.el)
.addClass('w2field w2ui-input')
.data('w2field', this)
.on('change', this.tmp.onChange)
.on('click', this.tmp.onClick) // ignore click because it messes overlays
.on('focus', this.tmp.onFocus)
.on('blur', this.tmp.onBlur)
.on('keydown', this.tmp.onKeydown)
.on('keyup', this.tmp.onKeyup)
.on('keypress', this.tmp.onKeypress)
.css(w2utils.cssPrefix('box-sizing', 'border-box'));
// format initial value
this.change($.Event('change'));
},
watchSize: function () {
var obj = this;
var tmp = $(obj.el).data('tmp') || {};
tmp.sizeTimer = setInterval(function () {
if ($(obj.el).parents('body').length > 0) {
obj.resize();
} else {
clearInterval(tmp.sizeTimer);
}
}, 200);
$(obj.el).data('tmp', tmp);
},
get: function () {
var ret;
if (['list', 'enum', 'file'].indexOf(this.type) != -1) {
ret = $(this.el).data('selected');
} else {
ret = $(this.el).val();
}
return ret;
},
set: function (val) {
if (['list', 'enum', 'file'].indexOf(this.type) != -1) {
$(this.el).data('selected', val).change();
this.refresh();
} else {
$(this.el).val(val);
}
},
setIndex: function (ind) {
var items = this.options.items;
if (items && items[ind]) {
$(this.el).data('selected', items[ind]).change();
this.refresh();
return true;
}
return false;
},
clear: function () {
var obj = this;
var options = this.options;
// if money then clear value
if (['money', 'currency'].indexOf(this.type) != -1) {
$(this.el).val($(this.el).val().replace(options.moneyRE, ''));
}
if (this.type == 'percent') {
$(this.el).val($(this.el).val().replace(/%/g, ''));
}
if (this.type == 'color') {
$(this.el).removeAttr('maxlength');
}
if (this.type == 'list') {
$(this.el).removeClass('w2ui-select');
}
this.type = 'clear';
var tmp = $(this.el).data('tmp');
if (!this.tmp) return;
// restore paddings
if (tmp != null) {
$(this.el).height('auto');
if (tmp && tmp['old-padding-left']) $(this.el).css('padding-left', tmp['old-padding-left']);
if (tmp && tmp['old-padding-right']) $(this.el).css('padding-right', tmp['old-padding-right']);
if (tmp && tmp['old-background-color']) $(this.el).css('background-color', tmp['old-background-color']);
if (tmp && tmp['old-border-color']) $(this.el).css('border-color', tmp['old-border-color']);
// remove resize watcher
clearInterval(tmp.sizeTimer);
}
// remove events and (data)
$(this.el)
.val(this.clean($(this.el).val()))
.removeClass('w2field')
.removeData() // removes all attached data
.off('change', this.tmp.onChange)
.off('click', this.tmp.onClick)
.off('focus', this.tmp.onFocus)
.off('blur', this.tmp.onBlur)
.off('keydown', this.tmp.onKeydown)
.off('keyup', this.tmp.onKeyup)
.off('keypress', this.tmp.onKeypress);
// remove helpers
for (var h in this.helpers) $(this.helpers[h]).remove();
this.helpers = {};
},
refresh: function () {
var obj = this;
var options = this.options;
var selected = $(this.el).data('selected');
var time = (new Date()).getTime();
// enum
if (['list'].indexOf(this.type) != -1) {
$(obj.el).parent().css('white-space', 'nowrap'); // needs this for arrow always to appear on the right side
// hide focus and show text
if (obj.helpers.prefix) obj.helpers.prefix.hide();
setTimeout(function () {
if (!obj.helpers.focus) return;
// if empty show no icon
if (!$.isEmptyObject(selected) && options.icon) {
options.prefix = '<span class="w2ui-icon '+ options.icon +'"style="cursor: pointer; font-size: 14px;' +
' display: inline-block; margin-top: -1px; color: #7F98AD;'+ options.iconStyle +'">'+
'</span>';
obj.addPrefix();
} else {
options.prefix = '';
obj.addPrefix();
}
// focus helper
var focus = obj.helpers.focus.find('input');
if ($(focus).val() == '') {
$(focus).css('text-indent', '-9999em').prev().css('opacity', 0);
$(obj.el).val(selected && selected.text != null ? selected.text : '');
} else {
$(focus).css('text-indent', 0).prev().css('opacity', 1);
$(obj.el).val('');
setTimeout(function () {
if (obj.helpers.prefix) obj.helpers.prefix.hide();
var tmp = 'position: absolute; opacity: 0; margin: 4px 0px 0px 2px; background-position: left !important;';
if (options.icon) {
$(focus).css('margin-left', '17px');
$(obj.helpers.focus).find('.icon-search').attr('style', tmp + 'width: 11px !important; opacity: 1; display: block');
} else {
$(focus).css('margin-left', '0px');
$(obj.helpers.focus).find('.icon-search').attr('style', tmp + 'width: 0px !important; opacity: 0; display: none');
}
}, 1);
}
// if readonly or disabled
if ($(obj.el).prop('readonly') || $(obj.el).prop('disabled')) {
setTimeout(function () {
$(obj.helpers.prefix).css('opacity', '0.6');
$(obj.helpers.suffix).css('opacity', '0.6');
}, 1);
} else {
setTimeout(function () {
$(obj.helpers.prefix).css('opacity', '1');
$(obj.helpers.suffix).css('opacity', '1');
}, 1);
}
}, 1);
}
if (['enum', 'file'].indexOf(this.type) != -1) {
var html = '';
for (var s in selected) {
var it = selected[s];
var ren = '';
if (typeof options.renderItem == 'function') {
ren = options.renderItem(it, s, '<div class="w2ui-list-remove" title="'+ w2utils.lang('Remove') +'" index="'+ s +'">  </div>');
} else {
ren = '<div class="w2ui-list-remove" title="'+ w2utils.lang('Remove') +'" index="'+ s +'">  </div>'+
(obj.type == 'enum' ? it.text : it.name + '<span class="file-size"> - '+ w2utils.formatSize(it.size) +'</span>');
}
html += '<li index="'+ s +'" style="max-width: '+ parseInt(options.maxWidth) + 'px; '+ (it.style ? it.style : '') +'">'+
ren +'</li>';
}
var div = obj.helpers.multi;
var ul = div.find('ul');
div.attr('style', div.attr('style') + ';' + options.style);
$(obj.el).css('z-index', '-1');
if ($(obj.el).prop('readonly') || $(obj.el).prop('disabled')) {
setTimeout(function () {
div[0].scrollTop = 0; // scroll to the top
div.addClass('w2ui-readonly')
.find('li').css('opacity', '0.9')
.parent().find('li.nomouse').hide()
.find('input').prop('readonly', true)
.parents('ul')
.find('.w2ui-list-remove').hide();
}, 1);
} else {
setTimeout(function () {
div.removeClass('w2ui-readonly')
.find('li').css('opacity', '1')
.parent().find('li.nomouse').show()
.find('input').prop('readonly', false)
.parents('ul')
.find('.w2ui-list-remove').show();
}, 1);
}
// clean
div.find('.w2ui-enum-placeholder').remove();
ul.find('li').not('li.nomouse').remove();
// add new list
if (html != '') {
ul.prepend(html);
} else if ($(obj.el).attr('placeholder') != null && div.find('input').val() == '') {
var style =
'padding-top: ' + $(this.el).css('padding-top') + ';'+
'padding-left: ' + $(this.el).css('padding-left') + '; ' +
'box-sizing: ' + $(this.el).css('box-sizing') + '; ' +
'line-height: ' + $(this.el).css('line-height') + '; ' +
'font-size: ' + $(this.el).css('font-size') + '; ' +
'font-family: ' + $(this.el).css('font-family') + '; ';
div.prepend('<div class="w2ui-enum-placeholder" style="'+ style +'">'+ $(obj.el).attr('placeholder') +'</div>');
}
// ITEMS events
div.off('scroll.w2field').on('scroll.w2field', function (event) {
var edata = obj.trigger({ phase: 'before', type: 'scroll', target: obj.el, originalEvent: event });
if (edata.isCancelled === true) return;
// event after
obj.trigger($.extend(edata, { phase: 'after' }));
})
.find('li')
.data('mouse', 'out')
.on('click', function (event) {
var target = (event.target.tagName.toUpperCase() == 'LI' ? event.target : $(event.target).parents('LI'));
var item = selected[$(target).attr('index')];
if ($(target).hasClass('nomouse')) return;
event.stopPropagation();
// trigger event
var edata = obj.trigger({ phase: 'before', type: 'click', target: obj.el, originalEvent: event.originalEvent, item: item });
if (edata.isCancelled === true) return;
// default behavior
if ($(event.target).hasClass('w2ui-list-remove')) {
if ($(obj.el).attr('readonly') || $(obj.el).attr('disabled')) return;
// trigger event
var edata = obj.trigger({ phase: 'before', type: 'remove', target: obj.el, originalEvent: event.originalEvent, item: item });
if (edata.isCancelled === true) return;
// default behavior
$().w2overlay();
selected.splice($(event.target).attr('index'), 1);
$(obj.el).trigger('change');
$(event.target).parent().fadeOut('fast');
setTimeout(function () {
obj.refresh();
// event after
obj.trigger($.extend(edata, { phase: 'after' }));
}, 300);
}
if (obj.type == 'file' && !$(event.target).hasClass('w2ui-list-remove')) {
var preview = '';
if ((/image/i).test(item.type)) { // image
preview = '<div style="padding: 3px;">'+
' <img src="'+ (item.content ? 'data:'+ item.type +';base64,'+ item.content : '') +'" style="max-width: 300px;" '+
' onload="var w = $(this).width(); var h = $(this).height(); '+
' if (w < 300 & h < 300) return; '+
' if (w >= h && w > 300) $(this).width(300);'+
' if (w < h && h > 300) $(this).height(300);"'+
' onerror="this.style.display = \'none\'"'+
' >'+
'</div>';
}
var td1 = 'style="padding: 3px; text-align: right; color: #777;"';
var td2 = 'style="padding: 3px"';
preview += '<div style="padding: 8px;">'+
' <table cellpadding="2"><tbody>'+
' <tr><td '+ td1 +'>'+ w2utils.lang('Name') +':</td><td '+ td2 +'>'+ item.name +'</td></tr>'+
' <tr><td '+ td1 +'>'+ w2utils.lang('Size') +':</td><td '+ td2 +'>'+ w2utils.formatSize(item.size) +'</td></tr>'+
' <tr><td '+ td1 +'>'+ w2utils.lang('Type') +':</td><td '+ td2 +'>' +
' <span style="width: 200px; display: block-inline; overflow: hidden; text-overflow: ellipsis; white-space: nowrap="nowrap";">'+ item.type +'</span>'+
' </td></tr>'+
' <tr><td '+ td1 +'>'+ w2utils.lang('Modified') +':</td><td '+ td2 +'>'+ w2utils.date(item.modified) +'</td></tr>'+
' </tbody></table>'+
'</div>';
$('#w2ui-overlay').remove();
$(target).w2overlay(preview);
}
// event after
obj.trigger($.extend(edata, { phase: 'after' }));
})
.on('mouseover', function (event) {
var target = (event.target.tagName.toUpperCase() == 'LI' ? event.target : $(event.target).parents('LI'));
if ($(target).hasClass('nomouse')) return;
if ($(target).data('mouse') == 'out') {
var item = selected[$(event.target).attr('index')];
// trigger event
var edata = obj.trigger({ phase: 'before', type: 'mouseOver', target: obj.el, originalEvent: event.originalEvent, item: item });
if (edata.isCancelled === true) return;
// event after
obj.trigger($.extend(edata, { phase: 'after' }));
}
$(target).data('mouse', 'over');
})
.on('mouseout', function (event) {
var target = (event.target.tagName.toUpperCase() == 'LI' ? event.target : $(event.target).parents('LI'));
if ($(target).hasClass('nomouse')) return;
$(target).data('mouse', 'leaving');
setTimeout(function () {
if ($(target).data('mouse') == 'leaving') {
$(target).data('mouse', 'out');
var item = selected[$(event.target).attr('index')];
// trigger event
var edata = obj.trigger({ phase: 'before', type: 'mouseOut', target: obj.el, originalEvent: event.originalEvent, item: item });
if (edata.isCancelled === true) return;
// event after
obj.trigger($.extend(edata, { phase: 'after' }));
}
}, 0);
});
// adjust height
$(this.el).height('auto');
var cntHeight = $(div).find('> div.w2ui-multi-items').height() + w2utils.getSize(div, '+height') * 2;
if (cntHeight < 26) cntHeight = 26;
if (cntHeight > options.maxHeight) cntHeight = options.maxHeight;
if (div.length > 0) div[0].scrollTop = 1000;
var inpHeight = w2utils.getSize($(this.el), 'height') - 2;
if (inpHeight > cntHeight) cntHeight = inpHeight;
$(div).css({ 'height': cntHeight + 'px', overflow: (cntHeight == options.maxHeight ? 'auto' : 'hidden') });
if (cntHeight < options.maxHeight) $(div).prop('scrollTop', 0);
$(this.el).css({ 'height' : (cntHeight + 2) + 'px' });
// update size
if (obj.type == 'enum') {
var tmp = obj.helpers.multi.find('input');
tmp.width(((tmp.val().length + 2) * 8) + 'px');
}
}
return (new Date()).getTime() - time;
},
reset: function () {
var obj = this;
var type = this.type;
this.clear();
this.type = type;
this.init();
},
// resizing width of list, enum, file controls
resize: function () {
var obj = this;
var new_width = $(obj.el).width();
var new_height = $(obj.el).height();
if (obj.tmp.current_width == new_width && new_height > 0) return;
var focus = this.helpers.focus;
var multi = this.helpers.multi;
var suffix = this.helpers.suffix;
var prefix = this.helpers.prefix;
// resize helpers
if (focus) {
focus.width($(obj.el).width());
}
if (multi) {
var width = (w2utils.getSize(obj.el, 'width')
- parseInt($(obj.el).css('margin-left'), 10)
- parseInt($(obj.el).css('margin-right'), 10));
$(multi).width(width);
}
if (suffix) {
obj.options.suffix = '<div class="arrow-down" style="margin-top: '+ ((parseInt($(obj.el).height()) - 6) / 2) +'px;"></div>';
obj.addSuffix();
}
if (prefix) {
obj.addPrefix();
}
// remember width
obj.tmp.current_width = new_width;
},
clean: function (val) {
//issue #499
if(typeof val == 'number'){
return val;
}
var options = this.options;
val = String(val).trim();
// clean
if (['int', 'float', 'money', 'currency', 'percent'].indexOf(this.type) != -1) {
if (typeof val == 'string') {
if (options.autoFormat && ['money', 'currency'].indexOf(this.type) != -1) val = String(val).replace(options.moneyRE, '');
if (options.autoFormat && this.type == 'percent') val = String(val).replace(options.percentRE, '');
if (options.autoFormat && ['int', 'float'].indexOf(this.type) != -1) val = String(val).replace(options.numberRE, '');
val = val.replace(/\s+/g, '').replace(w2utils.settings.groupSymbol, '').replace(w2utils.settings.decimalSymbol, '.');
}
if (parseFloat(val) == val) {
if (options.min != null && val < options.min) { val = options.min; $(this.el).val(options.min); }
if (options.max != null && val > options.max) { val = options.max; $(this.el).val(options.max); }
}
if (val !== '' && w2utils.isFloat(val)) val = Number(val); else val = '';
}
return val;
},
format: function (val) {
var options = this.options;
// autoformat numbers or money
if (options.autoFormat && val != '') {
switch (this.type) {
case 'money':
case 'currency':
val = w2utils.formatNumber(val, options.currencyPrecision, options.groupSymbol);
if (val != '') val = options.currencyPrefix + val + options.currencySuffix;
break;
case 'percent':
val = w2utils.formatNumber(val, options.precision, options.groupSymbol);
if (val != '') val += '%';
break;
case 'float':
val = w2utils.formatNumber(val, options.precision, options.groupSymbol);
break;
case 'int':
val = w2utils.formatNumber(val, 0, options.groupSymbol);
break;
}
}
return val;
},
change: function (event) {
var obj = this;
var options = obj.options;
// numeric
if (['int', 'float', 'money', 'currency', 'percent'].indexOf(this.type) != -1) {
// check max/min
var val = $(this.el).val();
var new_val = this.format(this.clean($(this.el).val()));
// if was modified
if (val != '' && val != new_val) {
$(this.el).val(new_val).change();
// cancel event
event.stopPropagation();
event.preventDefault();
return false;
}
}
// color
if (this.type == 'color') {
var color = '#' + $(this.el).val();
if ($(this.el).val().length != 6 && $(this.el).val().length != 3) color = '';
$(this.el).next().find('div').css('background-color', color);
if ($(obj.el).is(':focus')) this.updateOverlay();
}
// list, enum
if (['list', 'enum', 'file'].indexOf(this.type) != -1) {
obj.refresh();
// need time out to show icon indent properly
setTimeout(function () { obj.refresh(); }, 5);
}
// date, time
if (['date', 'time', 'datetime'].indexOf(this.type) != -1) {
// convert linux timestamps
var tmp = parseInt(obj.el.value);
if (w2utils.isInt(obj.el.value) && tmp > 3000) {
if (this.type == 'time') $(obj.el).val(w2utils.formatTime(new Date(tmp), options.format)).change();
if (this.type == 'date') $(obj.el).val(w2utils.formatDate(new Date(tmp), options.format)).change();
if (this.type == 'datetime') $(obj.el).val(w2utils.formatDateTime(new Date(tmp), options.format)).change();
}
}
},
click: function (event) {
event.stopPropagation();
// lists
if (['list', 'combo', 'enum'].indexOf(this.type) != -1) {
if (!$(this.el).is(':focus')) this.focus(event);
}
// other fields with drops
if (['date', 'time', 'color', 'datetime'].indexOf(this.type) != -1) {
this.updateOverlay();
}
},
focus: function (event) {
var obj = this;
var options = this.options;
// color, date, time
if (['color', 'date', 'time', 'datetime'].indexOf(obj.type) !== -1) {
if ($(obj.el).attr('readonly') || $(obj.el).attr('disabled')) return;
if ($("#w2ui-overlay").length > 0) $('#w2ui-overlay')[0].hide();
setTimeout(function () { obj.updateOverlay(); }, 150);
}
// menu
if (['list', 'combo', 'enum'].indexOf(obj.type) != -1) {
if ($(obj.el).attr('readonly') || $(obj.el).attr('disabled')) return;
if ($("#w2ui-overlay").length > 0) $('#w2ui-overlay')[0].hide();
obj.resize();
setTimeout(function () {
if (obj.type == 'list' && $(obj.el).is(':focus')) {
$(obj.helpers.focus).find('input').focus();
return;
}
obj.search();
setTimeout(function () { obj.updateOverlay(); }, 1);
}, 1);
}
// file
if (obj.type == 'file') {
$(obj.helpers.multi).css({ 'outline': 'auto 5px #7DB4F3', 'outline-offset': '-2px' });
}
},
blur: function (event) {
var obj = this;
var options = obj.options;
var val = $(obj.el).val().trim();
// hide overlay
if (['color', 'date', 'time', 'list', 'combo', 'enum', 'datetime'].indexOf(obj.type) != -1) {
if ($("#w2ui-overlay").length > 0) $('#w2ui-overlay')[0].hide();
}
if (['int', 'float', 'money', 'currency', 'percent'].indexOf(obj.type) != -1) {
if (val !== '' && !obj.checkType(val)) {
$(obj.el).val('').change();
if (options.silent === false) {
$(obj.el).w2tag('Not a valid number');
setTimeout(function () { $(obj.el).w2tag(''); }, 3000);
}
}
}
// date or time
if (['date', 'time', 'datetime'].indexOf(obj.type) != -1) {
// check if in range
if (val !== '' && !obj.inRange(obj.el.value)) {
$(obj.el).val('').removeData('selected').change();
if (options.silent === false) {
$(obj.el).w2tag('Not in range');
setTimeout(function () { $(obj.el).w2tag(''); }, 3000);
}
} else {
if (obj.type == 'date' && val !== '' && !w2utils.isDate(obj.el.value, options.format)) {
$(obj.el).val('').removeData('selected').change();
if (options.silent === false) {
$(obj.el).w2tag('Not a valid date');
setTimeout(function () { $(obj.el).w2tag(''); }, 3000);
}
}
else if (obj.type == 'time' && val !== '' && !w2utils.isTime(obj.el.value)) {
$(obj.el).val('').removeData('selected').change();
if (options.silent === false) {
$(obj.el).w2tag('Not a valid time');