ItemsTree.tsx 9.9 KB

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