ItemsTree.tsx 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. import React, {
  2. useEffect, useRef, useState, useMemo, useCallback,
  3. } from 'react';
  4. import path from 'path';
  5. import type { Nullable, IPageHasId, IPageToDeleteWithMeta } from '@growi/core';
  6. import { useGlobalSocket } from '@growi/core/dist/swr';
  7. import { useTranslation } from 'next-i18next';
  8. import { useRouter } from 'next/router';
  9. import { toastError, toastSuccess } from '~/client/util/toastr';
  10. import type { IPageForItem } from '~/interfaces/page';
  11. import type { AncestorsChildrenResult, RootPageResult, TargetAndAncestors } from '~/interfaces/page-listing-results';
  12. import type { OnDuplicatedFunction, OnDeletedFunction } from '~/interfaces/ui';
  13. import type { UpdateDescCountData, UpdateDescCountRawData } from '~/interfaces/websocket';
  14. import { SocketEventName } from '~/interfaces/websocket';
  15. import type { IPageForPageDuplicateModal } from '~/stores/modal';
  16. import { usePageDuplicateModal, usePageDeleteModal } from '~/stores/modal';
  17. import { mutateAllPageInfo, useCurrentPagePath, useSWRMUTxCurrentPage } from '~/stores/page';
  18. import {
  19. useSWRxPageAncestorsChildren, useSWRxRootPage, mutatePageTree, mutatePageList,
  20. } from '~/stores/page-listing';
  21. import { mutateSearching } from '~/stores/search';
  22. import { usePageTreeDescCountMap } from '~/stores/ui';
  23. import loggerFactory from '~/utils/logger';
  24. import { ItemNode, type TreeItemProps } from '../TreeItem';
  25. import ItemsTreeContentSkeleton from './ItemsTreeContentSkeleton';
  26. import styles from './ItemsTree.module.scss';
  27. const moduleClass = styles['grw-pagetree'] ?? '';
  28. const logger = loggerFactory('growi:cli:ItemsTree');
  29. /*
  30. * Utility to generate initial node
  31. */
  32. const generateInitialNodeBeforeResponse = (targetAndAncestors: Partial<IPageHasId>[]): ItemNode => {
  33. const nodes = targetAndAncestors.map((page): ItemNode => {
  34. return new ItemNode(page, []);
  35. });
  36. // update children for each node
  37. const rootNode = nodes.reduce((child, parent) => {
  38. parent.children = [child];
  39. return parent;
  40. });
  41. return rootNode;
  42. };
  43. const generateInitialNodeAfterResponse = (ancestorsChildren: Record<string, Partial<IPageHasId>[]>, rootNode: ItemNode): ItemNode => {
  44. const paths = Object.keys(ancestorsChildren);
  45. let currentNode = rootNode;
  46. paths.every((path) => {
  47. // stop rendering when non-migrated pages found
  48. if (currentNode == null) {
  49. return false;
  50. }
  51. const childPages = ancestorsChildren[path];
  52. currentNode.children = ItemNode.generateNodesFromPages(childPages);
  53. const nextNode = currentNode.children.filter((node) => {
  54. return paths.includes(node.page.path as string);
  55. })[0];
  56. currentNode = nextNode;
  57. return true;
  58. });
  59. return rootNode;
  60. };
  61. // user defined typeguard to assert the arg is not null
  62. type RenderingCondition = {
  63. ancestorsChildrenResult: AncestorsChildrenResult | undefined,
  64. rootPageResult: RootPageResult | undefined,
  65. }
  66. type SecondStageRenderingCondition = {
  67. ancestorsChildrenResult: AncestorsChildrenResult,
  68. rootPageResult: RootPageResult,
  69. }
  70. const isSecondStageRenderingCondition = (condition: RenderingCondition|SecondStageRenderingCondition): condition is SecondStageRenderingCondition => {
  71. return condition.ancestorsChildrenResult != null && condition.rootPageResult != null;
  72. };
  73. type ItemsTreeProps = {
  74. isEnableActions: boolean
  75. isReadOnlyUser: boolean
  76. isWipPageShown?: boolean
  77. targetPath: string
  78. targetPathOrId?: Nullable<string>
  79. targetAndAncestorsData?: TargetAndAncestors
  80. CustomTreeItem: React.FunctionComponent<TreeItemProps>
  81. onClickTreeItem?: (page: IPageForItem) => void;
  82. markTarget: (children: ItemNode[], targetPathOrId?: Nullable<string>) => void;
  83. }
  84. /*
  85. * ItemsTree
  86. */
  87. export const ItemsTree = (props: ItemsTreeProps): JSX.Element => {
  88. const {
  89. targetPath, targetPathOrId, targetAndAncestorsData, isEnableActions, isReadOnlyUser, isWipPageShown, CustomTreeItem, onClickTreeItem,
  90. } = props;
  91. const { t } = useTranslation();
  92. const router = useRouter();
  93. const { data: ancestorsChildrenResult, error: error1 } = useSWRxPageAncestorsChildren(targetPath, { suspense: true });
  94. const { data: rootPageResult, error: error2 } = useSWRxRootPage({ suspense: true });
  95. const { data: currentPagePath } = useCurrentPagePath();
  96. const { open: openDuplicateModal } = usePageDuplicateModal();
  97. const { open: openDeleteModal } = usePageDeleteModal();
  98. const { data: socket } = useGlobalSocket();
  99. const { data: ptDescCountMap, update: updatePtDescCountMap } = usePageTreeDescCountMap();
  100. // for mutation
  101. const { trigger: mutateCurrentPage } = useSWRMUTxCurrentPage();
  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. mutatePageTree();
  121. mutateSearching();
  122. mutatePageList();
  123. if (currentPagePath === fromPath || currentPagePath === toPath) {
  124. mutateCurrentPage();
  125. }
  126. }, [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. mutatePageTree();
  132. mutateSearching();
  133. mutatePageList();
  134. };
  135. openDuplicateModal(pageToDuplicate, { onDuplicated: duplicatedHandler });
  136. }, [openDuplicateModal, t]);
  137. const onClickDeleteMenuItem = useCallback((pageToDelete: IPageToDeleteWithMeta) => {
  138. const onDeletedHandler: OnDeletedFunction = (pathOrPathsToDelete, isRecursively, isCompletely) => {
  139. if (typeof pathOrPathsToDelete !== 'string') {
  140. return;
  141. }
  142. if (isCompletely) {
  143. toastSuccess(t('deleted_pages_completely', { path: pathOrPathsToDelete }));
  144. }
  145. else {
  146. toastSuccess(t('deleted_pages', { path: pathOrPathsToDelete }));
  147. }
  148. mutatePageTree();
  149. mutateSearching();
  150. mutatePageList();
  151. mutateAllPageInfo();
  152. if (currentPagePath === pathOrPathsToDelete) {
  153. mutateCurrentPage();
  154. router.push(isCompletely ? path.dirname(pathOrPathsToDelete) : `/trash${pathOrPathsToDelete}`);
  155. }
  156. };
  157. openDeleteModal([pageToDelete], { onDeleted: onDeletedHandler });
  158. }, [currentPagePath, mutateCurrentPage, openDeleteModal, router, t]);
  159. if (error1 != null || error2 != null) {
  160. // TODO: improve message
  161. toastError('Error occurred while fetching pages to render PageTree');
  162. return <></>;
  163. }
  164. let initialItemNode;
  165. /*
  166. * Render second stage
  167. */
  168. if (isSecondStageRenderingCondition(renderingCondition)) {
  169. initialItemNode = generateInitialNodeAfterResponse(
  170. renderingCondition.ancestorsChildrenResult.ancestorsChildren,
  171. new ItemNode(renderingCondition.rootPageResult.rootPage),
  172. );
  173. }
  174. /*
  175. * Before swr response comes back
  176. */
  177. else if (targetAndAncestorsData != null) {
  178. initialItemNode = generateInitialNodeBeforeResponse(targetAndAncestorsData.targetAndAncestors);
  179. }
  180. if (initialItemNode != null) {
  181. return (
  182. <ul className={`grw-pagetree ${moduleClass} list-group py-4`}>
  183. <CustomTreeItem
  184. key={initialItemNode.page.path}
  185. targetPathOrId={targetPathOrId}
  186. itemNode={initialItemNode}
  187. isOpen
  188. isEnableActions={isEnableActions}
  189. isWipPageShown={isWipPageShown}
  190. isReadOnlyUser={isReadOnlyUser}
  191. onRenamed={onRenamed}
  192. onClickDuplicateMenuItem={onClickDuplicateMenuItem}
  193. onClickDeleteMenuItem={onClickDeleteMenuItem}
  194. onClick={onClickTreeItem}
  195. />
  196. </ul>
  197. );
  198. }
  199. return <ItemsTreeContentSkeleton />;
  200. };