HandsontableModal.jsx 17 KB

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