nestedHeaders.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  1. import {
  2. addClass,
  3. removeClass,
  4. fastInnerHTML,
  5. empty,
  6. } from '../../helpers/dom/element';
  7. import { rangeEach } from '../../helpers/number';
  8. import { arrayEach } from '../../helpers/array';
  9. import { objectEach } from '../../helpers/object';
  10. import { toSingleLine } from '../../helpers/templateLiteralTag';
  11. import { warn } from '../../helpers/console';
  12. // eslint-disable-next-line import/extensions
  13. import { registerPlugin } from '../../plugins.js';
  14. import BasePlugin from '../_base';
  15. import { CellCoords } from '../../3rdparty/walkontable/src';
  16. import GhostTable from './utils/ghostTable';
  17. import './nestedHeaders.css';
  18. /**
  19. * @plugin NestedHeaders
  20. * @pro
  21. *
  22. * @description
  23. * The plugin allows to create a nested header structure, using the HTML's colspan attribute.
  24. *
  25. * To make any header wider (covering multiple table columns), it's corresponding configuration array element should be
  26. * provided as an object with `label` and `colspan` properties. The `label` property defines the header's label,
  27. * while the `colspan` property defines a number of columns that the header should cover.
  28. *
  29. * __Note__ that the plugin supports a *nested* structure, which means, any header cannot be wider than it's "parent". In
  30. * other words, headers cannot overlap each other.
  31. * @example
  32. *
  33. * ```js
  34. * const container = document.getElementById('example');
  35. * const hot = new Handsontable(container, {
  36. * date: getData(),
  37. * nestedHeaders: [
  38. * ['A', {label: 'B', colspan: 8}, 'C'],
  39. * ['D', {label: 'E', colspan: 4}, {label: 'F', colspan: 4}, 'G'],
  40. * ['H', {label: 'I', colspan: 2}, {label: 'J', colspan: 2}, {label: 'K', colspan: 2}, {label: 'L', colspan: 2}, 'M'],
  41. * ['N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W']
  42. * ],
  43. * ```
  44. */
  45. class NestedHeaders extends BasePlugin {
  46. constructor(hotInstance) {
  47. super(hotInstance);
  48. /**
  49. * Nested headers cached settings.
  50. *
  51. * @private
  52. * @type {Object}
  53. */
  54. this.settings = [];
  55. /**
  56. * Cached number of column header levels.
  57. *
  58. * @private
  59. * @type {Number}
  60. */
  61. this.columnHeaderLevelCount = 0;
  62. /**
  63. * Array of nested headers' colspans.
  64. *
  65. * @private
  66. * @type {Array}
  67. */
  68. this.colspanArray = [];
  69. /**
  70. * Custom helper for getting widths of the nested headers.
  71. * @TODO This should be changed after refactor handsontable/utils/ghostTable.
  72. *
  73. * @private
  74. * @type {GhostTable}
  75. */
  76. this.ghostTable = new GhostTable(this);
  77. }
  78. /**
  79. * Check if plugin is enabled
  80. *
  81. * @returns {Boolean}
  82. */
  83. isEnabled() {
  84. return !!this.hot.getSettings().nestedHeaders;
  85. }
  86. /**
  87. * Enables the plugin functionality for this Handsontable instance.
  88. */
  89. enablePlugin() {
  90. if (this.enabled) {
  91. return;
  92. }
  93. this.settings = this.hot.getSettings().nestedHeaders;
  94. this.addHook('afterGetColumnHeaderRenderers', array => this.onAfterGetColumnHeaderRenderers(array));
  95. this.addHook('afterInit', () => this.onAfterInit());
  96. this.addHook('afterOnCellMouseDown', (event, coords) => this.onAfterOnCellMouseDown(event, coords));
  97. this.addHook('beforeOnCellMouseOver', (event, coords, TD, blockCalculations) => this.onBeforeOnCellMouseOver(event, coords, TD, blockCalculations));
  98. this.addHook('afterViewportColumnCalculatorOverride', calc => this.onAfterViewportColumnCalculatorOverride(calc));
  99. this.addHook('modifyColWidth', (width, column) => this.onModifyColWidth(width, column));
  100. this.setupColspanArray();
  101. this.checkForFixedColumnsCollision();
  102. this.columnHeaderLevelCount = this.hot.view ? this.hot.view.wt.getSetting('columnHeaders').length : 0;
  103. super.enablePlugin();
  104. }
  105. /**
  106. * Disables the plugin functionality for this Handsontable instance.
  107. */
  108. disablePlugin() {
  109. this.clearColspans();
  110. this.settings = [];
  111. this.columnHeaderLevelCount = 0;
  112. this.colspanArray = [];
  113. this.ghostTable.clear();
  114. super.disablePlugin();
  115. }
  116. /**
  117. * Updates the plugin state. This method is executed when {@link Core#updateSettings} is invoked.
  118. */
  119. updatePlugin() {
  120. this.disablePlugin();
  121. this.enablePlugin();
  122. super.updatePlugin();
  123. this.ghostTable.buildWidthsMapper();
  124. }
  125. /**
  126. * Clear the colspans remaining after plugin usage.
  127. *
  128. * @private
  129. */
  130. clearColspans() {
  131. if (!this.hot.view) {
  132. return;
  133. }
  134. const headerLevels = this.hot.view.wt.getSetting('columnHeaders').length;
  135. const mainHeaders = this.hot.view.wt.wtTable.THEAD;
  136. const topHeaders = this.hot.view.wt.wtOverlays.topOverlay.clone.wtTable.THEAD;
  137. const topLeftCornerHeaders = this.hot.view.wt.wtOverlays.topLeftCornerOverlay ?
  138. this.hot.view.wt.wtOverlays.topLeftCornerOverlay.clone.wtTable.THEAD : null;
  139. for (let i = 0; i < headerLevels; i++) {
  140. const masterLevel = mainHeaders.childNodes[i];
  141. if (!masterLevel) {
  142. break;
  143. }
  144. const topLevel = topHeaders.childNodes[i];
  145. const topLeftCornerLevel = topLeftCornerHeaders ? topLeftCornerHeaders.childNodes[i] : null;
  146. for (let j = 0, masterNodes = masterLevel.childNodes.length; j < masterNodes; j++) {
  147. masterLevel.childNodes[j].removeAttribute('colspan');
  148. if (topLevel && topLevel.childNodes[j]) {
  149. topLevel.childNodes[j].removeAttribute('colspan');
  150. }
  151. if (topLeftCornerHeaders && topLeftCornerLevel && topLeftCornerLevel.childNodes[j]) {
  152. topLeftCornerLevel.childNodes[j].removeAttribute('colspan');
  153. }
  154. }
  155. }
  156. }
  157. /**
  158. * Check if the nested headers overlap the fixed columns overlay, if so - display a warning.
  159. *
  160. * @private
  161. */
  162. checkForFixedColumnsCollision() {
  163. const fixedColumnsLeft = this.hot.getSettings().fixedColumnsLeft;
  164. arrayEach(this.colspanArray, (value, i) => {
  165. if (this.getNestedParent(i, fixedColumnsLeft) !== fixedColumnsLeft) {
  166. warn(toSingleLine`You have declared a Nested Header overlapping the Fixed Columns section - it may lead to visual
  167. glitches. To prevent that kind of problems, split the nested headers between the fixed and non-fixed columns.`);
  168. }
  169. });
  170. }
  171. /**
  172. * Check if the configuration contains overlapping headers.
  173. *
  174. * @private
  175. */
  176. checkForOverlappingHeaders() {
  177. arrayEach(this.colspanArray, (level, i) => {
  178. arrayEach(this.colspanArray[i], (header, j) => {
  179. if (header.colspan > 1) {
  180. const row = this.levelToRowCoords(i);
  181. const childHeaders = this.getChildHeaders(row, j);
  182. if (childHeaders.length > 0) {
  183. let childColspanSum = 0;
  184. arrayEach(childHeaders, (col) => {
  185. childColspanSum += this.getColspan(row + 1, col);
  186. });
  187. if (childColspanSum > header.colspan) {
  188. warn(toSingleLine`Your Nested Headers plugin setup contains overlapping headers. This kind of configuration
  189. is currently not supported and might result in glitches.`);
  190. }
  191. return false;
  192. }
  193. }
  194. });
  195. });
  196. }
  197. /**
  198. * Create an internal array containing information of the headers with a colspan attribute.
  199. *
  200. * @private
  201. */
  202. setupColspanArray() {
  203. function checkIfExists(array, index) {
  204. if (!array[index]) {
  205. array[index] = [];
  206. }
  207. }
  208. objectEach(this.settings, (levelValues, level) => {
  209. objectEach(levelValues, (val, col, levelValue) => {
  210. checkIfExists(this.colspanArray, level);
  211. if (levelValue[col].colspan === void 0) {
  212. this.colspanArray[level].push({
  213. label: levelValue[col] || '',
  214. colspan: 1,
  215. hidden: false
  216. });
  217. } else {
  218. const colspan = levelValue[col].colspan || 1;
  219. this.colspanArray[level].push({
  220. label: levelValue[col].label || '',
  221. colspan,
  222. hidden: false
  223. });
  224. this.fillColspanArrayWithDummies(colspan, level);
  225. }
  226. });
  227. });
  228. }
  229. /**
  230. * Fill the "colspan array" with default data for the dummy hidden headers.
  231. *
  232. * @private
  233. * @param {Number} colspan The colspan value.
  234. * @param {Number} level Header level.
  235. */
  236. fillColspanArrayWithDummies(colspan, level) {
  237. rangeEach(0, colspan - 2, () => {
  238. this.colspanArray[level].push({
  239. label: '',
  240. colspan: 1,
  241. hidden: true,
  242. });
  243. });
  244. }
  245. /**
  246. * Generates the appropriate header renderer for a header row.
  247. *
  248. * @private
  249. * @param {Number} headerRow The header row.
  250. * @returns {Function}
  251. *
  252. * @fires Hooks#afterGetColHeader
  253. */
  254. headerRendererFactory(headerRow) {
  255. const _this = this;
  256. return function(index, TH) {
  257. TH.removeAttribute('colspan');
  258. removeClass(TH, 'hiddenHeader');
  259. // header row is the index of header row counting from the top (=> positive values)
  260. if (_this.colspanArray[headerRow][index] && _this.colspanArray[headerRow][index].colspan) {
  261. const colspan = _this.colspanArray[headerRow][index].colspan;
  262. const fixedColumnsLeft = _this.hot.getSettings().fixedColumnsLeft || 0;
  263. const topLeftCornerOverlay = _this.hot.view.wt.wtOverlays.topLeftCornerOverlay;
  264. const leftOverlay = _this.hot.view.wt.wtOverlays.leftOverlay;
  265. const isInTopLeftCornerOverlay = topLeftCornerOverlay ? topLeftCornerOverlay.clone.wtTable.THEAD.contains(TH) : false;
  266. const isInLeftOverlay = leftOverlay ? leftOverlay.clone.wtTable.THEAD.contains(TH) : false;
  267. if (colspan > 1) {
  268. TH.setAttribute('colspan', isInTopLeftCornerOverlay || isInLeftOverlay ? Math.min(colspan, fixedColumnsLeft - index) : colspan);
  269. }
  270. if (isInTopLeftCornerOverlay || isInLeftOverlay && index === fixedColumnsLeft - 1) {
  271. addClass(TH, 'overlayEdge');
  272. }
  273. }
  274. if (_this.colspanArray[headerRow][index] && _this.colspanArray[headerRow][index].hidden) {
  275. addClass(TH, 'hiddenHeader');
  276. }
  277. empty(TH);
  278. const divEl = document.createElement('DIV');
  279. addClass(divEl, 'relative');
  280. const spanEl = document.createElement('SPAN');
  281. addClass(spanEl, 'colHeader');
  282. fastInnerHTML(spanEl, _this.colspanArray[headerRow][index] ? _this.colspanArray[headerRow][index].label || '' : '');
  283. divEl.appendChild(spanEl);
  284. TH.appendChild(divEl);
  285. _this.hot.runHooks('afterGetColHeader', index, TH);
  286. };
  287. }
  288. /**
  289. * Returns the colspan for the provided coordinates.
  290. *
  291. * @private
  292. * @param {Number} row Row index.
  293. * @param {Number} column Column index.
  294. * @returns {Number}
  295. */
  296. getColspan(row, column) {
  297. const header = this.colspanArray[this.rowCoordsToLevel(row)][column];
  298. return header ? header.colspan : 1;
  299. }
  300. /**
  301. * Translates the level value (header row index from the top) to the row value (negative index).
  302. *
  303. * @private
  304. * @param {Number} level Header level.
  305. * @returns {Number}
  306. */
  307. levelToRowCoords(level) {
  308. return level - this.columnHeaderLevelCount;
  309. }
  310. /**
  311. * Translates the row value (negative index) to the level value (header row index from the top).
  312. *
  313. * @private
  314. * @param {Number} row Row index.
  315. * @returns {Number}
  316. */
  317. rowCoordsToLevel(row) {
  318. return row + this.columnHeaderLevelCount;
  319. }
  320. /**
  321. * Returns the column index of the "parent" nested header.
  322. *
  323. * @private
  324. * @param {Number} level Header level.
  325. * @param {Number} column Column index.
  326. * @returns {*}
  327. */
  328. getNestedParent(level, column) {
  329. if (level < 0) {
  330. return false;
  331. }
  332. const colspan = this.colspanArray[level][column] ? this.colspanArray[level][column].colspan : 1;
  333. const hidden = this.colspanArray[level][column] ? this.colspanArray[level][column].hidden : false;
  334. if (colspan > 1 || (colspan === 1 && hidden === false)) {
  335. return column;
  336. }
  337. let parentCol = column - 1;
  338. do {
  339. if (this.colspanArray[level][parentCol].colspan > 1) {
  340. break;
  341. }
  342. parentCol -= 1;
  343. } while (column >= 0);
  344. return parentCol;
  345. }
  346. /**
  347. * Returns (physical) indexes of headers below the header with provided coordinates.
  348. *
  349. * @private
  350. * @param {Number} row Row index.
  351. * @param {Number} column Column index.
  352. * @returns {Number[]}
  353. */
  354. getChildHeaders(row, column) {
  355. const level = this.rowCoordsToLevel(row);
  356. const childColspanLevel = this.colspanArray[level + 1];
  357. const nestedParentCol = this.getNestedParent(level, column);
  358. let colspan = this.colspanArray[level][column].colspan;
  359. const childHeaderRange = [];
  360. if (!childColspanLevel) {
  361. return childHeaderRange;
  362. }
  363. rangeEach(nestedParentCol, nestedParentCol + colspan - 1, (i) => {
  364. if (childColspanLevel[i] && childColspanLevel[i].colspan > 1) {
  365. colspan -= childColspanLevel[i].colspan - 1;
  366. }
  367. if (childColspanLevel[i] && !childColspanLevel[i].hidden && childHeaderRange.indexOf(i) === -1) {
  368. childHeaderRange.push(i);
  369. }
  370. });
  371. return childHeaderRange;
  372. }
  373. /**
  374. * Fill the remaining colspanArray entries for the undeclared column headers.
  375. *
  376. * @private
  377. */
  378. fillTheRemainingColspans() {
  379. objectEach(this.settings, (levelValue, level) => {
  380. rangeEach(this.colspanArray[level].length - 1, this.hot.countCols() - 1, (col) => {
  381. this.colspanArray[level].push({
  382. label: levelValue[col] || '',
  383. colspan: 1,
  384. hidden: false
  385. });
  386. }, true);
  387. });
  388. }
  389. /**
  390. * Updates headers highlight in nested structure.
  391. *
  392. * @private
  393. */
  394. updateHeadersHighlight() {
  395. const selection = this.hot.getSelectedLast();
  396. if (selection === void 0) {
  397. return;
  398. }
  399. const wtOverlays = this.hot.view.wt.wtOverlays;
  400. const selectionByHeader = this.hot.selection.isSelectedByColumnHeader();
  401. const from = Math.min(selection[1], selection[3]);
  402. const to = Math.max(selection[1], selection[3]);
  403. const levelLimit = selectionByHeader ? -1 : this.columnHeaderLevelCount - 1;
  404. const changes = [];
  405. const classNameModifier = className => (TH, modifier) => () => modifier(TH, className);
  406. const highlightHeader = classNameModifier('ht__highlight');
  407. const activeHeader = classNameModifier('ht__active_highlight');
  408. rangeEach(from, to, (column) => {
  409. for (let level = this.columnHeaderLevelCount - 1; level > -1; level--) {
  410. const visibleColumnIndex = this.getNestedParent(level, column);
  411. const topTH = wtOverlays.topOverlay ? wtOverlays.topOverlay.clone.wtTable.getColumnHeader(visibleColumnIndex, level) : void 0;
  412. const topLeftTH = wtOverlays.topLeftCornerOverlay ? wtOverlays.topLeftCornerOverlay.clone.wtTable.getColumnHeader(visibleColumnIndex, level) : void 0;
  413. const listTH = [topTH, topLeftTH];
  414. const colspanLen = this.getColspan(level - this.columnHeaderLevelCount, visibleColumnIndex);
  415. const isInSelection = visibleColumnIndex >= from && (visibleColumnIndex + colspanLen - 1) <= to;
  416. arrayEach(listTH, (TH) => {
  417. if (TH === void 0) {
  418. return false;
  419. }
  420. if ((!selectionByHeader && level < levelLimit) || (selectionByHeader && !isInSelection)) {
  421. changes.push(highlightHeader(TH, removeClass));
  422. if (selectionByHeader) {
  423. changes.push(activeHeader(TH, removeClass));
  424. }
  425. } else {
  426. changes.push(highlightHeader(TH, addClass));
  427. if (selectionByHeader) {
  428. changes.push(activeHeader(TH, addClass));
  429. }
  430. }
  431. });
  432. }
  433. });
  434. arrayEach(changes, fn => void fn());
  435. changes.length = 0;
  436. }
  437. /**
  438. * Make the renderer render the first nested column in its entirety.
  439. *
  440. * @private
  441. * @param {Object} calc Viewport column calculator.
  442. */
  443. onAfterViewportColumnCalculatorOverride(calc) {
  444. let newStartColumn = calc.startColumn;
  445. rangeEach(0, Math.max(this.columnHeaderLevelCount - 1, 0), (l) => {
  446. const startColumnNestedParent = this.getNestedParent(l, calc.startColumn);
  447. if (startColumnNestedParent < calc.startColumn) {
  448. newStartColumn = Math.min(newStartColumn, startColumnNestedParent);
  449. }
  450. });
  451. calc.startColumn = newStartColumn;
  452. }
  453. /**
  454. * Select all nested headers of clicked cell.
  455. *
  456. * @private
  457. * @param {MouseEvent} event Mouse event.
  458. * @param {Object} coords Clicked cell coords.
  459. */
  460. onAfterOnCellMouseDown(event, coords) {
  461. if (coords.row < 0) {
  462. const colspan = this.getColspan(coords.row, coords.col);
  463. const lastColIndex = coords.col + colspan - 1;
  464. if (colspan > 1) {
  465. const lastRowIndex = this.hot.countRows() - 1;
  466. this.hot.selection.setRangeEnd(new CellCoords(lastRowIndex, lastColIndex));
  467. }
  468. }
  469. }
  470. /**
  471. * Make the header-selection properly select the nested headers.
  472. *
  473. * @private
  474. * @param {MouseEvent} event Mouse event.
  475. * @param {Object} coords Clicked cell coords.
  476. * @param {HTMLElement} TD
  477. */
  478. onBeforeOnCellMouseOver(event, coords, TD, blockCalculations) {
  479. if (coords.row >= 0 || coords.col < 0 || !this.hot.view.isMouseDown()) {
  480. return;
  481. }
  482. const { from, to } = this.hot.getSelectedRangeLast();
  483. const colspan = this.getColspan(coords.row, coords.col);
  484. const lastColIndex = coords.col + colspan - 1;
  485. let changeDirection = false;
  486. if (from.col <= to.col) {
  487. if ((coords.col < from.col && lastColIndex === to.col) ||
  488. (coords.col < from.col && lastColIndex < from.col) ||
  489. (coords.col < from.col && lastColIndex >= from.col && lastColIndex < to.col)) {
  490. changeDirection = true;
  491. }
  492. } else if ((coords.col < to.col && lastColIndex > from.col) ||
  493. (coords.col > from.col) ||
  494. (coords.col <= to.col && lastColIndex > from.col) ||
  495. (coords.col > to.col && lastColIndex > from.col)) {
  496. changeDirection = true;
  497. }
  498. if (changeDirection) {
  499. [from.col, to.col] = [to.col, from.col];
  500. }
  501. if (colspan > 1) {
  502. blockCalculations.column = true;
  503. blockCalculations.cell = true;
  504. const columnRange = [];
  505. if (from.col === to.col) {
  506. if (lastColIndex <= from.col && coords.col < from.col) {
  507. columnRange.push(to.col, coords.col);
  508. } else {
  509. columnRange.push(coords.col < from.col ? coords.col : from.col, lastColIndex > to.col ? lastColIndex : to.col);
  510. }
  511. }
  512. if (from.col < to.col) {
  513. columnRange.push(coords.col < from.col ? coords.col : from.col, lastColIndex);
  514. }
  515. if (from.col > to.col) {
  516. columnRange.push(from.col, coords.col);
  517. }
  518. this.hot.selectColumns(...columnRange);
  519. }
  520. }
  521. /**
  522. * Cache column header count.
  523. *
  524. * @private
  525. */
  526. onAfterInit() {
  527. this.columnHeaderLevelCount = this.hot.view.wt.getSetting('columnHeaders').length;
  528. this.fillTheRemainingColspans();
  529. this.checkForOverlappingHeaders();
  530. this.ghostTable.buildWidthsMapper();
  531. }
  532. /**
  533. * `afterGetColumnHeader` hook callback - prepares the header structure.
  534. *
  535. * @private
  536. * @param {Array} renderersArray Array of renderers.
  537. */
  538. onAfterGetColumnHeaderRenderers(renderersArray) {
  539. if (renderersArray) {
  540. renderersArray.length = 0;
  541. for (let headersCount = this.colspanArray.length, i = headersCount - 1; i >= 0; i--) {
  542. renderersArray.push(this.headerRendererFactory(i));
  543. }
  544. renderersArray.reverse();
  545. }
  546. this.updateHeadersHighlight();
  547. }
  548. /**
  549. * `modifyColWidth` hook callback - returns width from cache, when is greater than incoming from hook.
  550. *
  551. * @private
  552. * @param width Width from hook.
  553. * @param column Visual index of an column.
  554. * @returns {Number}
  555. */
  556. onModifyColWidth(width, column) {
  557. const cachedWidth = this.ghostTable.widthsCache[column];
  558. return width > cachedWidth ? width : cachedWidth;
  559. }
  560. /**
  561. * Destroys the plugin instance.
  562. */
  563. destroy() {
  564. this.settings = null;
  565. this.columnHeaderLevelCount = null;
  566. this.colspanArray = null;
  567. super.destroy();
  568. }
  569. }
  570. registerPlugin('nestedHeaders', NestedHeaders);
  571. export default NestedHeaders;