autocompleteEditor.js 13 KB

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