HandsontableModal.jsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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 TableDataImportForm from './TableDataImportForm';
  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. this.state = {
  23. show: false,
  24. isDataImportAreaExpanded: false,
  25. isWindowExpanded: false,
  26. markdownTableOnInit: HandsontableModal.getDefaultMarkdownTable(),
  27. markdownTable: HandsontableModal.getDefaultMarkdownTable(),
  28. handsontableHeight: DEFAULT_HOT_HEIGHT,
  29. };
  30. this.init = this.init.bind(this);
  31. this.reset = this.reset.bind(this);
  32. this.cancel = this.cancel.bind(this);
  33. this.save = this.save.bind(this);
  34. this.afterLoadDataHandler = this.afterLoadDataHandler.bind(this);
  35. this.beforeColumnMoveHandler = this.beforeColumnMoveHandler.bind(this);
  36. this.beforeColumnResizeHandler = this.beforeColumnResizeHandler.bind(this);
  37. this.afterColumnResizeHandler = this.afterColumnResizeHandler.bind(this);
  38. this.modifyColWidthHandler = this.modifyColWidthHandler.bind(this);
  39. this.synchronizeAlignment = this.synchronizeAlignment.bind(this);
  40. this.alignButtonHandler = this.alignButtonHandler.bind(this);
  41. this.toggleDataImportArea = this.toggleDataImportArea.bind(this);
  42. this.importData = this.importData.bind(this);
  43. this.expandWindow = this.expandWindow.bind(this);
  44. this.contractWindow = this.contractWindow.bind(this);
  45. // create debounced method for expanding HotTable
  46. this.expandHotTableHeightWithDebounce = debounce(100, this.expandHotTableHeight);
  47. // a Set instance that stores column indices which are resized manually.
  48. // these columns will NOT be determined the width automatically by 'modifyColWidthHandler'
  49. this.manuallyResizedColumnIndicesSet = new Set();
  50. // generate setting object for HotTable instance
  51. this.handsontableSettings = Object.assign(HandsontableModal.getDefaultHandsontableSetting(), {
  52. contextMenu: this.createCustomizedContextMenu(),
  53. });
  54. }
  55. init(markdownTable) {
  56. const initMarkdownTable = markdownTable || HandsontableModal.getDefaultMarkdownTable();
  57. this.setState(
  58. {
  59. markdownTableOnInit: initMarkdownTable,
  60. markdownTable: initMarkdownTable.clone(),
  61. }
  62. );
  63. this.manuallyResizedColumnIndicesSet.clear();
  64. }
  65. createCustomizedContextMenu() {
  66. return {
  67. items: {
  68. 'row_above': {}, 'row_below': {}, 'col_left': {}, 'col_right': {},
  69. 'separator1': Handsontable.plugins.ContextMenu.SEPARATOR,
  70. 'remove_row': {}, 'remove_col': {},
  71. 'separator2': Handsontable.plugins.ContextMenu.SEPARATOR,
  72. 'custom_alignment': {
  73. name: 'Align columns',
  74. key: 'align_columns',
  75. submenu: {
  76. items: [
  77. {
  78. name: 'Left',
  79. key: 'align_columns:1',
  80. callback: (key, selection) => {this.align('l', selection[0].start.col, selection[0].end.col)}
  81. }, {
  82. name: 'Center',
  83. key: 'align_columns:2',
  84. callback: (key, selection) => {this.align('c', selection[0].start.col, selection[0].end.col)}
  85. }, {
  86. name: 'Right',
  87. key: 'align_columns:3',
  88. callback: (key, selection) => {this.align('r', selection[0].start.col, selection[0].end.col)}
  89. }
  90. ]
  91. }
  92. }
  93. }
  94. };
  95. }
  96. show(markdownTable) {
  97. this.init(markdownTable);
  98. this.setState({ show: true });
  99. }
  100. hide() {
  101. this.setState({
  102. show: false,
  103. isDataImportAreaExpanded: false,
  104. isWindowExpanded: false,
  105. });
  106. }
  107. reset() {
  108. this.setState({ markdownTable: this.state.markdownTableOnInit.clone() });
  109. }
  110. cancel() {
  111. this.hide();
  112. }
  113. save() {
  114. if (this.props.onSave != null) {
  115. this.props.onSave(this.state.markdownTable);
  116. }
  117. this.hide();
  118. }
  119. afterLoadDataHandler(initialLoad) {
  120. // clear 'manuallyResizedColumnIndicesSet' for the first loading
  121. if (initialLoad) {
  122. this.manuallyResizedColumnIndicesSet.clear();
  123. }
  124. this.synchronizeAlignment();
  125. }
  126. beforeColumnMoveHandler(columns, target) {
  127. // clear 'manuallyResizedColumnIndicesSet'
  128. this.manuallyResizedColumnIndicesSet.clear();
  129. }
  130. beforeColumnResizeHandler(currentColumn) {
  131. /*
  132. * The following bug disturbs to use 'beforeColumnResizeHandler' to store column index -- 2018.10.23 Yuki Takei
  133. * https://github.com/handsontable/handsontable/issues/3328
  134. *
  135. * At the moment, using 'afterColumnResizeHandler' instead.
  136. */
  137. // store column index
  138. // this.manuallyResizedColumnIndicesSet.add(currentColumn);
  139. }
  140. afterColumnResizeHandler(currentColumn) {
  141. /*
  142. * The following bug disturbs to use 'beforeColumnResizeHandler' to store column index -- 2018.10.23 Yuki Takei
  143. * https://github.com/handsontable/handsontable/issues/3328
  144. *
  145. * At the moment, using 'afterColumnResizeHandler' instead.
  146. */
  147. // store column index
  148. this.manuallyResizedColumnIndicesSet.add(currentColumn);
  149. // force re-render
  150. const hotInstance = this.refs.hotTable.hotInstance;
  151. hotInstance.render();
  152. }
  153. modifyColWidthHandler(width, column) {
  154. // return original width if the column index exists in 'manuallyResizedColumnIndicesSet'
  155. if (this.manuallyResizedColumnIndicesSet.has(column)) {
  156. return width;
  157. }
  158. // return fixed width if first initializing
  159. return Math.max(80, Math.min(400, width));
  160. }
  161. /**
  162. * change the markdownTable alignment and synchronize the handsontable alignment to it
  163. */
  164. align(direction, startCol, endCol) {
  165. this.setState((prevState) => {
  166. // change only align info, so share table data to avoid redundant copy
  167. const newMarkdownTable = new MarkdownTable(prevState.markdownTable.table, {align: [].concat(prevState.markdownTable.options.align)});
  168. for (let i = startCol; i <= endCol ; i++) {
  169. newMarkdownTable.options.align[i] = direction;
  170. }
  171. return { markdownTable: newMarkdownTable };
  172. }, () => {
  173. this.synchronizeAlignment();
  174. });
  175. }
  176. /**
  177. * synchronize the handsontable alignment to the markdowntable alignment
  178. */
  179. synchronizeAlignment() {
  180. if (this.refs.hotTable == null) {
  181. return;
  182. }
  183. const align = this.state.markdownTable.options.align;
  184. const hotInstance = this.refs.hotTable.hotInstance;
  185. for (let i = 0; i < align.length; i++) {
  186. for (let j = 0; j < hotInstance.countRows(); j++) {
  187. hotInstance.setCellMeta(j, i, 'className', MARKDOWNTABLE_TO_HANDSONTABLE_ALIGNMENT_SYMBOL_MAPPING[align[i]]);
  188. }
  189. }
  190. hotInstance.render();
  191. }
  192. alignButtonHandler(direction) {
  193. const selectedRange = this.refs.hotTable.hotInstance.getSelectedRange();
  194. if (selectedRange == null) return;
  195. let startCol;
  196. let endCol;
  197. if (selectedRange[0].from.col < selectedRange[0].to.col) {
  198. startCol = selectedRange[0].from.col;
  199. endCol = selectedRange[0].to.col;
  200. }
  201. else {
  202. startCol = selectedRange[0].to.col;
  203. endCol = selectedRange[0].from.col;
  204. }
  205. this.align(direction, startCol, endCol);
  206. }
  207. toggleDataImportArea() {
  208. this.setState({ isDataImportAreaExpanded: !this.state.isDataImportAreaExpanded });
  209. }
  210. importData(markdownTable) {
  211. this.init(markdownTable);
  212. this.toggleDataImportArea();
  213. }
  214. expandWindow() {
  215. this.setState({ isWindowExpanded: true });
  216. // invoke updateHotTableHeight method with delay
  217. // cz. Resizing this.refs.hotTableContainer is completed after a little delay after 'isWindowExpanded' set with 'true'
  218. this.expandHotTableHeightWithDebounce();
  219. }
  220. contractWindow() {
  221. this.setState({ isWindowExpanded: false, handsontableHeight: DEFAULT_HOT_HEIGHT });
  222. }
  223. /**
  224. * Expand the height of the Handsontable
  225. * by updating 'handsontableHeight' state
  226. * according to the height of this.refs.hotTableContainer
  227. */
  228. expandHotTableHeight() {
  229. if (this.state.isWindowExpanded && this.refs.hotTableContainer != null) {
  230. const height = this.refs.hotTableContainer.getBoundingClientRect().height;
  231. this.setState({ handsontableHeight: height });
  232. }
  233. }
  234. renderExpandOrContractButton() {
  235. const iconClassName = this.state.isWindowExpanded ? 'icon-size-actual' : 'icon-size-fullscreen';
  236. return (
  237. <button className="close mr-3" onClick={this.state.isWindowExpanded ? this.contractWindow : this.expandWindow}>
  238. <i className={iconClassName} style={{ fontSize: '0.8em' }} aria-hidden="true"></i>
  239. </button>
  240. );
  241. }
  242. render() {
  243. const dialogClassNames = ['handsontable-modal'];
  244. if (this.state.isWindowExpanded) {
  245. dialogClassNames.push('handsontable-modal-expanded');
  246. }
  247. const dialogClassName = dialogClassNames.join(' ');
  248. return (
  249. <Modal show={this.state.show} onHide={this.cancel} bsSize="large" dialogClassName={dialogClassName}>
  250. <Modal.Header closeButton>
  251. { this.renderExpandOrContractButton() }
  252. <Modal.Title>Edit Table</Modal.Title>
  253. </Modal.Header>
  254. <Modal.Body className="p-0 d-flex flex-column">
  255. <div className="px-4 py-3 modal-navbar">
  256. <Button className="m-r-20 data-import-button" onClick={this.toggleDataImportArea}>
  257. Data Import<i className={this.state.isDataImportAreaExpanded ? 'fa fa-angle-up' : 'fa fa-angle-down' }></i>
  258. </Button>
  259. <ButtonGroup>
  260. <Button onClick={() => { this.alignButtonHandler('l') }}><i className="ti-align-left"></i></Button>
  261. <Button onClick={() => { this.alignButtonHandler('c') }}><i className="ti-align-center"></i></Button>
  262. <Button onClick={() => { this.alignButtonHandler('r') }}><i className="ti-align-right"></i></Button>
  263. </ButtonGroup>
  264. <Collapse in={this.state.isDataImportAreaExpanded}>
  265. <div> {/* This div is necessary for smoothing animations. (https://react-bootstrap.github.io/utilities/transitions/#transitions-collapse) */}
  266. <TableDataImportForm onCancel={this.toggleDataImportArea} onImport={this.importData}/>
  267. </div>
  268. </Collapse>
  269. </div>
  270. <div ref="hotTableContainer" className="m-4 hot-table-container">
  271. <HotTable ref='hotTable' data={this.state.markdownTable.table}
  272. settings={this.handsontableSettings} height={this.state.handsontableHeight}
  273. afterLoadData={this.afterLoadDataHandler}
  274. modifyColWidth={this.modifyColWidthHandler}
  275. beforeColumnMove={this.beforeColumnMoveHandler}
  276. beforeColumnResize={this.beforeColumnResizeHandler}
  277. afterColumnResize={this.afterColumnResizeHandler}
  278. />
  279. </div>
  280. </Modal.Body>
  281. <Modal.Footer>
  282. <div className="d-flex justify-content-between">
  283. <Button bsStyle="danger" onClick={this.reset}>Reset</Button>
  284. <div className="d-flex">
  285. <Button bsStyle="default" onClick={this.cancel}>Cancel</Button>
  286. <Button bsStyle="primary" onClick={this.save}>Done</Button>
  287. </div>
  288. </div>
  289. </Modal.Footer>
  290. </Modal>
  291. );
  292. }
  293. static getDefaultMarkdownTable() {
  294. return new MarkdownTable(
  295. [
  296. ['col1', 'col2', 'col3'],
  297. ['', '', ''],
  298. ['', '', ''],
  299. ],
  300. {
  301. align: ['', '', '']
  302. }
  303. );
  304. }
  305. static getDefaultHandsontableSetting() {
  306. return {
  307. rowHeaders: true,
  308. colHeaders: true,
  309. manualRowMove: true,
  310. manualRowResize: true,
  311. manualColumnMove: true,
  312. manualColumnResize: true,
  313. selectionMode: 'multiple',
  314. outsideClickDeselects: false,
  315. };
  316. }
  317. }
  318. HandsontableModal.propTypes = {
  319. onSave: PropTypes.func
  320. };