HandsontableModal.tsx 18 KB

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