ItemsTree.tsx 9.8 KB

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