forked from angular-ui/ui-select
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathselect.js
370 lines (315 loc) · 11.4 KB
/
select.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
'use strict';
/**
* Add querySelectorAll() to jqLite.
*
* jqLite find() is limited to lookups by tag name.
* TODO This will change with future versions of AngularJS, to be removed when this happens
*
* See jqLite.find - why not use querySelectorAll? https://github.com/angular/angular.js/issues/3586
* See feat(jqLite): use querySelectorAll instead of getElementsByTagName in jqLite.find https://github.com/angular/angular.js/pull/3598
*/
if (angular.element.prototype.querySelectorAll === undefined) {
angular.element.prototype.querySelectorAll = function(selector) {
return angular.element(this[0].querySelectorAll(selector));
};
}
angular.module('ui.select', [])
.constant('uiSelectConfig', {
theme: 'select2',
placeholder: '' // Empty by default, like HTML tag <select>
})
/**
* Parses "repeat" attribute.
*
* Taken from AngularJS ngRepeat source code
* See https://github.com/angular/angular.js/blob/55848a9139/src/ng/directive/ngRepeat.js#L211
*
* Original discussion about parsing "repeat" attribute instead of fully relying on ng-repeat:
* https://github.com/angular-ui/ui-select/commit/5dd63ad#commitcomment-5504697
*/
.service('RepeatParser', function() {
var self = this;
/**
* Example:
* expression = "address in getAddress($select.search) track by $index
* lhs = "address",
* rhs = "getAddress($select.search)",
* trackByExp = "$index",
* valueIdentifier = "address",
* keyIdentifier = undefined
*/
self.parse = function(expression) {
var match = expression.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?\s*$/);
if (!match) {
throw new Error("Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
expression);
}
var lhs = match[1]; // Left-hand side
var rhs = match[2]; // Right-hand side
var trackByExp = match[3];
match = lhs.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/);
if (!match) {
throw new Error("'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.",
lhs);
}
var valueIdentifier = match[3] || match[1];
var keyIdentifier = match[2];
return {
lhs: lhs,
rhs: rhs,
trackByExp: trackByExp
};
};
self.getNgRepeatExpression = function(lhs, rhs, trackByExp) {
var expression = lhs + ' in ' + rhs;
if (trackByExp) {
expression += ' track by ' + trackByExp;
}
return expression;
};
})
/**
* Contains ui-select "intelligence".
*
* The goal is to limit dependency on the DOM whenever possible and
* put as much logic in the controller (instead of the link functions) as possible so it can be easily tested.
*/
.controller('uiSelectCtrl',
['$scope', '$element', '$timeout', 'RepeatParser', '$parse', '$q',
function($scope, $element, $timeout, RepeatParser, $parse, $q) {
var ctrl = this;
var EMPTY_SEARCH = '';
ctrl.placeholder = undefined;
ctrl.search = EMPTY_SEARCH;
ctrl.activeIndex = 0;
ctrl.items = [];
ctrl.selected = undefined;
ctrl.open = false;
ctrl.disabled = false;
ctrl.searchInput = $element.querySelectorAll('input.ui-select-search');
// When the user clicks on ui-select, displays the dropdown list
ctrl.activate = function() {
if (ctrl.disabled === false) {
ctrl.open = true;
// Give it time to appear before focus
$timeout(function() {
ctrl.searchInput[0].focus();
});
}
};
var _repeatRhsIsCollection = null;
var _repeatRhsFn = null;
ctrl.parseRepeatAttr = function(repeatAttr) {
var repeat = RepeatParser.parse(repeatAttr);
_repeatRhsFn = $parse(repeat.rhs);
var collectionOrPromise = _repeatRhsFn($scope);
// Hackish :/
// Determine if the repeat expression (repeat.rhs) gives us a collection or a promise
// If it is a collection we need to $watch it in order to update ctrl.items
_repeatRhsIsCollection = angular.isArray(collectionOrPromise);
if (_repeatRhsIsCollection) {
// See https://github.com/angular/angular.js/blob/55848a9139/src/ng/directive/ngRepeat.js#L259
$scope.$watchCollection(repeat.rhs, function(items) {
ctrl.items = items;
});
}
};
ctrl.populateItems = function() {
if (!_repeatRhsIsCollection) {
var promise = _repeatRhsFn($scope);
// See https://github.com/angular-ui/bootstrap/blob/d0024931de/src/typeahead/typeahead.js#L109
// See https://github.com/mgcrea/angular-strap/blob/1529ab4bbc/src/helpers/parse-options.js#L35
$q.when(promise).then(function(items) {
ctrl.items = items;
});
}
};
// When the user clicks on an item inside the dropdown list
ctrl.select = function(item) {
ctrl.selected = item;
ctrl.close();
// Using a watch instead of $scope.ngModel.$setViewValue(item)
};
ctrl.close = function() {
if (ctrl.open) {
ctrl.open = false;
if (_repeatRhsIsCollection) {
// This means if repeat.rhs is a promise, we keep the search term (ctrl.search)
// even after the dropdown being closed
ctrl.search = EMPTY_SEARCH;
}
}
};
var Key = {
Enter: 13,
Tab: 9,
Up: 38,
Down: 40,
Escape: 27
};
ctrl.onKeydown = function(key) {
var processed = true;
switch (key) {
case Key.Down:
if (ctrl.activeIndex < ctrl.items.length - 1) { ctrl.activeIndex++; }
break;
case Key.Up:
if (ctrl.activeIndex > 0) { ctrl.activeIndex--; }
break;
case Key.Tab:
case Key.Enter:
ctrl.select(ctrl.items[ctrl.activeIndex]);
break;
case Key.Escape:
ctrl.close();
break;
default:
processed = false;
}
return processed;
};
}])
.directive('uiSelect', ['$document', 'uiSelectConfig', function($document, uiSelectConfig) {
return {
restrict: 'EA',
templateUrl: function(tElement, tAttrs) {
var theme = tAttrs.theme || uiSelectConfig.theme;
return theme + '/select.tpl.html';
},
replace: true,
transclude: true,
require: ['uiSelect', 'ngModel'],
scope: true,
controller: 'uiSelectCtrl',
controllerAs: '$select',
link: function(scope, element, attrs, ctrls, transcludeFn) {
var $select = ctrls[0];
var ngModel = ctrls[1];
attrs.$observe('disabled', function() {
$select.disabled = attrs.disabled ? true : false;
});
scope.$watch('$select.selected', function(newValue, oldValue) {
if (ngModel.$viewValue !== newValue) {
ngModel.$setViewValue(newValue);
}
});
ngModel.$render = function() {
$select.selected = ngModel.$viewValue;
};
function ensureHighlightVisible() {
var container = element.querySelectorAll('.ui-select-choices-content');
var rows = container.querySelectorAll('.ui-select-choices-row');
var highlighted = rows[$select.activeIndex];
var posY = highlighted.offsetTop + highlighted.clientHeight - container[0].scrollTop;
var height = container[0].offsetHeight;
if (posY > height) {
container[0].scrollTop += posY - height;
} else if (posY < highlighted.clientHeight) {
container[0].scrollTop -= highlighted.clientHeight - posY;
}
}
// Bind to keyboard shortcuts
$select.searchInput.on('keydown', function(e) {
scope.$apply(function() {
var processed = $select.onKeydown(e.which);
if (processed) {
e.preventDefault();
e.stopPropagation();
ensureHighlightVisible();
}
});
});
// See Click everywhere but here event http://stackoverflow.com/questions/12931369
$document.on('mousedown', function(e) {
var contains = false;
if (window.jQuery) {
// Firefox 3.6 does not support element.contains()
// See Node.contains https://developer.mozilla.org/en-US/docs/Web/API/Node.contains
contains = $.contains(element[0], e.target);
} else {
contains = element[0].contains(e.target);
}
if (!contains) {
$select.close();
scope.$digest();
}
});
scope.$on('$destroy', function() {
$select.searchInput.off('keydown');
$document.off('mousedown');
});
// Move transcluded elements to their correct position on main template
transcludeFn(scope, function(clone) {
var transcluded = angular.element('<div>').append(clone);
// Child directives could be uncompiled at this point, so we check both alternatives,
// first for compiled version (by class) or uncompiled (by tag). We place the directives
// at the insertion points that are marked with ui-select-* classes inside the templates
var transMatch = transcluded.querySelectorAll('.ui-select-match');
transMatch = !transMatch.length ? transcluded.find('match') : transMatch;
element.querySelectorAll('.ui-select-match').replaceWith(transMatch);
var transChoices = transcluded.querySelectorAll('.ui-select-choices');
transChoices = !transChoices.length ? transcluded.find('choices') : transChoices;
element.querySelectorAll('.ui-select-choices').replaceWith(transChoices);
});
}
};
}])
.directive('choices', ['uiSelectConfig', 'RepeatParser', function(uiSelectConfig, RepeatParser) {
return {
restrict: 'EA',
require: '^uiSelect',
replace: true,
transclude: true,
templateUrl: function(tElement) {
// Gets theme attribute from parent (ui-select)
var theme = tElement.parent().attr('theme') || uiSelectConfig.theme;
return theme + '/choices.tpl.html';
},
compile: function(tElement, tAttrs) {
var repeat = RepeatParser.parse(tAttrs.repeat);
tElement.querySelectorAll('.ui-select-choices-row')
.attr('ng-repeat', RepeatParser.getNgRepeatExpression(repeat.lhs, '$select.items', repeat.trackByExp))
.attr('ng-mouseenter', '$select.activeIndex = $index')
.attr('ng-click', '$select.select(' + repeat.lhs + ')');
return function link(scope, element, attrs, $select) {
$select.parseRepeatAttr(attrs.repeat);
scope.$watch('$select.search', function() {
$select.activeIndex = 0;
$select.populateItems(attrs.repeat);
});
};
}
};
}])
.directive('match', ['uiSelectConfig', function(uiSelectConfig) {
return {
restrict: 'EA',
require: '^uiSelect',
replace: true,
transclude: true,
templateUrl: function(tElement) {
// Gets theme attribute from parent (ui-select)
var theme = tElement.parent().attr('theme') || uiSelectConfig.theme;
return theme + '/match.tpl.html';
},
link: function(scope, element, attrs, $select) {
attrs.$observe('placeholder', function(placeholder) {
$select.placeholder = placeholder || uiSelectConfig.placeholder;
});
}
};
}])
/**
* Highlights text that matches $select.search.
*
* Taken from AngularUI Bootstrap Typeahead
* See https://github.com/angular-ui/bootstrap/blob/d0024931de/src/typeahead/typeahead.js#L352
*/
.filter('highlight', function() {
function escapeRegexp(queryToEscape) {
return queryToEscape.replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1');
}
return function(matchItem, query) {
return query ? matchItem.replace(new RegExp(escapeRegexp(query), 'gi'), '<span class="ui-select-highlight">$&</span>') : matchItem;
};
});