Newer
Older
gitbucket_jkp / src / main / webapp / assets / vendors / jquery-textcomplete-1.8.4 / jquery.textcomplete.js
  1. (function (factory) {
  2. if (typeof define === 'function' && define.amd) {
  3. // AMD. Register as an anonymous module.
  4. define(['jquery'], factory);
  5. } else if (typeof module === "object" && module.exports) {
  6. var $ = require('jquery');
  7. module.exports = factory($);
  8. } else {
  9. // Browser globals
  10. factory(jQuery);
  11. }
  12. }(function (jQuery) {
  13.  
  14. /*!
  15. * jQuery.textcomplete
  16. *
  17. * Repository: https://github.com/yuku-t/jquery-textcomplete
  18. * License: MIT (https://github.com/yuku-t/jquery-textcomplete/blob/master/LICENSE)
  19. * Author: Yuku Takahashi
  20. */
  21.  
  22. if (typeof jQuery === 'undefined') {
  23. throw new Error('jQuery.textcomplete requires jQuery');
  24. }
  25.  
  26. +function ($) {
  27. 'use strict';
  28.  
  29. var warn = function (message) {
  30. if (console.warn) { console.warn(message); }
  31. };
  32.  
  33. var id = 1;
  34.  
  35. $.fn.textcomplete = function (strategies, option) {
  36. var args = Array.prototype.slice.call(arguments);
  37. return this.each(function () {
  38. var self = this;
  39. var $this = $(this);
  40. var completer = $this.data('textComplete');
  41. if (!completer) {
  42. option || (option = {});
  43. option._oid = id++; // unique object id
  44. completer = new $.fn.textcomplete.Completer(this, option);
  45. $this.data('textComplete', completer);
  46. }
  47. if (typeof strategies === 'string') {
  48. if (!completer) return;
  49. args.shift()
  50. completer[strategies].apply(completer, args);
  51. if (strategies === 'destroy') {
  52. $this.removeData('textComplete');
  53. }
  54. } else {
  55. // For backward compatibility.
  56. // TODO: Remove at v0.4
  57. $.each(strategies, function (obj) {
  58. $.each(['header', 'footer', 'placement', 'maxCount'], function (name) {
  59. if (obj[name]) {
  60. completer.option[name] = obj[name];
  61. warn(name + 'as a strategy param is deprecated. Use option.');
  62. delete obj[name];
  63. }
  64. });
  65. });
  66. completer.register($.fn.textcomplete.Strategy.parse(strategies, {
  67. el: self,
  68. $el: $this
  69. }));
  70. }
  71. });
  72. };
  73.  
  74. }(jQuery);
  75.  
  76. +function ($) {
  77. 'use strict';
  78.  
  79. // Exclusive execution control utility.
  80. //
  81. // func - The function to be locked. It is executed with a function named
  82. // `free` as the first argument. Once it is called, additional
  83. // execution are ignored until the free is invoked. Then the last
  84. // ignored execution will be replayed immediately.
  85. //
  86. // Examples
  87. //
  88. // var lockedFunc = lock(function (free) {
  89. // setTimeout(function { free(); }, 1000); // It will be free in 1 sec.
  90. // console.log('Hello, world');
  91. // });
  92. // lockedFunc(); // => 'Hello, world'
  93. // lockedFunc(); // none
  94. // lockedFunc(); // none
  95. // // 1 sec past then
  96. // // => 'Hello, world'
  97. // lockedFunc(); // => 'Hello, world'
  98. // lockedFunc(); // none
  99. //
  100. // Returns a wrapped function.
  101. var lock = function (func) {
  102. var locked, queuedArgsToReplay;
  103.  
  104. return function () {
  105. // Convert arguments into a real array.
  106. var args = Array.prototype.slice.call(arguments);
  107. if (locked) {
  108. // Keep a copy of this argument list to replay later.
  109. // OK to overwrite a previous value because we only replay
  110. // the last one.
  111. queuedArgsToReplay = args;
  112. return;
  113. }
  114. locked = true;
  115. var self = this;
  116. args.unshift(function replayOrFree() {
  117. if (queuedArgsToReplay) {
  118. // Other request(s) arrived while we were locked.
  119. // Now that the lock is becoming available, replay
  120. // the latest such request, then call back here to
  121. // unlock (or replay another request that arrived
  122. // while this one was in flight).
  123. var replayArgs = queuedArgsToReplay;
  124. queuedArgsToReplay = undefined;
  125. replayArgs.unshift(replayOrFree);
  126. func.apply(self, replayArgs);
  127. } else {
  128. locked = false;
  129. }
  130. });
  131. func.apply(this, args);
  132. };
  133. };
  134.  
  135. var isString = function (obj) {
  136. return Object.prototype.toString.call(obj) === '[object String]';
  137. };
  138.  
  139. var uniqueId = 0;
  140. var initializedEditors = [];
  141.  
  142. function Completer(element, option) {
  143. this.$el = $(element);
  144. this.id = 'textcomplete' + uniqueId++;
  145. this.strategies = [];
  146. this.views = [];
  147. this.option = $.extend({}, Completer.defaults, option);
  148.  
  149. if (!this.$el.is('input[type=text]') && !this.$el.is('input[type=search]') && !this.$el.is('textarea') && !element.isContentEditable && element.contentEditable != 'true') {
  150. throw new Error('textcomplete must be called on a Textarea or a ContentEditable.');
  151. }
  152.  
  153. // use ownerDocument to fix iframe / IE issues
  154. if (element === element.ownerDocument.activeElement) {
  155. // element has already been focused. Initialize view objects immediately.
  156. this.initialize()
  157. } else {
  158. // Initialize view objects lazily.
  159. var self = this;
  160. this.$el.one('focus.' + this.id, function () { self.initialize(); });
  161.  
  162. // Special handling for CKEditor: lazy init on instance load
  163. if ((!this.option.adapter || this.option.adapter == 'CKEditor') && typeof CKEDITOR != 'undefined' && (this.$el.is('textarea'))) {
  164. CKEDITOR.on("instanceReady", function(event) { //For multiple ckeditors on one page: this needs to be executed each time a ckeditor-instance is ready.
  165.  
  166. if($.inArray(event.editor.id, initializedEditors) == -1) { //For multiple ckeditors on one page: focus-eventhandler should only be added once for every editor.
  167. initializedEditors.push(event.editor.id);
  168. event.editor.on("focus", function(event2) {
  169. //replace the element with the Iframe element and flag it as CKEditor
  170. self.$el = $(event.editor.editable().$);
  171. if (!self.option.adapter) {
  172. self.option.adapter = $.fn.textcomplete['CKEditor'];
  173. }
  174. self.option.ckeditor_instance = event.editor; //For multiple ckeditors on one page: in the old code this was not executed when adapter was alread set. So we were ALWAYS working with the FIRST instance.
  175. self.initialize();
  176. });
  177. }
  178. });
  179. }
  180. }
  181. }
  182.  
  183. Completer.defaults = {
  184. appendTo: 'body',
  185. className: '', // deprecated option
  186. dropdownClassName: 'dropdown-menu textcomplete-dropdown',
  187. maxCount: 10,
  188. zIndex: '100',
  189. rightEdgeOffset: 30
  190. };
  191.  
  192. $.extend(Completer.prototype, {
  193. // Public properties
  194. // -----------------
  195.  
  196. id: null,
  197. option: null,
  198. strategies: null,
  199. adapter: null,
  200. dropdown: null,
  201. $el: null,
  202. $iframe: null,
  203.  
  204. // Public methods
  205. // --------------
  206.  
  207. initialize: function () {
  208. var element = this.$el.get(0);
  209. // check if we are in an iframe
  210. // we need to alter positioning logic if using an iframe
  211. if (this.$el.prop('ownerDocument') !== document && window.frames.length) {
  212. for (var iframeIndex = 0; iframeIndex < window.frames.length; iframeIndex++) {
  213. if (this.$el.prop('ownerDocument') === window.frames[iframeIndex].document) {
  214. this.$iframe = $(window.frames[iframeIndex].frameElement);
  215. break;
  216. }
  217. }
  218. }
  219. // Initialize view objects.
  220. this.dropdown = new $.fn.textcomplete.Dropdown(element, this, this.option);
  221. var Adapter, viewName;
  222. if (this.option.adapter) {
  223. Adapter = this.option.adapter;
  224. } else {
  225. if (this.$el.is('textarea') || this.$el.is('input[type=text]') || this.$el.is('input[type=search]')) {
  226. viewName = typeof element.selectionEnd === 'number' ? 'Textarea' : 'IETextarea';
  227. } else {
  228. viewName = 'ContentEditable';
  229. }
  230. Adapter = $.fn.textcomplete[viewName];
  231. }
  232. this.adapter = new Adapter(element, this, this.option);
  233. },
  234.  
  235. destroy: function () {
  236. this.$el.off('.' + this.id);
  237. if (this.adapter) {
  238. this.adapter.destroy();
  239. }
  240. if (this.dropdown) {
  241. this.dropdown.destroy();
  242. }
  243. this.$el = this.adapter = this.dropdown = null;
  244. },
  245.  
  246. deactivate: function () {
  247. if (this.dropdown) {
  248. this.dropdown.deactivate();
  249. }
  250. },
  251.  
  252. // Invoke textcomplete.
  253. trigger: function (text, skipUnchangedTerm) {
  254. if (!this.dropdown) { this.initialize(); }
  255. text != null || (text = this.adapter.getTextFromHeadToCaret());
  256. var searchQuery = this._extractSearchQuery(text);
  257. if (searchQuery.length) {
  258. var term = searchQuery[1];
  259. // Ignore shift-key, ctrl-key and so on.
  260. if (skipUnchangedTerm && this._term === term && term !== "") { return; }
  261. this._term = term;
  262. this._search.apply(this, searchQuery);
  263. } else {
  264. this._term = null;
  265. this.dropdown.deactivate();
  266. }
  267. },
  268.  
  269. fire: function (eventName) {
  270. var args = Array.prototype.slice.call(arguments, 1);
  271. this.$el.trigger(eventName, args);
  272. return this;
  273. },
  274.  
  275. register: function (strategies) {
  276. Array.prototype.push.apply(this.strategies, strategies);
  277. },
  278.  
  279. // Insert the value into adapter view. It is called when the dropdown is clicked
  280. // or selected.
  281. //
  282. // value - The selected element of the array callbacked from search func.
  283. // strategy - The Strategy object.
  284. // e - Click or keydown event object.
  285. select: function (value, strategy, e) {
  286. this._term = null;
  287. this.adapter.select(value, strategy, e);
  288. this.fire('change').fire('textComplete:select', value, strategy);
  289. this.adapter.focus();
  290. },
  291.  
  292. // Private properties
  293. // ------------------
  294.  
  295. _clearAtNext: true,
  296. _term: null,
  297.  
  298. // Private methods
  299. // ---------------
  300.  
  301. // Parse the given text and extract the first matching strategy.
  302. //
  303. // Returns an array including the strategy, the query term and the match
  304. // object if the text matches an strategy; otherwise returns an empty array.
  305. _extractSearchQuery: function (text) {
  306. for (var i = 0; i < this.strategies.length; i++) {
  307. var strategy = this.strategies[i];
  308. var context = strategy.context(text);
  309. if (context || context === '') {
  310. var matchRegexp = $.isFunction(strategy.match) ? strategy.match(text) : strategy.match;
  311. if (isString(context)) { text = context; }
  312. var match = text.match(matchRegexp);
  313. if (match) { return [strategy, match[strategy.index], match]; }
  314. }
  315. }
  316. return []
  317. },
  318.  
  319. // Call the search method of selected strategy..
  320. _search: lock(function (free, strategy, term, match) {
  321. var self = this;
  322. strategy.search(term, function (data, stillSearching) {
  323. if (!self.dropdown.shown) {
  324. self.dropdown.activate();
  325. }
  326. if (self._clearAtNext) {
  327. // The first callback in the current lock.
  328. self.dropdown.clear();
  329. self._clearAtNext = false;
  330. }
  331. self.dropdown.setPosition(self.adapter.getCaretPosition());
  332. self.dropdown.render(self._zip(data, strategy, term));
  333. if (!stillSearching) {
  334. // The last callback in the current lock.
  335. free();
  336. self._clearAtNext = true; // Call dropdown.clear at the next time.
  337. }
  338. }, match);
  339. }),
  340.  
  341. // Build a parameter for Dropdown#render.
  342. //
  343. // Examples
  344. //
  345. // this._zip(['a', 'b'], 's');
  346. // //=> [{ value: 'a', strategy: 's' }, { value: 'b', strategy: 's' }]
  347. _zip: function (data, strategy, term) {
  348. return $.map(data, function (value) {
  349. return { value: value, strategy: strategy, term: term };
  350. });
  351. }
  352. });
  353.  
  354. $.fn.textcomplete.Completer = Completer;
  355. }(jQuery);
  356.  
  357. +function ($) {
  358. 'use strict';
  359.  
  360. var $window = $(window);
  361.  
  362. var include = function (zippedData, datum) {
  363. var i, elem;
  364. var idProperty = datum.strategy.idProperty
  365. for (i = 0; i < zippedData.length; i++) {
  366. elem = zippedData[i];
  367. if (elem.strategy !== datum.strategy) continue;
  368. if (idProperty) {
  369. if (elem.value[idProperty] === datum.value[idProperty]) return true;
  370. } else {
  371. if (elem.value === datum.value) return true;
  372. }
  373. }
  374. return false;
  375. };
  376.  
  377. var dropdownViews = {};
  378. $(document).on('click', function (e) {
  379. var id = e.originalEvent && e.originalEvent.keepTextCompleteDropdown;
  380. $.each(dropdownViews, function (key, view) {
  381. if (key !== id) { view.deactivate(); }
  382. });
  383. });
  384.  
  385. var commands = {
  386. SKIP_DEFAULT: 0,
  387. KEY_UP: 1,
  388. KEY_DOWN: 2,
  389. KEY_ENTER: 3,
  390. KEY_PAGEUP: 4,
  391. KEY_PAGEDOWN: 5,
  392. KEY_ESCAPE: 6
  393. };
  394.  
  395. // Dropdown view
  396. // =============
  397.  
  398. // Construct Dropdown object.
  399. //
  400. // element - Textarea or contenteditable element.
  401. function Dropdown(element, completer, option) {
  402. this.$el = Dropdown.createElement(option);
  403. this.completer = completer;
  404. this.id = completer.id + 'dropdown';
  405. this._data = []; // zipped data.
  406. this.$inputEl = $(element);
  407. this.option = option;
  408.  
  409. // Override setPosition method.
  410. if (option.listPosition) { this.setPosition = option.listPosition; }
  411. if (option.height) { this.$el.height(option.height); }
  412. var self = this;
  413. $.each(['maxCount', 'placement', 'footer', 'header', 'noResultsMessage', 'className'], function (_i, name) {
  414. if (option[name] != null) { self[name] = option[name]; }
  415. });
  416. this._bindEvents(element);
  417. dropdownViews[this.id] = this;
  418. }
  419.  
  420. $.extend(Dropdown, {
  421. // Class methods
  422. // -------------
  423.  
  424. createElement: function (option) {
  425. var $parent = option.appendTo;
  426. if (!($parent instanceof $)) { $parent = $($parent); }
  427. var $el = $('<ul></ul>')
  428. .addClass(option.dropdownClassName)
  429. .attr('id', 'textcomplete-dropdown-' + option._oid)
  430. .css({
  431. display: 'none',
  432. left: 0,
  433. position: 'absolute',
  434. zIndex: option.zIndex
  435. })
  436. .appendTo($parent);
  437. return $el;
  438. }
  439. });
  440.  
  441. $.extend(Dropdown.prototype, {
  442. // Public properties
  443. // -----------------
  444.  
  445. $el: null, // jQuery object of ul.dropdown-menu element.
  446. $inputEl: null, // jQuery object of target textarea.
  447. completer: null,
  448. footer: null,
  449. header: null,
  450. id: null,
  451. maxCount: null,
  452. placement: '',
  453. shown: false,
  454. data: [], // Shown zipped data.
  455. className: '',
  456.  
  457. // Public methods
  458. // --------------
  459.  
  460. destroy: function () {
  461. // Don't remove $el because it may be shared by several textcompletes.
  462. this.deactivate();
  463.  
  464. this.$el.off('.' + this.id);
  465. this.$inputEl.off('.' + this.id);
  466. this.clear();
  467. this.$el.remove();
  468. this.$el = this.$inputEl = this.completer = null;
  469. delete dropdownViews[this.id]
  470. },
  471.  
  472. render: function (zippedData) {
  473. var contentsHtml = this._buildContents(zippedData);
  474. var unzippedData = $.map(zippedData, function (d) { return d.value; });
  475. if (zippedData.length) {
  476. var strategy = zippedData[0].strategy;
  477. if (strategy.id) {
  478. this.$el.attr('data-strategy', strategy.id);
  479. } else {
  480. this.$el.removeAttr('data-strategy');
  481. }
  482. this._renderHeader(unzippedData);
  483. this._renderFooter(unzippedData);
  484. if (contentsHtml) {
  485. this._renderContents(contentsHtml);
  486. this._fitToBottom();
  487. this._fitToRight();
  488. this._activateIndexedItem();
  489. }
  490. this._setScroll();
  491. } else if (this.noResultsMessage) {
  492. this._renderNoResultsMessage(unzippedData);
  493. } else if (this.shown) {
  494. this.deactivate();
  495. }
  496. },
  497.  
  498. setPosition: function (pos) {
  499. // Make the dropdown fixed if the input is also fixed
  500. // This can't be done during init, as textcomplete may be used on multiple elements on the same page
  501. // Because the same dropdown is reused behind the scenes, we need to recheck every time the dropdown is showed
  502. var position = 'absolute';
  503. // Check if input or one of its parents has positioning we need to care about
  504. this.$inputEl.add(this.$inputEl.parents()).each(function() {
  505. if($(this).css('position') === 'absolute') // The element has absolute positioning, so it's all OK
  506. return false;
  507. if($(this).css('position') === 'fixed') {
  508. pos.top -= $window.scrollTop();
  509. pos.left -= $window.scrollLeft();
  510. position = 'fixed';
  511. return false;
  512. }
  513. });
  514. this.$el.css(this._applyPlacement(pos));
  515. this.$el.css({ position: position }); // Update positioning
  516.  
  517. return this;
  518. },
  519.  
  520. clear: function () {
  521. this.$el.html('');
  522. this.data = [];
  523. this._index = 0;
  524. this._$header = this._$footer = this._$noResultsMessage = null;
  525. },
  526.  
  527. activate: function () {
  528. if (!this.shown) {
  529. this.clear();
  530. this.$el.show();
  531. if (this.className) { this.$el.addClass(this.className); }
  532. this.completer.fire('textComplete:show');
  533. this.shown = true;
  534. }
  535. return this;
  536. },
  537.  
  538. deactivate: function () {
  539. if (this.shown) {
  540. this.$el.hide();
  541. if (this.className) { this.$el.removeClass(this.className); }
  542. this.completer.fire('textComplete:hide');
  543. this.shown = false;
  544. }
  545. return this;
  546. },
  547.  
  548. isUp: function (e) {
  549. return e.keyCode === 38 || (e.ctrlKey && e.keyCode === 80); // UP, Ctrl-P
  550. },
  551.  
  552. isDown: function (e) {
  553. return e.keyCode === 40 || (e.ctrlKey && e.keyCode === 78); // DOWN, Ctrl-N
  554. },
  555.  
  556. isEnter: function (e) {
  557. var modifiers = e.ctrlKey || e.altKey || e.metaKey || e.shiftKey;
  558. return !modifiers && (e.keyCode === 13 || e.keyCode === 9 || (this.option.completeOnSpace === true && e.keyCode === 32)) // ENTER, TAB
  559. },
  560.  
  561. isPageup: function (e) {
  562. return e.keyCode === 33; // PAGEUP
  563. },
  564.  
  565. isPagedown: function (e) {
  566. return e.keyCode === 34; // PAGEDOWN
  567. },
  568.  
  569. isEscape: function (e) {
  570. return e.keyCode === 27; // ESCAPE
  571. },
  572.  
  573. // Private properties
  574. // ------------------
  575.  
  576. _data: null, // Currently shown zipped data.
  577. _index: null,
  578. _$header: null,
  579. _$noResultsMessage: null,
  580. _$footer: null,
  581.  
  582. // Private methods
  583. // ---------------
  584.  
  585. _bindEvents: function () {
  586. this.$el.on('mousedown.' + this.id, '.textcomplete-item', $.proxy(this._onClick, this));
  587. this.$el.on('touchstart.' + this.id, '.textcomplete-item', $.proxy(this._onClick, this));
  588. this.$el.on('mouseover.' + this.id, '.textcomplete-item', $.proxy(this._onMouseover, this));
  589. this.$inputEl.on('keydown.' + this.id, $.proxy(this._onKeydown, this));
  590. },
  591.  
  592. _onClick: function (e) {
  593. var $el = $(e.target);
  594. e.preventDefault();
  595. e.originalEvent.keepTextCompleteDropdown = this.id;
  596. if (!$el.hasClass('textcomplete-item')) {
  597. $el = $el.closest('.textcomplete-item');
  598. }
  599. var datum = this.data[parseInt($el.data('index'), 10)];
  600. this.completer.select(datum.value, datum.strategy, e);
  601. var self = this;
  602. // Deactive at next tick to allow other event handlers to know whether
  603. // the dropdown has been shown or not.
  604. setTimeout(function () {
  605. self.deactivate();
  606. if (e.type === 'touchstart') {
  607. self.$inputEl.focus();
  608. }
  609. }, 0);
  610. },
  611.  
  612. // Activate hovered item.
  613. _onMouseover: function (e) {
  614. var $el = $(e.target);
  615. e.preventDefault();
  616. if (!$el.hasClass('textcomplete-item')) {
  617. $el = $el.closest('.textcomplete-item');
  618. }
  619. this._index = parseInt($el.data('index'), 10);
  620. this._activateIndexedItem();
  621. },
  622.  
  623. _onKeydown: function (e) {
  624. if (!this.shown) { return; }
  625.  
  626. var command;
  627.  
  628. if ($.isFunction(this.option.onKeydown)) {
  629. command = this.option.onKeydown(e, commands);
  630. }
  631.  
  632. if (command == null) {
  633. command = this._defaultKeydown(e);
  634. }
  635.  
  636. switch (command) {
  637. case commands.KEY_UP:
  638. e.preventDefault();
  639. this._up();
  640. break;
  641. case commands.KEY_DOWN:
  642. e.preventDefault();
  643. this._down();
  644. break;
  645. case commands.KEY_ENTER:
  646. e.preventDefault();
  647. this._enter(e);
  648. break;
  649. case commands.KEY_PAGEUP:
  650. e.preventDefault();
  651. this._pageup();
  652. break;
  653. case commands.KEY_PAGEDOWN:
  654. e.preventDefault();
  655. this._pagedown();
  656. break;
  657. case commands.KEY_ESCAPE:
  658. e.preventDefault();
  659. this.deactivate();
  660. break;
  661. }
  662. },
  663.  
  664. _defaultKeydown: function (e) {
  665. if (this.isUp(e)) {
  666. return commands.KEY_UP;
  667. } else if (this.isDown(e)) {
  668. return commands.KEY_DOWN;
  669. } else if (this.isEnter(e)) {
  670. return commands.KEY_ENTER;
  671. } else if (this.isPageup(e)) {
  672. return commands.KEY_PAGEUP;
  673. } else if (this.isPagedown(e)) {
  674. return commands.KEY_PAGEDOWN;
  675. } else if (this.isEscape(e)) {
  676. return commands.KEY_ESCAPE;
  677. }
  678. },
  679.  
  680. _up: function () {
  681. if (this._index === 0) {
  682. this._index = this.data.length - 1;
  683. } else {
  684. this._index -= 1;
  685. }
  686. this._activateIndexedItem();
  687. this._setScroll();
  688. },
  689.  
  690. _down: function () {
  691. if (this._index === this.data.length - 1) {
  692. this._index = 0;
  693. } else {
  694. this._index += 1;
  695. }
  696. this._activateIndexedItem();
  697. this._setScroll();
  698. },
  699.  
  700. _enter: function (e) {
  701. var datum = this.data[parseInt(this._getActiveElement().data('index'), 10)];
  702. this.completer.select(datum.value, datum.strategy, e);
  703. this.deactivate();
  704. },
  705.  
  706. _pageup: function () {
  707. var target = 0;
  708. var threshold = this._getActiveElement().position().top - this.$el.innerHeight();
  709. this.$el.children().each(function (i) {
  710. if ($(this).position().top + $(this).outerHeight() > threshold) {
  711. target = i;
  712. return false;
  713. }
  714. });
  715. this._index = target;
  716. this._activateIndexedItem();
  717. this._setScroll();
  718. },
  719.  
  720. _pagedown: function () {
  721. var target = this.data.length - 1;
  722. var threshold = this._getActiveElement().position().top + this.$el.innerHeight();
  723. this.$el.children().each(function (i) {
  724. if ($(this).position().top > threshold) {
  725. target = i;
  726. return false
  727. }
  728. });
  729. this._index = target;
  730. this._activateIndexedItem();
  731. this._setScroll();
  732. },
  733.  
  734. _activateIndexedItem: function () {
  735. this.$el.find('.textcomplete-item.active').removeClass('active');
  736. this._getActiveElement().addClass('active');
  737. },
  738.  
  739. _getActiveElement: function () {
  740. return this.$el.children('.textcomplete-item:nth(' + this._index + ')');
  741. },
  742.  
  743. _setScroll: function () {
  744. var $activeEl = this._getActiveElement();
  745. var itemTop = $activeEl.position().top;
  746. var itemHeight = $activeEl.outerHeight();
  747. var visibleHeight = this.$el.innerHeight();
  748. var visibleTop = this.$el.scrollTop();
  749. if (this._index === 0 || this._index == this.data.length - 1 || itemTop < 0) {
  750. this.$el.scrollTop(itemTop + visibleTop);
  751. } else if (itemTop + itemHeight > visibleHeight) {
  752. this.$el.scrollTop(itemTop + itemHeight + visibleTop - visibleHeight);
  753. }
  754. },
  755.  
  756. _buildContents: function (zippedData) {
  757. var datum, i, index;
  758. var html = '';
  759. for (i = 0; i < zippedData.length; i++) {
  760. if (this.data.length === this.maxCount) break;
  761. datum = zippedData[i];
  762. if (include(this.data, datum)) { continue; }
  763. index = this.data.length;
  764. this.data.push(datum);
  765. html += '<li class="textcomplete-item" data-index="' + index + '"><a>';
  766. html += datum.strategy.template(datum.value, datum.term);
  767. html += '</a></li>';
  768. }
  769. return html;
  770. },
  771.  
  772. _renderHeader: function (unzippedData) {
  773. if (this.header) {
  774. if (!this._$header) {
  775. this._$header = $('<li class="textcomplete-header"></li>').prependTo(this.$el);
  776. }
  777. var html = $.isFunction(this.header) ? this.header(unzippedData) : this.header;
  778. this._$header.html(html);
  779. }
  780. },
  781.  
  782. _renderFooter: function (unzippedData) {
  783. if (this.footer) {
  784. if (!this._$footer) {
  785. this._$footer = $('<li class="textcomplete-footer"></li>').appendTo(this.$el);
  786. }
  787. var html = $.isFunction(this.footer) ? this.footer(unzippedData) : this.footer;
  788. this._$footer.html(html);
  789. }
  790. },
  791.  
  792. _renderNoResultsMessage: function (unzippedData) {
  793. if (this.noResultsMessage) {
  794. if (!this._$noResultsMessage) {
  795. this._$noResultsMessage = $('<li class="textcomplete-no-results-message"></li>').appendTo(this.$el);
  796. }
  797. var html = $.isFunction(this.noResultsMessage) ? this.noResultsMessage(unzippedData) : this.noResultsMessage;
  798. this._$noResultsMessage.html(html);
  799. }
  800. },
  801.  
  802. _renderContents: function (html) {
  803. if (this._$footer) {
  804. this._$footer.before(html);
  805. } else {
  806. this.$el.append(html);
  807. }
  808. },
  809.  
  810. _fitToBottom: function() {
  811. var windowScrollBottom = $window.scrollTop() + $window.height();
  812. var height = this.$el.height();
  813. if ((this.$el.position().top + height) > windowScrollBottom) {
  814. // only do this if we are not in an iframe
  815. if (!this.completer.$iframe) {
  816. this.$el.offset({top: windowScrollBottom - height});
  817. }
  818. }
  819. },
  820.  
  821. _fitToRight: function() {
  822. // We don't know how wide our content is until the browser positions us, and at that point it clips us
  823. // to the document width so we don't know if we would have overrun it. As a heuristic to avoid that clipping
  824. // (which makes our elements wrap onto the next line and corrupt the next item), if we're close to the right
  825. // edge, move left. We don't know how far to move left, so just keep nudging a bit.
  826. var tolerance = this.option.rightEdgeOffset; // pixels. Make wider than vertical scrollbar because we might not be able to use that space.
  827. var lastOffset = this.$el.offset().left, offset;
  828. var width = this.$el.width();
  829. var maxLeft = $window.width() - tolerance;
  830. while (lastOffset + width > maxLeft) {
  831. this.$el.offset({left: lastOffset - tolerance});
  832. offset = this.$el.offset().left;
  833. if (offset >= lastOffset) { break; }
  834. lastOffset = offset;
  835. }
  836. },
  837.  
  838. _applyPlacement: function (position) {
  839. // If the 'placement' option set to 'top', move the position above the element.
  840. if (this.placement.indexOf('top') !== -1) {
  841. // Overwrite the position object to set the 'bottom' property instead of the top.
  842. position = {
  843. top: 'auto',
  844. bottom: this.$el.parent().height() - position.top + position.lineHeight,
  845. left: position.left
  846. };
  847. } else {
  848. position.bottom = 'auto';
  849. delete position.lineHeight;
  850. }
  851. if (this.placement.indexOf('absleft') !== -1) {
  852. position.left = 0;
  853. } else if (this.placement.indexOf('absright') !== -1) {
  854. position.right = 0;
  855. position.left = 'auto';
  856. }
  857. return position;
  858. }
  859. });
  860.  
  861. $.fn.textcomplete.Dropdown = Dropdown;
  862. $.extend($.fn.textcomplete, commands);
  863. }(jQuery);
  864.  
  865. +function ($) {
  866. 'use strict';
  867.  
  868. // Memoize a search function.
  869. var memoize = function (func) {
  870. var memo = {};
  871. return function (term, callback) {
  872. if (memo[term]) {
  873. callback(memo[term]);
  874. } else {
  875. func.call(this, term, function (data) {
  876. memo[term] = (memo[term] || []).concat(data);
  877. callback.apply(null, arguments);
  878. });
  879. }
  880. };
  881. };
  882.  
  883. function Strategy(options) {
  884. $.extend(this, options);
  885. if (this.cache) { this.search = memoize(this.search); }
  886. }
  887.  
  888. Strategy.parse = function (strategiesArray, params) {
  889. return $.map(strategiesArray, function (strategy) {
  890. var strategyObj = new Strategy(strategy);
  891. strategyObj.el = params.el;
  892. strategyObj.$el = params.$el;
  893. return strategyObj;
  894. });
  895. };
  896.  
  897. $.extend(Strategy.prototype, {
  898. // Public properties
  899. // -----------------
  900.  
  901. // Required
  902. match: null,
  903. replace: null,
  904. search: null,
  905.  
  906. // Optional
  907. id: null,
  908. cache: false,
  909. context: function () { return true; },
  910. index: 2,
  911. template: function (obj) { return obj; },
  912. idProperty: null
  913. });
  914.  
  915. $.fn.textcomplete.Strategy = Strategy;
  916.  
  917. }(jQuery);
  918.  
  919. +function ($) {
  920. 'use strict';
  921.  
  922. var now = Date.now || function () { return new Date().getTime(); };
  923.  
  924. // Returns a function, that, as long as it continues to be invoked, will not
  925. // be triggered. The function will be called after it stops being called for
  926. // `wait` msec.
  927. //
  928. // This utility function was originally implemented at Underscore.js.
  929. var debounce = function (func, wait) {
  930. var timeout, args, context, timestamp, result;
  931. var later = function () {
  932. var last = now() - timestamp;
  933. if (last < wait) {
  934. timeout = setTimeout(later, wait - last);
  935. } else {
  936. timeout = null;
  937. result = func.apply(context, args);
  938. context = args = null;
  939. }
  940. };
  941.  
  942. return function () {
  943. context = this;
  944. args = arguments;
  945. timestamp = now();
  946. if (!timeout) {
  947. timeout = setTimeout(later, wait);
  948. }
  949. return result;
  950. };
  951. };
  952.  
  953. function Adapter () {}
  954.  
  955. $.extend(Adapter.prototype, {
  956. // Public properties
  957. // -----------------
  958.  
  959. id: null, // Identity.
  960. completer: null, // Completer object which creates it.
  961. el: null, // Textarea element.
  962. $el: null, // jQuery object of the textarea.
  963. option: null,
  964.  
  965. // Public methods
  966. // --------------
  967.  
  968. initialize: function (element, completer, option) {
  969. this.el = element;
  970. this.$el = $(element);
  971. this.id = completer.id + this.constructor.name;
  972. this.completer = completer;
  973. this.option = option;
  974.  
  975. if (this.option.debounce) {
  976. this._onKeyup = debounce(this._onKeyup, this.option.debounce);
  977. }
  978.  
  979. this._bindEvents();
  980. },
  981.  
  982. destroy: function () {
  983. this.$el.off('.' + this.id); // Remove all event handlers.
  984. this.$el = this.el = this.completer = null;
  985. },
  986.  
  987. // Update the element with the given value and strategy.
  988. //
  989. // value - The selected object. It is one of the item of the array
  990. // which was callbacked from the search function.
  991. // strategy - The Strategy associated with the selected value.
  992. select: function (/* value, strategy */) {
  993. throw new Error('Not implemented');
  994. },
  995.  
  996. // Returns the caret's relative coordinates from body's left top corner.
  997. getCaretPosition: function () {
  998. var position = this._getCaretRelativePosition();
  999. var offset = this.$el.offset();
  1000.  
  1001. // Calculate the left top corner of `this.option.appendTo` element.
  1002. var $parent = this.option.appendTo;
  1003. if ($parent) {
  1004. if (!($parent instanceof $)) { $parent = $($parent); }
  1005. var parentOffset = $parent.offsetParent().offset();
  1006. offset.top -= parentOffset.top;
  1007. offset.left -= parentOffset.left;
  1008. }
  1009.  
  1010. position.top += offset.top;
  1011. position.left += offset.left;
  1012. return position;
  1013. },
  1014.  
  1015. // Focus on the element.
  1016. focus: function () {
  1017. this.$el.focus();
  1018. },
  1019.  
  1020. // Private methods
  1021. // ---------------
  1022.  
  1023. _bindEvents: function () {
  1024. this.$el.on('keyup.' + this.id, $.proxy(this._onKeyup, this));
  1025. },
  1026.  
  1027. _onKeyup: function (e) {
  1028. if (this._skipSearch(e)) { return; }
  1029. this.completer.trigger(this.getTextFromHeadToCaret(), true);
  1030. },
  1031.  
  1032. // Suppress searching if it returns true.
  1033. _skipSearch: function (clickEvent) {
  1034. switch (clickEvent.keyCode) {
  1035. case 9: // TAB
  1036. case 13: // ENTER
  1037. case 16: // SHIFT
  1038. case 17: // CTRL
  1039. case 18: // ALT
  1040. case 33: // PAGEUP
  1041. case 34: // PAGEDOWN
  1042. case 40: // DOWN
  1043. case 38: // UP
  1044. case 27: // ESC
  1045. return true;
  1046. }
  1047. if (clickEvent.ctrlKey) switch (clickEvent.keyCode) {
  1048. case 78: // Ctrl-N
  1049. case 80: // Ctrl-P
  1050. return true;
  1051. }
  1052. }
  1053. });
  1054.  
  1055. $.fn.textcomplete.Adapter = Adapter;
  1056. }(jQuery);
  1057.  
  1058. +function ($) {
  1059. 'use strict';
  1060.  
  1061. // Textarea adapter
  1062. // ================
  1063. //
  1064. // Managing a textarea. It doesn't know a Dropdown.
  1065. function Textarea(element, completer, option) {
  1066. this.initialize(element, completer, option);
  1067. }
  1068.  
  1069. $.extend(Textarea.prototype, $.fn.textcomplete.Adapter.prototype, {
  1070. // Public methods
  1071. // --------------
  1072.  
  1073. // Update the textarea with the given value and strategy.
  1074. select: function (value, strategy, e) {
  1075. var pre = this.getTextFromHeadToCaret();
  1076. var post = this.el.value.substring(this.el.selectionEnd);
  1077. var newSubstr = strategy.replace(value, e);
  1078. var regExp;
  1079. if (typeof newSubstr !== 'undefined') {
  1080. if ($.isArray(newSubstr)) {
  1081. post = newSubstr[1] + post;
  1082. newSubstr = newSubstr[0];
  1083. }
  1084. regExp = $.isFunction(strategy.match) ? strategy.match(pre) : strategy.match;
  1085. pre = pre.replace(regExp, newSubstr);
  1086. this.$el.val(pre + post);
  1087. this.el.selectionStart = this.el.selectionEnd = pre.length;
  1088. }
  1089. },
  1090.  
  1091. getTextFromHeadToCaret: function () {
  1092. return this.el.value.substring(0, this.el.selectionEnd);
  1093. },
  1094.  
  1095. // Private methods
  1096. // ---------------
  1097.  
  1098. _getCaretRelativePosition: function () {
  1099. var p = $.fn.textcomplete.getCaretCoordinates(this.el, this.el.selectionStart);
  1100. return {
  1101. top: p.top + this._calculateLineHeight() - this.$el.scrollTop(),
  1102. left: p.left - this.$el.scrollLeft(),
  1103. lineHeight: this._calculateLineHeight()
  1104. };
  1105. },
  1106.  
  1107. _calculateLineHeight: function () {
  1108. var lineHeight = parseInt(this.$el.css('line-height'), 10);
  1109. if (isNaN(lineHeight)) {
  1110. // http://stackoverflow.com/a/4515470/1297336
  1111. var parentNode = this.el.parentNode;
  1112. var temp = document.createElement(this.el.nodeName);
  1113. var style = this.el.style;
  1114. temp.setAttribute(
  1115. 'style',
  1116. 'margin:0px;padding:0px;font-family:' + style.fontFamily + ';font-size:' + style.fontSize
  1117. );
  1118. temp.innerHTML = 'test';
  1119. parentNode.appendChild(temp);
  1120. lineHeight = temp.clientHeight;
  1121. parentNode.removeChild(temp);
  1122. }
  1123. return lineHeight;
  1124. }
  1125. });
  1126.  
  1127. $.fn.textcomplete.Textarea = Textarea;
  1128. }(jQuery);
  1129.  
  1130. +function ($) {
  1131. 'use strict';
  1132.  
  1133. var sentinelChar = '吶';
  1134.  
  1135. function IETextarea(element, completer, option) {
  1136. this.initialize(element, completer, option);
  1137. $('<span>' + sentinelChar + '</span>').css({
  1138. position: 'absolute',
  1139. top: -9999,
  1140. left: -9999
  1141. }).insertBefore(element);
  1142. }
  1143.  
  1144. $.extend(IETextarea.prototype, $.fn.textcomplete.Textarea.prototype, {
  1145. // Public methods
  1146. // --------------
  1147.  
  1148. select: function (value, strategy, e) {
  1149. var pre = this.getTextFromHeadToCaret();
  1150. var post = this.el.value.substring(pre.length);
  1151. var newSubstr = strategy.replace(value, e);
  1152. var regExp;
  1153. if (typeof newSubstr !== 'undefined') {
  1154. if ($.isArray(newSubstr)) {
  1155. post = newSubstr[1] + post;
  1156. newSubstr = newSubstr[0];
  1157. }
  1158. regExp = $.isFunction(strategy.match) ? strategy.match(pre) : strategy.match;
  1159. pre = pre.replace(regExp, newSubstr);
  1160. this.$el.val(pre + post);
  1161. this.el.focus();
  1162. var range = this.el.createTextRange();
  1163. range.collapse(true);
  1164. range.moveEnd('character', pre.length);
  1165. range.moveStart('character', pre.length);
  1166. range.select();
  1167. }
  1168. },
  1169.  
  1170. getTextFromHeadToCaret: function () {
  1171. this.el.focus();
  1172. var range = document.selection.createRange();
  1173. range.moveStart('character', -this.el.value.length);
  1174. var arr = range.text.split(sentinelChar)
  1175. return arr.length === 1 ? arr[0] : arr[1];
  1176. }
  1177. });
  1178.  
  1179. $.fn.textcomplete.IETextarea = IETextarea;
  1180. }(jQuery);
  1181.  
  1182. // NOTE: TextComplete plugin has contenteditable support but it does not work
  1183. // fine especially on old IEs.
  1184. // Any pull requests are REALLY welcome.
  1185.  
  1186. +function ($) {
  1187. 'use strict';
  1188.  
  1189. // ContentEditable adapter
  1190. // =======================
  1191. //
  1192. // Adapter for contenteditable elements.
  1193. function ContentEditable (element, completer, option) {
  1194. this.initialize(element, completer, option);
  1195. }
  1196.  
  1197. $.extend(ContentEditable.prototype, $.fn.textcomplete.Adapter.prototype, {
  1198. // Public methods
  1199. // --------------
  1200.  
  1201. // Update the content with the given value and strategy.
  1202. // When an dropdown item is selected, it is executed.
  1203. select: function (value, strategy, e) {
  1204. var pre = this.getTextFromHeadToCaret();
  1205. // use ownerDocument instead of window to support iframes
  1206. var sel = this.el.ownerDocument.getSelection();
  1207. var range = sel.getRangeAt(0);
  1208. var selection = range.cloneRange();
  1209. selection.selectNodeContents(range.startContainer);
  1210. var content = selection.toString();
  1211. var post = content.substring(range.startOffset);
  1212. var newSubstr = strategy.replace(value, e);
  1213. var regExp;
  1214. if (typeof newSubstr !== 'undefined') {
  1215. if ($.isArray(newSubstr)) {
  1216. post = newSubstr[1] + post;
  1217. newSubstr = newSubstr[0];
  1218. }
  1219. regExp = $.isFunction(strategy.match) ? strategy.match(pre) : strategy.match;
  1220. pre = pre.replace(regExp, newSubstr)
  1221. .replace(/ $/, "&nbsp"); // &nbsp necessary at least for CKeditor to not eat spaces
  1222. range.selectNodeContents(range.startContainer);
  1223. range.deleteContents();
  1224. // create temporary elements
  1225. var preWrapper = this.el.ownerDocument.createElement("div");
  1226. preWrapper.innerHTML = pre;
  1227. var postWrapper = this.el.ownerDocument.createElement("div");
  1228. postWrapper.innerHTML = post;
  1229. // create the fragment thats inserted
  1230. var fragment = this.el.ownerDocument.createDocumentFragment();
  1231. var childNode;
  1232. var lastOfPre;
  1233. while (childNode = preWrapper.firstChild) {
  1234. lastOfPre = fragment.appendChild(childNode);
  1235. }
  1236. while (childNode = postWrapper.firstChild) {
  1237. fragment.appendChild(childNode);
  1238. }
  1239. // insert the fragment & jump behind the last node in "pre"
  1240. range.insertNode(fragment);
  1241. range.setStartAfter(lastOfPre);
  1242. range.collapse(true);
  1243. sel.removeAllRanges();
  1244. sel.addRange(range);
  1245. }
  1246. },
  1247.  
  1248. // Private methods
  1249. // ---------------
  1250.  
  1251. // Returns the caret's relative position from the contenteditable's
  1252. // left top corner.
  1253. //
  1254. // Examples
  1255. //
  1256. // this._getCaretRelativePosition()
  1257. // //=> { top: 18, left: 200, lineHeight: 16 }
  1258. //
  1259. // Dropdown's position will be decided using the result.
  1260. _getCaretRelativePosition: function () {
  1261. var range = this.el.ownerDocument.getSelection().getRangeAt(0).cloneRange();
  1262. var wrapperNode = range.endContainer.parentNode;
  1263. var node = this.el.ownerDocument.createElement('span');
  1264. range.insertNode(node);
  1265. range.selectNodeContents(node);
  1266. range.deleteContents();
  1267. setTimeout(function() { wrapperNode.normalize(); }, 0);
  1268. var $node = $(node);
  1269. var position = $node.offset();
  1270. position.left -= this.$el.offset().left;
  1271. position.top += $node.height() - this.$el.offset().top;
  1272. position.lineHeight = $node.height();
  1273. // special positioning logic for iframes
  1274. // this is typically used for contenteditables such as tinymce or ckeditor
  1275. if (this.completer.$iframe) {
  1276. var iframePosition = this.completer.$iframe.offset();
  1277. position.top += iframePosition.top;
  1278. position.left += iframePosition.left;
  1279. // We need to get the scrollTop of the html-element inside the iframe and not of the body-element,
  1280. // because on IE the scrollTop of the body-element (this.$el) is always zero.
  1281. position.top -= $(this.completer.$iframe[0].contentWindow.document).scrollTop();
  1282. }
  1283. $node.remove();
  1284. return position;
  1285. },
  1286.  
  1287. // Returns the string between the first character and the caret.
  1288. // Completer will be triggered with the result for start autocompleting.
  1289. //
  1290. // Example
  1291. //
  1292. // // Suppose the html is '<b>hello</b> wor|ld' and | is the caret.
  1293. // this.getTextFromHeadToCaret()
  1294. // // => ' wor' // not '<b>hello</b> wor'
  1295. getTextFromHeadToCaret: function () {
  1296. var range = this.el.ownerDocument.getSelection().getRangeAt(0);
  1297. var selection = range.cloneRange();
  1298. selection.selectNodeContents(range.startContainer);
  1299. return selection.toString().substring(0, range.startOffset);
  1300. }
  1301. });
  1302.  
  1303. $.fn.textcomplete.ContentEditable = ContentEditable;
  1304. }(jQuery);
  1305.  
  1306. // NOTE: TextComplete plugin has contenteditable support but it does not work
  1307. // fine especially on old IEs.
  1308. // Any pull requests are REALLY welcome.
  1309.  
  1310. +function ($) {
  1311. 'use strict';
  1312.  
  1313. // CKEditor adapter
  1314. // =======================
  1315. //
  1316. // Adapter for CKEditor, based on contenteditable elements.
  1317. function CKEditor (element, completer, option) {
  1318. this.initialize(element, completer, option);
  1319. }
  1320.  
  1321. $.extend(CKEditor.prototype, $.fn.textcomplete.ContentEditable.prototype, {
  1322. _bindEvents: function () {
  1323. var $this = this;
  1324. this.option.ckeditor_instance.on('key', function(event) {
  1325. var domEvent = event.data;
  1326. $this._onKeyup(domEvent);
  1327. if ($this.completer.dropdown.shown && $this._skipSearch(domEvent)) {
  1328. return false;
  1329. }
  1330. }, null, null, 1); // 1 = Priority = Important!
  1331. // we actually also need the native event, as the CKEditor one is happening to late
  1332. this.$el.on('keyup.' + this.id, $.proxy(this._onKeyup, this));
  1333. },
  1334. });
  1335.  
  1336. $.fn.textcomplete.CKEditor = CKEditor;
  1337. }(jQuery);
  1338.  
  1339. // The MIT License (MIT)
  1340. //
  1341. // Copyright (c) 2015 Jonathan Ong me@jongleberry.com
  1342. //
  1343. // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
  1344. // associated documentation files (the "Software"), to deal in the Software without restriction,
  1345. // including without limitation the rights to use, copy, modify, merge, publish, distribute,
  1346. // sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
  1347. // furnished to do so, subject to the following conditions:
  1348. //
  1349. // The above copyright notice and this permission notice shall be included in all copies or
  1350. // substantial portions of the Software.
  1351. //
  1352. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
  1353. // NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  1354. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  1355. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  1356. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  1357. //
  1358. // https://github.com/component/textarea-caret-position
  1359.  
  1360. (function ($) {
  1361.  
  1362. // The properties that we copy into a mirrored div.
  1363. // Note that some browsers, such as Firefox,
  1364. // do not concatenate properties, i.e. padding-top, bottom etc. -> padding,
  1365. // so we have to do every single property specifically.
  1366. var properties = [
  1367. 'direction', // RTL support
  1368. 'boxSizing',
  1369. 'width', // on Chrome and IE, exclude the scrollbar, so the mirror div wraps exactly as the textarea does
  1370. 'height',
  1371. 'overflowX',
  1372. 'overflowY', // copy the scrollbar for IE
  1373.  
  1374. 'borderTopWidth',
  1375. 'borderRightWidth',
  1376. 'borderBottomWidth',
  1377. 'borderLeftWidth',
  1378. 'borderStyle',
  1379.  
  1380. 'paddingTop',
  1381. 'paddingRight',
  1382. 'paddingBottom',
  1383. 'paddingLeft',
  1384.  
  1385. // https://developer.mozilla.org/en-US/docs/Web/CSS/font
  1386. 'fontStyle',
  1387. 'fontVariant',
  1388. 'fontWeight',
  1389. 'fontStretch',
  1390. 'fontSize',
  1391. 'fontSizeAdjust',
  1392. 'lineHeight',
  1393. 'fontFamily',
  1394.  
  1395. 'textAlign',
  1396. 'textTransform',
  1397. 'textIndent',
  1398. 'textDecoration', // might not make a difference, but better be safe
  1399.  
  1400. 'letterSpacing',
  1401. 'wordSpacing',
  1402.  
  1403. 'tabSize',
  1404. 'MozTabSize'
  1405.  
  1406. ];
  1407.  
  1408. var isBrowser = (typeof window !== 'undefined');
  1409. var isFirefox = (isBrowser && window.mozInnerScreenX != null);
  1410.  
  1411. function getCaretCoordinates(element, position, options) {
  1412. if(!isBrowser) {
  1413. throw new Error('textarea-caret-position#getCaretCoordinates should only be called in a browser');
  1414. }
  1415.  
  1416. var debug = options && options.debug || false;
  1417. if (debug) {
  1418. var el = document.querySelector('#input-textarea-caret-position-mirror-div');
  1419. if ( el ) { el.parentNode.removeChild(el); }
  1420. }
  1421.  
  1422. // mirrored div
  1423. var div = document.createElement('div');
  1424. div.id = 'input-textarea-caret-position-mirror-div';
  1425. document.body.appendChild(div);
  1426.  
  1427. var style = div.style;
  1428. var computed = window.getComputedStyle? getComputedStyle(element) : element.currentStyle; // currentStyle for IE < 9
  1429.  
  1430. // default textarea styles
  1431. style.whiteSpace = 'pre-wrap';
  1432. if (element.nodeName !== 'INPUT')
  1433. style.wordWrap = 'break-word'; // only for textarea-s
  1434.  
  1435. // position off-screen
  1436. style.position = 'absolute'; // required to return coordinates properly
  1437. if (!debug)
  1438. style.visibility = 'hidden'; // not 'display: none' because we want rendering
  1439.  
  1440. // transfer the element's properties to the div
  1441. properties.forEach(function (prop) {
  1442. style[prop] = computed[prop];
  1443. });
  1444.  
  1445. if (isFirefox) {
  1446. // Firefox lies about the overflow property for textareas: https://bugzilla.mozilla.org/show_bug.cgi?id=984275
  1447. if (element.scrollHeight > parseInt(computed.height))
  1448. style.overflowY = 'scroll';
  1449. } else {
  1450. style.overflow = 'hidden'; // for Chrome to not render a scrollbar; IE keeps overflowY = 'scroll'
  1451. }
  1452.  
  1453. div.textContent = element.value.substring(0, position);
  1454. // the second special handling for input type="text" vs textarea: spaces need to be replaced with non-breaking spaces - http://stackoverflow.com/a/13402035/1269037
  1455. if (element.nodeName === 'INPUT')
  1456. div.textContent = div.textContent.replace(/\s/g, '\u00a0');
  1457.  
  1458. var span = document.createElement('span');
  1459. // Wrapping must be replicated *exactly*, including when a long word gets
  1460. // onto the next line, with whitespace at the end of the line before (#7).
  1461. // The *only* reliable way to do that is to copy the *entire* rest of the
  1462. // textarea's content into the <span> created at the caret position.
  1463. // for inputs, just '.' would be enough, but why bother?
  1464. span.textContent = element.value.substring(position) || '.'; // || because a completely empty faux span doesn't render at all
  1465. div.appendChild(span);
  1466.  
  1467. var coordinates = {
  1468. top: span.offsetTop + parseInt(computed['borderTopWidth']),
  1469. left: span.offsetLeft + parseInt(computed['borderLeftWidth'])
  1470. };
  1471.  
  1472. if (debug) {
  1473. span.style.backgroundColor = '#aaa';
  1474. } else {
  1475. document.body.removeChild(div);
  1476. }
  1477.  
  1478. return coordinates;
  1479. }
  1480.  
  1481. $.fn.textcomplete.getCaretCoordinates = getCaretCoordinates;
  1482.  
  1483. }(jQuery));
  1484.  
  1485. return jQuery;
  1486. }));