This repository was archived by the owner on Oct 2, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathuiSelectMultipleDirective.js
458 lines (410 loc) · 16.4 KB
/
uiSelectMultipleDirective.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
uis.directive('uiSelectMultiple', ['uiSelectMinErr','$timeout', function(uiSelectMinErr, $timeout) {
return {
restrict: 'EA',
require: ['^uiSelect', '^ngModel'],
controller: ['$scope','$timeout', function($scope, $timeout){
var ctrl = this,
$select = $scope.$select,
ngModel;
if (angular.isUndefined($select.selected))
$select.selected = [];
//Wait for link fn to inject it
$scope.$evalAsync(function(){ ngModel = $scope.ngModel; });
ctrl.activeMatchIndex = -1;
ctrl.updateModel = function(){
ngModel.$setViewValue(Date.now()); //Set timestamp as a unique string to force changes
ctrl.refreshComponent();
};
ctrl.refreshComponent = function(){
//Remove already selected items
//e.g. When user clicks on a selection, the selected array changes and
//the dropdown should remove that item
if($select.refreshItems){
$select.refreshItems();
}
if($select.sizeSearchInput){
$select.sizeSearchInput();
}
};
// Remove item from multiple select
ctrl.removeChoice = function(index, event){
// do not open the results dropdown
if(event) {
event.stopPropagation();
}
// if the choice is locked, don't remove it
if($select.isLocked(null, index)) return false;
var removedChoice = $select.selected[index];
var locals = {};
locals[$select.parserResult.itemName] = removedChoice;
$select.selected.splice(index, 1);
ctrl.activeMatchIndex = -1;
$select.sizeSearchInput();
// Give some time for scope propagation.
$timeout(function(){
$select.onRemoveCallback($scope, {
$item: removedChoice,
$model: $select.parserResult.modelMapper($scope, locals)
});
});
ctrl.updateModel();
return true;
};
}],
controllerAs: '$selectMultiple',
link: function(scope, element, attrs, ctrls) {
var $select = ctrls[0];
var ngModel = scope.ngModel = ctrls[1];
var $selectMultiple = scope.$selectMultiple;
//$select.selected = raw selected objects (ignoring any property binding)
$select.multiple = true;
//Input that will handle focus
$select.focusInput = $select.searchInput;
//Properly check for empty if set to multiple
ngModel.$isEmpty = function(value) {
return !value || value.length === 0;
};
//From view --> model
ngModel.$parsers.unshift(function () {
var locals = {},
result,
resultMultiple = [];
for (var j = $select.selected.length - 1; j >= 0; j--) {
locals = {};
locals[$select.parserResult.itemName] = $select.selected[j];
result = $select.parserResult.modelMapper(scope, locals);
resultMultiple.unshift(result);
}
return resultMultiple;
});
// From model --> view
ngModel.$formatters.unshift(function (inputValue) {
var data = $select.parserResult && $select.parserResult.source (scope, { $select : {search:''}}), //Overwrite $search
locals = {},
result;
if (!data) return inputValue;
var resultMultiple = [];
var checkFnMultiple = function(list, value){
if (!list || !list.length) return;
for (var p = list.length - 1; p >= 0; p--) {
locals[$select.parserResult.itemName] = list[p];
result = $select.parserResult.modelMapper(scope, locals);
if($select.parserResult.trackByExp){
var propsItemNameMatches = /(\w*)\./.exec($select.parserResult.trackByExp);
var matches = /\.([^\s]+)/.exec($select.parserResult.trackByExp);
if(propsItemNameMatches && propsItemNameMatches.length > 0 && propsItemNameMatches[1] == $select.parserResult.itemName){
if(matches && matches.length>0 && result[matches[1]] == value[matches[1]]){
resultMultiple.unshift(list[p]);
return true;
}
}
}
if (angular.equals(result,value)){
resultMultiple.unshift(list[p]);
return true;
}
}
return false;
};
if (!inputValue) return resultMultiple; //If ngModel was undefined
for (var k = inputValue.length - 1; k >= 0; k--) {
//Check model array of currently selected items
if (!checkFnMultiple($select.selected, inputValue[k])){
//Check model array of all items available
if (!checkFnMultiple(data, inputValue[k])){
//If not found on previous lists, just add it directly to resultMultiple
resultMultiple.unshift(inputValue[k]);
}
}
}
return resultMultiple;
});
//Watch for external model changes
scope.$watchCollection(function(){ return ngModel.$modelValue; }, function(newValue, oldValue) {
if (oldValue != newValue){
//update the view value with fresh data from items, if there is a valid model value
if(angular.isDefined(ngModel.$modelValue)) {
ngModel.$modelValue = null; //Force scope model value and ngModel value to be out of sync to re-run formatters
}
$selectMultiple.refreshComponent();
}
});
ngModel.$render = function() {
// Make sure that model value is array
if(!angular.isArray(ngModel.$viewValue)){
// Have tolerance for null or undefined values
if (isNil(ngModel.$viewValue)){
ngModel.$viewValue = [];
} else {
throw uiSelectMinErr('multiarr', "Expected model value to be array but got '{0}'", ngModel.$viewValue);
}
}
$select.selected = ngModel.$viewValue;
$selectMultiple.refreshComponent();
scope.$evalAsync(); //To force $digest
};
scope.$on('uis:select', function (event, item) {
if($select.selected.length >= $select.limit) {
return;
}
$select.selected.push(item);
var locals = {};
locals[$select.parserResult.itemName] = item;
$timeout(function(){
$select.onSelectCallback(scope, {
$item: item,
$model: $select.parserResult.modelMapper(scope, locals)
});
});
$selectMultiple.updateModel();
});
scope.$on('uis:activate', function () {
$selectMultiple.activeMatchIndex = -1;
});
scope.$watch('$select.disabled', function(newValue, oldValue) {
// As the search input field may now become visible, it may be necessary to recompute its size
if (oldValue && !newValue) $select.sizeSearchInput();
});
$select.searchInput.on('keydown', function(e) {
var key = e.which;
scope.$apply(function() {
var processed = false;
// var tagged = false; //Checkme
if(KEY.isHorizontalMovement(key)){
processed = _handleMatchSelection(key);
}
if (processed && key != KEY.TAB) {
//TODO Check si el tab selecciona aun correctamente
//Crear test
e.preventDefault();
e.stopPropagation();
}
});
});
function _getCaretPosition(el) {
if(angular.isNumber(el.selectionStart)) return el.selectionStart;
// selectionStart is not supported in IE8 and we don't want hacky workarounds so we compromise
else return el.value.length;
}
// Handles selected options in "multiple" mode
function _handleMatchSelection(key){
var caretPosition = _getCaretPosition($select.searchInput[0]),
length = $select.selected.length,
// none = -1,
first = 0,
last = length-1,
curr = $selectMultiple.activeMatchIndex,
next = $selectMultiple.activeMatchIndex+1,
prev = $selectMultiple.activeMatchIndex-1,
newIndex = curr;
if(caretPosition > 0 || ($select.search.length && key == KEY.RIGHT)) return false;
$select.close();
function getNewActiveMatchIndex(){
switch(key){
case KEY.LEFT:
// Select previous/first item
if(~$selectMultiple.activeMatchIndex) return prev;
// Select last item
else return last;
break;
case KEY.RIGHT:
// Open drop-down
if(!~$selectMultiple.activeMatchIndex || curr === last){
$select.activate();
return false;
}
// Select next/last item
else return next;
break;
case KEY.BACKSPACE:
// Remove selected item and select previous/first
if(~$selectMultiple.activeMatchIndex){
if($selectMultiple.removeChoice(curr)) {
return prev;
} else {
return curr;
}
} else {
// If nothing yet selected, select last item
return last;
}
break;
case KEY.DELETE:
// Remove selected item and select next item
if(~$selectMultiple.activeMatchIndex){
$selectMultiple.removeChoice($selectMultiple.activeMatchIndex);
return curr;
}
else return false;
}
}
newIndex = getNewActiveMatchIndex();
if(!$select.selected.length || newIndex === false) $selectMultiple.activeMatchIndex = -1;
else $selectMultiple.activeMatchIndex = Math.min(last,Math.max(first,newIndex));
return true;
}
$select.searchInput.on('keyup', function(e) {
if ( ! KEY.isVerticalMovement(e.which) ) {
scope.$evalAsync( function () {
$select.activeIndex = $select.taggingLabel === false ? -1 : 0;
});
}
// Push a "create new" item into array if there is a search string
if ( $select.tagging.isActivated && $select.search.length > 0 ) {
// return early with these keys
if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC || KEY.isVerticalMovement(e.which) ) {
return;
}
// always reset the activeIndex to the first item when tagging
$select.activeIndex = $select.taggingLabel === false ? -1 : 0;
// taggingLabel === false bypasses all of this
if ($select.taggingLabel === false) return;
var items = angular.copy( $select.items );
var stashArr = angular.copy( $select.items );
var newItem;
var item;
var hasTag = false;
var dupeIndex = -1;
var tagItems;
var tagItem;
// case for object tagging via transform `$select.tagging.fct` function
if ( $select.tagging.fct !== undefined) {
tagItems = $select.$filter('filter')(items,{'isTag': true});
if ( tagItems.length > 0 ) {
tagItem = tagItems[0];
}
// remove the first element, if it has the `isTag` prop we generate a new one with each keyup, shaving the previous
if ( items.length > 0 && tagItem ) {
hasTag = true;
items = items.slice(1,items.length);
stashArr = stashArr.slice(1,stashArr.length);
}
newItem = $select.tagging.fct($select.search);
// verify the new tag doesn't match the value of a possible selection choice or an already selected item.
if (
stashArr.some(function (origItem) {
return angular.equals(origItem, newItem);
}) ||
$select.selected.some(function (origItem) {
return angular.equals(origItem, newItem);
})
) {
scope.$evalAsync(function () {
$select.activeIndex = 0;
$select.items = items;
});
return;
}
if (newItem) newItem.isTag = true;
// handle newItem string and stripping dupes in tagging string context
} else {
// find any tagging items already in the $select.items array and store them
tagItems = $select.$filter('filter')(items,function (item) {
return item.match($select.taggingLabel);
});
if ( tagItems.length > 0 ) {
tagItem = tagItems[0];
}
item = items[0];
// remove existing tag item if found (should only ever be one tag item)
if ( item !== undefined && items.length > 0 && tagItem ) {
hasTag = true;
items = items.slice(1,items.length);
stashArr = stashArr.slice(1,stashArr.length);
}
newItem = $select.search+' '+$select.taggingLabel;
if ( _findApproxDupe($select.selected, $select.search) > -1 ) {
return;
}
// verify the the tag doesn't match the value of an existing item from
// the searched data set or the items already selected
if ( _findCaseInsensitiveDupe(stashArr.concat($select.selected)) ) {
// if there is a tag from prev iteration, strip it / queue the change
// and return early
if ( hasTag ) {
items = stashArr;
scope.$evalAsync( function () {
$select.activeIndex = 0;
$select.items = items;
});
}
return;
}
if ( _findCaseInsensitiveDupe(stashArr) ) {
// if there is a tag from prev iteration, strip it
if ( hasTag ) {
$select.items = stashArr.slice(1,stashArr.length);
}
return;
}
}
if ( hasTag ) dupeIndex = _findApproxDupe($select.selected, newItem);
// dupe found, shave the first item
if ( dupeIndex > -1 ) {
items = items.slice(dupeIndex+1,items.length-1);
} else {
items = [];
if (newItem) items.push(newItem);
items = items.concat(stashArr);
}
scope.$evalAsync( function () {
$select.activeIndex = 0;
$select.items = items;
if ($select.isGrouped) {
// update item references in groups, so that indexOf will work after angular.copy
var itemsWithoutTag = newItem ? items.slice(1) : items;
$select.setItemsFn(itemsWithoutTag);
if (newItem) {
// add tag item as a new group
$select.items.unshift(newItem);
$select.groups.unshift({name: '', items: [newItem], tagging: true});
}
}
});
}
});
function _findCaseInsensitiveDupe(arr) {
if ( arr === undefined || $select.search === undefined ) {
return false;
}
var hasDupe = arr.filter( function (origItem) {
if ( $select.search.toUpperCase() === undefined || origItem === undefined ) {
return false;
}
return origItem.toUpperCase() === $select.search.toUpperCase();
}).length > 0;
return hasDupe;
}
function _findApproxDupe(haystack, needle) {
var dupeIndex = -1;
if(angular.isArray(haystack)) {
var tempArr = angular.copy(haystack);
for (var i = 0; i <tempArr.length; i++) {
// handle the simple string version of tagging
if ( $select.tagging.fct === undefined ) {
// search the array for the match
if ( tempArr[i]+' '+$select.taggingLabel === needle ) {
dupeIndex = i;
}
// handle the object tagging implementation
} else {
var mockObj = tempArr[i];
if (angular.isObject(mockObj)) {
mockObj.isTag = true;
}
if ( angular.equals(mockObj, needle) ) {
dupeIndex = i;
}
}
}
}
return dupeIndex;
}
$select.searchInput.on('blur', function() {
$timeout(function() {
$selectMultiple.activeMatchIndex = -1;
});
});
}
};
}]);