HandsontableModal.tsx 19 KB

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