3ac514f13735ebe8f07141225a69ba288a6c3d9e39eb3826b35b97376103c1cafb993b041b5caaac268b5b68902b00080f1832b9908d18617f5398f2799ed1 13 KB

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