2
0

ItemsTree.tsx 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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 { PageTreeItem } from './PageTreeItem';
  29. import SimpleItem from './SimpleItem';
  30. import styles from './ItemsTree.module.scss';
  31. const logger = loggerFactory('growi:cli:ItemsTree');
  32. /*
  33. * Utility to generate initial node
  34. */
  35. const generateInitialNodeBeforeResponse = (targetAndAncestors: Partial<IPageHasId>[]): ItemNode => {
  36. const nodes = targetAndAncestors.map((page): ItemNode => {
  37. return new ItemNode(page, []);
  38. });
  39. // update children for each node
  40. const rootNode = nodes.reduce((child, parent) => {
  41. parent.children = [child];
  42. return parent;
  43. });
  44. return rootNode;
  45. };
  46. const generateInitialNodeAfterResponse = (ancestorsChildren: Record<string, Partial<IPageHasId>[]>, rootNode: ItemNode): ItemNode => {
  47. const paths = Object.keys(ancestorsChildren);
  48. let currentNode = rootNode;
  49. paths.every((path) => {
  50. // stop rendering when non-migrated pages found
  51. if (currentNode == null) {
  52. return false;
  53. }
  54. const childPages = ancestorsChildren[path];
  55. currentNode.children = ItemNode.generateNodesFromPages(childPages);
  56. const nextNode = currentNode.children.filter((node) => {
  57. return paths.includes(node.page.path as string);
  58. })[0];
  59. currentNode = nextNode;
  60. return true;
  61. });
  62. return rootNode;
  63. };
  64. // user defined typeguard to assert the arg is not null
  65. type RenderingCondition = {
  66. ancestorsChildrenResult: AncestorsChildrenResult | undefined,
  67. rootPageResult: RootPageResult | undefined,
  68. }
  69. type SecondStageRenderingCondition = {
  70. ancestorsChildrenResult: AncestorsChildrenResult,
  71. rootPageResult: RootPageResult,
  72. }
  73. const isSecondStageRenderingCondition = (condition: RenderingCondition|SecondStageRenderingCondition): condition is SecondStageRenderingCondition => {
  74. return condition.ancestorsChildrenResult != null && condition.rootPageResult != null;
  75. };
  76. type ItemsTreeProps = {
  77. isEnableActions: boolean
  78. isReadOnlyUser: boolean
  79. targetPath: string
  80. targetPathOrId?: Nullable<string>
  81. targetAndAncestorsData?: TargetAndAncestors
  82. }
  83. /*
  84. * ItemsTree
  85. */
  86. const ItemsTree = (props: ItemsTreeProps): JSX.Element => {
  87. const {
  88. targetPath, targetPathOrId, targetAndAncestorsData, isEnableActions, isReadOnlyUser,
  89. } = props;
  90. const { t } = useTranslation();
  91. const router = useRouter();
  92. const { data: ancestorsChildrenResult, error: error1 } = useSWRxPageAncestorsChildren(targetPath);
  93. const { data: rootPageResult, error: error2 } = useSWRxRootPage();
  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. // const PageTreeItem = CreatePageTreeItem();
  219. if (initialItemNode != null) {
  220. return (
  221. <ul className={`grw-pagetree ${styles['grw-pagetree']} list-group py-3`} ref={rootElemRef}>
  222. <PageTreeItem
  223. key={initialItemNode.page.path}
  224. targetPathOrId={targetPathOrId}
  225. itemNode={initialItemNode}
  226. isOpen
  227. isEnableActions={isEnableActions}
  228. isReadOnlyUser={isReadOnlyUser}
  229. onRenamed={onRenamed}
  230. onClickDuplicateMenuItem={onClickDuplicateMenuItem}
  231. onClickDeleteMenuItem={onClickDeleteMenuItem}
  232. />
  233. </ul>
  234. );
  235. }
  236. return <PageTreeContentSkeleton />;
  237. };
  238. export default ItemsTree;