-
Notifications
You must be signed in to change notification settings - Fork 0
/
ui-utils.js
2352 lines (2155 loc) · 82.3 KB
/
ui-utils.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
/**
* angular-ui-utils - Swiss-Army-Knife of AngularJS tools (with no external dependencies!)
* @version v0.2.2 - 2015-02-18
* @link http://angular-ui.github.com
* @license MIT License, http://www.opensource.org/licenses/MIT
*/
angular.module('ui.alias', []).config(['$compileProvider', 'uiAliasConfig', function($compileProvider, uiAliasConfig){
'use strict';
uiAliasConfig = uiAliasConfig || {};
angular.forEach(uiAliasConfig, function(config, alias){
if (angular.isString(config)) {
config = {
replace: true,
template: config
};
}
$compileProvider.directive(alias, function(){
return config;
});
});
}]);
/**
* General-purpose Event binding. Bind any event not natively supported by Angular
* Pass an object with keynames for events to ui-event
* Allows $event object and $params object to be passed
*
* @example <input ui-event="{ focus : 'counter++', blur : 'someCallback()' }">
* @example <input ui-event="{ myCustomEvent : 'myEventHandler($event, $params)'}">
*
* @param ui-event {string|object literal} The event to bind to as a string or a hash of events with their callbacks
*/
angular.module('ui.event',[]).directive('uiEvent', ['$parse',
function ($parse) {
'use strict';
return function ($scope, elm, attrs) {
var events = $scope.$eval(attrs.uiEvent);
angular.forEach(events, function (uiEvent, eventName) {
var fn = $parse(uiEvent);
elm.bind(eventName, function (evt) {
var params = Array.prototype.slice.call(arguments);
//Take out first paramater (event object);
params = params.splice(1);
fn($scope, {$event: evt, $params: params});
if (!$scope.$$phase) {
$scope.$apply();
}
});
});
};
}]);
/**
* A replacement utility for internationalization very similar to sprintf.
*
* @param replace {mixed} The tokens to replace depends on type
* string: all instances of $0 will be replaced
* array: each instance of $0, $1, $2 etc. will be placed with each array item in corresponding order
* object: all attributes will be iterated through, with :key being replaced with its corresponding value
* @return string
*
* @example: 'Hello :name, how are you :day'.format({ name:'John', day:'Today' })
* @example: 'Records $0 to $1 out of $2 total'.format(['10', '20', '3000'])
* @example: '$0 agrees to all mentions $0 makes in the event that $0 hits a tree while $0 is driving drunk'.format('Bob')
*/
angular.module('ui.format',[]).filter('format', function(){
'use strict';
return function(value, replace) {
var target = value;
if (angular.isString(target) && replace !== undefined) {
if (!angular.isArray(replace) && !angular.isObject(replace)) {
replace = [replace];
}
if (angular.isArray(replace)) {
var rlen = replace.length;
var rfx = function (str, i) {
i = parseInt(i, 10);
return (i >= 0 && i < rlen) ? replace[i] : str;
};
target = target.replace(/\$([0-9]+)/g, rfx);
}
else {
angular.forEach(replace, function(value, key){
target = target.split(':' + key).join(value);
});
}
}
return target;
};
});
/**
* Wraps the
* @param text {string} haystack to search through
* @param search {string} needle to search for
* @param [caseSensitive] {boolean} optional boolean to use case-sensitive searching
*/
angular.module('ui.highlight',[]).filter('highlight', function () {
'use strict';
return function (text, search, caseSensitive) {
if (text && (search || angular.isNumber(search))) {
text = text.toString();
search = search.toString();
if (caseSensitive) {
return text.split(search).join('<span class="ui-match">' + search + '</span>');
} else {
return text.replace(new RegExp(search, 'gi'), '<span class="ui-match">$&</span>');
}
} else {
return text;
}
};
});
// modeled after: angular-1.0.7/src/ng/directive/ngInclude.js
angular.module('ui.include',[])
.directive('uiInclude', ['$http', '$templateCache', '$anchorScroll', '$compile',
function($http, $templateCache, $anchorScroll, $compile) {
'use strict';
return {
restrict: 'ECA',
terminal: true,
compile: function(element, attr) {
var srcExp = attr.uiInclude || attr.src,
fragExp = attr.fragment || '',
onloadExp = attr.onload || '',
autoScrollExp = attr.autoscroll;
return function(scope, element) {
var changeCounter = 0,
childScope;
var clearContent = function() {
if (childScope) {
childScope.$destroy();
childScope = null;
}
element.html('');
};
function ngIncludeWatchAction() {
var thisChangeId = ++changeCounter;
var src = scope.$eval(srcExp);
var fragment = scope.$eval(fragExp);
if (src) {
$http.get(src, {cache: $templateCache}).success(function(response) {
if (thisChangeId !== changeCounter) { return; }
if (childScope) { childScope.$destroy(); }
childScope = scope.$new();
var contents;
if (fragment) {
contents = angular.element('<div/>').html(response).find(fragment);
}
else {
contents = angular.element('<div/>').html(response).contents();
}
element.html(contents);
$compile(contents)(childScope);
if (angular.isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
$anchorScroll();
}
childScope.$emit('$includeContentLoaded');
scope.$eval(onloadExp);
}).error(function() {
if (thisChangeId === changeCounter) { clearContent(); }
});
} else { clearContent(); }
}
scope.$watch(fragExp, ngIncludeWatchAction);
scope.$watch(srcExp, ngIncludeWatchAction);
};
}
};
}]);
/**
* Provides an easy way to toggle a checkboxes indeterminate property
*
* @example <input type="checkbox" ui-indeterminate="isUnkown">
*/
angular.module('ui.indeterminate',[]).directive('uiIndeterminate', [
function () {
'use strict';
return {
compile: function(tElm, tAttrs) {
if (!tAttrs.type || tAttrs.type.toLowerCase() !== 'checkbox') {
return angular.noop;
}
return function ($scope, elm, attrs) {
$scope.$watch(attrs.uiIndeterminate, function(newVal) {
elm[0].indeterminate = !!newVal;
});
};
}
};
}]);
/**
* Converts variable-esque naming conventions to something presentational, capitalized words separated by space.
* @param {String} value The value to be parsed and prettified.
* @param {String} [inflector] The inflector to use. Default: humanize.
* @return {String}
* @example {{ 'Here Is my_phoneNumber' | inflector:'humanize' }} => Here Is My Phone Number
* {{ 'Here Is my_phoneNumber' | inflector:'underscore' }} => here_is_my_phone_number
* {{ 'Here Is my_phoneNumber' | inflector:'variable' }} => hereIsMyPhoneNumber
*/
angular.module('ui.inflector',[]).filter('inflector', function () {
'use strict';
function tokenize(text) {
text = text.replace(/([A-Z])|([\-|\_])/g, function(_, $1) { return ' ' + ($1 || ''); });
return text.replace(/\s\s+/g, ' ').trim().toLowerCase().split(' ');
}
function capitalizeTokens(tokens) {
var result = [];
angular.forEach(tokens, function(token) {
result.push(token.charAt(0).toUpperCase() + token.substr(1));
});
return result;
}
var inflectors = {
humanize: function (value) {
return capitalizeTokens(tokenize(value)).join(' ');
},
underscore: function (value) {
return tokenize(value).join('_');
},
variable: function (value) {
value = tokenize(value);
value = value[0] + capitalizeTokens(value.slice(1)).join('');
return value;
}
};
return function (text, inflector) {
if (inflector !== false && angular.isString(text)) {
inflector = inflector || 'humanize';
return inflectors[inflector](text);
} else {
return text;
}
};
});
/**
* General-purpose jQuery wrapper. Simply pass the plugin name as the expression.
*
* It is possible to specify a default set of parameters for each jQuery plugin.
* Under the jq key, namespace each plugin by that which will be passed to ui-jq.
* Unfortunately, at this time you can only pre-define the first parameter.
* @example { jq : { datepicker : { showOn:'click' } } }
*
* @param ui-jq {string} The $elm.[pluginName]() to call.
* @param [ui-options] {mixed} Expression to be evaluated and passed as options to the function
* Multiple parameters can be separated by commas
* @param [ui-refresh] {expression} Watch expression and refire plugin on changes
*
* @example <input ui-jq="datepicker" ui-options="{showOn:'click'},secondParameter,thirdParameter" ui-refresh="iChange">
*/
angular.module('ui.jq',[]).
value('uiJqConfig',{}).
directive('uiJq', ['uiJqConfig', '$timeout', function uiJqInjectingFunction(uiJqConfig, $timeout) {
'use strict';
return {
restrict: 'A',
compile: function uiJqCompilingFunction(tElm, tAttrs) {
if (!angular.isFunction(tElm[tAttrs.uiJq])) {
throw new Error('ui-jq: The "' + tAttrs.uiJq + '" function does not exist');
}
var options = uiJqConfig && uiJqConfig[tAttrs.uiJq];
return function uiJqLinkingFunction(scope, elm, attrs) {
// If change compatibility is enabled, the form input's "change" event will trigger an "input" event
if (attrs.ngModel && elm.is('select,input,textarea')) {
elm.bind('change', function() {
elm.trigger('input');
});
}
function createLinkOptions(){
var linkOptions = [];
// If ui-options are passed, merge (or override) them onto global defaults and pass to the jQuery method
if (attrs.uiOptions) {
linkOptions = scope.$eval('[' + attrs.uiOptions + ']');
if (angular.isObject(options) && angular.isObject(linkOptions[0])) {
linkOptions[0] = angular.extend({}, options, linkOptions[0]);
}
} else if (options) {
linkOptions = [options];
}
return linkOptions;
}
// Call jQuery method and pass relevant options
function callPlugin() {
$timeout(function() {
elm[attrs.uiJq].apply(elm, createLinkOptions());
}, 0, false);
}
// If ui-refresh is used, re-fire the the method upon every change
if (attrs.uiRefresh) {
scope.$watch(attrs.uiRefresh, function() {
callPlugin();
});
}
callPlugin();
};
}
};
}]);
angular.module('ui.keypress',[]).
factory('keypressHelper', ['$parse', function keypress($parse){
'use strict';
var keysByCode = {
8: 'backspace',
9: 'tab',
13: 'enter',
27: 'esc',
32: 'space',
33: 'pageup',
34: 'pagedown',
35: 'end',
36: 'home',
37: 'left',
38: 'up',
39: 'right',
40: 'down',
45: 'insert',
46: 'delete'
};
var capitaliseFirstLetter = function (string) {
return string.charAt(0).toUpperCase() + string.slice(1);
};
return function(mode, scope, elm, attrs) {
var params, combinations = [];
params = scope.$eval(attrs['ui'+capitaliseFirstLetter(mode)]);
// Prepare combinations for simple checking
angular.forEach(params, function (v, k) {
var combination, expression;
expression = $parse(v);
angular.forEach(k.split(' '), function(variation) {
combination = {
expression: expression,
keys: {}
};
angular.forEach(variation.split('-'), function (value) {
combination.keys[value] = true;
});
combinations.push(combination);
});
});
// Check only matching of pressed keys one of the conditions
elm.bind(mode, function (event) {
// No need to do that inside the cycle
var metaPressed = !!(event.metaKey && !event.ctrlKey);
var altPressed = !!event.altKey;
var ctrlPressed = !!event.ctrlKey;
var shiftPressed = !!event.shiftKey;
var keyCode = event.keyCode;
// normalize keycodes
if (mode === 'keypress' && !shiftPressed && keyCode >= 97 && keyCode <= 122) {
keyCode = keyCode - 32;
}
// Iterate over prepared combinations
angular.forEach(combinations, function (combination) {
var mainKeyPressed = combination.keys[keysByCode[keyCode]] || combination.keys[keyCode.toString()];
var metaRequired = !!combination.keys.meta;
var altRequired = !!combination.keys.alt;
var ctrlRequired = !!combination.keys.ctrl;
var shiftRequired = !!combination.keys.shift;
if (
mainKeyPressed &&
( metaRequired === metaPressed ) &&
( altRequired === altPressed ) &&
( ctrlRequired === ctrlPressed ) &&
( shiftRequired === shiftPressed )
) {
// Run the function
scope.$apply(function () {
combination.expression(scope, { '$event': event });
});
}
});
});
};
}]);
/**
* Bind one or more handlers to particular keys or their combination
* @param hash {mixed} keyBindings Can be an object or string where keybinding expression of keys or keys combinations and AngularJS Exspressions are set. Object syntax: "{ keys1: expression1 [, keys2: expression2 [ , ... ]]}". String syntax: ""expression1 on keys1 [ and expression2 on keys2 [ and ... ]]"". Expression is an AngularJS Expression, and key(s) are dash-separated combinations of keys and modifiers (one or many, if any. Order does not matter). Supported modifiers are 'ctrl', 'shift', 'alt' and key can be used either via its keyCode (13 for Return) or name. Named keys are 'backspace', 'tab', 'enter', 'esc', 'space', 'pageup', 'pagedown', 'end', 'home', 'left', 'up', 'right', 'down', 'insert', 'delete'.
* @example <input ui-keypress="{enter:'x = 1', 'ctrl-shift-space':'foo()', 'shift-13':'bar()'}" /> <input ui-keypress="foo = 2 on ctrl-13 and bar('hello') on shift-esc" />
**/
angular.module('ui.keypress').directive('uiKeydown', ['keypressHelper', function(keypressHelper){
'use strict';
return {
link: function (scope, elm, attrs) {
keypressHelper('keydown', scope, elm, attrs);
}
};
}]);
angular.module('ui.keypress').directive('uiKeypress', ['keypressHelper', function(keypressHelper){
'use strict';
return {
link: function (scope, elm, attrs) {
keypressHelper('keypress', scope, elm, attrs);
}
};
}]);
angular.module('ui.keypress').directive('uiKeyup', ['keypressHelper', function(keypressHelper){
'use strict';
return {
link: function (scope, elm, attrs) {
keypressHelper('keyup', scope, elm, attrs);
}
};
}]);
/*
Attaches input mask onto input element
*/
angular.module('ui.mask', [])
.value('uiMaskConfig', {
'maskDefinitions': {
'9': /\d/,
'A': /[a-zA-Z]/,
'*': /[a-zA-Z0-9]/
},
'clearOnBlur': true
})
.directive('uiMask', ['uiMaskConfig', '$parse', function (maskConfig, $parse) {
'use strict';
return {
priority: 100,
require: 'ngModel',
restrict: 'A',
compile: function uiMaskCompilingFunction(){
var options = maskConfig;
return function uiMaskLinkingFunction(scope, iElement, iAttrs, controller){
var maskProcessed = false, eventsBound = false,
maskCaretMap, maskPatterns, maskPlaceholder, maskComponents,
// Minimum required length of the value to be considered valid
minRequiredLength,
value, valueMasked, isValid,
// Vars for initializing/uninitializing
originalPlaceholder = iAttrs.placeholder,
originalMaxlength = iAttrs.maxlength,
// Vars used exclusively in eventHandler()
oldValue, oldValueUnmasked, oldCaretPosition, oldSelectionLength;
function initialize(maskAttr){
if (!angular.isDefined(maskAttr)) {
return uninitialize();
}
processRawMask(maskAttr);
if (!maskProcessed) {
return uninitialize();
}
initializeElement();
bindEventListeners();
return true;
}
function initPlaceholder(placeholderAttr) {
if(! angular.isDefined(placeholderAttr)) {
return;
}
maskPlaceholder = placeholderAttr;
// If the mask is processed, then we need to update the value
if (maskProcessed) {
eventHandler();
}
}
function formatter(fromModelValue){
if (!maskProcessed) {
return fromModelValue;
}
value = unmaskValue(fromModelValue || '');
isValid = validateValue(value);
controller.$setValidity('mask', isValid);
return isValid && value.length ? maskValue(value) : undefined;
}
function parser(fromViewValue){
if (!maskProcessed) {
return fromViewValue;
}
value = unmaskValue(fromViewValue || '');
isValid = validateValue(value);
// We have to set viewValue manually as the reformatting of the input
// value performed by eventHandler() doesn't happen until after
// this parser is called, which causes what the user sees in the input
// to be out-of-sync with what the controller's $viewValue is set to.
controller.$viewValue = value.length ? maskValue(value) : '';
controller.$setValidity('mask', isValid);
if (value === '' && iAttrs.required) {
controller.$setValidity('required', !controller.$error.required);
}
return isValid ? value : undefined;
}
var linkOptions = {};
if (iAttrs.uiOptions) {
linkOptions = scope.$eval('[' + iAttrs.uiOptions + ']');
if (angular.isObject(linkOptions[0])) {
// we can't use angular.copy nor angular.extend, they lack the power to do a deep merge
linkOptions = (function(original, current){
for(var i in original) {
if (Object.prototype.hasOwnProperty.call(original, i)) {
if (current[i] === undefined) {
current[i] = angular.copy(original[i]);
} else {
angular.extend(current[i], original[i]);
}
}
}
return current;
})(options, linkOptions[0]);
}
} else {
linkOptions = options;
}
iAttrs.$observe('uiMask', initialize);
iAttrs.$observe('placeholder', initPlaceholder);
var modelViewValue = false;
iAttrs.$observe('modelViewValue', function(val) {
if(val === 'true') {
modelViewValue = true;
}
});
scope.$watch(iAttrs.ngModel, function(val) {
if(modelViewValue && val) {
var model = $parse(iAttrs.ngModel);
model.assign(scope, controller.$viewValue);
}
});
controller.$formatters.push(formatter);
controller.$parsers.push(parser);
function uninitialize(){
maskProcessed = false;
unbindEventListeners();
if (angular.isDefined(originalPlaceholder)) {
iElement.attr('placeholder', originalPlaceholder);
} else {
iElement.removeAttr('placeholder');
}
if (angular.isDefined(originalMaxlength)) {
iElement.attr('maxlength', originalMaxlength);
} else {
iElement.removeAttr('maxlength');
}
iElement.val(controller.$modelValue);
controller.$viewValue = controller.$modelValue;
return false;
}
function initializeElement(){
value = oldValueUnmasked = unmaskValue(controller.$viewValue || '');
valueMasked = oldValue = maskValue(value);
isValid = validateValue(value);
var viewValue = isValid && value.length ? valueMasked : '';
if (iAttrs.maxlength) { // Double maxlength to allow pasting new val at end of mask
iElement.attr('maxlength', maskCaretMap[maskCaretMap.length - 1] * 2);
}
iElement.attr('placeholder', maskPlaceholder);
iElement.val(viewValue);
controller.$viewValue = viewValue;
// Not using $setViewValue so we don't clobber the model value and dirty the form
// without any kind of user interaction.
}
function bindEventListeners(){
if (eventsBound) {
return;
}
iElement.bind('blur', blurHandler);
iElement.bind('mousedown mouseup', mouseDownUpHandler);
iElement.bind('input keyup click focus', eventHandler);
eventsBound = true;
}
function unbindEventListeners(){
if (!eventsBound) {
return;
}
iElement.unbind('blur', blurHandler);
iElement.unbind('mousedown', mouseDownUpHandler);
iElement.unbind('mouseup', mouseDownUpHandler);
iElement.unbind('input', eventHandler);
iElement.unbind('keyup', eventHandler);
iElement.unbind('click', eventHandler);
iElement.unbind('focus', eventHandler);
eventsBound = false;
}
function validateValue(value){
// Zero-length value validity is ngRequired's determination
return value.length ? value.length >= minRequiredLength : true;
}
function unmaskValue(value){
var valueUnmasked = '',
maskPatternsCopy = maskPatterns.slice();
// Preprocess by stripping mask components from value
value = value.toString();
angular.forEach(maskComponents, function (component){
value = value.replace(component, '');
});
angular.forEach(value.split(''), function (chr){
if (maskPatternsCopy.length && maskPatternsCopy[0].test(chr)) {
valueUnmasked += chr;
maskPatternsCopy.shift();
}
});
return valueUnmasked;
}
function maskValue(unmaskedValue){
var valueMasked = '',
maskCaretMapCopy = maskCaretMap.slice();
angular.forEach(maskPlaceholder.split(''), function (chr, i){
if (unmaskedValue.length && i === maskCaretMapCopy[0]) {
valueMasked += unmaskedValue.charAt(0) || '_';
unmaskedValue = unmaskedValue.substr(1);
maskCaretMapCopy.shift();
}
else {
valueMasked += chr;
}
});
return valueMasked;
}
function getPlaceholderChar(i) {
var placeholder = iAttrs.placeholder;
if (typeof placeholder !== 'undefined' && placeholder[i]) {
return placeholder[i];
} else {
return '_';
}
}
// Generate array of mask components that will be stripped from a masked value
// before processing to prevent mask components from being added to the unmasked value.
// E.g., a mask pattern of '+7 9999' won't have the 7 bleed into the unmasked value.
// If a maskable char is followed by a mask char and has a mask
// char behind it, we'll split it into it's own component so if
// a user is aggressively deleting in the input and a char ahead
// of the maskable char gets deleted, we'll still be able to strip
// it in the unmaskValue() preprocessing.
function getMaskComponents() {
return maskPlaceholder.replace(/[_]+/g, '_').replace(/([^_]+)([a-zA-Z0-9])([^_])/g, '$1$2_$3').split('_');
}
function processRawMask(mask){
var characterCount = 0;
maskCaretMap = [];
maskPatterns = [];
maskPlaceholder = '';
if (typeof mask === 'string') {
minRequiredLength = 0;
var isOptional = false,
splitMask = mask.split('');
angular.forEach(splitMask, function (chr, i){
if (linkOptions.maskDefinitions[chr]) {
maskCaretMap.push(characterCount);
maskPlaceholder += getPlaceholderChar(i);
maskPatterns.push(linkOptions.maskDefinitions[chr]);
characterCount++;
if (!isOptional) {
minRequiredLength++;
}
}
else if (chr === '?') {
isOptional = true;
}
else {
maskPlaceholder += chr;
characterCount++;
}
});
}
// Caret position immediately following last position is valid.
maskCaretMap.push(maskCaretMap.slice().pop() + 1);
maskComponents = getMaskComponents();
maskProcessed = maskCaretMap.length > 1 ? true : false;
}
function blurHandler(){
if (linkOptions.clearOnBlur) {
oldCaretPosition = 0;
oldSelectionLength = 0;
if (!isValid || value.length === 0) {
valueMasked = '';
iElement.val('');
scope.$apply(function () {
controller.$setViewValue('');
});
}
}
}
function mouseDownUpHandler(e){
if (e.type === 'mousedown') {
iElement.bind('mouseout', mouseoutHandler);
} else {
iElement.unbind('mouseout', mouseoutHandler);
}
}
iElement.bind('mousedown mouseup', mouseDownUpHandler);
function mouseoutHandler(){
/*jshint validthis: true */
oldSelectionLength = getSelectionLength(this);
iElement.unbind('mouseout', mouseoutHandler);
}
function eventHandler(e){
/*jshint validthis: true */
e = e || {};
// Allows more efficient minification
var eventWhich = e.which,
eventType = e.type;
// Prevent shift and ctrl from mucking with old values
if (eventWhich === 16 || eventWhich === 91) { return;}
var val = iElement.val(),
valOld = oldValue,
valMasked,
valUnmasked = unmaskValue(val),
valUnmaskedOld = oldValueUnmasked,
valAltered = false,
caretPos = getCaretPosition(this) || 0,
caretPosOld = oldCaretPosition || 0,
caretPosDelta = caretPos - caretPosOld,
caretPosMin = maskCaretMap[0],
caretPosMax = maskCaretMap[valUnmasked.length] || maskCaretMap.slice().shift(),
selectionLenOld = oldSelectionLength || 0,
isSelected = getSelectionLength(this) > 0,
wasSelected = selectionLenOld > 0,
// Case: Typing a character to overwrite a selection
isAddition = (val.length > valOld.length) || (selectionLenOld && val.length > valOld.length - selectionLenOld),
// Case: Delete and backspace behave identically on a selection
isDeletion = (val.length < valOld.length) || (selectionLenOld && val.length === valOld.length - selectionLenOld),
isSelection = (eventWhich >= 37 && eventWhich <= 40) && e.shiftKey, // Arrow key codes
isKeyLeftArrow = eventWhich === 37,
// Necessary due to "input" event not providing a key code
isKeyBackspace = eventWhich === 8 || (eventType !== 'keyup' && isDeletion && (caretPosDelta === -1)),
isKeyDelete = eventWhich === 46 || (eventType !== 'keyup' && isDeletion && (caretPosDelta === 0 ) && !wasSelected),
// Handles cases where caret is moved and placed in front of invalid maskCaretMap position. Logic below
// ensures that, on click or leftward caret placement, caret is moved leftward until directly right of
// non-mask character. Also applied to click since users are (arguably) more likely to backspace
// a character when clicking within a filled input.
caretBumpBack = (isKeyLeftArrow || isKeyBackspace || eventType === 'click') && caretPos > caretPosMin;
oldSelectionLength = getSelectionLength(this);
// These events don't require any action
if (isSelection || (isSelected && (eventType === 'click' || eventType === 'keyup'))) {
return;
}
// Value Handling
// ==============
// User attempted to delete but raw value was unaffected--correct this grievous offense
if ((eventType === 'input') && isDeletion && !wasSelected && valUnmasked === valUnmaskedOld) {
while (isKeyBackspace && caretPos > caretPosMin && !isValidCaretPosition(caretPos)) {
caretPos--;
}
while (isKeyDelete && caretPos < caretPosMax && maskCaretMap.indexOf(caretPos) === -1) {
caretPos++;
}
var charIndex = maskCaretMap.indexOf(caretPos);
// Strip out non-mask character that user would have deleted if mask hadn't been in the way.
valUnmasked = valUnmasked.substring(0, charIndex) + valUnmasked.substring(charIndex + 1);
valAltered = true;
}
// Update values
valMasked = maskValue(valUnmasked);
oldValue = valMasked;
oldValueUnmasked = valUnmasked;
iElement.val(valMasked);
if (valAltered) {
// We've altered the raw value after it's been $digest'ed, we need to $apply the new value.
scope.$apply(function (){
controller.$setViewValue(valUnmasked);
});
}
// Caret Repositioning
// ===================
// Ensure that typing always places caret ahead of typed character in cases where the first char of
// the input is a mask char and the caret is placed at the 0 position.
if (isAddition && (caretPos <= caretPosMin)) {
caretPos = caretPosMin + 1;
}
if (caretBumpBack) {
caretPos--;
}
// Make sure caret is within min and max position limits
caretPos = caretPos > caretPosMax ? caretPosMax : caretPos < caretPosMin ? caretPosMin : caretPos;
// Scoot the caret back or forth until it's in a non-mask position and within min/max position limits
while (!isValidCaretPosition(caretPos) && caretPos > caretPosMin && caretPos < caretPosMax) {
caretPos += caretBumpBack ? -1 : 1;
}
if ((caretBumpBack && caretPos < caretPosMax) || (isAddition && !isValidCaretPosition(caretPosOld))) {
caretPos++;
}
oldCaretPosition = caretPos;
setCaretPosition(this, caretPos);
}
function isValidCaretPosition(pos){ return maskCaretMap.indexOf(pos) > -1; }
function getCaretPosition(input){
if (!input) return 0;
if (input.selectionStart !== undefined) {
return input.selectionStart;
} else if (document.selection) {
// Curse you IE
input.focus();
var selection = document.selection.createRange();
selection.moveStart('character', input.value ? -input.value.length : 0);
return selection.text.length;
}
return 0;
}
function setCaretPosition(input, pos){
if (!input) return 0;
if (input.offsetWidth === 0 || input.offsetHeight === 0) {
return; // Input's hidden
}
if (input.setSelectionRange) {
input.focus();
input.setSelectionRange(pos, pos);
}
else if (input.createTextRange) {
// Curse you IE
var range = input.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}
function getSelectionLength(input){
if (!input) return 0;
if (input.selectionStart !== undefined) {
return (input.selectionEnd - input.selectionStart);
}
if (document.selection) {
return (document.selection.createRange().text.length);
}
return 0;
}
// https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (searchElement /*, fromIndex */){
if (this === null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
if (len === 0) {
return -1;
}
var n = 0;
if (arguments.length > 1) {
n = Number(arguments[1]);
if (n !== n) { // shortcut for verifying if it's NaN
n = 0;
} else if (n !== 0 && n !== Infinity && n !== -Infinity) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
};
}
};
}
};
}
]);
/**
* Add a clear button to form inputs to reset their value
*/
angular.module('ui.reset',[]).value('uiResetConfig',null).directive('uiReset', ['uiResetConfig', function (uiResetConfig) {
'use strict';
var resetValue = null;
if (uiResetConfig !== undefined){
resetValue = uiResetConfig;
}
return {
require: 'ngModel',
link: function (scope, elm, attrs, ctrl) {
var aElement;
aElement = angular.element('<a class="ui-reset" />');
elm.wrap('<span class="ui-resetwrap" />').after(aElement);
aElement.bind('click', function (e) {
e.preventDefault();
scope.$apply(function () {
if (attrs.uiReset){
ctrl.$setViewValue(scope.$eval(attrs.uiReset));
}else{
ctrl.$setViewValue(resetValue);
}
ctrl.$render();
});
});
}
};