ItemsTree.tsx 9.9 KB

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