HandsontableModal.jsx 18 KB

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