HandsontableModal.tsx 17 KB

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