scratch – Blame information for rev 125

Subversion Repositories:
Rev:
Rev Author Line No. Line
125 office 1 (function ($) {
2 "use strict";
3  
4 var defaultOptions = {
5 tagClass: function(item) {
6 return 'label label-info';
7 },
8 focusClass: 'focus',
9 itemValue: function(item) {
10 return item ? item.toString() : item;
11 },
12 itemText: function(item) {
13 return this.itemValue(item);
14 },
15 itemTitle: function(item) {
16 return null;
17 },
18 freeInput: true,
19 addOnBlur: true,
20 maxTags: undefined,
21 maxChars: undefined,
22 confirmKeys: [13, 44],
23 delimiter: ',',
24 delimiterRegex: null,
25 cancelConfirmKeysOnEmpty: false,
26 onTagExists: function(item, $tag) {
27 $tag.hide().fadeIn();
28 },
29 trimValue: false,
30 allowDuplicates: false,
31 triggerChange: true
32 };
33  
34 /**
35 * Constructor function
36 */
37 function TagsInput(element, options) {
38 this.isInit = true;
39 this.itemsArray = [];
40  
41 this.$element = $(element);
42 this.$element.hide();
43  
44 this.isSelect = (element.tagName === 'SELECT');
45 this.multiple = (this.isSelect && element.hasAttribute('multiple'));
46 this.objectItems = options && options.itemValue;
47 this.placeholderText = element.hasAttribute('placeholder') ? this.$element.attr('placeholder') : '';
48 this.inputSize = Math.max(1, this.placeholderText.length);
49  
50 this.$container = $('<div class="bootstrap-tagsinput"></div>');
51 this.$input = $('<input type="text" placeholder="' + this.placeholderText + '"/>').appendTo(this.$container);
52  
53 this.$element.before(this.$container);
54  
55 this.build(options);
56 this.isInit = false;
57 }
58  
59 TagsInput.prototype = {
60 constructor: TagsInput,
61  
62 /**
63 * Adds the given item as a new tag. Pass true to dontPushVal to prevent
64 * updating the elements val()
65 */
66 add: function(item, dontPushVal, options) {
67 var self = this;
68  
69 if (self.options.maxTags && self.itemsArray.length >= self.options.maxTags)
70 return;
71  
72 // Ignore falsey values, except false
73 if (item !== false && !item)
74 return;
75  
76 // Trim value
77 if (typeof item === "string" && self.options.trimValue) {
78 item = $.trim(item);
79 }
80  
81 // Throw an error when trying to add an object while the itemValue option was not set
82 if (typeof item === "object" && !self.objectItems)
83 throw("Can't add objects when itemValue option is not set");
84  
85 // Ignore strings only containg whitespace
86 if (item.toString().match(/^\s*$/))
87 return;
88  
89 // If SELECT but not multiple, remove current tag
90 if (self.isSelect && !self.multiple && self.itemsArray.length > 0)
91 self.remove(self.itemsArray[0]);
92  
93 if (typeof item === "string" && this.$element[0].tagName === 'INPUT') {
94 var delimiter = (self.options.delimiterRegex) ? self.options.delimiterRegex : self.options.delimiter;
95 var items = item.split(delimiter);
96 if (items.length > 1) {
97 for (var i = 0; i < items.length; i++) {
98 this.add(items[i], true);
99 }
100  
101 if (!dontPushVal)
102 self.pushVal(self.options.triggerChange);
103 return;
104 }
105 }
106  
107 var itemValue = self.options.itemValue(item),
108 itemText = self.options.itemText(item),
109 tagClass = self.options.tagClass(item),
110 itemTitle = self.options.itemTitle(item);
111  
112 // Ignore items allready added
113 var existing = $.grep(self.itemsArray, function(item) { return self.options.itemValue(item) === itemValue; } )[0];
114 if (existing && !self.options.allowDuplicates) {
115 // Invoke onTagExists
116 if (self.options.onTagExists) {
117 var $existingTag = $(".tag", self.$container).filter(function() { return $(this).data("item") === existing; });
118 self.options.onTagExists(item, $existingTag);
119 }
120 return;
121 }
122  
123 // if length greater than limit
124 if (self.items().toString().length + item.length + 1 > self.options.maxInputLength)
125 return;
126  
127 // raise beforeItemAdd arg
128 var beforeItemAddEvent = $.Event('beforeItemAdd', { item: item, cancel: false, options: options});
129 self.$element.trigger(beforeItemAddEvent);
130 if (beforeItemAddEvent.cancel)
131 return;
132  
133 // register item in internal array and map
134 self.itemsArray.push(item);
135  
136 // add a tag element
137  
138 var $tag = $('<span class="tag ' + htmlEncode(tagClass) + (itemTitle !== null ? ('" title="' + itemTitle) : '') + '">' + htmlEncode(itemText) + '<span data-role="remove"></span></span>');
139 $tag.data('item', item);
140 self.findInputWrapper().before($tag);
141 $tag.after(' ');
142  
143 // Check to see if the tag exists in its raw or uri-encoded form
144 var optionExists = (
145 $('option[value="' + encodeURIComponent(itemValue) + '"]', self.$element).length ||
146 $('option[value="' + htmlEncode(itemValue) + '"]', self.$element).length
147 );
148  
149 // add <option /> if item represents a value not present in one of the <select />'s options
150 if (self.isSelect && !optionExists) {
151 var $option = $('<option selected>' + htmlEncode(itemText) + '</option>');
152 $option.data('item', item);
153 $option.attr('value', itemValue);
154 self.$element.append($option);
155 }
156  
157 if (!dontPushVal)
158 self.pushVal(self.options.triggerChange);
159  
160 // Add class when reached maxTags
161 if (self.options.maxTags === self.itemsArray.length || self.items().toString().length === self.options.maxInputLength)
162 self.$container.addClass('bootstrap-tagsinput-max');
163  
164 // If using typeahead, once the tag has been added, clear the typeahead value so it does not stick around in the input.
165 if ($('.typeahead, .twitter-typeahead', self.$container).length) {
166 self.$input.typeahead('val', '');
167 }
168  
169 if (this.isInit) {
170 self.$element.trigger($.Event('itemAddedOnInit', { item: item, options: options }));
171 } else {
172 self.$element.trigger($.Event('itemAdded', { item: item, options: options }));
173 }
174 },
175  
176 /**
177 * Removes the given item. Pass true to dontPushVal to prevent updating the
178 * elements val()
179 */
180 remove: function(item, dontPushVal, options) {
181 var self = this;
182  
183 if (self.objectItems) {
184 if (typeof item === "object")
185 item = $.grep(self.itemsArray, function(other) { return self.options.itemValue(other) == self.options.itemValue(item); } );
186 else
187 item = $.grep(self.itemsArray, function(other) { return self.options.itemValue(other) == item; } );
188  
189 item = item[item.length-1];
190 }
191  
192 if (item) {
193 var beforeItemRemoveEvent = $.Event('beforeItemRemove', { item: item, cancel: false, options: options });
194 self.$element.trigger(beforeItemRemoveEvent);
195 if (beforeItemRemoveEvent.cancel)
196 return;
197  
198 $('.tag', self.$container).filter(function() { return $(this).data('item') === item; }).remove();
199 $('option', self.$element).filter(function() { return $(this).data('item') === item; }).remove();
200 if($.inArray(item, self.itemsArray) !== -1)
201 self.itemsArray.splice($.inArray(item, self.itemsArray), 1);
202 }
203  
204 if (!dontPushVal)
205 self.pushVal(self.options.triggerChange);
206  
207 // Remove class when reached maxTags
208 if (self.options.maxTags > self.itemsArray.length)
209 self.$container.removeClass('bootstrap-tagsinput-max');
210  
211 self.$element.trigger($.Event('itemRemoved', { item: item, options: options }));
212 },
213  
214 /**
215 * Removes all items
216 */
217 removeAll: function() {
218 var self = this;
219  
220 $('.tag', self.$container).remove();
221 $('option', self.$element).remove();
222  
223 while(self.itemsArray.length > 0)
224 self.itemsArray.pop();
225  
226 self.pushVal(self.options.triggerChange);
227 },
228  
229 /**
230 * Refreshes the tags so they match the text/value of their corresponding
231 * item.
232 */
233 refresh: function() {
234 var self = this;
235 $('.tag', self.$container).each(function() {
236 var $tag = $(this),
237 item = $tag.data('item'),
238 itemValue = self.options.itemValue(item),
239 itemText = self.options.itemText(item),
240 tagClass = self.options.tagClass(item);
241  
242 // Update tag's class and inner text
243 $tag.attr('class', null);
244 $tag.addClass('tag ' + htmlEncode(tagClass));
245 $tag.contents().filter(function() {
246 return this.nodeType == 3;
247 })[0].nodeValue = htmlEncode(itemText);
248  
249 if (self.isSelect) {
250 var option = $('option', self.$element).filter(function() { return $(this).data('item') === item; });
251 option.attr('value', itemValue);
252 }
253 });
254 },
255  
256 /**
257 * Returns the items added as tags
258 */
259 items: function() {
260 return this.itemsArray;
261 },
262  
263 /**
264 * Assembly value by retrieving the value of each item, and set it on the
265 * element.
266 */
267 pushVal: function() {
268 var self = this,
269 val = $.map(self.items(), function(item) {
270 return self.options.itemValue(item).toString();
271 });
272  
273 self.$element.val(val, true);
274  
275 if (self.options.triggerChange)
276 self.$element.trigger('change');
277 },
278  
279 /**
280 * Initializes the tags input behaviour on the element
281 */
282 build: function(options) {
283 var self = this;
284  
285 self.options = $.extend({}, defaultOptions, options);
286 // When itemValue is set, freeInput should always be false
287 if (self.objectItems)
288 self.options.freeInput = false;
289  
290 makeOptionItemFunction(self.options, 'itemValue');
291 makeOptionItemFunction(self.options, 'itemText');
292 makeOptionFunction(self.options, 'tagClass');
293  
294 // Typeahead Bootstrap version 2.3.2
295 if (self.options.typeahead) {
296 var typeahead = self.options.typeahead || {};
297  
298 makeOptionFunction(typeahead, 'source');
299  
300 self.$input.typeahead($.extend({}, typeahead, {
301 source: function (query, process) {
302 function processItems(items) {
303 var texts = [];
304  
305 for (var i = 0; i < items.length; i++) {
306 var text = self.options.itemText(items[i]);
307 map[text] = items[i];
308 texts.push(text);
309 }
310 process(texts);
311 }
312  
313 this.map = {};
314 var map = this.map,
315 data = typeahead.source(query);
316  
317 if ($.isFunction(data.success)) {
318 // support for Angular callbacks
319 data.success(processItems);
320 } else if ($.isFunction(data.then)) {
321 // support for Angular promises
322 data.then(processItems);
323 } else {
324 // support for functions and jquery promises
325 $.when(data)
326 .then(processItems);
327 }
328 },
329 updater: function (text) {
330 self.add(this.map[text]);
331 return this.map[text];
332 },
333 matcher: function (text) {
334 return (text.toLowerCase().indexOf(this.query.trim().toLowerCase()) !== -1);
335 },
336 sorter: function (texts) {
337 return texts.sort();
338 },
339 highlighter: function (text) {
340 var regex = new RegExp( '(' + this.query + ')', 'gi' );
341 return text.replace( regex, "<strong>$1</strong>" );
342 }
343 }));
344 }
345  
346 // typeahead.js
347 if (self.options.typeaheadjs) {
348 var typeaheadConfig = null;
349 var typeaheadDatasets = {};
350  
351 // Determine if main configurations were passed or simply a dataset
352 var typeaheadjs = self.options.typeaheadjs;
353 if ($.isArray(typeaheadjs)) {
354 typeaheadConfig = typeaheadjs[0];
355 typeaheadDatasets = typeaheadjs[1];
356 } else {
357 typeaheadDatasets = typeaheadjs;
358 }
359  
360 self.$input.typeahead(typeaheadConfig, typeaheadDatasets).on('typeahead:selected', $.proxy(function (obj, datum) {
361 if (typeaheadDatasets.valueKey)
362 self.add(datum[typeaheadDatasets.valueKey]);
363 else
364 self.add(datum);
365 self.$input.typeahead('val', '');
366 }, self));
367 }
368  
369 self.$container.on('click', $.proxy(function(event) {
370 if (! self.$element.attr('disabled')) {
371 self.$input.removeAttr('disabled');
372 }
373 self.$input.focus();
374 }, self));
375  
376 if (self.options.addOnBlur && self.options.freeInput) {
377 self.$input.on('focusout', $.proxy(function(event) {
378 // HACK: only process on focusout when no typeahead opened, to
379 // avoid adding the typeahead text as tag
380 if ($('.typeahead, .twitter-typeahead', self.$container).length === 0) {
381 self.add(self.$input.val());
382 self.$input.val('');
383 }
384 }, self));
385 }
386  
387 // Toggle the 'focus' css class on the container when it has focus
388 self.$container.on({
389 focusin: function() {
390 self.$container.addClass(self.options.focusClass);
391 },
392 focusout: function() {
393 self.$container.removeClass(self.options.focusClass);
394 },
395 });
396  
397 self.$container.on('keydown', 'input', $.proxy(function(event) {
398 var $input = $(event.target),
399 $inputWrapper = self.findInputWrapper();
400  
401 if (self.$element.attr('disabled')) {
402 self.$input.attr('disabled', 'disabled');
403 return;
404 }
405  
406 switch (event.which) {
407 // BACKSPACE
408 case 8:
409 if (doGetCaretPosition($input[0]) === 0) {
410 var prev = $inputWrapper.prev();
411 if (prev.length) {
412 self.remove(prev.data('item'));
413 }
414 }
415 break;
416  
417 // DELETE
418 case 46:
419 if (doGetCaretPosition($input[0]) === 0) {
420 var next = $inputWrapper.next();
421 if (next.length) {
422 self.remove(next.data('item'));
423 }
424 }
425 break;
426  
427 // LEFT ARROW
428 case 37:
429 // Try to move the input before the previous tag
430 var $prevTag = $inputWrapper.prev();
431 if ($input.val().length === 0 && $prevTag[0]) {
432 $prevTag.before($inputWrapper);
433 $input.focus();
434 }
435 break;
436 // RIGHT ARROW
437 case 39:
438 // Try to move the input after the next tag
439 var $nextTag = $inputWrapper.next();
440 if ($input.val().length === 0 && $nextTag[0]) {
441 $nextTag.after($inputWrapper);
442 $input.focus();
443 }
444 break;
445 default:
446 // ignore
447 }
448  
449 // Reset internal input's size
450 var textLength = $input.val().length,
451 wordSpace = Math.ceil(textLength / 5),
452 size = textLength + wordSpace + 1;
453 $input.attr('size', Math.max(this.inputSize, $input.val().length));
454 }, self));
455  
456 self.$container.on('keypress', 'input', $.proxy(function(event) {
457 var $input = $(event.target);
458  
459 if (self.$element.attr('disabled')) {
460 self.$input.attr('disabled', 'disabled');
461 return;
462 }
463  
464 var text = $input.val(),
465 maxLengthReached = self.options.maxChars && text.length >= self.options.maxChars;
466 if (self.options.freeInput && (keyCombinationInList(event, self.options.confirmKeys) || maxLengthReached)) {
467 // Only attempt to add a tag if there is data in the field
468 if (text.length !== 0) {
469 self.add(maxLengthReached ? text.substr(0, self.options.maxChars) : text);
470 $input.val('');
471 }
472  
473 // If the field is empty, let the event triggered fire as usual
474 if (self.options.cancelConfirmKeysOnEmpty === false) {
475 event.preventDefault();
476 }
477 }
478  
479 // Reset internal input's size
480 var textLength = $input.val().length,
481 wordSpace = Math.ceil(textLength / 5),
482 size = textLength + wordSpace + 1;
483 $input.attr('size', Math.max(this.inputSize, $input.val().length));
484 }, self));
485  
486 // Remove icon clicked
487 self.$container.on('click', '[data-role=remove]', $.proxy(function(event) {
488 if (self.$element.attr('disabled')) {
489 return;
490 }
491 self.remove($(event.target).closest('.tag').data('item'));
492 }, self));
493  
494 // Only add existing value as tags when using strings as tags
495 if (self.options.itemValue === defaultOptions.itemValue) {
496 if (self.$element[0].tagName === 'INPUT') {
497 self.add(self.$element.val());
498 } else {
499 $('option', self.$element).each(function() {
500 self.add($(this).attr('value'), true);
501 });
502 }
503 }
504 },
505  
506 /**
507 * Removes all tagsinput behaviour and unregsiter all event handlers
508 */
509 destroy: function() {
510 var self = this;
511  
512 // Unbind events
513 self.$container.off('keypress', 'input');
514 self.$container.off('click', '[role=remove]');
515  
516 self.$container.remove();
517 self.$element.removeData('tagsinput');
518 self.$element.show();
519 },
520  
521 /**
522 * Sets focus on the tagsinput
523 */
524 focus: function() {
525 this.$input.focus();
526 },
527  
528 /**
529 * Returns the internal input element
530 */
531 input: function() {
532 return this.$input;
533 },
534  
535 /**
536 * Returns the element which is wrapped around the internal input. This
537 * is normally the $container, but typeahead.js moves the $input element.
538 */
539 findInputWrapper: function() {
540 var elt = this.$input[0],
541 container = this.$container[0];
542 while(elt && elt.parentNode !== container)
543 elt = elt.parentNode;
544  
545 return $(elt);
546 }
547 };
548  
549 /**
550 * Register JQuery plugin
551 */
552 $.fn.tagsinput = function(arg1, arg2, arg3) {
553 var results = [];
554  
555 this.each(function() {
556 var tagsinput = $(this).data('tagsinput');
557 // Initialize a new tags input
558 if (!tagsinput) {
559 tagsinput = new TagsInput(this, arg1);
560 $(this).data('tagsinput', tagsinput);
561 results.push(tagsinput);
562  
563 if (this.tagName === 'SELECT') {
564 $('option', $(this)).attr('selected', 'selected');
565 }
566  
567 // Init tags from $(this).val()
568 $(this).val($(this).val());
569 } else if (!arg1 && !arg2) {
570 // tagsinput already exists
571 // no function, trying to init
572 results.push(tagsinput);
573 } else if(tagsinput[arg1] !== undefined) {
574 // Invoke function on existing tags input
575 if(tagsinput[arg1].length === 3 && arg3 !== undefined){
576 var retVal = tagsinput[arg1](arg2, null, arg3);
577 }else{
578 var retVal = tagsinput[arg1](arg2);
579 }
580 if (retVal !== undefined)
581 results.push(retVal);
582 }
583 });
584  
585 if ( typeof arg1 == 'string') {
586 // Return the results from the invoked function calls
587 return results.length > 1 ? results : results[0];
588 } else {
589 return results;
590 }
591 };
592  
593 $.fn.tagsinput.Constructor = TagsInput;
594  
595 /**
596 * Most options support both a string or number as well as a function as
597 * option value. This function makes sure that the option with the given
598 * key in the given options is wrapped in a function
599 */
600 function makeOptionItemFunction(options, key) {
601 if (typeof options[key] !== 'function') {
602 var propertyName = options[key];
603 options[key] = function(item) { return item[propertyName]; };
604 }
605 }
606 function makeOptionFunction(options, key) {
607 if (typeof options[key] !== 'function') {
608 var value = options[key];
609 options[key] = function() { return value; };
610 }
611 }
612 /**
613 * HtmlEncodes the given value
614 */
615 var htmlEncodeContainer = $('<div />');
616 function htmlEncode(value) {
617 if (value) {
618 return htmlEncodeContainer.text(value).html();
619 } else {
620 return '';
621 }
622 }
623  
624 /**
625 * Returns the position of the caret in the given input field
626 * http://flightschool.acylt.com/devnotes/caret-position-woes/
627 */
628 function doGetCaretPosition(oField) {
629 var iCaretPos = 0;
630 if (document.selection) {
631 oField.focus ();
632 var oSel = document.selection.createRange();
633 oSel.moveStart ('character', -oField.value.length);
634 iCaretPos = oSel.text.length;
635 } else if (oField.selectionStart || oField.selectionStart == '0') {
636 iCaretPos = oField.selectionStart;
637 }
638 return (iCaretPos);
639 }
640  
641 /**
642 * Returns boolean indicates whether user has pressed an expected key combination.
643 * @param object keyPressEvent: JavaScript event object, refer
644 * http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
645 * @param object lookupList: expected key combinations, as in:
646 * [13, {which: 188, shiftKey: true}]
647 */
648 function keyCombinationInList(keyPressEvent, lookupList) {
649 var found = false;
650 $.each(lookupList, function (index, keyCombination) {
651 if (typeof (keyCombination) === 'number' && keyPressEvent.which === keyCombination) {
652 found = true;
653 return false;
654 }
655  
656 if (keyPressEvent.which === keyCombination.which) {
657 var alt = !keyCombination.hasOwnProperty('altKey') || keyPressEvent.altKey === keyCombination.altKey,
658 shift = !keyCombination.hasOwnProperty('shiftKey') || keyPressEvent.shiftKey === keyCombination.shiftKey,
659 ctrl = !keyCombination.hasOwnProperty('ctrlKey') || keyPressEvent.ctrlKey === keyCombination.ctrlKey;
660 if (alt && shift && ctrl) {
661 found = true;
662 return false;
663 }
664 }
665 });
666  
667 return found;
668 }
669  
670 /**
671 * Initialize tagsinput behaviour on inputs and selects which have
672 * data-role=tagsinput
673 */
674 $(function() {
675 $("input[data-role=tagsinput], select[multiple][data-role=tagsinput]").tagsinput();
676 });
677 })(window.jQuery);