jquery.textcomplete.js 46 KB

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