inputosaurus.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  1. /**
  2. * Inputosaurus Text
  3. *
  4. * Must be instantiated on an <input> element
  5. * Allows multiple input items. Each item is represented with a removable tag that appears to be inside the input area.
  6. *
  7. * @requires:
  8. *
  9. * jQuery 1.7+
  10. * jQueryUI 1.8+ Core
  11. *
  12. * @version 0.1.6
  13. * @author Dan Kielp <dan@sproutsocial.com>
  14. * @created October 3,2012
  15. *
  16. */
  17. (function($) {
  18. var inputosaurustext = {
  19. version: "0.1.6",
  20. eventprefix: "inputosaurus",
  21. options: {
  22. // bindable events
  23. //
  24. // 'change' - triggered whenever a tag is added or removed (should be similar to binding the the change event of the instantiated input
  25. // 'keyup' - keyup event on the newly created input
  26. // while typing, the user can separate values using these delimiters
  27. // the value tags are created on the fly when an inputDelimiter is detected
  28. inputDelimiters : [',', ';'],
  29. // this separator is used to rejoin all input items back to the value of the original <input>
  30. outputDelimiter : ',',
  31. allowDuplicates : false,
  32. parseOnBlur : false,
  33. // optional wrapper for widget
  34. wrapperElement : null,
  35. width : null,
  36. // simply passing an autoComplete source (array, string or function) will instantiate autocomplete functionality
  37. autoCompleteSource : '',
  38. // When forcing users to select from the autocomplete list, allow them to press 'Enter' to select an item if it's the only option left.
  39. activateFinalResult : false,
  40. // manipulate and return the input value after parseInput() parsing
  41. // the array of tag names is passed and expected to be returned as an array after manipulation
  42. parseHook : null,
  43. // define a placeholder to display when the input is empty
  44. placeholder: null,
  45. // when you check for duplicates it check for the case
  46. caseSensitiveDuplicates: false
  47. },
  48. _create: function() {
  49. var widget = this,
  50. els = {},
  51. o = widget.options,
  52. placeholder = o.placeholder || this.element.attr('placeholder') || null;
  53. this._chosenValues = [];
  54. // Create the elements
  55. els.ul = $('<ul class="inputosaurus-container">');
  56. els.input = $('<input type="text" />');
  57. els.inputCont = $('<li class="inputosaurus-input inputosaurus-required"></li>');
  58. els.origInputCont = $('<li class="inputosaurus-input-hidden inputosaurus-required">');
  59. // define starting placeholder
  60. if (placeholder) {
  61. o.placeholder = placeholder;
  62. els.input.attr('placeholder', o.placeholder);
  63. if (o.width) {
  64. els.input.css('min-width', o.width - 50);
  65. }
  66. }
  67. o.wrapperElement && o.wrapperElement.append(els.ul);
  68. this.element.replaceWith(o.wrapperElement || els.ul);
  69. els.origInputCont.append(this.element).hide();
  70. els.inputCont.append(els.input);
  71. els.ul.append(els.inputCont);
  72. els.ul.append(els.origInputCont);
  73. o.width && els.ul.css('width', o.width);
  74. this.elements = els;
  75. widget._attachEvents();
  76. // if instantiated input already contains a value, parse that junk
  77. if($.trim(this.element.val())){
  78. els.input.val( this.element.val() );
  79. this.parseInput();
  80. }
  81. this._instAutocomplete();
  82. },
  83. _instAutocomplete : function() {
  84. if(this.options.autoCompleteSource){
  85. var widget = this;
  86. this.elements.input.autocomplete({
  87. position : {
  88. of : this.elements.ul
  89. },
  90. source : this.options.autoCompleteSource,
  91. minLength : 1,
  92. select : function(ev, ui){
  93. ev.preventDefault();
  94. widget.elements.input.val(ui.item.value);
  95. widget.parseInput();
  96. },
  97. open : function() {
  98. // Older versions of jQueryUI have a different namespace
  99. var auto = $(this).data('ui-autocomplete') || $(this).data('autocomplete');
  100. var menu = auto.menu,
  101. $menuItems;
  102. // zIndex will force the element on top of anything (like a dialog it's in)
  103. menu.element.zIndex && menu.element.zIndex($(this).zIndex() + 1);
  104. menu.element.width(widget.elements.ul.outerWidth());
  105. // auto-activate the result if it's the only one
  106. if(widget.options.activateFinalResult){
  107. $menuItems = menu.element.find('li');
  108. // activate single item to allow selection upon pressing 'Enter'
  109. if($menuItems.size() === 1){
  110. menu[menu.activate ? 'activate' : 'focus']($.Event('click'), $menuItems);
  111. }
  112. }
  113. }
  114. });
  115. }
  116. },
  117. _autoCompleteMenuPosition : function() {
  118. var widget;
  119. if(this.options.autoCompleteSource){
  120. widget = this.elements.input.data('ui-autocomplete') || this.elements.input.data('autocomplete');
  121. widget && widget.menu.element.position({
  122. of: this.elements.ul,
  123. my: 'left top',
  124. at: 'left bottom',
  125. collision: 'none'
  126. });
  127. }
  128. },
  129. /*_closeAutoCompleteMenu : function() {
  130. if(this.options.autoCompleteSource){
  131. this.elements.input.autocomplete('close');
  132. }
  133. },*/
  134. parseInput : function(ev) {
  135. var widget = (ev && ev.data.widget) || this,
  136. val,
  137. delimiterFound = false,
  138. values = [];
  139. val = widget.elements.input.val();
  140. val && (delimiterFound = widget._containsDelimiter(val));
  141. if(delimiterFound !== false){
  142. values = val.split(delimiterFound);
  143. } else if(!ev || ev.which === $.ui.keyCode.ENTER && !$('.ui-menu-item.ui-state-focus').size() && !$('.ui-menu-item .ui-state-focus').size() && !$('#ui-active-menuitem').size()){
  144. values.push(val);
  145. ev && ev.preventDefault();
  146. // prevent autoComplete menu click from causing a false 'blur'
  147. } else if(ev.type === 'blur' && !$('#ui-active-menuitem').size()){
  148. values.push(val);
  149. }
  150. $.isFunction(widget.options.parseHook) && (values = widget.options.parseHook(values));
  151. if(values.length){
  152. widget._setChosen(values);
  153. widget.elements.input.val('');
  154. widget._resizeInput();
  155. }
  156. widget._resetPlaceholder();
  157. },
  158. _inputFocus : function(ev) {
  159. var widget = ev.data.widget || this;
  160. widget.elements.input.value || (widget.options.autoCompleteSource.length && widget.elements.input.autocomplete('search', ''));
  161. },
  162. _inputKeypress : function(ev) {
  163. var widget = ev.data.widget || this;
  164. ev.type === 'keyup' && widget._trigger('keyup', ev, widget);
  165. switch(ev.which){
  166. case $.ui.keyCode.BACKSPACE:
  167. ev.type === 'keydown' && widget._inputBackspace(ev);
  168. break;
  169. case $.ui.keyCode.LEFT:
  170. ev.type === 'keydown' && widget._inputBackspace(ev);
  171. break;
  172. default :
  173. widget.parseInput(ev);
  174. widget._resizeInput(ev);
  175. }
  176. // reposition autoComplete menu as <ul> grows and shrinks vertically
  177. if(widget.options.autoCompleteSource){
  178. setTimeout(function(){widget._autoCompleteMenuPosition.call(widget);}, 200);
  179. }
  180. },
  181. // the input dynamically resizes based on the length of its value
  182. _resizeInput : function(ev) {
  183. var widget = (ev && ev.data.widget) || this,
  184. maxWidth = widget.elements.ul.width(),
  185. val = widget.elements.input.val(),
  186. txtWidth = 25 + val.length * 8;
  187. widget.elements.input.width(txtWidth < maxWidth ? txtWidth : maxWidth);
  188. },
  189. // resets placeholder on representative input
  190. _resetPlaceholder: function () {
  191. var placeholder = this.options.placeholder,
  192. input = this.elements.input,
  193. width = this.options.width || 'inherit';
  194. if (placeholder && this.element.val().length === 0) {
  195. input.attr('placeholder', placeholder).css('min-width', width - 50)
  196. }else {
  197. input.attr('placeholder', '').css('min-width', 'inherit')
  198. }
  199. },
  200. // if our input contains no value and backspace has been pressed, select the last tag
  201. _inputBackspace : function(ev) {
  202. var widget = (ev && ev.data.widget) || this;
  203. lastTag = widget.elements.ul.find('li:not(.inputosaurus-required):last');
  204. // IE goes back in history if the event isn't stopped
  205. ev.stopPropagation();
  206. if((!$(ev.currentTarget).val() || (('selectionStart' in ev.currentTarget) && ev.currentTarget.selectionStart === 0 && ev.currentTarget.selectionEnd === 0)) && lastTag.size()){
  207. ev.preventDefault();
  208. lastTag.find('a').focus();
  209. }
  210. },
  211. _editTag : function(ev) {
  212. var widget = (ev && ev.data.widget) || this,
  213. tagName = '',
  214. $closest = $(ev.currentTarget).closest('li'),
  215. tagKey = $closest.data('ui-inputosaurus') || $closest.data('inputosaurus');
  216. if(!tagKey){
  217. return true;
  218. }
  219. ev.preventDefault();
  220. $.each(widget._chosenValues, function(i,v) {
  221. v.key === tagKey && (tagName = v.value);
  222. });
  223. widget.elements.input.val(tagName);
  224. widget._removeTag(ev);
  225. widget._resizeInput(ev);
  226. },
  227. _tagKeypress : function(ev) {
  228. var widget = ev.data.widget;
  229. switch(ev.which){
  230. case $.ui.keyCode.BACKSPACE:
  231. ev && ev.preventDefault();
  232. ev && ev.stopPropagation();
  233. $(ev.currentTarget).trigger('click');
  234. break;
  235. // 'e' - edit tag (removes tag and places value into visible input
  236. case 69:
  237. widget._editTag(ev);
  238. break;
  239. case $.ui.keyCode.LEFT:
  240. ev.type === 'keydown' && widget._prevTag(ev);
  241. break;
  242. case $.ui.keyCode.RIGHT:
  243. ev.type === 'keydown' && widget._nextTag(ev);
  244. break;
  245. case $.ui.keyCode.DOWN:
  246. ev.type === 'keydown' && widget._focus(ev);
  247. break;
  248. }
  249. },
  250. // select the previous tag or input if no more tags exist
  251. _prevTag : function(ev) {
  252. var widget = (ev && ev.data.widget) || this,
  253. tag = $(ev.currentTarget).closest('li'),
  254. previous = tag.prev();
  255. if(previous.is('li')){
  256. previous.find('a').focus();
  257. } else {
  258. widget._focus();
  259. }
  260. },
  261. // select the next tag or input if no more tags exist
  262. _nextTag : function(ev) {
  263. var widget = (ev && ev.data.widget) || this,
  264. tag = $(ev.currentTarget).closest('li'),
  265. next = tag.next();
  266. if(next.is('li:not(.inputosaurus-input)')){
  267. next.find('a').focus();
  268. } else {
  269. widget._focus();
  270. }
  271. },
  272. // return the inputDelimiter that was detected or false if none were found
  273. _containsDelimiter : function(tagStr) {
  274. var found = false;
  275. $.each(this.options.inputDelimiters, function(k,v) {
  276. if(tagStr.indexOf(v) !== -1){
  277. found = v;
  278. }
  279. });
  280. return found;
  281. },
  282. _setChosen : function(valArr) {
  283. var self = this;
  284. if(!$.isArray(valArr)){
  285. return false;
  286. }
  287. $.each(valArr, function(k,v) {
  288. var exists = false,
  289. obj = {
  290. key : '',
  291. value : ''
  292. };
  293. v = $.trim(v);
  294. $.each(self._chosenValues, function(kk,vv) {
  295. if(!self.options.caseSensitiveDuplicates){
  296. vv.value.toLowerCase() === v.toLowerCase() && (exists = true);
  297. }
  298. else{
  299. vv.value === v && (exists = true);
  300. }
  301. });
  302. if(v !== '' && (!exists || self.options.allowDuplicates)){
  303. obj.key = 'mi_' + Math.random().toString( 16 ).slice( 2, 10 );
  304. obj.value = v;
  305. self._chosenValues.push(obj);
  306. self._renderTags();
  307. }
  308. });
  309. self._setValue(self._buildValue());
  310. },
  311. _buildValue : function() {
  312. var widget = this,
  313. value = '';
  314. $.each(this._chosenValues, function(k,v) {
  315. value += value.length ? widget.options.outputDelimiter + v.value : v.value;
  316. });
  317. return value;
  318. },
  319. _setValue : function(value) {
  320. var val = this.element.val();
  321. if(val !== value){
  322. this.element.val(value);
  323. this._trigger('change');
  324. }
  325. },
  326. // @name text for tag
  327. // @className optional className for <li>
  328. _createTag : function(name, key, className) {
  329. className = className ? ' class="' + className + '"' : '';
  330. if(name !== undefined){
  331. return $('<li' + className + ' data-inputosaurus="' + key + '"><span>' + name + '</span> <a href="javascript:void(0);" class="ficon">&#x2716;</a></li>');
  332. }
  333. },
  334. _renderTags : function() {
  335. var self = this;
  336. this.elements.ul.find('li:not(.inputosaurus-required)').remove();
  337. $.each(this._chosenValues, function(k,v) {
  338. var el = self._createTag(v.value, v.key);
  339. self.elements.ul.find('li.inputosaurus-input').before(el);
  340. });
  341. },
  342. _removeTag : function(ev) {
  343. var $closest = $(ev.currentTarget).closest('li'),
  344. key = $closest.data('ui-inputosaurus') || $closest.data('inputosaurus'),
  345. indexFound = false,
  346. widget = (ev && ev.data.widget) || this;
  347. $.each(widget._chosenValues, function(k,v) {
  348. if(key === v.key){
  349. indexFound = k;
  350. }
  351. });
  352. indexFound !== false && widget._chosenValues.splice(indexFound, 1);
  353. widget._setValue(widget._buildValue());
  354. $(ev.currentTarget).closest('li').remove();
  355. widget.elements.input.focus();
  356. },
  357. _focus : function(ev) {
  358. var widget = (ev && ev.data.widget) || this,
  359. $closest = $(ev.target).closest('li'),
  360. $data = $closest.data('ui-inputosaurus') || $closest.data('inputosaurus');
  361. if(!ev || !$data){
  362. widget.elements.input.focus();
  363. }
  364. },
  365. _tagFocus : function(ev) {
  366. $(ev.currentTarget).parent()[ev.type === 'focusout' ? 'removeClass' : 'addClass']('inputosaurus-selected');
  367. },
  368. refresh : function() {
  369. var delim = this.options.outputDelimiter,
  370. val = this.element.val(),
  371. values = [];
  372. values.push(val);
  373. delim && (values = val.split(delim));
  374. if(values.length){
  375. this._chosenValues = [];
  376. $.isFunction(this.options.parseHook) && (values = this.options.parseHook(values));
  377. this._setChosen(values);
  378. this._renderTags();
  379. this.elements.input.val('');
  380. this._resizeInput();
  381. }
  382. },
  383. _attachEvents : function() {
  384. var widget = this;
  385. this.elements.input.on('keyup.inputosaurus', {widget : widget}, this._inputKeypress);
  386. this.elements.input.on('keydown.inputosaurus', {widget : widget}, this._inputKeypress);
  387. this.elements.input.on('change.inputosaurus', {widget : widget}, this._inputKeypress);
  388. this.elements.input.on('focus.inputosaurus', {widget : widget}, this._inputFocus);
  389. this.options.parseOnBlur && this.elements.input.on('blur.inputosaurus', {widget : widget}, this.parseInput);
  390. this.elements.ul.on('click.inputosaurus', {widget : widget}, this._focus);
  391. this.elements.ul.on('click.inputosaurus', 'a', {widget : widget}, this._removeTag);
  392. this.elements.ul.on('dblclick.inputosaurus', 'li', {widget : widget}, this._editTag);
  393. this.elements.ul.on('focus.inputosaurus', 'a', {widget : widget}, this._tagFocus);
  394. this.elements.ul.on('blur.inputosaurus', 'a', {widget : widget}, this._tagFocus);
  395. this.elements.ul.on('keydown.inputosaurus', 'a', {widget : widget}, this._tagKeypress);
  396. },
  397. _destroy: function() {
  398. this.elements.input.unbind('.inputosaurus');
  399. this.elements.ul.replaceWith(this.element);
  400. }
  401. };
  402. $.widget("ui.inputosaurus", inputosaurustext);
  403. })(jQuery);