ItemsTree.tsx 8.9 KB

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