HandsontableModal.tsx 17 KB

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