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