HandsontableModal.tsx 17 KB

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