ItemsTree.tsx 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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/apiNotification';
  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 { useIsEnabledAttachTitleHeader } from '~/stores/context';
  15. import {
  16. IPageForPageDuplicateModal, usePageDuplicateModal, usePageDeleteModal,
  17. } 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 { useGlobalSocket } from '~/stores/websocket';
  25. import loggerFactory from '~/utils/logger';
  26. import PageTreeContentSkeleton from '../Skeleton/PageTreeContentSkeleton';
  27. import Item from './Item';
  28. import { ItemNode } from './ItemNode';
  29. import styles from './ItemsTree.module.scss';
  30. const logger = loggerFactory('growi:cli:ItemsTree');
  31. /*
  32. * Utility to generate initial node
  33. */
  34. const generateInitialNodeBeforeResponse = (targetAndAncestors: Partial<IPageHasId>[]): ItemNode => {
  35. const nodes = targetAndAncestors.map((page): ItemNode => {
  36. return new ItemNode(page, []);
  37. });
  38. // update children for each node
  39. const rootNode = nodes.reduce((child, parent) => {
  40. parent.children = [child];
  41. return parent;
  42. });
  43. return rootNode;
  44. };
  45. const generateInitialNodeAfterResponse = (ancestorsChildren: Record<string, Partial<IPageHasId>[]>, rootNode: ItemNode): ItemNode => {
  46. const paths = Object.keys(ancestorsChildren);
  47. let currentNode = rootNode;
  48. paths.every((path) => {
  49. // stop rendering when non-migrated pages found
  50. if (currentNode == null) {
  51. return false;
  52. }
  53. const childPages = ancestorsChildren[path];
  54. currentNode.children = ItemNode.generateNodesFromPages(childPages);
  55. const nextNode = currentNode.children.filter((node) => {
  56. return paths.includes(node.page.path as string);
  57. })[0];
  58. currentNode = nextNode;
  59. return true;
  60. });
  61. return rootNode;
  62. };
  63. // user defined typeguard to assert the arg is not null
  64. type RenderingCondition = {
  65. ancestorsChildrenResult: AncestorsChildrenResult | undefined,
  66. rootPageResult: RootPageResult | undefined,
  67. }
  68. type SecondStageRenderingCondition = {
  69. ancestorsChildrenResult: AncestorsChildrenResult,
  70. rootPageResult: RootPageResult,
  71. }
  72. const isSecondStageRenderingCondition = (condition: RenderingCondition|SecondStageRenderingCondition): condition is SecondStageRenderingCondition => {
  73. return condition.ancestorsChildrenResult != null && condition.rootPageResult != null;
  74. };
  75. type ItemsTreeProps = {
  76. isEnableActions: 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,
  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 { data: isEnabledAttachTitleHeader } = useIsEnabledAttachTitleHeader();
  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. <Item
  221. key={initialItemNode.page.path}
  222. targetPathOrId={targetPathOrId}
  223. itemNode={initialItemNode}
  224. isOpen
  225. isEnabledAttachTitleHeader={isEnabledAttachTitleHeader}
  226. isEnableActions={isEnableActions}
  227. onRenamed={onRenamed}
  228. onClickDuplicateMenuItem={onClickDuplicateMenuItem}
  229. onClickDeleteMenuItem={onClickDeleteMenuItem}
  230. />
  231. </ul>
  232. );
  233. }
  234. return <PageTreeContentSkeleton />;
  235. };
  236. export default ItemsTree;