ItemsTree.tsx 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. import React, {
  2. useEffect, useRef, useState, useMemo, useCallback,
  3. } from 'react';
  4. import { Nullable } from '@growi/core';
  5. import { useTranslation } from 'next-i18next';
  6. import { debounce } from 'throttle-debounce';
  7. import { toastError, toastSuccess } from '~/client/util/apiNotification';
  8. import { IPageHasId, IPageToDeleteWithMeta } from '~/interfaces/page';
  9. import { AncestorsChildrenResult, RootPageResult, TargetAndAncestors } from '~/interfaces/page-listing-results';
  10. import { OnDuplicatedFunction, OnDeletedFunction } from '~/interfaces/ui';
  11. import { SocketEventName, UpdateDescCountData, UpdateDescCountRawData } from '~/interfaces/websocket';
  12. import { useIsEnabledAttachTitleHeader } from '~/stores/context';
  13. import {
  14. IPageForPageDuplicateModal, usePageDuplicateModal, usePageDeleteModal,
  15. } from '~/stores/modal';
  16. import { useCurrentPagePath, usePageInfoTermManager, useSWRxCurrentPage } from '~/stores/page';
  17. import {
  18. usePageTreeTermManager, useSWRxPageAncestorsChildren, useSWRxRootPage, useDescendantsPageListForCurrentPathTermManager,
  19. } from '~/stores/page-listing';
  20. import { useFullTextSearchTermManager } from '~/stores/search';
  21. import { usePageTreeDescCountMap, useSidebarScrollerRef } from '~/stores/ui';
  22. import { useGlobalSocket } from '~/stores/websocket';
  23. import loggerFactory from '~/utils/logger';
  24. import Item from './Item';
  25. import { ItemNode } from './ItemNode';
  26. import styles from './ItemsTree.module.scss';
  27. const logger = loggerFactory('growi:cli:ItemsTree');
  28. /*
  29. * Utility to generate initial node
  30. */
  31. const generateInitialNodeBeforeResponse = (targetAndAncestors: Partial<IPageHasId>[]): ItemNode => {
  32. const nodes = targetAndAncestors.map((page): ItemNode => {
  33. return new ItemNode(page, []);
  34. });
  35. // update children for each node
  36. const rootNode = nodes.reduce((child, parent) => {
  37. parent.children = [child];
  38. return parent;
  39. });
  40. return rootNode;
  41. };
  42. const generateInitialNodeAfterResponse = (ancestorsChildren: Record<string, Partial<IPageHasId>[]>, rootNode: ItemNode): ItemNode => {
  43. const paths = Object.keys(ancestorsChildren);
  44. let currentNode = rootNode;
  45. paths.every((path) => {
  46. // stop rendering when non-migrated pages found
  47. if (currentNode == null) {
  48. return false;
  49. }
  50. const childPages = ancestorsChildren[path];
  51. currentNode.children = ItemNode.generateNodesFromPages(childPages);
  52. const nextNode = currentNode.children.filter((node) => {
  53. return paths.includes(node.page.path as string);
  54. })[0];
  55. currentNode = nextNode;
  56. return true;
  57. });
  58. return rootNode;
  59. };
  60. // user defined typeguard to assert the arg is not null
  61. type RenderingCondition = {
  62. ancestorsChildrenResult: AncestorsChildrenResult | undefined,
  63. rootPageResult: RootPageResult | undefined,
  64. }
  65. type SecondStageRenderingCondition = {
  66. ancestorsChildrenResult: AncestorsChildrenResult,
  67. rootPageResult: RootPageResult,
  68. }
  69. const isSecondStageRenderingCondition = (condition: RenderingCondition|SecondStageRenderingCondition): condition is SecondStageRenderingCondition => {
  70. return condition.ancestorsChildrenResult != null && condition.rootPageResult != null;
  71. };
  72. type ItemsTreeProps = {
  73. isEnableActions: boolean
  74. targetPath: string
  75. targetPathOrId?: Nullable<string>
  76. targetAndAncestorsData?: TargetAndAncestors
  77. }
  78. /*
  79. * ItemsTree
  80. */
  81. const ItemsTree = (props: ItemsTreeProps): JSX.Element => {
  82. const {
  83. targetPath, targetPathOrId, targetAndAncestorsData, isEnableActions,
  84. } = props;
  85. const { t } = useTranslation();
  86. const { data: ancestorsChildrenResult, error: error1 } = useSWRxPageAncestorsChildren(targetPath);
  87. const { data: rootPageResult, error: error2 } = useSWRxRootPage();
  88. const { data: currentPagePath } = useCurrentPagePath();
  89. const { data: isEnabledAttachTitleHeader } = useIsEnabledAttachTitleHeader();
  90. const { open: openDuplicateModal } = usePageDuplicateModal();
  91. const { open: openDeleteModal } = usePageDeleteModal();
  92. const { data: sidebarScrollerRef } = useSidebarScrollerRef();
  93. const { data: socket } = useGlobalSocket();
  94. const { data: ptDescCountMap, update: updatePtDescCountMap } = usePageTreeDescCountMap();
  95. // for mutation
  96. const { mutate: mutateCurrentPage } = useSWRxCurrentPage();
  97. const { advance: advancePt } = usePageTreeTermManager();
  98. const { advance: advanceFts } = useFullTextSearchTermManager();
  99. const { advance: advanceDpl } = useDescendantsPageListForCurrentPathTermManager();
  100. const { advance: advancePi } = usePageInfoTermManager();
  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. advancePt();
  122. advanceFts();
  123. advanceDpl();
  124. if (currentPagePath === fromPath || currentPagePath === toPath) {
  125. mutateCurrentPage();
  126. }
  127. }, [advanceDpl, advanceFts, advancePt, 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. advancePt();
  133. advanceFts();
  134. advanceDpl();
  135. };
  136. openDuplicateModal(pageToDuplicate, { onDuplicated: duplicatedHandler });
  137. }, [advanceDpl, advanceFts, advancePt, openDuplicateModal, t]);
  138. const onClickDeleteMenuItem = useCallback((pageToDelete: IPageToDeleteWithMeta) => {
  139. const onDeletedHandler: OnDeletedFunction = (pathOrPathsToDelete, isRecursively, isCompletely) => {
  140. if (typeof pathOrPathsToDelete !== 'string') {
  141. return;
  142. }
  143. const path = pathOrPathsToDelete;
  144. if (isCompletely) {
  145. toastSuccess(t('deleted_pages_completely', { path }));
  146. }
  147. else {
  148. toastSuccess(t('deleted_pages', { path }));
  149. }
  150. advancePt();
  151. advanceFts();
  152. advanceDpl();
  153. advancePi();
  154. if (currentPagePath === pathOrPathsToDelete) {
  155. mutateCurrentPage();
  156. }
  157. };
  158. openDeleteModal([pageToDelete], { onDeleted: onDeletedHandler });
  159. }, [advanceDpl, advanceFts, advancePi, advancePt, currentPagePath, mutateCurrentPage, openDeleteModal, 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 p-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 <></>;
  235. };
  236. export default ItemsTree;