ItemsTree.tsx 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. import React, {
  2. useEffect, useRef, useState, useMemo, useCallback,
  3. } from 'react';
  4. import path from 'path';
  5. import type { Nullable, IPageHasId, IPageToDeleteWithMeta } from '@growi/core';
  6. import { useTranslation } from 'next-i18next';
  7. import { useRouter } from 'next/router';
  8. import { debounce } from 'throttle-debounce';
  9. import { toastError, toastSuccess } from '~/client/util/toastr';
  10. import { AncestorsChildrenResult, RootPageResult, TargetAndAncestors } from '~/interfaces/page-listing-results';
  11. import { OnDuplicatedFunction, OnDeletedFunction } from '~/interfaces/ui';
  12. import { SocketEventName, UpdateDescCountData, UpdateDescCountRawData } from '~/interfaces/websocket';
  13. import {
  14. IPageForPageDuplicateModal, usePageDuplicateModal, usePageDeleteModal,
  15. } from '~/stores/modal';
  16. import { mutateAllPageInfo, useCurrentPagePath, useSWRMUTxCurrentPage } from '~/stores/page';
  17. import {
  18. useSWRxPageAncestorsChildren, useSWRxRootPage, mutatePageTree, mutatePageList,
  19. } from '~/stores/page-listing';
  20. import { mutateSearching } from '~/stores/search';
  21. import { usePageTreeDescCountMap, useSidebarScrollerRef } from '~/stores/ui';
  22. import { useGlobalSocket } from '~/stores/websocket';
  23. import loggerFactory from '~/utils/logger';
  24. import { ItemNode, SimpleItemProps } from '../TreeItem';
  25. import PageTreeContentSkeleton from './PageTreeContentSkeleton';
  26. import styles from './ItemsTree.module.scss';
  27. const logger = loggerFactory('growi:cli:ItemsTree');
  28. /*
  29. * Utility to generate initial node
  30. */
  31. const generateInitialNodeBeforeResponse = (targetAndAncestors: Partial<IPageHasId>[]): ItemNode => {
  32. const nodes = targetAndAncestors.map((page): ItemNode => {
  33. return new ItemNode(page, []);
  34. });
  35. // update children for each node
  36. const rootNode = nodes.reduce((child, parent) => {
  37. parent.children = [child];
  38. return parent;
  39. });
  40. return rootNode;
  41. };
  42. const generateInitialNodeAfterResponse = (ancestorsChildren: Record<string, Partial<IPageHasId>[]>, rootNode: ItemNode): ItemNode => {
  43. const paths = Object.keys(ancestorsChildren);
  44. let currentNode = rootNode;
  45. paths.every((path) => {
  46. // stop rendering when non-migrated pages found
  47. if (currentNode == null) {
  48. return false;
  49. }
  50. const childPages = ancestorsChildren[path];
  51. currentNode.children = ItemNode.generateNodesFromPages(childPages);
  52. const nextNode = currentNode.children.filter((node) => {
  53. return paths.includes(node.page.path as string);
  54. })[0];
  55. currentNode = nextNode;
  56. return true;
  57. });
  58. return rootNode;
  59. };
  60. // user defined typeguard to assert the arg is not null
  61. type RenderingCondition = {
  62. ancestorsChildrenResult: AncestorsChildrenResult | undefined,
  63. rootPageResult: RootPageResult | undefined,
  64. }
  65. type SecondStageRenderingCondition = {
  66. ancestorsChildrenResult: AncestorsChildrenResult,
  67. rootPageResult: RootPageResult,
  68. }
  69. const isSecondStageRenderingCondition = (condition: RenderingCondition|SecondStageRenderingCondition): condition is SecondStageRenderingCondition => {
  70. return condition.ancestorsChildrenResult != null && condition.rootPageResult != null;
  71. };
  72. type ItemsTreeProps = {
  73. isEnableActions: boolean
  74. isReadOnlyUser: boolean
  75. targetPath: string
  76. targetPathOrId?: Nullable<string>
  77. targetAndAncestorsData?: TargetAndAncestors
  78. CustomTreeItem: React.FunctionComponent<SimpleItemProps>
  79. }
  80. /*
  81. * ItemsTree
  82. */
  83. export const ItemsTree = (props: ItemsTreeProps): JSX.Element => {
  84. const {
  85. targetPath, targetPathOrId, targetAndAncestorsData, isEnableActions, isReadOnlyUser, CustomTreeItem,
  86. } = props;
  87. const { t } = useTranslation();
  88. const router = useRouter();
  89. const { data: ancestorsChildrenResult, error: error1 } = useSWRxPageAncestorsChildren(targetPath, { suspense: true });
  90. const { data: rootPageResult, error: error2 } = useSWRxRootPage({ suspense: true });
  91. const { data: currentPagePath } = useCurrentPagePath();
  92. const { open: openDuplicateModal } = usePageDuplicateModal();
  93. const { open: openDeleteModal } = usePageDeleteModal();
  94. const { data: sidebarScrollerRef } = useSidebarScrollerRef();
  95. const { data: socket } = useGlobalSocket();
  96. const { data: ptDescCountMap, update: updatePtDescCountMap } = usePageTreeDescCountMap();
  97. // for mutation
  98. const { trigger: mutateCurrentPage } = useSWRMUTxCurrentPage();
  99. const [isInitialScrollCompleted, setIsInitialScrollCompleted] = useState(false);
  100. const rootElemRef = useRef(null);
  101. const renderingCondition = useMemo(() => {
  102. return {
  103. ancestorsChildrenResult,
  104. rootPageResult,
  105. };
  106. }, [ancestorsChildrenResult, rootPageResult]);
  107. useEffect(() => {
  108. if (socket == null) {
  109. return;
  110. }
  111. socket.on(SocketEventName.UpdateDescCount, (data: UpdateDescCountRawData) => {
  112. // save to global state
  113. const newData: UpdateDescCountData = new Map(Object.entries(data));
  114. updatePtDescCountMap(newData);
  115. });
  116. return () => { socket.off(SocketEventName.UpdateDescCount) };
  117. }, [socket, ptDescCountMap, updatePtDescCountMap]);
  118. const onRenamed = useCallback((fromPath: string | undefined, toPath: string) => {
  119. mutatePageTree();
  120. mutateSearching();
  121. mutatePageList();
  122. if (currentPagePath === fromPath || currentPagePath === toPath) {
  123. mutateCurrentPage();
  124. }
  125. }, [currentPagePath, mutateCurrentPage]);
  126. const onClickDuplicateMenuItem = useCallback((pageToDuplicate: IPageForPageDuplicateModal) => {
  127. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  128. const duplicatedHandler: OnDuplicatedFunction = (fromPath, toPath) => {
  129. toastSuccess(t('duplicated_pages', { fromPath }));
  130. mutatePageTree();
  131. mutateSearching();
  132. mutatePageList();
  133. };
  134. openDuplicateModal(pageToDuplicate, { onDuplicated: duplicatedHandler });
  135. }, [openDuplicateModal, t]);
  136. const onClickDeleteMenuItem = useCallback((pageToDelete: IPageToDeleteWithMeta) => {
  137. const onDeletedHandler: OnDeletedFunction = (pathOrPathsToDelete, isRecursively, isCompletely) => {
  138. if (typeof pathOrPathsToDelete !== 'string') {
  139. return;
  140. }
  141. if (isCompletely) {
  142. toastSuccess(t('deleted_pages_completely', { path: pathOrPathsToDelete }));
  143. }
  144. else {
  145. toastSuccess(t('deleted_pages', { path: pathOrPathsToDelete }));
  146. }
  147. mutatePageTree();
  148. mutateSearching();
  149. mutatePageList();
  150. mutateAllPageInfo();
  151. if (currentPagePath === pathOrPathsToDelete) {
  152. mutateCurrentPage();
  153. router.push(isCompletely ? path.dirname(pathOrPathsToDelete) : `/trash${pathOrPathsToDelete}`);
  154. }
  155. };
  156. openDeleteModal([pageToDelete], { onDeleted: onDeletedHandler });
  157. }, [currentPagePath, mutateCurrentPage, openDeleteModal, router, t]);
  158. // *************************** Scroll on init ***************************
  159. const scrollOnInit = useCallback(() => {
  160. const scrollTargetElement = document.getElementById('grw-pagetree-current-page-item');
  161. if (sidebarScrollerRef?.current == null || scrollTargetElement == null) {
  162. return;
  163. }
  164. logger.debug('scrollOnInit has invoked');
  165. const scrollElement = sidebarScrollerRef.current.getScrollElement();
  166. // NOTE: could not use scrollIntoView
  167. // https://stackoverflow.com/questions/11039885/scrollintoview-causing-the-whole-page-to-move
  168. // calculate the center point
  169. const scrollTop = scrollTargetElement.offsetTop - scrollElement.getBoundingClientRect().height / 2;
  170. scrollElement.scrollTo({ top: scrollTop });
  171. setIsInitialScrollCompleted(true);
  172. }, [sidebarScrollerRef]);
  173. const scrollOnInitDebounced = useMemo(() => debounce(500, scrollOnInit), [scrollOnInit]);
  174. useEffect(() => {
  175. if (!isSecondStageRenderingCondition(renderingCondition) || isInitialScrollCompleted) {
  176. return;
  177. }
  178. const rootElement = rootElemRef.current as HTMLElement | null;
  179. if (rootElement == null) {
  180. return;
  181. }
  182. const observerCallback = (mutationRecords: MutationRecord[]) => {
  183. mutationRecords.forEach(() => scrollOnInitDebounced());
  184. };
  185. const observer = new MutationObserver(observerCallback);
  186. observer.observe(rootElement, { childList: true, subtree: true });
  187. // first call for the situation that all rendering is complete at this point
  188. scrollOnInitDebounced();
  189. return () => {
  190. observer.disconnect();
  191. };
  192. }, [isInitialScrollCompleted, renderingCondition, scrollOnInitDebounced]);
  193. // ******************************* end *******************************
  194. if (error1 != null || error2 != null) {
  195. // TODO: improve message
  196. toastError('Error occurred while fetching pages to render PageTree');
  197. return <></>;
  198. }
  199. let initialItemNode;
  200. /*
  201. * Render second stage
  202. */
  203. if (isSecondStageRenderingCondition(renderingCondition)) {
  204. initialItemNode = generateInitialNodeAfterResponse(
  205. renderingCondition.ancestorsChildrenResult.ancestorsChildren,
  206. new ItemNode(renderingCondition.rootPageResult.rootPage),
  207. );
  208. }
  209. /*
  210. * Before swr response comes back
  211. */
  212. else if (targetAndAncestorsData != null) {
  213. initialItemNode = generateInitialNodeBeforeResponse(targetAndAncestorsData.targetAndAncestors);
  214. }
  215. if (initialItemNode != null) {
  216. return (
  217. <ul className={`grw-pagetree ${styles['grw-pagetree']} list-group py-3`} ref={rootElemRef}>
  218. <CustomTreeItem
  219. key={initialItemNode.page.path}
  220. targetPathOrId={targetPathOrId}
  221. itemNode={initialItemNode}
  222. isOpen
  223. isEnableActions={isEnableActions}
  224. isReadOnlyUser={isReadOnlyUser}
  225. onRenamed={onRenamed}
  226. onClickDuplicateMenuItem={onClickDuplicateMenuItem}
  227. onClickDeleteMenuItem={onClickDeleteMenuItem}
  228. />
  229. </ul>
  230. );
  231. }
  232. return <PageTreeContentSkeleton />;
  233. };