HandsontableModal.jsx 17 KB

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