HandsontableModal.jsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. import {
  4. Collapse,
  5. Modal, ModalHeader, ModalBody, ModalFooter,
  6. } from 'reactstrap';
  7. import Handsontable from 'handsontable';
  8. import { HotTable } from '@handsontable/react';
  9. import { debounce } from 'throttle-debounce';
  10. import MarkdownTableDataImportForm from './MarkdownTableDataImportForm';
  11. import MarkdownTable from '../../models/MarkdownTable';
  12. const DEFAULT_HOT_HEIGHT = 300;
  13. const MARKDOWNTABLE_TO_HANDSONTABLE_ALIGNMENT_SYMBOL_MAPPING = {
  14. r: 'htRight',
  15. c: 'htCenter',
  16. l: 'htLeft',
  17. '': '',
  18. };
  19. export default class HandsontableModal extends React.PureComponent {
  20. constructor(props) {
  21. super(props);
  22. /*
  23. * ## Note ##
  24. * Currently, this component try to synchronize the cells data and alignment data of state.markdownTable with these of the HotTable.
  25. * However, changes made by the following operations are not synchronized.
  26. *
  27. * 1. move columns: Alignment changes are synchronized but data changes are not.
  28. * 2. move rows: Data changes are not synchronized.
  29. * 3. insert columns or rows: Data changes are synchronized but alignment changes are not.
  30. * 4. delete columns or rows: Data changes are synchronized but alignment changes are not.
  31. *
  32. * However, all operations are reflected in the data to be saved because the HotTable data is used when the save method is called.
  33. */
  34. this.state = {
  35. show: false,
  36. isDataImportAreaExpanded: false,
  37. isWindowExpanded: false,
  38. markdownTableOnInit: HandsontableModal.getDefaultMarkdownTable(),
  39. markdownTable: HandsontableModal.getDefaultMarkdownTable(),
  40. handsontableHeight: DEFAULT_HOT_HEIGHT,
  41. };
  42. this.init = this.init.bind(this);
  43. this.reset = this.reset.bind(this);
  44. this.cancel = this.cancel.bind(this);
  45. this.save = this.save.bind(this);
  46. this.afterLoadDataHandler = this.afterLoadDataHandler.bind(this);
  47. this.beforeColumnResizeHandler = this.beforeColumnResizeHandler.bind(this);
  48. this.afterColumnResizeHandler = this.afterColumnResizeHandler.bind(this);
  49. this.modifyColWidthHandler = this.modifyColWidthHandler.bind(this);
  50. this.beforeColumnMoveHandler = this.beforeColumnMoveHandler.bind(this);
  51. this.afterColumnMoveHandler = this.afterColumnMoveHandler.bind(this);
  52. this.synchronizeAlignment = this.synchronizeAlignment.bind(this);
  53. this.alignButtonHandler = this.alignButtonHandler.bind(this);
  54. this.toggleDataImportArea = this.toggleDataImportArea.bind(this);
  55. this.importData = this.importData.bind(this);
  56. this.expandWindow = this.expandWindow.bind(this);
  57. this.contractWindow = this.contractWindow.bind(this);
  58. // create debounced method for expanding HotTable
  59. this.expandHotTableHeightWithDebounce = debounce(100, this.expandHotTableHeight);
  60. // a Set instance that stores column indices which are resized manually.
  61. // these columns will NOT be determined the width automatically by 'modifyColWidthHandler'
  62. this.manuallyResizedColumnIndicesSet = new Set();
  63. // generate setting object for HotTable instance
  64. this.handsontableSettings = Object.assign(HandsontableModal.getDefaultHandsontableSetting(), {
  65. contextMenu: this.createCustomizedContextMenu(),
  66. });
  67. }
  68. init(markdownTable) {
  69. const initMarkdownTable = markdownTable || HandsontableModal.getDefaultMarkdownTable();
  70. this.setState(
  71. {
  72. markdownTableOnInit: initMarkdownTable,
  73. markdownTable: initMarkdownTable.clone(),
  74. },
  75. );
  76. this.manuallyResizedColumnIndicesSet.clear();
  77. }
  78. createCustomizedContextMenu() {
  79. return {
  80. items: {
  81. row_above: {},
  82. row_below: {},
  83. col_left: {},
  84. col_right: {},
  85. separator1: Handsontable.plugins.ContextMenu.SEPARATOR,
  86. remove_row: {},
  87. remove_col: {},
  88. separator2: Handsontable.plugins.ContextMenu.SEPARATOR,
  89. custom_alignment: {
  90. name: 'Align columns',
  91. key: 'align_columns',
  92. submenu: {
  93. items: [
  94. {
  95. name: 'Left',
  96. key: 'align_columns:1',
  97. callback: (key, selection) => { this.align('l', selection[0].start.col, selection[0].end.col) },
  98. }, {
  99. name: 'Center',
  100. key: 'align_columns:2',
  101. callback: (key, selection) => { this.align('c', selection[0].start.col, selection[0].end.col) },
  102. }, {
  103. name: 'Right',
  104. key: 'align_columns:3',
  105. callback: (key, selection) => { this.align('r', selection[0].start.col, selection[0].end.col) },
  106. },
  107. ],
  108. },
  109. },
  110. },
  111. };
  112. }
  113. show(markdownTable) {
  114. this.init(markdownTable);
  115. this.setState({ show: true });
  116. }
  117. hide() {
  118. this.setState({
  119. show: false,
  120. isDataImportAreaExpanded: false,
  121. isWindowExpanded: false,
  122. });
  123. }
  124. /**
  125. * Reset table data to initial value
  126. *
  127. * ## Note ##
  128. * It may not return completely to the initial state because of the manualColumnMove operations.
  129. * https://github.com/handsontable/handsontable/issues/5591
  130. */
  131. reset() {
  132. this.setState({ markdownTable: this.state.markdownTableOnInit.clone() });
  133. }
  134. cancel() {
  135. this.hide();
  136. }
  137. save() {
  138. const markdownTable = new MarkdownTable(
  139. this.hotTable.hotInstance.getData(),
  140. { align: [].concat(this.state.markdownTable.options.align) },
  141. ).normalizeCells();
  142. if (this.props.onSave != null) {
  143. this.props.onSave(markdownTable);
  144. }
  145. this.hide();
  146. }
  147. /**
  148. * An afterLoadData hook
  149. *
  150. * This performs the following operations.
  151. * - clear 'manuallyResizedColumnIndicesSet' for the first loading
  152. * - synchronize the handsontable alignment to the markdowntable alignment
  153. *
  154. * ## Note ##
  155. * The afterLoadData hook is called when one of the following states of this component are passed into the setState.
  156. *
  157. * - markdownTable
  158. * - handsontableHeight
  159. *
  160. * In detail, when the setState method is called with those state passed,
  161. * React will start re-render process for the HotTable of this component because the HotTable receives those state values by props.
  162. * HotTable#shouldComponentUpdate is called in this re-render process and calls the updateSettings method for the Handsontable instance.
  163. * In updateSettings method, the loadData method is called in some case.
  164. * (refs: https://github.com/handsontable/handsontable/blob/6.2.0/src/core.js#L1652-L1657)
  165. * The updateSettings method calls in the HotTable always lead to call the loadData method because the HotTable passes data source by settings.data.
  166. * After the loadData method is executed, afterLoadData hooks are called.
  167. */
  168. afterLoadDataHandler(initialLoad) {
  169. if (initialLoad) {
  170. this.manuallyResizedColumnIndicesSet.clear();
  171. }
  172. this.synchronizeAlignment();
  173. }
  174. beforeColumnResizeHandler(currentColumn) {
  175. /*
  176. * The following bug disturbs to use 'beforeColumnResizeHandler' to store column index -- 2018.10.23 Yuki Takei
  177. * https://github.com/handsontable/handsontable/issues/3328
  178. *
  179. * At the moment, using 'afterColumnResizeHandler' instead.
  180. */
  181. // store column index
  182. // this.manuallyResizedColumnIndicesSet.add(currentColumn);
  183. }
  184. afterColumnResizeHandler(currentColumn) {
  185. /*
  186. * The following bug disturbs to use 'beforeColumnResizeHandler' to store column index -- 2018.10.23 Yuki Takei
  187. * https://github.com/handsontable/handsontable/issues/3328
  188. *
  189. * At the moment, using 'afterColumnResizeHandler' instead.
  190. */
  191. // store column index
  192. this.manuallyResizedColumnIndicesSet.add(currentColumn);
  193. // force re-render
  194. const hotInstance = this.hotTable.hotInstance;
  195. hotInstance.render();
  196. }
  197. modifyColWidthHandler(width, column) {
  198. // return original width if the column index exists in 'manuallyResizedColumnIndicesSet'
  199. if (this.manuallyResizedColumnIndicesSet.has(column)) {
  200. return width;
  201. }
  202. // return fixed width if first initializing
  203. return Math.max(80, Math.min(400, width));
  204. }
  205. beforeColumnMoveHandler(columns, target) {
  206. // clear 'manuallyResizedColumnIndicesSet'
  207. this.manuallyResizedColumnIndicesSet.clear();
  208. }
  209. /**
  210. * An afterColumnMove hook.
  211. *
  212. * This synchronizes alignment when columns are moved by manualColumnMove
  213. */
  214. afterColumnMoveHandler(columns, target) {
  215. const align = [].concat(this.state.markdownTable.options.align);
  216. const removed = align.splice(columns[0], columns.length);
  217. /*
  218. * The following is a description of the algorithm for the alignment synchronization.
  219. *
  220. * Consider the case where the target is X and the columns are [2,3] and data is as follows.
  221. *
  222. * 0 1 2 3 4 5 (insert position number)
  223. * +-+-+-+-+-+
  224. * | | | | | |
  225. * +-+-+-+-+-+
  226. * 0 1 2 3 4 (column index number)
  227. *
  228. * At first, remove columns by the splice.
  229. *
  230. * 0 1 2 4 5
  231. * +-+-+ +-+
  232. * | | | | |
  233. * +-+-+ +-+
  234. * 0 1 4
  235. *
  236. * Next, insert those columns into a new position.
  237. * However the target number is a insert position number before deletion, it may be changed.
  238. * These are changed as follows.
  239. *
  240. * Before:
  241. * 0 1 2 4 5
  242. * +-+-+ +-+
  243. * | | | | |
  244. * +-+-+ +-+
  245. *
  246. * After:
  247. * 0 1 2 2 3
  248. * +-+-+ +-+
  249. * | | | | |
  250. * +-+-+ +-+
  251. *
  252. * If X is 0, 1 or 2, that is, lower than columns[0], the target number is not changed.
  253. * If X is 4 or 5, that is, higher than columns[columns.length - 1], the target number is modified to the original value minus columns.length.
  254. *
  255. */
  256. let insertPosition = 0;
  257. if (target <= columns[0]) {
  258. insertPosition = target;
  259. }
  260. else if (columns[columns.length - 1] < target) {
  261. insertPosition = target - columns.length;
  262. }
  263. align.splice(...[insertPosition, 0].concat(removed));
  264. this.setState((prevState) => {
  265. // change only align info, so share table data to avoid redundant copy
  266. const newMarkdownTable = new MarkdownTable(prevState.markdownTable.table, { align });
  267. return { markdownTable: newMarkdownTable };
  268. }, () => {
  269. this.synchronizeAlignment();
  270. });
  271. }
  272. /**
  273. * change the markdownTable alignment and synchronize the handsontable alignment to it
  274. */
  275. align(direction, startCol, endCol) {
  276. this.setState((prevState) => {
  277. // change only align info, so share table data to avoid redundant copy
  278. const newMarkdownTable = new MarkdownTable(prevState.markdownTable.table, { align: [].concat(prevState.markdownTable.options.align) });
  279. for (let i = startCol; i <= endCol; i++) {
  280. newMarkdownTable.options.align[i] = direction;
  281. }
  282. return { markdownTable: newMarkdownTable };
  283. }, () => {
  284. this.synchronizeAlignment();
  285. });
  286. }
  287. /**
  288. * synchronize the handsontable alignment to the markdowntable alignment
  289. */
  290. synchronizeAlignment() {
  291. if (this.hotTable == null) {
  292. return;
  293. }
  294. const align = this.state.markdownTable.options.align;
  295. const hotInstance = this.hotTable.hotInstance;
  296. for (let i = 0; i < align.length; i++) {
  297. for (let j = 0; j < hotInstance.countRows(); j++) {
  298. hotInstance.setCellMeta(j, i, 'className', MARKDOWNTABLE_TO_HANDSONTABLE_ALIGNMENT_SYMBOL_MAPPING[align[i]]);
  299. }
  300. }
  301. hotInstance.render();
  302. }
  303. alignButtonHandler(direction) {
  304. const selectedRange = this.hotTable.hotInstance.getSelectedRange();
  305. if (selectedRange == null) return;
  306. let startCol;
  307. let endCol;
  308. if (selectedRange[0].from.col < selectedRange[0].to.col) {
  309. startCol = selectedRange[0].from.col;
  310. endCol = selectedRange[0].to.col;
  311. }
  312. else {
  313. startCol = selectedRange[0].to.col;
  314. endCol = selectedRange[0].from.col;
  315. }
  316. this.align(direction, startCol, endCol);
  317. }
  318. toggleDataImportArea() {
  319. this.setState({ isDataImportAreaExpanded: !this.state.isDataImportAreaExpanded });
  320. }
  321. /**
  322. * Import a markdowntable
  323. *
  324. * ## Note ##
  325. * The manualColumnMove operation affects the column order of imported data.
  326. * https://github.com/handsontable/handsontable/issues/5591
  327. */
  328. importData(markdownTable) {
  329. this.init(markdownTable);
  330. this.toggleDataImportArea();
  331. }
  332. expandWindow() {
  333. this.setState({ isWindowExpanded: true });
  334. // invoke updateHotTableHeight method with delay
  335. // cz. Resizing this.refs.hotTableContainer is completed after a little delay after 'isWindowExpanded' set with 'true'
  336. this.expandHotTableHeightWithDebounce();
  337. }
  338. contractWindow() {
  339. this.setState({ isWindowExpanded: false, handsontableHeight: DEFAULT_HOT_HEIGHT });
  340. }
  341. /**
  342. * Expand the height of the Handsontable
  343. * by updating 'handsontableHeight' state
  344. * according to the height of this.refs.hotTableContainer
  345. */
  346. expandHotTableHeight() {
  347. if (this.state.isWindowExpanded && this.hotTableContainer != null) {
  348. const height = this.hotTableContainer.getBoundingClientRect().height;
  349. this.setState({ handsontableHeight: height });
  350. }
  351. }
  352. renderExpandOrContractButton() {
  353. const iconClassName = this.state.isWindowExpanded ? 'icon-size-actual' : 'icon-size-fullscreen';
  354. return (
  355. <button type="button" className="close" onClick={this.state.isWindowExpanded ? this.contractWindow : this.expandWindow}>
  356. <i className={iconClassName} style={{ fontSize: '0.8em' }} aria-hidden="true"></i>
  357. </button>
  358. );
  359. }
  360. renderCloseButton() {
  361. return (
  362. <button type="button" className="close" onClick={this.cancel} aria-label="Close">
  363. <span aria-hidden="true">&times;</span>
  364. </button>
  365. );
  366. }
  367. render() {
  368. const dialogClassNames = ['handsontable-modal'];
  369. if (this.state.isWindowExpanded) {
  370. dialogClassNames.push('handsontable-modal-expanded');
  371. }
  372. const dialogClassName = dialogClassNames.join(' ');
  373. // eslint-disable-next-line no-unused-vars
  374. const buttons = (
  375. <span>
  376. {/* change order because of `float: right` by '.close' class */}
  377. {this.renderCloseButton()}
  378. {this.renderExpandOrContractButton()}
  379. </span>
  380. );
  381. return (
  382. <Modal isOpen={this.state.show} toggle={this.cancel} size="lg" className={dialogClassName}>
  383. <ModalHeader tag="h4" toggle={this.cancel} close={buttons} className="bg-primary text-light">
  384. Edit Table
  385. </ModalHeader>
  386. <ModalBody className="p-0 d-flex flex-column">
  387. <div className="px-4 py-3 border-bottom bg-light">
  388. <button
  389. type="button"
  390. className="mr-4 data-import-button btn btn-secondary"
  391. data-toggle="collapse"
  392. data-target="#collapseDataImport"
  393. aria-expanded={this.state.isDataImportAreaExpanded}
  394. onClick={this.toggleDataImportArea}
  395. >
  396. <span className="mr-3">Data Import</span><i className={this.state.isDataImportAreaExpanded ? 'fa fa-angle-up' : 'fa fa-angle-down'}></i>
  397. </button>
  398. <div role="group" className="btn-group">
  399. <button type="button" className="btn btn-secondary" onClick={() => { this.alignButtonHandler('l') }}><i className="ti-align-left"></i></button>
  400. <button type="button" className="btn btn-secondary" onClick={() => { this.alignButtonHandler('c') }}><i className="ti-align-center"></i></button>
  401. <button type="button" className="btn btn-secondary" onClick={() => { this.alignButtonHandler('r') }}><i className="ti-align-right"></i></button>
  402. </div>
  403. <Collapse isOpen={this.state.isDataImportAreaExpanded}>
  404. <div className="mt-4">
  405. <MarkdownTableDataImportForm onCancel={this.toggleDataImportArea} onImport={this.importData} />
  406. </div>
  407. </Collapse>
  408. </div>
  409. <div ref={(c) => { this.hotTableContainer = c }} className="m-4 hot-table-container">
  410. <HotTable
  411. ref={(c) => { this.hotTable = c }}
  412. data={this.state.markdownTable.table}
  413. settings={this.handsontableSettings}
  414. height={this.state.handsontableHeight}
  415. afterLoadData={this.afterLoadDataHandler}
  416. modifyColWidth={this.modifyColWidthHandler}
  417. beforeColumnMove={this.beforeColumnMoveHandler}
  418. beforeColumnResize={this.beforeColumnResizeHandler}
  419. afterColumnResize={this.afterColumnResizeHandler}
  420. afterColumnMove={this.afterColumnMoveHandler}
  421. />
  422. </div>
  423. </ModalBody>
  424. <ModalFooter className="grw-modal-footer">
  425. <button type="button" className="btn btn-danger" onClick={this.reset}>Reset</button>
  426. <div className="ml-auto">
  427. <button type="button" className="mr-2 btn btn-secondary" onClick={this.cancel}>Cancel</button>
  428. <button type="button" className="btn btn-primary" onClick={this.save}>Done</button>
  429. </div>
  430. </ModalFooter>
  431. </Modal>
  432. );
  433. }
  434. static getDefaultMarkdownTable() {
  435. return new MarkdownTable(
  436. [
  437. ['col1', 'col2', 'col3'],
  438. ['', '', ''],
  439. ['', '', ''],
  440. ],
  441. {
  442. align: ['', '', ''],
  443. },
  444. );
  445. }
  446. static getDefaultHandsontableSetting() {
  447. return {
  448. rowHeaders: true,
  449. colHeaders: true,
  450. manualRowMove: true,
  451. manualRowResize: true,
  452. manualColumnMove: true,
  453. manualColumnResize: true,
  454. selectionMode: 'multiple',
  455. outsideClickDeselects: false,
  456. };
  457. }
  458. }
  459. HandsontableModal.propTypes = {
  460. onSave: PropTypes.func,
  461. };