HandsontableModal.jsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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.Component {
  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. handsontableSetting: HandsontableModal.getDefaultHandsontableSetting()
  32. };
  33. this.init = this.init.bind(this);
  34. this.reset = this.reset.bind(this);
  35. this.cancel = this.cancel.bind(this);
  36. this.save = this.save.bind(this);
  37. this.synchronizeAlignment = this.synchronizeAlignment.bind(this);
  38. this.alignButtonHandler = this.alignButtonHandler.bind(this);
  39. this.toggleDataImportArea = this.toggleDataImportArea.bind(this);
  40. this.expandWindow = this.expandWindow.bind(this);
  41. this.contractWindow = this.contractWindow.bind(this);
  42. // create debounced method for expanding HotTable
  43. this.expandHotTableHeightWithDebounce = debounce(100, this.expandHotTableHeight);
  44. }
  45. init(markdownTable) {
  46. const initMarkdownTable = markdownTable || HandsontableModal.getDefaultMarkdownTable();
  47. this.setState(
  48. {
  49. markdownTableOnInit: initMarkdownTable,
  50. markdownTable: initMarkdownTable.clone(),
  51. handsontableSetting: Object.assign({}, this.state.handsontableSetting, {
  52. afterUpdateSettings: this.synchronizeAlignment,
  53. contextMenu: this.createCustomizedContextMenu()
  54. })
  55. }
  56. );
  57. }
  58. createCustomizedContextMenu() {
  59. return {
  60. items: {
  61. 'row_above': {}, 'row_below': {}, 'col_left': {}, 'col_right': {},
  62. 'separator1': Handsontable.plugins.ContextMenu.SEPARATOR,
  63. 'remove_row': {}, 'remove_col': {},
  64. 'separator2': Handsontable.plugins.ContextMenu.SEPARATOR,
  65. 'custom_alignment': {
  66. name: 'Align columns',
  67. key: 'align_columns',
  68. submenu: {
  69. items: [
  70. {
  71. name: 'Left',
  72. key: 'align_columns:1',
  73. callback: (key, selection) => {this.align('l', selection[0].start.col, selection[0].end.col)}
  74. }, {
  75. name: 'Center',
  76. key: 'align_columns:2',
  77. callback: (key, selection) => {this.align('c', selection[0].start.col, selection[0].end.col)}
  78. }, {
  79. name: 'Right',
  80. key: 'align_columns:3',
  81. callback: (key, selection) => {this.align('r', selection[0].start.col, selection[0].end.col)}
  82. }
  83. ]
  84. }
  85. }
  86. }
  87. };
  88. }
  89. show(markdownTable) {
  90. this.init(markdownTable);
  91. this.setState({ show: true });
  92. }
  93. reset() {
  94. this.setState({ markdownTable: this.state.markdownTableOnInit.clone() });
  95. }
  96. cancel() {
  97. this.setState({ show: false });
  98. }
  99. save() {
  100. if (this.props.onSave != null) {
  101. this.props.onSave(this.state.markdownTable);
  102. }
  103. this.setState({ show: false });
  104. }
  105. /**
  106. * change the markdownTable alignment and synchronize the handsontable alignment to it
  107. */
  108. align(direction, startCol, endCol) {
  109. this.setState((prevState) => {
  110. // change only align info, so share table data to avoid redundant copy
  111. const newMarkdownTable = new MarkdownTable(prevState.markdownTable.table, {align: [].concat(prevState.markdownTable.options.align)});
  112. for (let i = startCol; i <= endCol ; i++) {
  113. newMarkdownTable.options.align[i] = direction;
  114. }
  115. return { markdownTable: newMarkdownTable };
  116. }, () => {
  117. this.synchronizeAlignment();
  118. });
  119. }
  120. /**
  121. * synchronize the handsontable alignment to the markdowntable alignment
  122. */
  123. synchronizeAlignment() {
  124. const align = this.state.markdownTable.options.align;
  125. const hotInstance = this.refs.hotTable.hotInstance;
  126. for (let i = 0; i < align.length; i++) {
  127. for (let j = 0; j < hotInstance.countRows(); j++) {
  128. hotInstance.setCellMeta(j, i, 'className', MARKDOWNTABLE_TO_HANDSONTABLE_ALIGNMENT_SYMBOL_MAPPING[align[i]]);
  129. }
  130. }
  131. hotInstance.render();
  132. }
  133. alignButtonHandler(direction) {
  134. const selectedRange = this.refs.hotTable.hotInstance.getSelectedRange();
  135. if (selectedRange == null) return;
  136. let startCol;
  137. let endCol;
  138. if (selectedRange[0].from.col < selectedRange[0].to.col) {
  139. startCol = selectedRange[0].from.col;
  140. endCol = selectedRange[0].to.col;
  141. }
  142. else {
  143. startCol = selectedRange[0].to.col;
  144. endCol = selectedRange[0].from.col;
  145. }
  146. this.align(direction, startCol, endCol);
  147. }
  148. toggleDataImportArea() {
  149. this.setState({ isDataImportAreaExpanded: !this.state.isDataImportAreaExpanded });
  150. }
  151. expandWindow() {
  152. this.setState({ isWindowExpanded: true });
  153. // invoke updateHotTableHeight method with delay
  154. // cz. Resizing this.refs.hotTableContainer is completed after a little delay after 'isWindowExpanded' set with 'true'
  155. this.expandHotTableHeightWithDebounce();
  156. }
  157. contractWindow() {
  158. this.setState({ isWindowExpanded: false, handsontableHeight: DEFAULT_HOT_HEIGHT });
  159. }
  160. /**
  161. * Expand the height of the Handsontable
  162. * by updating 'handsontableHeight' state
  163. * according to the height of this.refs.hotTableContainer
  164. */
  165. expandHotTableHeight() {
  166. if (this.state.isWindowExpanded && this.refs.hotTableContainer != null) {
  167. const height = this.refs.hotTableContainer.getBoundingClientRect().height;
  168. this.setState({ handsontableHeight: height });
  169. }
  170. }
  171. renderExpandOrContractButton() {
  172. const iconClassName = this.state.isWindowExpanded ? 'icon-size-actual' : 'icon-size-fullscreen';
  173. return (
  174. <button className="close mr-3" onClick={this.state.isWindowExpanded ? this.contractWindow : this.expandWindow}>
  175. <i className={iconClassName} style={{ fontSize: '0.8em' }} aria-hidden="true"></i>
  176. </button>
  177. );
  178. }
  179. render() {
  180. const dialogClassNames = ['handsontable-modal'];
  181. if (this.state.isWindowExpanded) {
  182. dialogClassNames.push('handsontable-modal-expanded');
  183. }
  184. const dialogClassName = dialogClassNames.join(' ');
  185. return (
  186. <Modal show={this.state.show} onHide={this.cancel} bsSize="large" dialogClassName={dialogClassName}>
  187. <Modal.Header closeButton>
  188. { this.renderExpandOrContractButton() }
  189. <Modal.Title>Edit Table</Modal.Title>
  190. </Modal.Header>
  191. <Modal.Body className="p-0 d-flex flex-column">
  192. <div className="px-4 py-3 modal-navbar">
  193. <Button className="m-r-20 data-import-button" onClick={this.toggleDataImportArea}>
  194. Data Import<i className={this.state.isDataImportAreaExpanded ? 'fa fa-angle-up' : 'fa fa-angle-down' }></i>
  195. </Button>
  196. <ButtonGroup>
  197. <Button onClick={() => { this.alignButtonHandler('l') }}><i className="ti-align-left"></i></Button>
  198. <Button onClick={() => { this.alignButtonHandler('c') }}><i className="ti-align-center"></i></Button>
  199. <Button onClick={() => { this.alignButtonHandler('r') }}><i className="ti-align-right"></i></Button>
  200. </ButtonGroup>
  201. <Collapse in={this.state.isDataImportAreaExpanded}>
  202. <div> {/* This div is necessary for smoothing animations. (https://react-bootstrap.github.io/utilities/transitions/#transitions-collapse) */}
  203. <form action="" className="data-import-form pt-5">
  204. <FormGroup>
  205. <ControlLabel>Select Data Format</ControlLabel>
  206. <FormControl componentClass="select" placeholder="select">
  207. <option value="select">CSV</option>
  208. <option value="other">TSV</option>
  209. <option value="other">HTML</option>
  210. </FormControl>
  211. </FormGroup>
  212. <FormGroup>
  213. <ControlLabel>Import Data</ControlLabel>
  214. <FormControl componentClass="textarea" placeholder="Paste table data" style={{ height: 200 }} />
  215. </FormGroup>
  216. <div className="d-flex justify-content-end">
  217. <Button bsStyle="default" onClick={this.toggleDataImportArea}>Cancel</Button>
  218. <Button bsStyle="primary">Import</Button>
  219. </div>
  220. </form>
  221. </div>
  222. </Collapse>
  223. </div>
  224. <div ref="hotTableContainer" className="m-4 hot-table-container">
  225. <HotTable ref='hotTable' data={this.state.markdownTable.table} settings={this.state.handsontableSetting} height={this.state.handsontableHeight} />
  226. </div>
  227. </Modal.Body>
  228. <Modal.Footer>
  229. <div className="d-flex justify-content-between">
  230. <Button bsStyle="danger" onClick={this.reset}>Reset</Button>
  231. <div className="d-flex">
  232. <Button bsStyle="default" onClick={this.cancel}>Cancel</Button>
  233. <Button bsStyle="primary" onClick={this.save}>Done</Button>
  234. </div>
  235. </div>
  236. </Modal.Footer>
  237. </Modal>
  238. );
  239. }
  240. static getDefaultMarkdownTable() {
  241. return new MarkdownTable(
  242. [
  243. ['col1', 'col2', 'col3'],
  244. ['', '', ''],
  245. ['', '', ''],
  246. ],
  247. {
  248. align: ['', '', '']
  249. }
  250. );
  251. }
  252. static getDefaultHandsontableSetting() {
  253. return {
  254. rowHeaders: true,
  255. colHeaders: true,
  256. manualRowMove: true,
  257. manualRowResize: true,
  258. manualColumnMove: true,
  259. manualColumnResize: true,
  260. selectionMode: 'multiple',
  261. outsideClickDeselects: false,
  262. modifyColWidth: function(width) {
  263. return Math.max(80, Math.min(400, width));
  264. }
  265. };
  266. }
  267. }
  268. HandsontableModal.propTypes = {
  269. onSave: PropTypes.func
  270. };