]> git.mxchange.org Git - friendica.git/blob - library/jquery-textcomplete/jquery.textcomplete.js
rework autocomplete: initial commit
[friendica.git] / library / jquery-textcomplete / jquery.textcomplete.js
1 /*!
2  * jQuery.textcomplete
3  *
4  * Repository: https://github.com/yuku-t/jquery-textcomplete
5  * License:    MIT (https://github.com/yuku-t/jquery-textcomplete/blob/master/LICENSE)
6  * Author:     Yuku Takahashi
7  */
8
9 if (typeof jQuery === 'undefined') {
10   throw new Error('jQuery.textcomplete requires jQuery');
11 }
12
13 +function ($) {
14   'use strict';
15
16   var warn = function (message) {
17     if (console.warn) { console.warn(message); }
18   };
19
20   $.fn.textcomplete = function (strategies, option) {
21     var args = Array.prototype.slice.call(arguments);
22     return this.each(function () {
23       var $this = $(this);
24       var completer = $this.data('textComplete');
25       if (!completer) {
26         completer = new $.fn.textcomplete.Completer(this, option || {});
27         $this.data('textComplete', completer);
28       }
29       if (typeof strategies === 'string') {
30         if (!completer) return;
31         args.shift()
32         completer[strategies].apply(completer, args);
33         if (strategies === 'destroy') {
34           $this.removeData('textComplete');
35         }
36       } else {
37         // For backward compatibility.
38         // TODO: Remove at v0.4
39         $.each(strategies, function (obj) {
40           $.each(['header', 'footer', 'placement', 'maxCount'], function (name) {
41             if (obj[name]) {
42               completer.option[name] = obj[name];
43               warn(name + 'as a strategy param is deprecated. Use option.');
44               delete obj[name];
45             }
46           });
47         });
48         completer.register($.fn.textcomplete.Strategy.parse(strategies));
49       }
50     });
51   };
52
53 }(jQuery);
54
55 +function ($) {
56   'use strict';
57
58   // Exclusive execution control utility.
59   //
60   // func - The function to be locked. It is executed with a function named
61   //        `free` as the first argument. Once it is called, additional
62   //        execution are ignored until the free is invoked. Then the last
63   //        ignored execution will be replayed immediately.
64   //
65   // Examples
66   //
67   //   var lockedFunc = lock(function (free) {
68   //     setTimeout(function { free(); }, 1000); // It will be free in 1 sec.
69   //     console.log('Hello, world');
70   //   });
71   //   lockedFunc();  // => 'Hello, world'
72   //   lockedFunc();  // none
73   //   lockedFunc();  // none
74   //   // 1 sec past then
75   //   // => 'Hello, world'
76   //   lockedFunc();  // => 'Hello, world'
77   //   lockedFunc();  // none
78   //
79   // Returns a wrapped function.
80   var lock = function (func) {
81     var locked, queuedArgsToReplay;
82
83     return function () {
84       // Convert arguments into a real array.
85       var args = Array.prototype.slice.call(arguments);
86       if (locked) {
87         // Keep a copy of this argument list to replay later.
88         // OK to overwrite a previous value because we only replay
89         // the last one.
90         queuedArgsToReplay = args;
91         return;
92       }
93       locked = true;
94       var self = this;
95       args.unshift(function replayOrFree() {
96         if (queuedArgsToReplay) {
97           // Other request(s) arrived while we were locked.
98           // Now that the lock is becoming available, replay
99           // the latest such request, then call back here to
100           // unlock (or replay another request that arrived
101           // while this one was in flight).
102           var replayArgs = queuedArgsToReplay;
103           queuedArgsToReplay = undefined;
104           replayArgs.unshift(replayOrFree);
105           func.apply(self, replayArgs);
106         } else {
107           locked = false;
108         }
109       });
110       func.apply(this, args);
111     };
112   };
113
114   var isString = function (obj) {
115     return Object.prototype.toString.call(obj) === '[object String]';
116   };
117
118   var uniqueId = 0;
119
120   function Completer(element, option) {
121     this.$el        = $(element);
122     this.id         = 'textcomplete' + uniqueId++;
123     this.strategies = [];
124     this.views      = [];
125     this.option     = $.extend({}, Completer._getDefaults(), option);
126
127     if (!this.$el.is('input[type=text]') && !this.$el.is('textarea') && !element.isContentEditable && element.contentEditable != 'true') {
128       throw new Error('textcomplete must be called on a Textarea or a ContentEditable.');
129     }
130
131     if (element === document.activeElement) {
132       // element has already been focused. Initialize view objects immediately.
133       this.initialize()
134     } else {
135       // Initialize view objects lazily.
136       var self = this;
137       this.$el.one('focus.' + this.id, function () { self.initialize(); });
138     }
139   }
140
141   Completer._getDefaults = function () {
142     if (!Completer.DEFAULTS) {
143       Completer.DEFAULTS = {
144         appendTo: $('body'),
145         zIndex: '100'
146       };
147     }
148
149     return Completer.DEFAULTS;
150   }
151
152   $.extend(Completer.prototype, {
153     // Public properties
154     // -----------------
155
156     id:         null,
157     option:     null,
158     strategies: null,
159     adapter:    null,
160     dropdown:   null,
161     $el:        null,
162
163     // Public methods
164     // --------------
165
166     initialize: function () {
167       var element = this.$el.get(0);
168       // Initialize view objects.
169       this.dropdown = new $.fn.textcomplete.Dropdown(element, this, this.option);
170       var Adapter, viewName;
171       if (this.option.adapter) {
172         Adapter = this.option.adapter;
173       } else {
174         if (this.$el.is('textarea') || this.$el.is('input[type=text]')) {
175           viewName = typeof element.selectionEnd === 'number' ? 'Textarea' : 'IETextarea';
176         } else {
177           viewName = 'ContentEditable';
178         }
179         Adapter = $.fn.textcomplete[viewName];
180       }
181       this.adapter = new Adapter(element, this, this.option);
182     },
183
184     destroy: function () {
185       this.$el.off('.' + this.id);
186       if (this.adapter) {
187         this.adapter.destroy();
188       }
189       if (this.dropdown) {
190         this.dropdown.destroy();
191       }
192       this.$el = this.adapter = this.dropdown = null;
193     },
194
195     // Invoke textcomplete.
196     trigger: function (text, skipUnchangedTerm) {
197       if (!this.dropdown) { this.initialize(); }
198       text != null || (text = this.adapter.getTextFromHeadToCaret());
199       var searchQuery = this._extractSearchQuery(text);
200       if (searchQuery.length) {
201         var term = searchQuery[1];
202         // Ignore shift-key, ctrl-key and so on.
203         if (skipUnchangedTerm && this._term === term) { return; }
204         this._term = term;
205         this._search.apply(this, searchQuery);
206       } else {
207         this._term = null;
208         this.dropdown.deactivate();
209       }
210     },
211
212     fire: function (eventName) {
213       var args = Array.prototype.slice.call(arguments, 1);
214       this.$el.trigger(eventName, args);
215       return this;
216     },
217
218     register: function (strategies) {
219       Array.prototype.push.apply(this.strategies, strategies);
220     },
221
222     // Insert the value into adapter view. It is called when the dropdown is clicked
223     // or selected.
224     //
225     // value    - The selected element of the array callbacked from search func.
226     // strategy - The Strategy object.
227     select: function (value, strategy) {
228       this.adapter.select(value, strategy);
229       this.fire('change').fire('textComplete:select', value, strategy);
230       this.adapter.focus();
231     },
232
233     // Private properties
234     // ------------------
235
236     _clearAtNext: true,
237     _term:        null,
238
239     // Private methods
240     // ---------------
241
242     // Parse the given text and extract the first matching strategy.
243     //
244     // Returns an array including the strategy, the query term and the match
245     // object if the text matches an strategy; otherwise returns an empty array.
246     _extractSearchQuery: function (text) {
247       for (var i = 0; i < this.strategies.length; i++) {
248         var strategy = this.strategies[i];
249         var context = strategy.context(text);
250         if (context || context === '') {
251           if (isString(context)) { text = context; }
252           var match = text.match(strategy.match);
253           if (match) { return [strategy, match[strategy.index], match]; }
254         }
255       }
256       return []
257     },
258
259     // Call the search method of selected strategy..
260     _search: lock(function (free, strategy, term, match) {
261       var self = this;
262       strategy.search(term, function (data, stillSearching) {
263         if (!self.dropdown.shown) {
264           self.dropdown.activate();
265           self.dropdown.setPosition(self.adapter.getCaretPosition());
266         }
267         if (self._clearAtNext) {
268           // The first callback in the current lock.
269           self.dropdown.clear();
270           self._clearAtNext = false;
271         }
272         self.dropdown.render(self._zip(data, strategy));
273         if (!stillSearching) {
274           // The last callback in the current lock.
275           free();
276           self._clearAtNext = true; // Call dropdown.clear at the next time.
277         }
278       }, match);
279     }),
280
281     // Build a parameter for Dropdown#render.
282     //
283     // Examples
284     //
285     //  this._zip(['a', 'b'], 's');
286     //  //=> [{ value: 'a', strategy: 's' }, { value: 'b', strategy: 's' }]
287     _zip: function (data, strategy) {
288       return $.map(data, function (value) {
289         return { value: value, strategy: strategy };
290       });
291     }
292   });
293
294   $.fn.textcomplete.Completer = Completer;
295 }(jQuery);
296
297 +function ($) {
298   'use strict';
299
300   var include = function (zippedData, datum) {
301     var i, elem;
302     var idProperty = datum.strategy.idProperty
303     for (i = 0; i < zippedData.length; i++) {
304       elem = zippedData[i];
305       if (elem.strategy !== datum.strategy) continue;
306       if (idProperty) {
307         if (elem.value[idProperty] === datum.value[idProperty]) return true;
308       } else {
309         if (elem.value === datum.value) return true;
310       }
311     }
312     return false;
313   };
314
315   var dropdownViews = {};
316   $(document).on('click', function (e) {
317     var id = e.originalEvent && e.originalEvent.keepTextCompleteDropdown;
318     $.each(dropdownViews, function (key, view) {
319       if (key !== id) { view.deactivate(); }
320     });
321   });
322
323   // Dropdown view
324   // =============
325
326   // Construct Dropdown object.
327   //
328   // element - Textarea or contenteditable element.
329   function Dropdown(element, completer, option) {
330     this.$el       = Dropdown.findOrCreateElement(option);
331     this.completer = completer;
332     this.id        = completer.id + 'dropdown';
333     this._data     = []; // zipped data.
334     this.$inputEl  = $(element);
335     this.option    = option;
336
337     // Override setPosition method.
338     if (option.listPosition) { this.setPosition = option.listPosition; }
339     if (option.height) { this.$el.height(option.height); }
340     var self = this;
341     $.each(['maxCount', 'placement', 'footer', 'header', 'className'], function (_i, name) {
342       if (option[name] != null) { self[name] = option[name]; }
343     });
344     this._bindEvents(element);
345     dropdownViews[this.id] = this;
346   }
347
348   $.extend(Dropdown, {
349     // Class methods
350     // -------------
351
352     findOrCreateElement: function (option) {
353       var $parent = option.appendTo;
354       if (!($parent instanceof $)) { $parent = $($parent); }
355       var $el = $parent.children('.dropdown-menu')
356       if (!$el.length) {
357         $el = $('<ul class="dropdown-menu"></ul>').css({
358           display: 'none',
359           left: 0,
360           position: 'absolute',
361           zIndex: option.zIndex
362         }).appendTo($parent);
363       }
364       return $el;
365     }
366   });
367
368   $.extend(Dropdown.prototype, {
369     // Public properties
370     // -----------------
371
372     $el:       null,  // jQuery object of ul.dropdown-menu element.
373     $inputEl:  null,  // jQuery object of target textarea.
374     completer: null,
375     footer:    null,
376     header:    null,
377     id:        null,
378     maxCount:  10,
379     placement: '',
380     shown:     false,
381     data:      [],     // Shown zipped data.
382     className: '',
383
384     // Public methods
385     // --------------
386
387     destroy: function () {
388       // Don't remove $el because it may be shared by several textcompletes.
389       this.deactivate();
390
391       this.$el.off('.' + this.id);
392       this.$inputEl.off('.' + this.id);
393       this.clear();
394       this.$el = this.$inputEl = this.completer = null;
395       delete dropdownViews[this.id]
396     },
397
398     render: function (zippedData) {
399       var contentsHtml = this._buildContents(zippedData);
400       var unzippedData = $.map(this.data, function (d) { return d.value; });
401       if (this.data.length) {
402         this._renderHeader(unzippedData);
403         this._renderFooter(unzippedData);
404         if (contentsHtml) {
405           this._renderContents(contentsHtml);
406           this._activateIndexedItem();
407         }
408         this._setScroll();
409       } else if (this.shown) {
410         this.deactivate();
411       }
412     },
413
414     setPosition: function (position) {
415       this.$el.css(this._applyPlacement(position));
416
417       // Make the dropdown fixed if the input is also fixed
418       // This can't be done during init, as textcomplete may be used on multiple elements on the same page
419       // Because the same dropdown is reused behind the scenes, we need to recheck every time the dropdown is showed
420       var position = 'absolute';
421       // Check if input or one of its parents has positioning we need to care about
422       this.$inputEl.add(this.$inputEl.parents()).each(function() { 
423         if($(this).css('position') === 'absolute') // The element has absolute positioning, so it's all OK
424           return false;
425         if($(this).css('position') === 'fixed') {
426           position = 'fixed';
427           return false;
428         }
429       });
430       this.$el.css({ position: position }); // Update positioning
431
432       return this;
433     },
434
435     clear: function () {
436       this.$el.html('');
437       this.data = [];
438       this._index = 0;
439       this._$header = this._$footer = null;
440     },
441
442     activate: function () {
443       if (!this.shown) {
444         this.clear();
445         this.$el.show();
446         if (this.className) { this.$el.addClass(this.className); }
447         this.completer.fire('textComplete:show');
448         this.shown = true;
449       }
450       return this;
451     },
452
453     deactivate: function () {
454       if (this.shown) {
455         this.$el.hide();
456         if (this.className) { this.$el.removeClass(this.className); }
457         this.completer.fire('textComplete:hide');
458         this.shown = false;
459       }
460       return this;
461     },
462
463     isUp: function (e) {
464       return e.keyCode === 38 || (e.ctrlKey && e.keyCode === 80);  // UP, Ctrl-P
465     },
466
467     isDown: function (e) {
468       return e.keyCode === 40 || (e.ctrlKey && e.keyCode === 78);  // DOWN, Ctrl-N
469     },
470
471     isEnter: function (e) {
472       var modifiers = e.ctrlKey || e.altKey || e.metaKey || e.shiftKey;
473       return !modifiers && (e.keyCode === 13 || e.keyCode === 9 || (this.option.completeOnSpace === true && e.keyCode === 32))  // ENTER, TAB
474     },
475
476     isPageup: function (e) {
477       return e.keyCode === 33;  // PAGEUP
478     },
479
480     isPagedown: function (e) {
481       return e.keyCode === 34;  // PAGEDOWN
482     },
483
484     // Private properties
485     // ------------------
486
487     _data:    null,  // Currently shown zipped data.
488     _index:   null,
489     _$header: null,
490     _$footer: null,
491
492     // Private methods
493     // ---------------
494
495     _bindEvents: function () {
496       this.$el.on('mousedown.' + this.id, '.textcomplete-item', $.proxy(this._onClick, this))
497       this.$el.on('mouseover.' + this.id, '.textcomplete-item', $.proxy(this._onMouseover, this));
498       this.$inputEl.on('keydown.' + this.id, $.proxy(this._onKeydown, this));
499     },
500
501     _onClick: function (e) {
502       var $el = $(e.target);
503       e.preventDefault();
504       e.originalEvent.keepTextCompleteDropdown = this.id;
505       if (!$el.hasClass('textcomplete-item')) {
506         $el = $el.closest('.textcomplete-item');
507       }
508       var datum = this.data[parseInt($el.data('index'), 10)];
509       this.completer.select(datum.value, datum.strategy);
510       var self = this;
511       // Deactive at next tick to allow other event handlers to know whether
512       // the dropdown has been shown or not.
513       setTimeout(function () { self.deactivate(); }, 0);
514     },
515
516     // Activate hovered item.
517     _onMouseover: function (e) {
518       var $el = $(e.target);
519       e.preventDefault();
520       if (!$el.hasClass('textcomplete-item')) {
521         $el = $el.closest('.textcomplete-item');
522       }
523       this._index = parseInt($el.data('index'), 10);
524       this._activateIndexedItem();
525     },
526
527     _onKeydown: function (e) {
528       if (!this.shown) { return; }
529       if (this.isUp(e)) {
530         e.preventDefault();
531         this._up();
532       } else if (this.isDown(e)) {
533         e.preventDefault();
534         this._down();
535       } else if (this.isEnter(e)) {
536         e.preventDefault();
537         this._enter();
538       } else if (this.isPageup(e)) {
539         e.preventDefault();
540         this._pageup();
541       } else if (this.isPagedown(e)) {
542         e.preventDefault();
543         this._pagedown();
544       }
545     },
546
547     _up: function () {
548       if (this._index === 0) {
549         this._index = this.data.length - 1;
550       } else {
551         this._index -= 1;
552       }
553       this._activateIndexedItem();
554       this._setScroll();
555     },
556
557     _down: function () {
558       if (this._index === this.data.length - 1) {
559         this._index = 0;
560       } else {
561         this._index += 1;
562       }
563       this._activateIndexedItem();
564       this._setScroll();
565     },
566
567     _enter: function () {
568       var datum = this.data[parseInt(this._getActiveElement().data('index'), 10)];
569       this.completer.select(datum.value, datum.strategy);
570       this._setScroll();
571     },
572
573     _pageup: function () {
574       var target = 0;
575       var threshold = this._getActiveElement().position().top - this.$el.innerHeight();
576       this.$el.children().each(function (i) {
577         if ($(this).position().top + $(this).outerHeight() > threshold) {
578           target = i;
579           return false;
580         }
581       });
582       this._index = target;
583       this._activateIndexedItem();
584       this._setScroll();
585     },
586
587     _pagedown: function () {
588       var target = this.data.length - 1;
589       var threshold = this._getActiveElement().position().top + this.$el.innerHeight();
590       this.$el.children().each(function (i) {
591         if ($(this).position().top > threshold) {
592           target = i;
593           return false
594         }
595       });
596       this._index = target;
597       this._activateIndexedItem();
598       this._setScroll();
599     },
600
601     _activateIndexedItem: function () {
602       this.$el.find('.textcomplete-item.active').removeClass('active');
603       this._getActiveElement().addClass('active');
604     },
605
606     _getActiveElement: function () {
607       return this.$el.children('.textcomplete-item:nth(' + this._index + ')');
608     },
609
610     _setScroll: function () {
611       var $activeEl = this._getActiveElement();
612       var itemTop = $activeEl.position().top;
613       var itemHeight = $activeEl.outerHeight();
614       var visibleHeight = this.$el.innerHeight();
615       var visibleTop = this.$el.scrollTop();
616       if (this._index === 0 || this._index == this.data.length - 1 || itemTop < 0) {
617         this.$el.scrollTop(itemTop + visibleTop);
618       } else if (itemTop + itemHeight > visibleHeight) {
619         this.$el.scrollTop(itemTop + itemHeight + visibleTop - visibleHeight);
620       }
621     },
622
623     _buildContents: function (zippedData) {
624       var datum, i, index;
625       var html = '';
626       for (i = 0; i < zippedData.length; i++) {
627         if (this.data.length === this.maxCount) break;
628         datum = zippedData[i];
629         if (include(this.data, datum)) { continue; }
630         index = this.data.length;
631         this.data.push(datum);
632         html += '<li class="textcomplete-item" data-index="' + index + '"><a>';
633         html +=   datum.strategy.template(datum.value);
634         html += '</a></li>';
635       }
636       return html;
637     },
638
639     _renderHeader: function (unzippedData) {
640       if (this.header) {
641         if (!this._$header) {
642           this._$header = $('<li class="textcomplete-header"></li>').prependTo(this.$el);
643         }
644         var html = $.isFunction(this.header) ? this.header(unzippedData) : this.header;
645         this._$header.html(html);
646       }
647     },
648
649     _renderFooter: function (unzippedData) {
650       if (this.footer) {
651         if (!this._$footer) {
652           this._$footer = $('<li class="textcomplete-footer"></li>').appendTo(this.$el);
653         }
654         var html = $.isFunction(this.footer) ? this.footer(unzippedData) : this.footer;
655         this._$footer.html(html);
656       }
657     },
658
659     _renderContents: function (html) {
660       if (this._$footer) {
661         this._$footer.before(html);
662       } else {
663         this.$el.append(html);
664       }
665     },
666
667     _applyPlacement: function (position) { 
668       // If the 'placement' option set to 'top', move the position above the element.
669       if (this.placement.indexOf('top') !== -1) {
670         // Overwrite the position object to set the 'bottom' property instead of the top.
671         position = {
672           top: 'auto',
673           bottom: this.$el.parent().height() - position.top + position.lineHeight,
674           left: position.left
675         };
676       } else {
677         position.bottom = 'auto';
678         delete position.lineHeight;
679       }
680       if (this.placement.indexOf('absleft') !== -1) {
681         position.left = 0;
682       } else if (this.placement.indexOf('absright') !== -1) {
683         position.right = 0;
684         position.left = 'auto';
685       }
686       return position;
687     }
688   });
689
690   $.fn.textcomplete.Dropdown = Dropdown;
691 }(jQuery);
692
693 +function ($) {
694   'use strict';
695
696   // Memoize a search function.
697   var memoize = function (func) {
698     var memo = {};
699     return function (term, callback) {
700       if (memo[term]) {
701         callback(memo[term]);
702       } else {
703         func.call(this, term, function (data) {
704           memo[term] = (memo[term] || []).concat(data);
705           callback.apply(null, arguments);
706         });
707       }
708     };
709   };
710
711   function Strategy(options) {
712     $.extend(this, options);
713     if (this.cache) { this.search = memoize(this.search); }
714   }
715
716   Strategy.parse = function (optionsArray) {
717     return $.map(optionsArray, function (options) {
718       return new Strategy(options);
719     });
720   };
721
722   $.extend(Strategy.prototype, {
723     // Public properties
724     // -----------------
725
726     // Required
727     match:      null,
728     replace:    null,
729     search:     null,
730
731     // Optional
732     cache:      false,
733     context:    function () { return true; },
734     index:      2,
735     template:   function (obj) { return obj; },
736     idProperty: null
737   });
738
739   $.fn.textcomplete.Strategy = Strategy;
740
741 }(jQuery);
742
743 +function ($) {
744   'use strict';
745
746   var now = Date.now || function () { return new Date().getTime(); };
747
748   // Returns a function, that, as long as it continues to be invoked, will not
749   // be triggered. The function will be called after it stops being called for
750   // `wait` msec.
751   //
752   // This utility function was originally implemented at Underscore.js.
753   var debounce = function (func, wait) {
754     var timeout, args, context, timestamp, result;
755     var later = function () {
756       var last = now() - timestamp;
757       if (last < wait) {
758         timeout = setTimeout(later, wait - last);
759       } else {
760         timeout = null;
761         result = func.apply(context, args);
762         context = args = null;
763       }
764     };
765
766     return function () {
767       context = this;
768       args = arguments;
769       timestamp = now();
770       if (!timeout) {
771         timeout = setTimeout(later, wait);
772       }
773       return result;
774     };
775   };
776
777   function Adapter () {}
778
779   $.extend(Adapter.prototype, {
780     // Public properties
781     // -----------------
782
783     id:        null, // Identity.
784     completer: null, // Completer object which creates it.
785     el:        null, // Textarea element.
786     $el:       null, // jQuery object of the textarea.
787     option:    null,
788
789     // Public methods
790     // --------------
791
792     initialize: function (element, completer, option) {
793       this.el        = element;
794       this.$el       = $(element);
795       this.id        = completer.id + this.constructor.name;
796       this.completer = completer;
797       this.option    = option;
798
799       if (this.option.debounce) {
800         this._onKeyup = debounce(this._onKeyup, this.option.debounce);
801       }
802
803       this._bindEvents();
804     },
805
806     destroy: function () {
807       this.$el.off('.' + this.id); // Remove all event handlers.
808       this.$el = this.el = this.completer = null;
809     },
810
811     // Update the element with the given value and strategy.
812     //
813     // value    - The selected object. It is one of the item of the array
814     //            which was callbacked from the search function.
815     // strategy - The Strategy associated with the selected value.
816     select: function (/* value, strategy */) {
817       throw new Error('Not implemented');
818     },
819
820     // Returns the caret's relative coordinates from body's left top corner.
821     //
822     // FIXME: Calculate the left top corner of `this.option.appendTo` element.
823     getCaretPosition: function () {
824       var position = this._getCaretRelativePosition();
825       var offset = this.$el.offset();
826       position.top += offset.top;
827       position.left += offset.left;
828       return position;
829     },
830
831     // Focus on the element.
832     focus: function () {
833       this.$el.focus();
834     },
835
836     // Private methods
837     // ---------------
838
839     _bindEvents: function () {
840       this.$el.on('keyup.' + this.id, $.proxy(this._onKeyup, this));
841     },
842
843     _onKeyup: function (e) {
844       if (this._skipSearch(e)) { return; }
845       this.completer.trigger(this.getTextFromHeadToCaret(), true);
846     },
847
848     // Suppress searching if it returns true.
849     _skipSearch: function (clickEvent) {
850       switch (clickEvent.keyCode) {
851         case 40: // DOWN
852         case 38: // UP
853           return true;
854       }
855       if (clickEvent.ctrlKey) switch (clickEvent.keyCode) {
856         case 78: // Ctrl-N
857         case 80: // Ctrl-P
858           return true;
859       }
860     }
861   });
862
863   $.fn.textcomplete.Adapter = Adapter;
864 }(jQuery);
865
866 +function ($) {
867   'use strict';
868
869   // Textarea adapter
870   // ================
871   //
872   // Managing a textarea. It doesn't know a Dropdown.
873   function Textarea(element, completer, option) {
874     this.initialize(element, completer, option);
875   }
876
877   Textarea.DIV_PROPERTIES = {
878     left: -9999,
879     position: 'absolute',
880     top: 0,
881     whiteSpace: 'pre-wrap'
882   }
883
884   Textarea.COPY_PROPERTIES = [
885     'border-width', 'font-family', 'font-size', 'font-style', 'font-variant',
886     'font-weight', 'height', 'letter-spacing', 'word-spacing', 'line-height',
887     'text-decoration', 'text-align', 'width', 'padding-top', 'padding-right',
888     'padding-bottom', 'padding-left', 'margin-top', 'margin-right',
889     'margin-bottom', 'margin-left', 'border-style', 'box-sizing', 'tab-size'
890   ];
891
892   $.extend(Textarea.prototype, $.fn.textcomplete.Adapter.prototype, {
893     // Public methods
894     // --------------
895
896     // Update the textarea with the given value and strategy.
897     select: function (value, strategy) {
898       var pre = this.getTextFromHeadToCaret();
899       var post = this.el.value.substring(this.el.selectionEnd);
900       var newSubstr = strategy.replace(value);
901       if ($.isArray(newSubstr)) {
902         post = newSubstr[1] + post;
903         newSubstr = newSubstr[0];
904       }
905       pre = pre.replace(strategy.match, newSubstr);
906       this.$el.val(pre + post);
907       this.el.selectionStart = this.el.selectionEnd = pre.length;
908     },
909
910     // Private methods
911     // ---------------
912
913     // Returns the caret's relative coordinates from textarea's left top corner.
914     //
915     // Browser native API does not provide the way to know the position of
916     // caret in pixels, so that here we use a kind of hack to accomplish
917     // the aim. First of all it puts a dummy div element and completely copies
918     // the textarea's style to the element, then it inserts the text and a
919     // span element into the textarea.
920     // Consequently, the span element's position is the thing what we want.
921     _getCaretRelativePosition: function () {
922       var dummyDiv = $('<div></div>').css(this._copyCss())
923         .text(this.getTextFromHeadToCaret());
924       var span = $('<span></span>').text('.').appendTo(dummyDiv);
925       this.$el.before(dummyDiv);
926       var position = span.position();
927       position.top += span.height() - this.$el.scrollTop();
928       position.lineHeight = span.height();
929       dummyDiv.remove();
930       return position;
931     },
932
933     _copyCss: function () {
934       return $.extend({
935         // Set 'scroll' if a scrollbar is being shown; otherwise 'auto'.
936         overflow: this.el.scrollHeight > this.el.offsetHeight ? 'scroll' : 'auto'
937       }, Textarea.DIV_PROPERTIES, this._getStyles());
938     },
939
940     _getStyles: (function ($) {
941       var color = $('<div></div>').css(['color']).color;
942       if (typeof color !== 'undefined') {
943         return function () {
944           return this.$el.css(Textarea.COPY_PROPERTIES);
945         };
946       } else { // jQuery < 1.8
947         return function () {
948           var $el = this.$el;
949           var styles = {};
950           $.each(Textarea.COPY_PROPERTIES, function (i, property) {
951             styles[property] = $el.css(property);
952           });
953           return styles;
954         };
955       }
956     })($),
957
958     getTextFromHeadToCaret: function () {
959       return this.el.value.substring(0, this.el.selectionEnd);
960     }
961   });
962
963   $.fn.textcomplete.Textarea = Textarea;
964 }(jQuery);
965
966 +function ($) {
967   'use strict';
968
969   var sentinelChar = '吶';
970
971   function IETextarea(element, completer, option) {
972     this.initialize(element, completer, option);
973     $('<span>' + sentinelChar + '</span>').css({
974       position: 'absolute',
975       top: -9999,
976       left: -9999
977     }).insertBefore(element);
978   }
979
980   $.extend(IETextarea.prototype, $.fn.textcomplete.Textarea.prototype, {
981     // Public methods
982     // --------------
983
984     select: function (value, strategy) {
985       var pre = this.getTextFromHeadToCaret();
986       var post = this.el.value.substring(pre.length);
987       var newSubstr = strategy.replace(value);
988       if ($.isArray(newSubstr)) {
989         post = newSubstr[1] + post;
990         newSubstr = newSubstr[0];
991       }
992       pre = pre.replace(strategy.match, newSubstr);
993       this.$el.val(pre + post);
994       this.el.focus();
995       var range = this.el.createTextRange();
996       range.collapse(true);
997       range.moveEnd('character', pre.length);
998       range.moveStart('character', pre.length);
999       range.select();
1000     },
1001
1002     getTextFromHeadToCaret: function () {
1003       this.el.focus();
1004       var range = document.selection.createRange();
1005       range.moveStart('character', -this.el.value.length);
1006       var arr = range.text.split(sentinelChar)
1007       return arr.length === 1 ? arr[0] : arr[1];
1008     }
1009   });
1010
1011   $.fn.textcomplete.IETextarea = IETextarea;
1012 }(jQuery);
1013
1014 // NOTE: TextComplete plugin has contenteditable support but it does not work
1015 //       fine especially on old IEs.
1016 //       Any pull requests are REALLY welcome.
1017
1018 +function ($) {
1019   'use strict';
1020
1021   // ContentEditable adapter
1022   // =======================
1023   //
1024   // Adapter for contenteditable elements.
1025   function ContentEditable (element, completer, option) {
1026     this.initialize(element, completer, option);
1027   }
1028
1029   $.extend(ContentEditable.prototype, $.fn.textcomplete.Adapter.prototype, {
1030     // Public methods
1031     // --------------
1032
1033     // Update the content with the given value and strategy.
1034     // When an dropdown item is selected, it is executed.
1035     select: function (value, strategy) {
1036       var pre = this.getTextFromHeadToCaret();
1037       var sel = window.getSelection()
1038       var range = sel.getRangeAt(0);
1039       var selection = range.cloneRange();
1040       selection.selectNodeContents(range.startContainer);
1041       var content = selection.toString();
1042       var post = content.substring(range.startOffset);
1043       var newSubstr = strategy.replace(value);
1044       if ($.isArray(newSubstr)) {
1045         post = newSubstr[1] + post;
1046         newSubstr = newSubstr[0];
1047       }
1048       pre = pre.replace(strategy.match, newSubstr);
1049       range.selectNodeContents(range.startContainer);
1050       range.deleteContents();
1051       var node = document.createTextNode(pre + post);
1052       range.insertNode(node);
1053       range.setStart(node, pre.length);
1054       range.collapse(true);
1055       sel.removeAllRanges();
1056       sel.addRange(range);
1057     },
1058
1059     // Private methods
1060     // ---------------
1061
1062     // Returns the caret's relative position from the contenteditable's
1063     // left top corner.
1064     //
1065     // Examples
1066     //
1067     //   this._getCaretRelativePosition()
1068     //   //=> { top: 18, left: 200, lineHeight: 16 }
1069     //
1070     // Dropdown's position will be decided using the result.
1071     _getCaretRelativePosition: function () {
1072       var range = window.getSelection().getRangeAt(0).cloneRange();
1073       var node = document.createElement('span');
1074       range.insertNode(node);
1075       range.selectNodeContents(node);
1076       range.deleteContents();
1077       var $node = $(node);
1078       var position = $node.offset();
1079       position.left -= this.$el.offset().left;
1080       position.top += $node.height() - this.$el.offset().top;
1081       position.lineHeight = $node.height();
1082       var dir = this.$el.attr('dir') || this.$el.css('direction');
1083       if (dir === 'rtl') { position.left -= this.listView.$el.width(); }
1084       return position;
1085     },
1086
1087     // Returns the string between the first character and the caret.
1088     // Completer will be triggered with the result for start autocompleting.
1089     //
1090     // Example
1091     //
1092     //   // Suppose the html is '<b>hello</b> wor|ld' and | is the caret.
1093     //   this.getTextFromHeadToCaret()
1094     //   // => ' wor'  // not '<b>hello</b> wor'
1095     getTextFromHeadToCaret: function () {
1096       var range = window.getSelection().getRangeAt(0);
1097       var selection = range.cloneRange();
1098       selection.selectNodeContents(range.startContainer);
1099       return selection.toString().substring(0, range.startOffset);
1100     }
1101   });
1102
1103   $.fn.textcomplete.ContentEditable = ContentEditable;
1104 }(jQuery);