ItemsTree.tsx 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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, 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 [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. advancePt();
  121. advanceFts();
  122. advanceDpl();
  123. if (currentPagePath === fromPath || currentPagePath === toPath) {
  124. mutateCurrentPage();
  125. }
  126. }, [advanceDpl, advanceFts, advancePt, 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. advancePt();
  132. advanceFts();
  133. advanceDpl();
  134. };
  135. openDuplicateModal(pageToDuplicate, { onDuplicated: duplicatedHandler });
  136. }, [advanceDpl, advanceFts, advancePt, openDuplicateModal, t]);
  137. const onClickDeleteMenuItem = useCallback((pageToDelete: IPageToDeleteWithMeta) => {
  138. const onDeletedHandler: OnDeletedFunction = (pathOrPathsToDelete, isRecursively, isCompletely) => {
  139. if (typeof pathOrPathsToDelete !== 'string') {
  140. return;
  141. }
  142. const path = pathOrPathsToDelete;
  143. if (isCompletely) {
  144. toastSuccess(t('deleted_pages_completely', { path }));
  145. }
  146. else {
  147. toastSuccess(t('deleted_pages', { path }));
  148. }
  149. advancePt();
  150. advanceFts();
  151. advanceDpl();
  152. if (currentPagePath === pathOrPathsToDelete) {
  153. mutateCurrentPage();
  154. }
  155. };
  156. openDeleteModal([pageToDelete], { onDeleted: onDeletedHandler });
  157. }, [advanceDpl, advanceFts, advancePt, currentPagePath, mutateCurrentPage, openDeleteModal, t]);
  158. // *************************** Scroll on init ***************************
  159. const scrollOnInit = useCallback(() => {
  160. const scrollTargetElement = document.getElementById('grw-pagetree-current-page-item');
  161. if (sidebarScrollerRef?.current == null || scrollTargetElement == null) {
  162. return;
  163. }
  164. logger.debug('scrollOnInit has invoked');
  165. const scrollElement = sidebarScrollerRef.current.getScrollElement();
  166. // NOTE: could not use scrollIntoView
  167. // https://stackoverflow.com/questions/11039885/scrollintoview-causing-the-whole-page-to-move
  168. // calculate the center point
  169. const scrollTop = scrollTargetElement.offsetTop - scrollElement.getBoundingClientRect().height / 2;
  170. scrollElement.scrollTo({ top: scrollTop });
  171. setIsInitialScrollCompleted(true);
  172. }, [sidebarScrollerRef]);
  173. const scrollOnInitDebounced = useMemo(() => debounce(500, scrollOnInit), [scrollOnInit]);
  174. useEffect(() => {
  175. if (!isSecondStageRenderingCondition(renderingCondition) || isInitialScrollCompleted) {
  176. return;
  177. }
  178. const rootElement = rootElemRef.current as HTMLElement | null;
  179. if (rootElement == null) {
  180. return;
  181. }
  182. const observerCallback = (mutationRecords: MutationRecord[]) => {
  183. mutationRecords.forEach(() => scrollOnInitDebounced());
  184. };
  185. const observer = new MutationObserver(observerCallback);
  186. observer.observe(rootElement, { childList: true, subtree: true });
  187. // first call for the situation that all rendering is complete at this point
  188. scrollOnInitDebounced();
  189. return () => {
  190. observer.disconnect();
  191. };
  192. }, [isInitialScrollCompleted, renderingCondition, scrollOnInitDebounced]);
  193. // ******************************* end *******************************
  194. if (error1 != null || error2 != null) {
  195. // TODO: improve message
  196. toastError('Error occurred while fetching pages to render PageTree');
  197. return <></>;
  198. }
  199. let initialItemNode;
  200. /*
  201. * Render second stage
  202. */
  203. if (isSecondStageRenderingCondition(renderingCondition)) {
  204. initialItemNode = generateInitialNodeAfterResponse(
  205. renderingCondition.ancestorsChildrenResult.ancestorsChildren,
  206. new ItemNode(renderingCondition.rootPageResult.rootPage),
  207. );
  208. }
  209. /*
  210. * Before swr response comes back
  211. */
  212. else if (targetAndAncestorsData != null) {
  213. initialItemNode = generateInitialNodeBeforeResponse(targetAndAncestorsData.targetAndAncestors);
  214. }
  215. if (initialItemNode != null) {
  216. return (
  217. <ul className={`grw-pagetree ${styles['grw-pagetree']} list-group p-3`} ref={rootElemRef}>
  218. <Item
  219. key={initialItemNode.page.path}
  220. targetPathOrId={targetPathOrId}
  221. itemNode={initialItemNode}
  222. isOpen
  223. isEnabledAttachTitleHeader={isEnabledAttachTitleHeader}
  224. isEnableActions={isEnableActions}
  225. onRenamed={onRenamed}
  226. onClickDuplicateMenuItem={onClickDuplicateMenuItem}
  227. onClickDeleteMenuItem={onClickDeleteMenuItem}
  228. />
  229. </ul>
  230. );
  231. }
  232. return <></>;
  233. };
  234. export default ItemsTree;