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
9 if (typeof jQuery === 'undefined') {
10 throw new Error('jQuery.textcomplete requires jQuery');
16 var warn = function (message) {
17 if (console.warn) { console.warn(message); }
20 $.fn.textcomplete = function (strategies, option) {
21 var args = Array.prototype.slice.call(arguments);
22 return this.each(function () {
24 var completer = $this.data('textComplete');
26 completer = new $.fn.textcomplete.Completer(this, option || {});
27 $this.data('textComplete', completer);
29 if (typeof strategies === 'string') {
30 if (!completer) return;
32 completer[strategies].apply(completer, args);
33 if (strategies === 'destroy') {
34 $this.removeData('textComplete');
37 // For backward compatibility.
38 // TODO: Remove at v0.4
39 $.each(strategies, function (obj) {
40 $.each(['header', 'footer', 'placement', 'maxCount'], function (name) {
42 completer.option[name] = obj[name];
43 warn(name + 'as a strategy param is deprecated. Use option.');
48 completer.register($.fn.textcomplete.Strategy.parse(strategies));
58 // Exclusive execution control utility.
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.
67 // var lockedFunc = lock(function (free) {
68 // setTimeout(function { free(); }, 1000); // It will be free in 1 sec.
69 // console.log('Hello, world');
71 // lockedFunc(); // => 'Hello, world'
72 // lockedFunc(); // none
73 // lockedFunc(); // none
75 // // => 'Hello, world'
76 // lockedFunc(); // => 'Hello, world'
77 // lockedFunc(); // none
79 // Returns a wrapped function.
80 var lock = function (func) {
81 var locked, queuedArgsToReplay;
84 // Convert arguments into a real array.
85 var args = Array.prototype.slice.call(arguments);
87 // Keep a copy of this argument list to replay later.
88 // OK to overwrite a previous value because we only replay
90 queuedArgsToReplay = args;
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);
110 func.apply(this, args);
114 var isString = function (obj) {
115 return Object.prototype.toString.call(obj) === '[object String]';
120 function Completer(element, option) {
121 this.$el = $(element);
122 this.id = 'textcomplete' + uniqueId++;
123 this.strategies = [];
125 this.option = $.extend({}, Completer._getDefaults(), option);
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.');
131 if (element === document.activeElement) {
132 // element has already been focused. Initialize view objects immediately.
135 // Initialize view objects lazily.
137 this.$el.one('focus.' + this.id, function () { self.initialize(); });
141 Completer._getDefaults = function () {
142 if (!Completer.DEFAULTS) {
143 Completer.DEFAULTS = {
149 return Completer.DEFAULTS;
152 $.extend(Completer.prototype, {
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;
174 if (this.$el.is('textarea') || this.$el.is('input[type=text]')) {
175 viewName = typeof element.selectionEnd === 'number' ? 'Textarea' : 'IETextarea';
177 viewName = 'ContentEditable';
179 Adapter = $.fn.textcomplete[viewName];
181 this.adapter = new Adapter(element, this, this.option);
184 destroy: function () {
185 this.$el.off('.' + this.id);
187 this.adapter.destroy();
190 this.dropdown.destroy();
192 this.$el = this.adapter = this.dropdown = null;
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; }
205 this._search.apply(this, searchQuery);
208 this.dropdown.deactivate();
212 fire: function (eventName) {
213 var args = Array.prototype.slice.call(arguments, 1);
214 this.$el.trigger(eventName, args);
218 register: function (strategies) {
219 Array.prototype.push.apply(this.strategies, strategies);
222 // Insert the value into adapter view. It is called when the dropdown is clicked
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();
233 // Private properties
234 // ------------------
242 // Parse the given text and extract the first matching strategy.
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]; }
259 // Call the search method of selected strategy..
260 _search: lock(function (free, strategy, term, match) {
262 strategy.search(term, function (data, stillSearching) {
263 if (!self.dropdown.shown) {
264 self.dropdown.activate();
265 self.dropdown.setPosition(self.adapter.getCaretPosition());
267 if (self._clearAtNext) {
268 // The first callback in the current lock.
269 self.dropdown.clear();
270 self._clearAtNext = false;
272 self.dropdown.render(self._zip(data, strategy));
273 if (!stillSearching) {
274 // The last callback in the current lock.
276 self._clearAtNext = true; // Call dropdown.clear at the next time.
281 // Build a parameter for Dropdown#render.
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 };
294 $.fn.textcomplete.Completer = Completer;
300 var include = function (zippedData, datum) {
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;
307 if (elem.value[idProperty] === datum.value[idProperty]) return true;
309 if (elem.value === datum.value) return true;
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(); }
326 // Construct Dropdown object.
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;
337 // Override setPosition method.
338 if (option.listPosition) { this.setPosition = option.listPosition; }
339 if (option.height) { this.$el.height(option.height); }
341 $.each(['maxCount', 'placement', 'footer', 'header', 'className'], function (_i, name) {
342 if (option[name] != null) { self[name] = option[name]; }
344 this._bindEvents(element);
345 dropdownViews[this.id] = this;
352 findOrCreateElement: function (option) {
353 var $parent = option.appendTo;
354 if (!($parent instanceof $)) { $parent = $($parent); }
355 var $el = $parent.children('.dropdown-menu')
357 $el = $('<ul class="dropdown-menu"></ul>').css({
360 position: 'absolute',
361 zIndex: option.zIndex
362 }).appendTo($parent);
368 $.extend(Dropdown.prototype, {
372 $el: null, // jQuery object of ul.dropdown-menu element.
373 $inputEl: null, // jQuery object of target textarea.
381 data: [], // Shown zipped data.
387 destroy: function () {
388 // Don't remove $el because it may be shared by several textcompletes.
391 this.$el.off('.' + this.id);
392 this.$inputEl.off('.' + this.id);
394 this.$el = this.$inputEl = this.completer = null;
395 delete dropdownViews[this.id]
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);
405 this._renderContents(contentsHtml);
406 this._activateIndexedItem();
409 } else if (this.shown) {
414 setPosition: function (position) {
415 this.$el.css(this._applyPlacement(position));
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
425 if($(this).css('position') === 'fixed') {
430 this.$el.css({ position: position }); // Update positioning
439 this._$header = this._$footer = null;
442 activate: function () {
446 if (this.className) { this.$el.addClass(this.className); }
447 this.completer.fire('textComplete:show');
453 deactivate: function () {
456 if (this.className) { this.$el.removeClass(this.className); }
457 this.completer.fire('textComplete:hide');
464 return e.keyCode === 38 || (e.ctrlKey && e.keyCode === 80); // UP, Ctrl-P
467 isDown: function (e) {
468 return e.keyCode === 40 || (e.ctrlKey && e.keyCode === 78); // DOWN, Ctrl-N
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
476 isPageup: function (e) {
477 return e.keyCode === 33; // PAGEUP
480 isPagedown: function (e) {
481 return e.keyCode === 34; // PAGEDOWN
484 // Private properties
485 // ------------------
487 _data: null, // Currently shown zipped data.
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));
501 _onClick: function (e) {
502 var $el = $(e.target);
504 e.originalEvent.keepTextCompleteDropdown = this.id;
505 if (!$el.hasClass('textcomplete-item')) {
506 $el = $el.closest('.textcomplete-item');
508 var datum = this.data[parseInt($el.data('index'), 10)];
509 this.completer.select(datum.value, datum.strategy);
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);
516 // Activate hovered item.
517 _onMouseover: function (e) {
518 var $el = $(e.target);
520 if (!$el.hasClass('textcomplete-item')) {
521 $el = $el.closest('.textcomplete-item');
523 this._index = parseInt($el.data('index'), 10);
524 this._activateIndexedItem();
527 _onKeydown: function (e) {
528 if (!this.shown) { return; }
532 } else if (this.isDown(e)) {
535 } else if (this.isEnter(e)) {
538 } else if (this.isPageup(e)) {
541 } else if (this.isPagedown(e)) {
548 if (this._index === 0) {
549 this._index = this.data.length - 1;
553 this._activateIndexedItem();
558 if (this._index === this.data.length - 1) {
563 this._activateIndexedItem();
567 _enter: function () {
568 var datum = this.data[parseInt(this._getActiveElement().data('index'), 10)];
569 this.completer.select(datum.value, datum.strategy);
573 _pageup: function () {
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) {
582 this._index = target;
583 this._activateIndexedItem();
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) {
596 this._index = target;
597 this._activateIndexedItem();
601 _activateIndexedItem: function () {
602 this.$el.find('.textcomplete-item.active').removeClass('active');
603 this._getActiveElement().addClass('active');
606 _getActiveElement: function () {
607 return this.$el.children('.textcomplete-item:nth(' + this._index + ')');
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);
623 _buildContents: function (zippedData) {
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);
639 _renderHeader: function (unzippedData) {
641 if (!this._$header) {
642 this._$header = $('<li class="textcomplete-header"></li>').prependTo(this.$el);
644 var html = $.isFunction(this.header) ? this.header(unzippedData) : this.header;
645 this._$header.html(html);
649 _renderFooter: function (unzippedData) {
651 if (!this._$footer) {
652 this._$footer = $('<li class="textcomplete-footer"></li>').appendTo(this.$el);
654 var html = $.isFunction(this.footer) ? this.footer(unzippedData) : this.footer;
655 this._$footer.html(html);
659 _renderContents: function (html) {
661 this._$footer.before(html);
663 this.$el.append(html);
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.
673 bottom: this.$el.parent().height() - position.top + position.lineHeight,
677 position.bottom = 'auto';
678 delete position.lineHeight;
680 if (this.placement.indexOf('absleft') !== -1) {
682 } else if (this.placement.indexOf('absright') !== -1) {
684 position.left = 'auto';
690 $.fn.textcomplete.Dropdown = Dropdown;
696 // Memoize a search function.
697 var memoize = function (func) {
699 return function (term, callback) {
701 callback(memo[term]);
703 func.call(this, term, function (data) {
704 memo[term] = (memo[term] || []).concat(data);
705 callback.apply(null, arguments);
711 function Strategy(options) {
712 $.extend(this, options);
713 if (this.cache) { this.search = memoize(this.search); }
716 Strategy.parse = function (optionsArray) {
717 return $.map(optionsArray, function (options) {
718 return new Strategy(options);
722 $.extend(Strategy.prototype, {
733 context: function () { return true; },
735 template: function (obj) { return obj; },
739 $.fn.textcomplete.Strategy = Strategy;
746 var now = Date.now || function () { return new Date().getTime(); };
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
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;
758 timeout = setTimeout(later, wait - last);
761 result = func.apply(context, args);
762 context = args = null;
771 timeout = setTimeout(later, wait);
777 function Adapter () {}
779 $.extend(Adapter.prototype, {
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.
792 initialize: function (element, completer, option) {
794 this.$el = $(element);
795 this.id = completer.id + this.constructor.name;
796 this.completer = completer;
797 this.option = option;
799 if (this.option.debounce) {
800 this._onKeyup = debounce(this._onKeyup, this.option.debounce);
806 destroy: function () {
807 this.$el.off('.' + this.id); // Remove all event handlers.
808 this.$el = this.el = this.completer = null;
811 // Update the element with the given value and strategy.
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');
820 // Returns the caret's relative coordinates from body's left top corner.
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;
831 // Focus on the element.
839 _bindEvents: function () {
840 this.$el.on('keyup.' + this.id, $.proxy(this._onKeyup, this));
843 _onKeyup: function (e) {
844 if (this._skipSearch(e)) { return; }
845 this.completer.trigger(this.getTextFromHeadToCaret(), true);
848 // Suppress searching if it returns true.
849 _skipSearch: function (clickEvent) {
850 switch (clickEvent.keyCode) {
855 if (clickEvent.ctrlKey) switch (clickEvent.keyCode) {
863 $.fn.textcomplete.Adapter = Adapter;
872 // Managing a textarea. It doesn't know a Dropdown.
873 function Textarea(element, completer, option) {
874 this.initialize(element, completer, option);
877 Textarea.DIV_PROPERTIES = {
879 position: 'absolute',
881 whiteSpace: 'pre-wrap'
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'
892 $.extend(Textarea.prototype, $.fn.textcomplete.Adapter.prototype, {
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];
905 pre = pre.replace(strategy.match, newSubstr);
906 this.$el.val(pre + post);
907 this.el.selectionStart = this.el.selectionEnd = pre.length;
913 // Returns the caret's relative coordinates from textarea's left top corner.
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();
933 _copyCss: function () {
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());
940 _getStyles: (function ($) {
941 var color = $('<div></div>').css(['color']).color;
942 if (typeof color !== 'undefined') {
944 return this.$el.css(Textarea.COPY_PROPERTIES);
946 } else { // jQuery < 1.8
950 $.each(Textarea.COPY_PROPERTIES, function (i, property) {
951 styles[property] = $el.css(property);
958 getTextFromHeadToCaret: function () {
959 return this.el.value.substring(0, this.el.selectionEnd);
963 $.fn.textcomplete.Textarea = Textarea;
969 var sentinelChar = '吶';
971 function IETextarea(element, completer, option) {
972 this.initialize(element, completer, option);
973 $('<span>' + sentinelChar + '</span>').css({
974 position: 'absolute',
977 }).insertBefore(element);
980 $.extend(IETextarea.prototype, $.fn.textcomplete.Textarea.prototype, {
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];
992 pre = pre.replace(strategy.match, newSubstr);
993 this.$el.val(pre + post);
995 var range = this.el.createTextRange();
996 range.collapse(true);
997 range.moveEnd('character', pre.length);
998 range.moveStart('character', pre.length);
1002 getTextFromHeadToCaret: function () {
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];
1011 $.fn.textcomplete.IETextarea = IETextarea;
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.
1021 // ContentEditable adapter
1022 // =======================
1024 // Adapter for contenteditable elements.
1025 function ContentEditable (element, completer, option) {
1026 this.initialize(element, completer, option);
1029 $.extend(ContentEditable.prototype, $.fn.textcomplete.Adapter.prototype, {
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];
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);
1062 // Returns the caret's relative position from the contenteditable's
1067 // this._getCaretRelativePosition()
1068 // //=> { top: 18, left: 200, lineHeight: 16 }
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(); }
1087 // Returns the string between the first character and the caret.
1088 // Completer will be triggered with the result for start autocompleting.
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);
1103 $.fn.textcomplete.ContentEditable = ContentEditable;