HandsontableModal.tsx 17 KB

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