ItemsTree.tsx 9.5 KB

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