ItemsTree.tsx 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. import React, { FC, useEffect, useState } from 'react';
  2. import { useTranslation } from 'react-i18next';
  3. import { usePageTreeTermManager, useSWRxPageAncestorsChildren, useSWRxRootPage } from '~/stores/page-listing';
  4. import { TargetAndAncestors } from '~/interfaces/page-listing-results';
  5. import { IPageHasId, IPageToDeleteWithMeta } from '~/interfaces/page';
  6. import { OnDuplicatedFunction, OnRenamedFunction, OnDeletedFunction } from '~/interfaces/ui';
  7. import { SocketEventName, UpdateDescCountData, UpdateDescCountRawData } from '~/interfaces/websocket';
  8. import { toastError, toastSuccess } from '~/client/util/apiNotification';
  9. import {
  10. IPageForPageDuplicateModal, usePageDuplicateModal, IPageForPageRenameModal, usePageRenameModal, usePageDeleteModal,
  11. } from '~/stores/modal';
  12. import { smoothScrollIntoView } from '~/client/util/smooth-scroll';
  13. import { useIsEnabledAttachTitleHeader } from '~/stores/context';
  14. import { useFullTextSearchTermManager } from '~/stores/search';
  15. import { useDescendantsPageListForCurrentPathTermManager } from '~/stores/page';
  16. import { useGlobalSocket } from '~/stores/websocket';
  17. import { usePageTreeDescCountMap } from '~/stores/ui';
  18. import { ItemNode } from './ItemNode';
  19. import Item from './Item';
  20. /*
  21. * Utility to generate initial node
  22. */
  23. const generateInitialNodeBeforeResponse = (targetAndAncestors: Partial<IPageHasId>[]): ItemNode => {
  24. const nodes = targetAndAncestors.map((page): ItemNode => {
  25. return new ItemNode(page, []);
  26. });
  27. // update children for each node
  28. const rootNode = nodes.reduce((child, parent) => {
  29. parent.children = [child];
  30. return parent;
  31. });
  32. return rootNode;
  33. };
  34. const generateInitialNodeAfterResponse = (ancestorsChildren: Record<string, Partial<IPageHasId>[]>, rootNode: ItemNode): ItemNode => {
  35. const paths = Object.keys(ancestorsChildren);
  36. let currentNode = rootNode;
  37. paths.every((path) => {
  38. // stop rendering when non-migrated pages found
  39. if (currentNode == null) {
  40. return false;
  41. }
  42. const childPages = ancestorsChildren[path];
  43. currentNode.children = ItemNode.generateNodesFromPages(childPages);
  44. const nextNode = currentNode.children.filter((node) => {
  45. return paths.includes(node.page.path as string);
  46. })[0];
  47. currentNode = nextNode;
  48. return true;
  49. });
  50. return rootNode;
  51. };
  52. type ItemsTreeProps = {
  53. isEnableActions: boolean
  54. targetPath: string
  55. targetPathOrId?: string
  56. targetAndAncestorsData?: TargetAndAncestors
  57. }
  58. const renderByInitialNode = (
  59. initialNode: ItemNode,
  60. isEnableActions: boolean,
  61. isScrolled: boolean,
  62. targetPathOrId?: string,
  63. isEnabledAttachTitleHeader?: boolean,
  64. onClickDuplicateMenuItem?: (pageToDuplicate: IPageForPageDuplicateModal) => void,
  65. onClickRenameMenuItem?: (pageToRename: IPageForPageRenameModal) => void,
  66. onClickDeleteMenuItem?: (pageToDelete: IPageToDeleteWithMeta) => void,
  67. ): JSX.Element => {
  68. return (
  69. <ul className="grw-pagetree list-group p-3">
  70. <Item
  71. key={initialNode.page.path}
  72. targetPathOrId={targetPathOrId}
  73. itemNode={initialNode}
  74. isOpen
  75. isEnabledAttachTitleHeader={isEnabledAttachTitleHeader}
  76. isEnableActions={isEnableActions}
  77. onClickDuplicateMenuItem={onClickDuplicateMenuItem}
  78. onClickRenameMenuItem={onClickRenameMenuItem}
  79. onClickDeleteMenuItem={onClickDeleteMenuItem}
  80. isScrolled={isScrolled}
  81. />
  82. </ul>
  83. );
  84. };
  85. // --- Auto scroll related vars and util ---
  86. const SCROLL_OFFSET_TOP = window.innerHeight / 2;
  87. const scrollTargetItem = () => {
  88. const scrollElement = document.getElementById('grw-sidebar-contents-scroll-target');
  89. const target = document.getElementById('grw-pagetree-is-target');
  90. if (scrollElement != null && target != null) {
  91. smoothScrollIntoView(target, SCROLL_OFFSET_TOP, scrollElement);
  92. }
  93. };
  94. // --- end ---
  95. /*
  96. * ItemsTree
  97. */
  98. const ItemsTree: FC<ItemsTreeProps> = (props: ItemsTreeProps) => {
  99. const {
  100. targetPath, targetPathOrId, targetAndAncestorsData, isEnableActions,
  101. } = props;
  102. const { t } = useTranslation();
  103. const { data: ancestorsChildrenData, error: error1 } = useSWRxPageAncestorsChildren(targetPath);
  104. const { data: rootPageData, error: error2 } = useSWRxRootPage();
  105. const { data: isEnabledAttachTitleHeader } = useIsEnabledAttachTitleHeader();
  106. const { open: openDuplicateModal } = usePageDuplicateModal();
  107. const { open: openRenameModal } = usePageRenameModal();
  108. const { open: openDeleteModal } = usePageDeleteModal();
  109. const [isScrolled, setIsScrolled] = useState(false);
  110. const { data: socket } = useGlobalSocket();
  111. const { data: ptDescCountMap, update: updatePtDescCountMap } = usePageTreeDescCountMap();
  112. // for mutation
  113. const { advance: advancePt } = usePageTreeTermManager();
  114. const { advance: advanceFts } = useFullTextSearchTermManager();
  115. const { advance: advanceDpl } = useDescendantsPageListForCurrentPathTermManager();
  116. const scrollItem = () => {
  117. scrollTargetItem();
  118. setIsScrolled(true);
  119. };
  120. useEffect(() => {
  121. document.addEventListener('targetItemRendered', scrollItem);
  122. return () => {
  123. document.removeEventListener('targetItemRendered', scrollItem);
  124. };
  125. }, []);
  126. useEffect(() => {
  127. if (socket == null) {
  128. return;
  129. }
  130. // socket
  131. socket.on(SocketEventName.UpdateDescCount, (data: UpdateDescCountRawData) => {
  132. // save to global state
  133. const newData: UpdateDescCountData = new Map(Object.entries(data));
  134. updatePtDescCountMap(newData);
  135. });
  136. }, [socket, ptDescCountMap, updatePtDescCountMap]);
  137. const onClickDuplicateMenuItem = (pageToDuplicate: IPageForPageDuplicateModal) => {
  138. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  139. const duplicatedHandler: OnDuplicatedFunction = (fromPath, toPath) => {
  140. toastSuccess(t('duplicated_pages', { fromPath }));
  141. advancePt();
  142. advanceFts();
  143. advanceDpl();
  144. };
  145. openDuplicateModal(pageToDuplicate, { onDuplicated: duplicatedHandler });
  146. };
  147. const onClickRenameMenuItem = (pageToRename: IPageForPageRenameModal) => {
  148. const renamedHandler: OnRenamedFunction = (path) => {
  149. toastSuccess(t('renamed_pages', { path }));
  150. // TODO: revalidation by https://redmine.weseek.co.jp/issues/89258
  151. };
  152. openRenameModal(pageToRename, { onRenamed: renamedHandler });
  153. };
  154. const onClickDeleteMenuItem = (pageToDelete: IPageToDeleteWithMeta) => {
  155. const onDeletedHandler: OnDeletedFunction = (pathOrPathsToDelete, isRecursively, isCompletely) => {
  156. if (typeof pathOrPathsToDelete !== 'string') {
  157. return;
  158. }
  159. const path = pathOrPathsToDelete;
  160. if (isCompletely) {
  161. toastSuccess(t('deleted_pages_completely', { path }));
  162. }
  163. else {
  164. toastSuccess(t('deleted_pages', { path }));
  165. }
  166. advancePt();
  167. advanceFts();
  168. advanceDpl();
  169. };
  170. openDeleteModal([pageToDelete], { onDeleted: onDeletedHandler });
  171. };
  172. if (error1 != null || error2 != null) {
  173. // TODO: improve message
  174. toastError('Error occurred while fetching pages to render PageTree');
  175. return null;
  176. }
  177. /*
  178. * Render completely
  179. */
  180. if (ancestorsChildrenData != null && rootPageData != null) {
  181. const initialNode = generateInitialNodeAfterResponse(ancestorsChildrenData.ancestorsChildren, new ItemNode(rootPageData.rootPage));
  182. return renderByInitialNode(
  183. // eslint-disable-next-line max-len
  184. initialNode, isEnableActions, isScrolled, targetPathOrId, isEnabledAttachTitleHeader, onClickDuplicateMenuItem, onClickRenameMenuItem, onClickDeleteMenuItem,
  185. );
  186. }
  187. /*
  188. * Before swr response comes back
  189. */
  190. if (targetAndAncestorsData != null) {
  191. const initialNode = generateInitialNodeBeforeResponse(targetAndAncestorsData.targetAndAncestors);
  192. return renderByInitialNode(
  193. // eslint-disable-next-line max-len
  194. initialNode, isEnableActions, isScrolled, targetPathOrId, isEnabledAttachTitleHeader, onClickDuplicateMenuItem, onClickRenameMenuItem, onClickDeleteMenuItem,
  195. );
  196. }
  197. return null;
  198. };
  199. export default ItemsTree;