PageRenderTime 48ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/files/bootstrap.tagsinput/0.7.1/bootstrap-tagsinput.js

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