ItemsTree.tsx 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. import React, {
  2. useEffect, useRef, useState, useMemo, useCallback,
  3. } from 'react';
  4. import { useTranslation } from 'react-i18next';
  5. import { debounce } from 'throttle-debounce';
  6. import loggerFactory from '~/utils/logger';
  7. import { usePageTreeTermManager, useSWRxPageAncestorsChildren, useSWRxRootPage } from '~/stores/page-listing';
  8. import { AncestorsChildrenResult, RootPageResult, TargetAndAncestors } from '~/interfaces/page-listing-results';
  9. import { IPageHasId, IPageToDeleteWithMeta } from '~/interfaces/page';
  10. import { OnDuplicatedFunction, OnDeletedFunction } from '~/interfaces/ui';
  11. import { SocketEventName, UpdateDescCountData, UpdateDescCountRawData } from '~/interfaces/websocket';
  12. import { toastError, toastSuccess } from '~/client/util/apiNotification';
  13. import {
  14. IPageForPageDuplicateModal, usePageDuplicateModal, usePageDeleteModal,
  15. } from '~/stores/modal';
  16. import { useIsEnabledAttachTitleHeader } from '~/stores/context';
  17. import { useFullTextSearchTermManager } from '~/stores/search';
  18. import { useDescendantsPageListForCurrentPathTermManager } from '~/stores/page';
  19. import { useGlobalSocket } from '~/stores/websocket';
  20. import { usePageTreeDescCountMap, useSidebarScrollerRef } from '~/stores/ui';
  21. import { ItemNode } from './ItemNode';
  22. import Item from './Item';
  23. const logger = loggerFactory('growi:cli:ItemsTree');
  24. /*
  25. * Utility to generate initial node
  26. */
  27. const generateInitialNodeBeforeResponse = (targetAndAncestors: Partial<IPageHasId>[]): ItemNode => {
  28. const nodes = targetAndAncestors.map((page): ItemNode => {
  29. return new ItemNode(page, []);
  30. });
  31. // update children for each node
  32. const rootNode = nodes.reduce((child, parent) => {
  33. parent.children = [child];
  34. return parent;
  35. });
  36. return rootNode;
  37. };
  38. const generateInitialNodeAfterResponse = (ancestorsChildren: Record<string, Partial<IPageHasId>[]>, rootNode: ItemNode): ItemNode => {
  39. const paths = Object.keys(ancestorsChildren);
  40. let currentNode = rootNode;
  41. paths.every((path) => {
  42. // stop rendering when non-migrated pages found
  43. if (currentNode == null) {
  44. return false;
  45. }
  46. const childPages = ancestorsChildren[path];
  47. currentNode.children = ItemNode.generateNodesFromPages(childPages);
  48. const nextNode = currentNode.children.filter((node) => {
  49. return paths.includes(node.page.path as string);
  50. })[0];
  51. currentNode = nextNode;
  52. return true;
  53. });
  54. return rootNode;
  55. };
  56. // user defined typeguard to assert the arg is not null
  57. type RenderingCondition = {
  58. ancestorsChildrenResult: AncestorsChildrenResult | undefined,
  59. rootPageResult: RootPageResult | undefined,
  60. }
  61. type SecondStageRenderingCondition = {
  62. ancestorsChildrenResult: AncestorsChildrenResult,
  63. rootPageResult: RootPageResult,
  64. }
  65. const isSecondStageRenderingCondition = (condition: RenderingCondition|SecondStageRenderingCondition): condition is SecondStageRenderingCondition => {
  66. return condition.ancestorsChildrenResult != null && condition.rootPageResult != null;
  67. };
  68. type ItemsTreeProps = {
  69. isEnableActions: boolean
  70. targetPath: string
  71. targetPathOrId?: string
  72. targetAndAncestorsData?: TargetAndAncestors
  73. }
  74. /*
  75. * ItemsTree
  76. */
  77. const ItemsTree = (props: ItemsTreeProps): JSX.Element => {
  78. const {
  79. targetPath, targetPathOrId, targetAndAncestorsData, isEnableActions,
  80. } = props;
  81. const { t } = useTranslation();
  82. const { data: ancestorsChildrenResult, error: error1 } = useSWRxPageAncestorsChildren(targetPath);
  83. const { data: rootPageResult, error: error2 } = useSWRxRootPage();
  84. const { data: isEnabledAttachTitleHeader } = useIsEnabledAttachTitleHeader();
  85. const { open: openDuplicateModal } = usePageDuplicateModal();
  86. const { open: openDeleteModal } = usePageDeleteModal();
  87. const { data: sidebarScrollerRef } = useSidebarScrollerRef();
  88. const { data: socket } = useGlobalSocket();
  89. const { data: ptDescCountMap, update: updatePtDescCountMap } = usePageTreeDescCountMap();
  90. // for mutation
  91. const { advance: advancePt } = usePageTreeTermManager();
  92. const { advance: advanceFts } = useFullTextSearchTermManager();
  93. const { advance: advanceDpl } = useDescendantsPageListForCurrentPathTermManager();
  94. const [isInitialScrollCompleted, setIsInitialScrollCompleted] = useState(false);
  95. const rootElemRef = useRef(null);
  96. const renderingCondition = useMemo(() => {
  97. return {
  98. ancestorsChildrenResult,
  99. rootPageResult,
  100. };
  101. }, [ancestorsChildrenResult, rootPageResult]);
  102. useEffect(() => {
  103. if (socket == null) {
  104. return;
  105. }
  106. socket.on(SocketEventName.UpdateDescCount, (data: UpdateDescCountRawData) => {
  107. // save to global state
  108. const newData: UpdateDescCountData = new Map(Object.entries(data));
  109. updatePtDescCountMap(newData);
  110. });
  111. return () => { socket.off(SocketEventName.UpdateDescCount) };
  112. }, [socket, ptDescCountMap, updatePtDescCountMap]);
  113. const onRenamed = () => {
  114. advancePt();
  115. advanceFts();
  116. advanceDpl();
  117. };
  118. const onClickDuplicateMenuItem = (pageToDuplicate: IPageForPageDuplicateModal) => {
  119. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  120. const duplicatedHandler: OnDuplicatedFunction = (fromPath, toPath) => {
  121. toastSuccess(t('duplicated_pages', { fromPath }));
  122. advancePt();
  123. advanceFts();
  124. advanceDpl();
  125. };
  126. openDuplicateModal(pageToDuplicate, { onDuplicated: duplicatedHandler });
  127. };
  128. const onClickDeleteMenuItem = (pageToDelete: IPageToDeleteWithMeta) => {
  129. const onDeletedHandler: OnDeletedFunction = (pathOrPathsToDelete, isRecursively, isCompletely) => {
  130. if (typeof pathOrPathsToDelete !== 'string') {
  131. return;
  132. }
  133. const path = pathOrPathsToDelete;
  134. if (isCompletely) {
  135. toastSuccess(t('deleted_pages_completely', { path }));
  136. }
  137. else {
  138. toastSuccess(t('deleted_pages', { path }));
  139. }
  140. advancePt();
  141. advanceFts();
  142. advanceDpl();
  143. };
  144. openDeleteModal([pageToDelete], { onDeleted: onDeletedHandler });
  145. };
  146. // *************************** Scroll on init ***************************
  147. const scrollOnInit = useCallback(() => {
  148. const scrollTargetElement = document.getElementById('grw-pagetree-current-page-item');
  149. if (sidebarScrollerRef?.current == null || scrollTargetElement == null) {
  150. return;
  151. }
  152. logger.debug('scrollOnInit has invoked');
  153. const scrollElement = sidebarScrollerRef.current.getScrollElement();
  154. // NOTE: could not use scrollIntoView
  155. // https://stackoverflow.com/questions/11039885/scrollintoview-causing-the-whole-page-to-move
  156. // calculate the center point
  157. const scrollTop = scrollTargetElement.offsetTop - scrollElement.getBoundingClientRect().height / 2;
  158. scrollElement.scrollTo({ top: scrollTop });
  159. setIsInitialScrollCompleted(true);
  160. }, [sidebarScrollerRef]);
  161. const scrollOnInitDebounced = useMemo(() => debounce(500, scrollOnInit), [scrollOnInit]);
  162. useEffect(() => {
  163. if (!isSecondStageRenderingCondition(renderingCondition) || isInitialScrollCompleted) {
  164. return;
  165. }
  166. const rootElement = rootElemRef.current as HTMLElement | null;
  167. if (rootElement == null) {
  168. return;
  169. }
  170. const observerCallback = (mutationRecords: MutationRecord[]) => {
  171. mutationRecords.forEach(() => scrollOnInitDebounced());
  172. };
  173. const observer = new MutationObserver(observerCallback);
  174. observer.observe(rootElement, { childList: true, subtree: true });
  175. // first call for the situation that all rendering is complete at this point
  176. scrollOnInitDebounced();
  177. return () => {
  178. observer.disconnect();
  179. };
  180. }, [isInitialScrollCompleted, renderingCondition, scrollOnInitDebounced]);
  181. // ******************************* end *******************************
  182. if (error1 != null || error2 != null) {
  183. // TODO: improve message
  184. toastError('Error occurred while fetching pages to render PageTree');
  185. return <></>;
  186. }
  187. let initialItemNode;
  188. /*
  189. * Render second stage
  190. */
  191. if (isSecondStageRenderingCondition(renderingCondition)) {
  192. initialItemNode = generateInitialNodeAfterResponse(
  193. renderingCondition.ancestorsChildrenResult.ancestorsChildren,
  194. new ItemNode(renderingCondition.rootPageResult.rootPage),
  195. );
  196. }
  197. /*
  198. * Before swr response comes back
  199. */
  200. else if (targetAndAncestorsData != null) {
  201. initialItemNode = generateInitialNodeBeforeResponse(targetAndAncestorsData.targetAndAncestors);
  202. }
  203. if (initialItemNode != null) {
  204. return (
  205. <ul className="grw-pagetree list-group p-3" ref={rootElemRef}>
  206. <Item
  207. key={initialItemNode.page.path}
  208. targetPathOrId={targetPathOrId}
  209. itemNode={initialItemNode}
  210. isOpen
  211. isEnabledAttachTitleHeader={isEnabledAttachTitleHeader}
  212. isEnableActions={isEnableActions}
  213. onRenamed={onRenamed}
  214. onClickDuplicateMenuItem={onClickDuplicateMenuItem}
  215. onClickDeleteMenuItem={onClickDeleteMenuItem}
  216. />
  217. </ul>
  218. );
  219. }
  220. return <></>;
  221. };
  222. export default ItemsTree;