nestedHeaders.js 20 KB

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