HandsontableModal.jsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. import Modal from 'react-bootstrap/es/Modal';
  4. import Button from 'react-bootstrap/es/Button';
  5. import ButtonGroup from 'react-bootstrap/es/ButtonGroup';
  6. import Collapse from 'react-bootstrap/es/Collapse';
  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.refs.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. (refs: https://github.com/handsontable/handsontable/blob/6.2.0/src/core.js#L1652-L1657)
  164. * The updateSettings method calls in the HotTable always lead to call the loadData method because the HotTable passes data source by settings.data.
  165. * After the loadData method is executed, afterLoadData hooks are called.
  166. */
  167. afterLoadDataHandler(initialLoad) {
  168. if (initialLoad) {
  169. this.manuallyResizedColumnIndicesSet.clear();
  170. }
  171. this.synchronizeAlignment();
  172. }
  173. beforeColumnResizeHandler(currentColumn) {
  174. /*
  175. * The following bug disturbs to use 'beforeColumnResizeHandler' to store column index -- 2018.10.23 Yuki Takei
  176. * https://github.com/handsontable/handsontable/issues/3328
  177. *
  178. * At the moment, using 'afterColumnResizeHandler' instead.
  179. */
  180. // store column index
  181. // this.manuallyResizedColumnIndicesSet.add(currentColumn);
  182. }
  183. afterColumnResizeHandler(currentColumn) {
  184. /*
  185. * The following bug disturbs to use 'beforeColumnResizeHandler' to store column index -- 2018.10.23 Yuki Takei
  186. * https://github.com/handsontable/handsontable/issues/3328
  187. *
  188. * At the moment, using 'afterColumnResizeHandler' instead.
  189. */
  190. // store column index
  191. this.manuallyResizedColumnIndicesSet.add(currentColumn);
  192. // force re-render
  193. const hotInstance = this.refs.hotTable.hotInstance;
  194. hotInstance.render();
  195. }
  196. modifyColWidthHandler(width, column) {
  197. // return original width if the column index exists in 'manuallyResizedColumnIndicesSet'
  198. if (this.manuallyResizedColumnIndicesSet.has(column)) {
  199. return width;
  200. }
  201. // return fixed width if first initializing
  202. return Math.max(80, Math.min(400, width));
  203. }
  204. beforeColumnMoveHandler(columns, target) {
  205. // clear 'manuallyResizedColumnIndicesSet'
  206. this.manuallyResizedColumnIndicesSet.clear();
  207. }
  208. /**
  209. * An afterColumnMove hook.
  210. *
  211. * This synchronizes alignment when columns are moved by manualColumnMove
  212. */
  213. afterColumnMoveHandler(columns, target) {
  214. const align = [].concat(this.state.markdownTable.options.align);
  215. const removed = align.splice(columns[0], columns.length);
  216. /*
  217. * The following is a description of the algorithm for the alignment synchronization.
  218. *
  219. * Consider the case where the target is X and the columns are [2,3] and data is as follows.
  220. *
  221. * 0 1 2 3 4 5 (insert position number)
  222. * +-+-+-+-+-+
  223. * | | | | | |
  224. * +-+-+-+-+-+
  225. * 0 1 2 3 4 (column index number)
  226. *
  227. * At first, remove columns by the splice.
  228. *
  229. * 0 1 2 4 5
  230. * +-+-+ +-+
  231. * | | | | |
  232. * +-+-+ +-+
  233. * 0 1 4
  234. *
  235. * Next, insert those columns into a new position.
  236. * However the target number is a insert position number before deletion, it may be changed.
  237. * These are changed as follows.
  238. *
  239. * Before:
  240. * 0 1 2 4 5
  241. * +-+-+ +-+
  242. * | | | | |
  243. * +-+-+ +-+
  244. *
  245. * After:
  246. * 0 1 2 2 3
  247. * +-+-+ +-+
  248. * | | | | |
  249. * +-+-+ +-+
  250. *
  251. * If X is 0, 1 or 2, that is, lower than columns[0], the target number is not changed.
  252. * 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.
  253. *
  254. */
  255. let insertPosition = 0;
  256. if (target <= columns[0]) {
  257. insertPosition = target;
  258. }
  259. else if (columns[columns.length - 1] < target) {
  260. insertPosition = target - columns.length;
  261. }
  262. align.splice(...[insertPosition, 0].concat(removed));
  263. this.setState((prevState) => {
  264. // change only align info, so share table data to avoid redundant copy
  265. const newMarkdownTable = new MarkdownTable(prevState.markdownTable.table, { align });
  266. return { markdownTable: newMarkdownTable };
  267. }, () => {
  268. this.synchronizeAlignment();
  269. });
  270. }
  271. /**
  272. * change the markdownTable alignment and synchronize the handsontable alignment to it
  273. */
  274. align(direction, startCol, endCol) {
  275. this.setState((prevState) => {
  276. // change only align info, so share table data to avoid redundant copy
  277. const newMarkdownTable = new MarkdownTable(prevState.markdownTable.table, { align: [].concat(prevState.markdownTable.options.align) });
  278. for (let i = startCol; i <= endCol; i++) {
  279. newMarkdownTable.options.align[i] = direction;
  280. }
  281. return { markdownTable: newMarkdownTable };
  282. }, () => {
  283. this.synchronizeAlignment();
  284. });
  285. }
  286. /**
  287. * synchronize the handsontable alignment to the markdowntable alignment
  288. */
  289. synchronizeAlignment() {
  290. if (this.refs.hotTable == null) {
  291. return;
  292. }
  293. const align = this.state.markdownTable.options.align;
  294. const hotInstance = this.refs.hotTable.hotInstance;
  295. for (let i = 0; i < align.length; i++) {
  296. for (let j = 0; j < hotInstance.countRows(); j++) {
  297. hotInstance.setCellMeta(j, i, 'className', MARKDOWNTABLE_TO_HANDSONTABLE_ALIGNMENT_SYMBOL_MAPPING[align[i]]);
  298. }
  299. }
  300. hotInstance.render();
  301. }
  302. alignButtonHandler(direction) {
  303. const selectedRange = this.refs.hotTable.hotInstance.getSelectedRange();
  304. if (selectedRange == null) return;
  305. let startCol;
  306. let endCol;
  307. if (selectedRange[0].from.col < selectedRange[0].to.col) {
  308. startCol = selectedRange[0].from.col;
  309. endCol = selectedRange[0].to.col;
  310. }
  311. else {
  312. startCol = selectedRange[0].to.col;
  313. endCol = selectedRange[0].from.col;
  314. }
  315. this.align(direction, startCol, endCol);
  316. }
  317. toggleDataImportArea() {
  318. this.setState({ isDataImportAreaExpanded: !this.state.isDataImportAreaExpanded });
  319. }
  320. /**
  321. * Import a markdowntable
  322. *
  323. * ## Note ##
  324. * The manualColumnMove operation affects the column order of imported data.
  325. * https://github.com/handsontable/handsontable/issues/5591
  326. */
  327. importData(markdownTable) {
  328. this.init(markdownTable);
  329. this.toggleDataImportArea();
  330. }
  331. expandWindow() {
  332. this.setState({ isWindowExpanded: true });
  333. // invoke updateHotTableHeight method with delay
  334. // cz. Resizing this.refs.hotTableContainer is completed after a little delay after 'isWindowExpanded' set with 'true'
  335. this.expandHotTableHeightWithDebounce();
  336. }
  337. contractWindow() {
  338. this.setState({ isWindowExpanded: false, handsontableHeight: DEFAULT_HOT_HEIGHT });
  339. }
  340. /**
  341. * Expand the height of the Handsontable
  342. * by updating 'handsontableHeight' state
  343. * according to the height of this.refs.hotTableContainer
  344. */
  345. expandHotTableHeight() {
  346. if (this.state.isWindowExpanded && this.refs.hotTableContainer != null) {
  347. const height = this.refs.hotTableContainer.getBoundingClientRect().height;
  348. this.setState({ handsontableHeight: height });
  349. }
  350. }
  351. renderExpandOrContractButton() {
  352. const iconClassName = this.state.isWindowExpanded ? 'icon-size-actual' : 'icon-size-fullscreen';
  353. return (
  354. <button className="close mr-3" onClick={this.state.isWindowExpanded ? this.contractWindow : this.expandWindow}>
  355. <i className={iconClassName} style={{ fontSize: '0.8em' }} aria-hidden="true"></i>
  356. </button>
  357. );
  358. }
  359. render() {
  360. const dialogClassNames = ['handsontable-modal'];
  361. if (this.state.isWindowExpanded) {
  362. dialogClassNames.push('handsontable-modal-expanded');
  363. }
  364. const dialogClassName = dialogClassNames.join(' ');
  365. return (
  366. <Modal show={this.state.show} onHide={this.cancel} bsSize="large" dialogClassName={dialogClassName}>
  367. <Modal.Header closeButton>
  368. { this.renderExpandOrContractButton() }
  369. <Modal.Title>Edit Table</Modal.Title>
  370. </Modal.Header>
  371. <Modal.Body className="p-0 d-flex flex-column">
  372. <div className="px-4 py-3 modal-navbar">
  373. <Button className="m-r-20 data-import-button" onClick={this.toggleDataImportArea}>
  374. Data Import<i className={this.state.isDataImportAreaExpanded ? 'fa fa-angle-up' : 'fa fa-angle-down'}></i>
  375. </Button>
  376. <ButtonGroup>
  377. <Button onClick={() => { this.alignButtonHandler('l') }}><i className="ti-align-left"></i></Button>
  378. <Button onClick={() => { this.alignButtonHandler('c') }}><i className="ti-align-center"></i></Button>
  379. <Button onClick={() => { this.alignButtonHandler('r') }}><i className="ti-align-right"></i></Button>
  380. </ButtonGroup>
  381. <Collapse in={this.state.isDataImportAreaExpanded}>
  382. <div> {/* This div is necessary for smoothing animations. (https://react-bootstrap.github.io/utilities/transitions/#transitions-collapse) */}
  383. <MarkdownTableDataImportForm onCancel={this.toggleDataImportArea} onImport={this.importData} />
  384. </div>
  385. </Collapse>
  386. </div>
  387. <div ref="hotTableContainer" className="m-4 hot-table-container">
  388. <HotTable
  389. ref="hotTable"
  390. data={this.state.markdownTable.table}
  391. settings={this.handsontableSettings}
  392. height={this.state.handsontableHeight}
  393. afterLoadData={this.afterLoadDataHandler}
  394. modifyColWidth={this.modifyColWidthHandler}
  395. beforeColumnMove={this.beforeColumnMoveHandler}
  396. beforeColumnResize={this.beforeColumnResizeHandler}
  397. afterColumnResize={this.afterColumnResizeHandler}
  398. afterColumnMove={this.afterColumnMoveHandler}
  399. />
  400. </div>
  401. </Modal.Body>
  402. <Modal.Footer>
  403. <div className="d-flex justify-content-between">
  404. <Button bsStyle="danger" onClick={this.reset}>Reset</Button>
  405. <div className="d-flex">
  406. <Button bsStyle="default" onClick={this.cancel}>Cancel</Button>
  407. <Button bsStyle="primary" onClick={this.save}>Done</Button>
  408. </div>
  409. </div>
  410. </Modal.Footer>
  411. </Modal>
  412. );
  413. }
  414. static getDefaultMarkdownTable() {
  415. return new MarkdownTable(
  416. [
  417. ['col1', 'col2', 'col3'],
  418. ['', '', ''],
  419. ['', '', ''],
  420. ],
  421. {
  422. align: ['', '', ''],
  423. },
  424. );
  425. }
  426. static getDefaultHandsontableSetting() {
  427. return {
  428. rowHeaders: true,
  429. colHeaders: true,
  430. manualRowMove: true,
  431. manualRowResize: true,
  432. manualColumnMove: true,
  433. manualColumnResize: true,
  434. selectionMode: 'multiple',
  435. outsideClickDeselects: false,
  436. };
  437. }
  438. }
  439. HandsontableModal.propTypes = {
  440. onSave: PropTypes.func,
  441. };