PageRenderTime 79ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/ajax/libs/bootstrap-tagsinput/0.7.0/bootstrap-tagsinput.js

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