autocompleteEditor.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. 'use strict';
  2. exports.__esModule = true;
  3. var _unicode = require('./../helpers/unicode');
  4. var _mixed = require('./../helpers/mixed');
  5. var _string = require('./../helpers/string');
  6. var _array = require('./../helpers/array');
  7. var _element = require('./../helpers/dom/element');
  8. var _handsontableEditor = require('./handsontableEditor');
  9. var _handsontableEditor2 = _interopRequireDefault(_handsontableEditor);
  10. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  11. var AutocompleteEditor = _handsontableEditor2.default.prototype.extend();
  12. /**
  13. * @private
  14. * @editor AutocompleteEditor
  15. * @class AutocompleteEditor
  16. * @dependencies HandsontableEditor
  17. */
  18. AutocompleteEditor.prototype.init = function () {
  19. _handsontableEditor2.default.prototype.init.apply(this, arguments);
  20. this.query = null;
  21. this.strippedChoices = [];
  22. this.rawChoices = [];
  23. };
  24. AutocompleteEditor.prototype.getValue = function () {
  25. var _this2 = this;
  26. var selectedValue = this.rawChoices.find(function (value) {
  27. var strippedValue = _this2.stripValueIfNeeded(value);
  28. return strippedValue === _this2.TEXTAREA.value;
  29. });
  30. if ((0, _mixed.isDefined)(selectedValue)) {
  31. return selectedValue;
  32. }
  33. return this.TEXTAREA.value;
  34. };
  35. AutocompleteEditor.prototype.createElements = function () {
  36. _handsontableEditor2.default.prototype.createElements.apply(this, arguments);
  37. (0, _element.addClass)(this.htContainer, 'autocompleteEditor');
  38. (0, _element.addClass)(this.htContainer, window.navigator.platform.indexOf('Mac') === -1 ? '' : 'htMacScroll');
  39. };
  40. var skipOne = false;
  41. function onBeforeKeyDown(event) {
  42. skipOne = false;
  43. var editor = this.getActiveEditor();
  44. if ((0, _unicode.isPrintableChar)(event.keyCode) || event.keyCode === _unicode.KEY_CODES.BACKSPACE || event.keyCode === _unicode.KEY_CODES.DELETE || event.keyCode === _unicode.KEY_CODES.INSERT) {
  45. var timeOffset = 0;
  46. // on ctl+c / cmd+c don't update suggestion list
  47. if (event.keyCode === _unicode.KEY_CODES.C && (event.ctrlKey || event.metaKey)) {
  48. return;
  49. }
  50. if (!editor.isOpened()) {
  51. timeOffset += 10;
  52. }
  53. if (editor.htEditor) {
  54. editor.instance._registerTimeout(setTimeout(function () {
  55. editor.queryChoices(editor.TEXTAREA.value);
  56. skipOne = true;
  57. }, timeOffset));
  58. }
  59. }
  60. }
  61. AutocompleteEditor.prototype.prepare = function () {
  62. this.instance.addHook('beforeKeyDown', onBeforeKeyDown);
  63. _handsontableEditor2.default.prototype.prepare.apply(this, arguments);
  64. };
  65. AutocompleteEditor.prototype.open = function () {
  66. // Ugly fix for handsontable which grab window object for autocomplete scroll listener instead table element.
  67. this.TEXTAREA_PARENT.style.overflow = 'auto';
  68. _handsontableEditor2.default.prototype.open.apply(this, arguments);
  69. this.TEXTAREA_PARENT.style.overflow = '';
  70. var choicesListHot = this.htEditor.getInstance();
  71. var _this = this;
  72. var trimDropdown = this.cellProperties.trimDropdown === void 0 ? true : this.cellProperties.trimDropdown;
  73. this.TEXTAREA.style.visibility = 'visible';
  74. this.focus();
  75. choicesListHot.updateSettings({
  76. colWidths: trimDropdown ? [(0, _element.outerWidth)(this.TEXTAREA) - 2] : void 0,
  77. width: trimDropdown ? (0, _element.outerWidth)(this.TEXTAREA) + (0, _element.getScrollbarWidth)() + 2 : void 0,
  78. afterRenderer: function afterRenderer(TD, row, col, prop, value, cellProperties) {
  79. var _this$cellProperties = _this.cellProperties,
  80. filteringCaseSensitive = _this$cellProperties.filteringCaseSensitive,
  81. allowHtml = _this$cellProperties.allowHtml;
  82. var indexOfMatch = void 0;
  83. var match = void 0;
  84. value = (0, _mixed.stringify)(value);
  85. if (value && !allowHtml) {
  86. indexOfMatch = filteringCaseSensitive === true ? value.indexOf(this.query) : value.toLowerCase().indexOf(_this.query.toLowerCase());
  87. if (indexOfMatch !== -1) {
  88. match = value.substr(indexOfMatch, _this.query.length);
  89. value = value.replace(match, '<strong>' + match + '</strong>');
  90. }
  91. }
  92. TD.innerHTML = value;
  93. },
  94. autoColumnSize: true,
  95. modifyColWidth: function modifyColWidth(width, col) {
  96. // workaround for <strong> text overlapping the dropdown, not really accurate
  97. var autoWidths = this.getPlugin('autoColumnSize').widths;
  98. if (autoWidths[col]) {
  99. width = autoWidths[col];
  100. }
  101. return trimDropdown ? width : width + 15;
  102. }
  103. });
  104. // Add additional space for autocomplete holder
  105. this.htEditor.view.wt.wtTable.holder.parentNode.style['padding-right'] = (0, _element.getScrollbarWidth)() + 2 + 'px';
  106. if (skipOne) {
  107. skipOne = false;
  108. }
  109. _this.instance._registerTimeout(setTimeout(function () {
  110. _this.queryChoices(_this.TEXTAREA.value);
  111. }, 0));
  112. };
  113. AutocompleteEditor.prototype.close = function () {
  114. _handsontableEditor2.default.prototype.close.apply(this, arguments);
  115. };
  116. AutocompleteEditor.prototype.queryChoices = function (query) {
  117. var _this3 = this;
  118. this.query = query;
  119. var source = this.cellProperties.source;
  120. if (typeof source == 'function') {
  121. source.call(this.cellProperties, query, function (choices) {
  122. _this3.rawChoices = choices;
  123. _this3.updateChoicesList(_this3.stripValuesIfNeeded(choices));
  124. });
  125. } else if (Array.isArray(source)) {
  126. this.rawChoices = source;
  127. this.updateChoicesList(this.stripValuesIfNeeded(source));
  128. } else {
  129. this.updateChoicesList([]);
  130. }
  131. };
  132. AutocompleteEditor.prototype.updateChoicesList = function (choices) {
  133. var pos = (0, _element.getCaretPosition)(this.TEXTAREA);
  134. var endPos = (0, _element.getSelectionEndPosition)(this.TEXTAREA);
  135. var sortByRelevanceSetting = this.cellProperties.sortByRelevance;
  136. var filterSetting = this.cellProperties.filter;
  137. var orderByRelevance = null;
  138. var highlightIndex = null;
  139. if (sortByRelevanceSetting) {
  140. orderByRelevance = AutocompleteEditor.sortByRelevance(this.stripValueIfNeeded(this.getValue()), choices, this.cellProperties.filteringCaseSensitive);
  141. }
  142. var orderByRelevanceLength = Array.isArray(orderByRelevance) ? orderByRelevance.length : 0;
  143. if (filterSetting === false) {
  144. if (orderByRelevanceLength) {
  145. highlightIndex = orderByRelevance[0];
  146. }
  147. } else {
  148. var sorted = [];
  149. for (var i = 0, choicesCount = choices.length; i < choicesCount; i++) {
  150. if (sortByRelevanceSetting && orderByRelevanceLength <= i) {
  151. break;
  152. }
  153. if (orderByRelevanceLength) {
  154. sorted.push(choices[orderByRelevance[i]]);
  155. } else {
  156. sorted.push(choices[i]);
  157. }
  158. }
  159. highlightIndex = 0;
  160. choices = sorted;
  161. }
  162. this.strippedChoices = choices;
  163. this.htEditor.loadData((0, _array.pivot)([choices]));
  164. this.updateDropdownHeight();
  165. this.flipDropdownIfNeeded();
  166. if (this.cellProperties.strict === true) {
  167. this.highlightBestMatchingChoice(highlightIndex);
  168. }
  169. this.instance.listen();
  170. this.TEXTAREA.focus();
  171. (0, _element.setCaretPosition)(this.TEXTAREA, pos, pos === endPos ? void 0 : endPos);
  172. };
  173. AutocompleteEditor.prototype.flipDropdownIfNeeded = function () {
  174. var textareaOffset = (0, _element.offset)(this.TEXTAREA);
  175. var textareaHeight = (0, _element.outerHeight)(this.TEXTAREA);
  176. var dropdownHeight = this.getDropdownHeight();
  177. var trimmingContainer = (0, _element.getTrimmingContainer)(this.instance.view.wt.wtTable.TABLE);
  178. var trimmingContainerScrollTop = trimmingContainer.scrollTop;
  179. var headersHeight = (0, _element.outerHeight)(this.instance.view.wt.wtTable.THEAD);
  180. var containerOffset = {
  181. row: 0,
  182. col: 0
  183. };
  184. if (trimmingContainer !== window) {
  185. containerOffset = (0, _element.offset)(trimmingContainer);
  186. }
  187. var spaceAbove = textareaOffset.top - containerOffset.top - headersHeight + trimmingContainerScrollTop;
  188. var spaceBelow = trimmingContainer.scrollHeight - spaceAbove - headersHeight - textareaHeight;
  189. var flipNeeded = dropdownHeight > spaceBelow && spaceAbove > spaceBelow;
  190. if (flipNeeded) {
  191. this.flipDropdown(dropdownHeight);
  192. } else {
  193. this.unflipDropdown();
  194. }
  195. this.limitDropdownIfNeeded(flipNeeded ? spaceAbove : spaceBelow, dropdownHeight);
  196. return flipNeeded;
  197. };
  198. AutocompleteEditor.prototype.limitDropdownIfNeeded = function (spaceAvailable, dropdownHeight) {
  199. if (dropdownHeight > spaceAvailable) {
  200. var tempHeight = 0;
  201. var i = 0;
  202. var lastRowHeight = 0;
  203. var height = null;
  204. do {
  205. lastRowHeight = this.htEditor.getRowHeight(i) || this.htEditor.view.wt.wtSettings.settings.defaultRowHeight;
  206. tempHeight += lastRowHeight;
  207. i++;
  208. } while (tempHeight < spaceAvailable);
  209. height = tempHeight - lastRowHeight;
  210. if (this.htEditor.flipped) {
  211. this.htEditor.rootElement.style.top = parseInt(this.htEditor.rootElement.style.top, 10) + dropdownHeight - height + 'px';
  212. }
  213. this.setDropdownHeight(tempHeight - lastRowHeight);
  214. }
  215. };
  216. AutocompleteEditor.prototype.flipDropdown = function (dropdownHeight) {
  217. var dropdownStyle = this.htEditor.rootElement.style;
  218. dropdownStyle.position = 'absolute';
  219. dropdownStyle.top = -dropdownHeight + 'px';
  220. this.htEditor.flipped = true;
  221. };
  222. AutocompleteEditor.prototype.unflipDropdown = function () {
  223. var dropdownStyle = this.htEditor.rootElement.style;
  224. if (dropdownStyle.position === 'absolute') {
  225. dropdownStyle.position = '';
  226. dropdownStyle.top = '';
  227. }
  228. this.htEditor.flipped = void 0;
  229. };
  230. AutocompleteEditor.prototype.updateDropdownHeight = function () {
  231. var currentDropdownWidth = this.htEditor.getColWidth(0) + (0, _element.getScrollbarWidth)() + 2;
  232. var trimDropdown = this.cellProperties.trimDropdown;
  233. this.htEditor.updateSettings({
  234. height: this.getDropdownHeight(),
  235. width: trimDropdown ? void 0 : currentDropdownWidth
  236. });
  237. this.htEditor.view.wt.wtTable.alignOverlaysWithTrimmingContainer();
  238. };
  239. AutocompleteEditor.prototype.setDropdownHeight = function (height) {
  240. this.htEditor.updateSettings({
  241. height: height
  242. });
  243. };
  244. AutocompleteEditor.prototype.finishEditing = function (restoreOriginalValue) {
  245. if (!restoreOriginalValue) {
  246. this.instance.removeHook('beforeKeyDown', onBeforeKeyDown);
  247. }
  248. _handsontableEditor2.default.prototype.finishEditing.apply(this, arguments);
  249. };
  250. AutocompleteEditor.prototype.highlightBestMatchingChoice = function (index) {
  251. if (typeof index === 'number') {
  252. this.htEditor.selectCell(index, 0);
  253. } else {
  254. this.htEditor.deselectCell();
  255. }
  256. };
  257. /**
  258. * Filters and sorts by relevance
  259. * @param value
  260. * @param choices
  261. * @param caseSensitive
  262. * @returns {Array} array of indexes in original choices array
  263. */
  264. AutocompleteEditor.sortByRelevance = function (value, choices, caseSensitive) {
  265. var choicesRelevance = [];
  266. var currentItem = void 0;
  267. var valueLength = value.length;
  268. var valueIndex = void 0;
  269. var charsLeft = void 0;
  270. var result = [];
  271. var i = void 0;
  272. var choicesCount = choices.length;
  273. if (valueLength === 0) {
  274. for (i = 0; i < choicesCount; i++) {
  275. result.push(i);
  276. }
  277. return result;
  278. }
  279. for (i = 0; i < choicesCount; i++) {
  280. currentItem = (0, _string.stripTags)((0, _mixed.stringify)(choices[i]));
  281. if (caseSensitive) {
  282. valueIndex = currentItem.indexOf(value);
  283. } else {
  284. valueIndex = currentItem.toLowerCase().indexOf(value.toLowerCase());
  285. }
  286. if (valueIndex !== -1) {
  287. charsLeft = currentItem.length - valueIndex - valueLength;
  288. choicesRelevance.push({
  289. baseIndex: i,
  290. index: valueIndex,
  291. charsLeft: charsLeft,
  292. value: currentItem
  293. });
  294. }
  295. }
  296. choicesRelevance.sort(function (a, b) {
  297. if (b.index === -1) {
  298. return -1;
  299. }
  300. if (a.index === -1) {
  301. return 1;
  302. }
  303. if (a.index < b.index) {
  304. return -1;
  305. } else if (b.index < a.index) {
  306. return 1;
  307. } else if (a.index === b.index) {
  308. if (a.charsLeft < b.charsLeft) {
  309. return -1;
  310. } else if (a.charsLeft > b.charsLeft) {
  311. return 1;
  312. }
  313. }
  314. return 0;
  315. });
  316. for (i = 0, choicesCount = choicesRelevance.length; i < choicesCount; i++) {
  317. result.push(choicesRelevance[i].baseIndex);
  318. }
  319. return result;
  320. };
  321. AutocompleteEditor.prototype.getDropdownHeight = function () {
  322. var firstRowHeight = this.htEditor.getInstance().getRowHeight(0) || 23;
  323. var visibleRows = this.cellProperties.visibleRows;
  324. return this.strippedChoices.length >= visibleRows ? visibleRows * firstRowHeight : this.strippedChoices.length * firstRowHeight + 8;
  325. };
  326. AutocompleteEditor.prototype.stripValueIfNeeded = function (value) {
  327. return this.stripValuesIfNeeded([value])[0];
  328. };
  329. AutocompleteEditor.prototype.stripValuesIfNeeded = function (values) {
  330. var allowHtml = this.cellProperties.allowHtml;
  331. var stringifiedValues = (0, _array.arrayMap)(values, function (value) {
  332. return (0, _mixed.stringify)(value);
  333. });
  334. var strippedValues = (0, _array.arrayMap)(stringifiedValues, function (value) {
  335. return allowHtml ? value : (0, _string.stripTags)(value);
  336. });
  337. return strippedValues;
  338. };
  339. AutocompleteEditor.prototype.allowKeyEventPropagation = function (keyCode) {
  340. var selected = { row: this.htEditor.getSelectedRange() ? this.htEditor.getSelectedRange().from.row : -1 };
  341. var allowed = false;
  342. if (keyCode === _unicode.KEY_CODES.ARROW_DOWN && selected.row > 0 && selected.row < this.htEditor.countRows() - 1) {
  343. allowed = true;
  344. }
  345. if (keyCode === _unicode.KEY_CODES.ARROW_UP && selected.row > -1) {
  346. allowed = true;
  347. }
  348. return allowed;
  349. };
  350. AutocompleteEditor.prototype.discardEditor = function (result) {
  351. _handsontableEditor2.default.prototype.discardEditor.apply(this, arguments);
  352. this.instance.view.render();
  353. };
  354. exports.default = AutocompleteEditor;