HandsontableModal.jsx 13 KB

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