HandsontableModal.tsx 19 KB

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