6932001bb0b5afa2b44e7ce3a5d9c5d10fed263f6282fce31122a428021eff97ff34d200415642f856e2b972f3ed18ae679297891c931e1fdd9cca4c5fac38 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688
  1. import Core from './../../core';
  2. import {
  3. addClass,
  4. empty,
  5. fastInnerHTML,
  6. getScrollbarWidth,
  7. isChildOf,
  8. removeClass,
  9. } from './../../helpers/dom/element';
  10. import {arrayEach, arrayFilter, arrayReduce} from './../../helpers/array';
  11. import Cursor from './cursor';
  12. import EventManager from './../../eventManager';
  13. import {mixin, hasOwnProperty} from './../../helpers/object';
  14. import {debounce} from './../../helpers/function';
  15. import {filterSeparators, hasSubMenu, isDisabled, isItemHidden, isSeparator, isSelectionDisabled, normalizeSelection} from './utils';
  16. import {KEY_CODES} from './../../helpers/unicode';
  17. import localHooks from './../../mixins/localHooks';
  18. import {SEPARATOR} from './predefinedItems';
  19. import {stopImmediatePropagation} from './../../helpers/dom/event';
  20. /**
  21. * @class Menu
  22. * @plugin ContextMenu
  23. */
  24. class Menu {
  25. constructor(hotInstance, options) {
  26. this.hot = hotInstance;
  27. this.options = options || {
  28. parent: null,
  29. name: null,
  30. className: '',
  31. keepInViewport: true,
  32. standalone: false
  33. };
  34. this.eventManager = new EventManager(this);
  35. this.container = this.createContainer(this.options.name);
  36. this.hotMenu = null;
  37. this.hotSubMenus = {};
  38. this.parentMenu = this.options.parent || null;
  39. this.menuItems = null;
  40. this.origOutsideClickDeselects = null;
  41. this.keyEvent = false;
  42. this.offset = {
  43. above: 0,
  44. below: 0,
  45. left: 0,
  46. right: 0
  47. };
  48. this._afterScrollCallback = null;
  49. this.registerEvents();
  50. }
  51. /**
  52. * Register event listeners.
  53. *
  54. * @private
  55. */
  56. registerEvents() {
  57. this.eventManager.addEventListener(document.documentElement, 'mousedown', (event) => this.onDocumentMouseDown(event));
  58. }
  59. /**
  60. * Set array of objects which defines menu items.
  61. *
  62. * @param {Array} menuItems Menu items to display.
  63. */
  64. setMenuItems(menuItems) {
  65. this.menuItems = menuItems;
  66. }
  67. /**
  68. * Set offset menu position for specified area (`above`, `below`, `left` or `right`).
  69. *
  70. * @param {String} area Specified area name (`above`, `below`, `left` or `right`).
  71. * @param {Number} offset Offset value.
  72. */
  73. setOffset(area, offset = 0) {
  74. this.offset[area] = offset;
  75. }
  76. /**
  77. * Check if menu is using as sub-menu.
  78. *
  79. * @returns {Boolean}
  80. */
  81. isSubMenu() {
  82. return this.parentMenu !== null;
  83. }
  84. /**
  85. * Open menu.
  86. */
  87. open() {
  88. this.container.removeAttribute('style');
  89. this.container.style.display = 'block';
  90. const delayedOpenSubMenu = debounce((row) => this.openSubMenu(row), 300);
  91. let filteredItems = arrayFilter(this.menuItems, (item) => isItemHidden(item, this.hot));
  92. filteredItems = filterSeparators(filteredItems, SEPARATOR);
  93. let settings = {
  94. data: filteredItems,
  95. colHeaders: false,
  96. colWidths: [200],
  97. autoRowSize: false,
  98. readOnly: true,
  99. copyPaste: false,
  100. columns: [{
  101. data: 'name',
  102. renderer: (hot, TD, row, col, prop, value) => this.menuItemRenderer(hot, TD, row, col, prop, value)
  103. }],
  104. renderAllRows: true,
  105. fragmentSelection: 'cell',
  106. disableVisualSelection: 'area',
  107. beforeKeyDown: (event) => this.onBeforeKeyDown(event),
  108. afterOnCellMouseOver: (event, coords, TD) => {
  109. if (this.isAllSubMenusClosed()) {
  110. delayedOpenSubMenu(coords.row);
  111. } else {
  112. this.openSubMenu(coords.row);
  113. }
  114. },
  115. rowHeights: (row) => (filteredItems[row].name === SEPARATOR ? 1 : 23)
  116. };
  117. this.origOutsideClickDeselects = this.hot.getSettings().outsideClickDeselects;
  118. this.hot.getSettings().outsideClickDeselects = false;
  119. this.hotMenu = new Core(this.container, settings);
  120. this.hotMenu.addHook('afterInit', () => this.onAfterInit());
  121. this.hotMenu.addHook('afterSelection', (r, c, r2, c2, preventScrolling) => this.onAfterSelection(r, c, r2, c2, preventScrolling));
  122. this.hotMenu.init();
  123. this.hotMenu.listen();
  124. this.blockMainTableCallbacks();
  125. this.runLocalHooks('afterOpen');
  126. }
  127. /**
  128. * Close menu.
  129. *
  130. * @param {Boolean} [closeParent=false] if `true` try to close parent menu if exists.
  131. */
  132. close(closeParent = false) {
  133. if (!this.isOpened()) {
  134. return;
  135. }
  136. if (closeParent && this.parentMenu) {
  137. this.parentMenu.close();
  138. } else {
  139. this.closeAllSubMenus();
  140. this.container.style.display = 'none';
  141. this.releaseMainTableCallbacks();
  142. this.hotMenu.destroy();
  143. this.hotMenu = null;
  144. this.hot.getSettings().outsideClickDeselects = this.origOutsideClickDeselects;
  145. this.runLocalHooks('afterClose');
  146. if (this.parentMenu) {
  147. this.parentMenu.hotMenu.listen();
  148. }
  149. }
  150. }
  151. /**
  152. * Open sub menu at the provided row index.
  153. *
  154. * @param {Number} row Row index.
  155. * @returns {Menu|Boolean} Returns created menu or `false` if no one menu was created.
  156. */
  157. openSubMenu(row) {
  158. if (!this.hotMenu) {
  159. return false;
  160. }
  161. let cell = this.hotMenu.getCell(row, 0);
  162. this.closeAllSubMenus();
  163. if (!cell || !hasSubMenu(cell)) {
  164. return false;
  165. }
  166. let dataItem = this.hotMenu.getSourceDataAtRow(row);
  167. let subMenu = new Menu(this.hot, {
  168. parent: this,
  169. name: dataItem.name,
  170. className: this.options.className,
  171. keepInViewport: true
  172. });
  173. subMenu.setMenuItems(dataItem.submenu.items);
  174. subMenu.open();
  175. subMenu.setPosition(cell.getBoundingClientRect());
  176. this.hotSubMenus[dataItem.key] = subMenu;
  177. return subMenu;
  178. }
  179. /**
  180. * Close sub menu at row index.
  181. *
  182. * @param {Number} row Row index.
  183. */
  184. closeSubMenu(row) {
  185. let dataItem = this.hotMenu.getSourceDataAtRow(row);
  186. let menus = this.hotSubMenus[dataItem.key];
  187. if (menus) {
  188. menus.destroy();
  189. delete this.hotSubMenus[dataItem.key];
  190. }
  191. }
  192. /**
  193. * Close all opened sub menus.
  194. */
  195. closeAllSubMenus() {
  196. arrayEach(this.hotMenu.getData(), (value, row) => this.closeSubMenu(row));
  197. }
  198. /**
  199. * Checks if all created and opened sub menus are closed.
  200. *
  201. * @returns {Boolean}
  202. */
  203. isAllSubMenusClosed() {
  204. return Object.keys(this.hotSubMenus).length === 0;
  205. }
  206. /**
  207. * Destroy instance.
  208. */
  209. destroy() {
  210. this.clearLocalHooks();
  211. this.close();
  212. this.parentMenu = null;
  213. this.eventManager.destroy();
  214. }
  215. /**
  216. * Checks if menu was opened.
  217. *
  218. * @returns {Boolean} Returns `true` if menu was opened.
  219. */
  220. isOpened() {
  221. return this.hotMenu !== null;
  222. }
  223. /**
  224. * Execute menu command.
  225. *
  226. * @param {Event} [event]
  227. */
  228. executeCommand(event) {
  229. if (!this.isOpened() || !this.hotMenu.getSelected()) {
  230. return;
  231. }
  232. const selectedItem = this.hotMenu.getSourceDataAtRow(this.hotMenu.getSelected()[0]);
  233. this.runLocalHooks('select', selectedItem, event);
  234. if (selectedItem.isCommand === false || selectedItem.name === SEPARATOR) {
  235. return;
  236. }
  237. const selRange = this.hot.getSelectedRange();
  238. const normalizedSelection = selRange ? normalizeSelection(selRange) : {};
  239. let autoClose = true;
  240. // Don't close context menu if item is disabled or it has submenu
  241. if (selectedItem.disabled === true ||
  242. (typeof selectedItem.disabled === 'function' && selectedItem.disabled.call(this.hot) === true) ||
  243. selectedItem.submenu) {
  244. autoClose = false;
  245. }
  246. this.runLocalHooks('executeCommand', selectedItem.key, normalizedSelection, event);
  247. if (this.isSubMenu()) {
  248. this.parentMenu.runLocalHooks('executeCommand', selectedItem.key, normalizedSelection, event);
  249. }
  250. if (autoClose) {
  251. this.close(true);
  252. }
  253. }
  254. /**
  255. * Set menu position based on dom event or based on literal object.
  256. *
  257. * @param {Event|Object} coords Event or literal Object with coordinates.
  258. */
  259. setPosition(coords) {
  260. const cursor = new Cursor(coords);
  261. if (this.options.keepInViewport) {
  262. if (cursor.fitsBelow(this.container)) {
  263. this.setPositionBelowCursor(cursor);
  264. } else if (cursor.fitsAbove(this.container)) {
  265. this.setPositionAboveCursor(cursor);
  266. } else {
  267. this.setPositionBelowCursor(cursor);
  268. }
  269. if (cursor.fitsOnRight(this.container)) {
  270. this.setPositionOnRightOfCursor(cursor);
  271. } else {
  272. this.setPositionOnLeftOfCursor(cursor);
  273. }
  274. } else {
  275. this.setPositionBelowCursor(cursor);
  276. this.setPositionOnRightOfCursor(cursor);
  277. }
  278. }
  279. /**
  280. * Set menu position above cursor object.
  281. *
  282. * @param {Cursor} cursor `Cursor` object.
  283. */
  284. setPositionAboveCursor(cursor) {
  285. let top = this.offset.above + cursor.top - this.container.offsetHeight;
  286. if (this.isSubMenu()) {
  287. top = cursor.top + cursor.cellHeight - this.container.offsetHeight + 3;
  288. }
  289. this.container.style.top = `${top}px`;
  290. }
  291. /**
  292. * Set menu position below cursor object.
  293. *
  294. * @param {Cursor} cursor `Cursor` object.
  295. */
  296. setPositionBelowCursor(cursor) {
  297. let top = this.offset.below + cursor.top;
  298. if (this.isSubMenu()) {
  299. top = cursor.top - 1;
  300. }
  301. this.container.style.top = `${top}px`;
  302. }
  303. /**
  304. * Set menu position on the right of cursor object.
  305. *
  306. * @param {Cursor} cursor `Cursor` object.
  307. */
  308. setPositionOnRightOfCursor(cursor) {
  309. let left;
  310. if (this.isSubMenu()) {
  311. left = 1 + cursor.left + cursor.cellWidth;
  312. } else {
  313. left = this.offset.right + 1 + cursor.left;
  314. }
  315. this.container.style.left = `${left}px`;
  316. }
  317. /**
  318. * Set menu position on the left of cursor object.
  319. *
  320. * @param {Cursor} cursor `Cursor` object.
  321. */
  322. setPositionOnLeftOfCursor(cursor) {
  323. let left = this.offset.left + cursor.left - this.container.offsetWidth + getScrollbarWidth() + 4;
  324. this.container.style.left = `${left}px`;
  325. }
  326. /**
  327. * Select first cell in opened menu.
  328. */
  329. selectFirstCell() {
  330. let cell = this.hotMenu.getCell(0, 0);
  331. if (isSeparator(cell) || isDisabled(cell) || isSelectionDisabled(cell)) {
  332. this.selectNextCell(0, 0);
  333. } else {
  334. this.hotMenu.selectCell(0, 0);
  335. }
  336. }
  337. /**
  338. * Select last cell in opened menu.
  339. */
  340. selectLastCell() {
  341. let lastRow = this.hotMenu.countRows() - 1;
  342. let cell = this.hotMenu.getCell(lastRow, 0);
  343. if (isSeparator(cell) || isDisabled(cell) || isSelectionDisabled(cell)) {
  344. this.selectPrevCell(lastRow, 0);
  345. } else {
  346. this.hotMenu.selectCell(lastRow, 0);
  347. }
  348. }
  349. /**
  350. * Select next cell in opened menu.
  351. *
  352. * @param {Number} row Row index.
  353. * @param {Number} col Column index.
  354. */
  355. selectNextCell(row, col) {
  356. let nextRow = row + 1;
  357. let cell = nextRow < this.hotMenu.countRows() ? this.hotMenu.getCell(nextRow, col) : null;
  358. if (!cell) {
  359. return;
  360. }
  361. if (isSeparator(cell) || isDisabled(cell) || isSelectionDisabled(cell)) {
  362. this.selectNextCell(nextRow, col);
  363. } else {
  364. this.hotMenu.selectCell(nextRow, col);
  365. }
  366. }
  367. /**
  368. * Select previous cell in opened menu.
  369. *
  370. * @param {Number} row Row index.
  371. * @param {Number} col Column index.
  372. */
  373. selectPrevCell(row, col) {
  374. let prevRow = row - 1;
  375. let cell = prevRow >= 0 ? this.hotMenu.getCell(prevRow, col) : null;
  376. if (!cell) {
  377. return;
  378. }
  379. if (isSeparator(cell) || isDisabled(cell) || isSelectionDisabled(cell)) {
  380. this.selectPrevCell(prevRow, col);
  381. } else {
  382. this.hotMenu.selectCell(prevRow, col);
  383. }
  384. }
  385. /**
  386. * Menu item renderer.
  387. *
  388. * @private
  389. */
  390. menuItemRenderer(hot, TD, row, col, prop, value) {
  391. let item = hot.getSourceDataAtRow(row);
  392. let wrapper = document.createElement('div');
  393. let isSubMenu = (item) => hasOwnProperty(item, 'submenu');
  394. let itemIsSeparator = (item) => new RegExp(SEPARATOR, 'i').test(item.name);
  395. let itemIsDisabled = (item) => item.disabled === true || (typeof item.disabled == 'function' && item.disabled.call(this.hot) === true);
  396. let itemIsSelectionDisabled = (item) => item.disableSelection;
  397. if (typeof value === 'function') {
  398. value = value.call(this.hot);
  399. }
  400. empty(TD);
  401. addClass(wrapper, 'htItemWrapper');
  402. TD.appendChild(wrapper);
  403. if (itemIsSeparator(item)) {
  404. addClass(TD, 'htSeparator');
  405. } else if (typeof item.renderer === 'function') {
  406. addClass(TD, 'htCustomMenuRenderer');
  407. TD.appendChild(item.renderer(hot, wrapper, row, col, prop, value));
  408. } else {
  409. fastInnerHTML(wrapper, value);
  410. }
  411. if (itemIsDisabled(item)) {
  412. addClass(TD, 'htDisabled');
  413. this.eventManager.addEventListener(TD, 'mouseenter', () => hot.deselectCell());
  414. } else if (itemIsSelectionDisabled(item)) {
  415. addClass(TD, 'htSelectionDisabled');
  416. this.eventManager.addEventListener(TD, 'mouseenter', () => hot.deselectCell());
  417. } else if (isSubMenu(item)) {
  418. addClass(TD, 'htSubmenu');
  419. if (itemIsSelectionDisabled(item)) {
  420. this.eventManager.addEventListener(TD, 'mouseenter', () => hot.deselectCell());
  421. } else {
  422. this.eventManager.addEventListener(TD, 'mouseenter', () => hot.selectCell(row, col, void 0, void 0, false, false));
  423. }
  424. } else {
  425. removeClass(TD, 'htSubmenu');
  426. removeClass(TD, 'htDisabled');
  427. if (itemIsSelectionDisabled(item)) {
  428. this.eventManager.addEventListener(TD, 'mouseenter', () => hot.deselectCell());
  429. } else {
  430. this.eventManager.addEventListener(TD, 'mouseenter', () => hot.selectCell(row, col, void 0, void 0, false, false));
  431. }
  432. }
  433. }
  434. /**
  435. * Create container/wrapper for handsontable.
  436. *
  437. * @private
  438. * @param {String} [name] Class name.
  439. * @returns {HTMLElement}
  440. */
  441. createContainer(name = null) {
  442. if (name) {
  443. name = name.replace(/[^A-z0-9]/g, '_');
  444. name = `${this.options.className}Sub_${name}`;
  445. }
  446. let container;
  447. if (name) {
  448. container = document.querySelector(`.${this.options.className}.${name}`);
  449. } else {
  450. container = document.querySelector(`.${this.options.className}`);
  451. }
  452. if (!container) {
  453. container = document.createElement('div');
  454. addClass(container, `htMenu ${this.options.className}`);
  455. if (name) {
  456. addClass(container, name);
  457. }
  458. document.getElementsByTagName('body')[0].appendChild(container);
  459. }
  460. return container;
  461. }
  462. /**
  463. * @private
  464. */
  465. blockMainTableCallbacks() {
  466. this._afterScrollCallback = function() {};
  467. this.hot.addHook('afterScrollVertically', this._afterScrollCallback);
  468. this.hot.addHook('afterScrollHorizontally', this._afterScrollCallback);
  469. }
  470. /**
  471. * @private
  472. */
  473. releaseMainTableCallbacks() {
  474. if (this._afterScrollCallback) {
  475. this.hot.removeHook('afterScrollVertically', this._afterScrollCallback);
  476. this.hot.removeHook('afterScrollHorizontally', this._afterScrollCallback);
  477. this._afterScrollCallback = null;
  478. }
  479. }
  480. /**
  481. * On before key down listener.
  482. *
  483. * @private
  484. * @param {Event} event
  485. */
  486. onBeforeKeyDown(event) {
  487. let selection = this.hotMenu.getSelected();
  488. let stopEvent = false;
  489. this.keyEvent = true;
  490. switch (event.keyCode) {
  491. case KEY_CODES.ESCAPE:
  492. this.close();
  493. stopEvent = true;
  494. break;
  495. case KEY_CODES.ENTER:
  496. if (selection) {
  497. if (this.hotMenu.getSourceDataAtRow(selection[0]).submenu) {
  498. stopEvent = true;
  499. } else {
  500. this.executeCommand(event);
  501. this.close(true);
  502. }
  503. }
  504. break;
  505. case KEY_CODES.ARROW_DOWN:
  506. if (selection) {
  507. this.selectNextCell(selection[0], selection[1]);
  508. } else {
  509. this.selectFirstCell();
  510. }
  511. stopEvent = true;
  512. break;
  513. case KEY_CODES.ARROW_UP:
  514. if (selection) {
  515. this.selectPrevCell(selection[0], selection[1]);
  516. } else {
  517. this.selectLastCell();
  518. }
  519. stopEvent = true;
  520. break;
  521. case KEY_CODES.ARROW_RIGHT:
  522. if (selection) {
  523. let menu = this.openSubMenu(selection[0]);
  524. if (menu) {
  525. menu.selectFirstCell();
  526. }
  527. }
  528. stopEvent = true;
  529. break;
  530. case KEY_CODES.ARROW_LEFT:
  531. if (selection && this.isSubMenu()) {
  532. this.close();
  533. if (this.parentMenu) {
  534. this.parentMenu.hotMenu.listen();
  535. }
  536. stopEvent = true;
  537. }
  538. break;
  539. default:
  540. break;
  541. }
  542. if (stopEvent) {
  543. event.preventDefault();
  544. stopImmediatePropagation(event);
  545. }
  546. this.keyEvent = false;
  547. }
  548. /**
  549. * On after init listener.
  550. *
  551. * @private
  552. */
  553. onAfterInit() {
  554. const data = this.hotMenu.getSettings().data;
  555. const hiderStyle = this.hotMenu.view.wt.wtTable.hider.style;
  556. const holderStyle = this.hotMenu.view.wt.wtTable.holder.style;
  557. let currentHiderWidth = parseInt(hiderStyle.width, 10);
  558. let realHeight = arrayReduce(data, (accumulator, value) => accumulator + (value.name === SEPARATOR ? 1 : 26), 0);
  559. holderStyle.width = `${currentHiderWidth + 22}px`;
  560. holderStyle.height = `${realHeight + 4}px`;
  561. hiderStyle.height = holderStyle.height;
  562. }
  563. /**
  564. * On after selection listener.
  565. *
  566. * @param {Number} r Selection start row index.
  567. * @param {Number} c Selection start column index.
  568. * @param {Number} r2 Selection end row index.
  569. * @param {Number} c2 Selection end column index.
  570. * @param {Object} preventScrolling Object with `value` property where its value change will be observed.
  571. */
  572. onAfterSelection(r, c, r2, c2, preventScrolling) {
  573. if (this.keyEvent === false) {
  574. preventScrolling.value = true;
  575. }
  576. }
  577. /**
  578. * Document mouse down listener.
  579. *
  580. * @private
  581. * @param {Event} event
  582. */
  583. onDocumentMouseDown(event) {
  584. if (!this.isOpened()) {
  585. return;
  586. }
  587. if (this.container && isChildOf(event.target, this.container)) {
  588. this.executeCommand(event);
  589. }
  590. // Close menu when clicked element is not belongs to menu itself
  591. if (this.options.standalone && this.hotMenu && !isChildOf(event.target, this.hotMenu.rootElement)) {
  592. this.close(true);
  593. // Automatically close menu when clicked element is not belongs to menu or submenu (not necessarily to itself)
  594. } else if ((this.isAllSubMenusClosed() || this.isSubMenu()) &&
  595. (!isChildOf(event.target, '.htMenu') && isChildOf(event.target, document))) {
  596. this.close(true);
  597. }
  598. }
  599. }
  600. mixin(Menu, localHooks);
  601. export default Menu;