ItemsTree.tsx 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. import React, {
  2. useEffect, 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['items-tree'] ?? '';
  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. }
  83. /*
  84. * ItemsTree
  85. */
  86. export const ItemsTree = (props: ItemsTreeProps): JSX.Element => {
  87. const {
  88. targetPath, targetPathOrId, targetAndAncestorsData, isEnableActions, isReadOnlyUser, isWipPageShown, CustomTreeItem, onClickTreeItem,
  89. } = props;
  90. const { t } = useTranslation();
  91. const router = useRouter();
  92. const { data: ancestorsChildrenResult, error: error1 } = useSWRxPageAncestorsChildren(targetPath, { suspense: true });
  93. const { data: rootPageResult, error: error2 } = useSWRxRootPage({ suspense: true });
  94. const { data: currentPagePath } = useCurrentPagePath();
  95. const { open: openDuplicateModal } = usePageDuplicateModal();
  96. const { open: openDeleteModal } = usePageDeleteModal();
  97. const { data: socket } = useGlobalSocket();
  98. const { data: ptDescCountMap, update: updatePtDescCountMap } = usePageTreeDescCountMap();
  99. // for mutation
  100. const { trigger: mutateCurrentPage } = useSWRMUTxCurrentPage();
  101. const renderingCondition = useMemo(() => {
  102. return {
  103. ancestorsChildrenResult,
  104. rootPageResult,
  105. };
  106. }, [ancestorsChildrenResult, rootPageResult]);
  107. useEffect(() => {
  108. if (socket == null) {
  109. return;
  110. }
  111. socket.on(SocketEventName.UpdateDescCount, (data: UpdateDescCountRawData) => {
  112. // save to global state
  113. const newData: UpdateDescCountData = new Map(Object.entries(data));
  114. updatePtDescCountMap(newData);
  115. });
  116. return () => { socket.off(SocketEventName.UpdateDescCount) };
  117. }, [socket, ptDescCountMap, updatePtDescCountMap]);
  118. const onRenamed = useCallback((fromPath: string | undefined, toPath: string) => {
  119. mutatePageTree();
  120. mutateSearching();
  121. mutatePageList();
  122. if (currentPagePath === fromPath || currentPagePath === toPath) {
  123. mutateCurrentPage();
  124. }
  125. }, [currentPagePath, mutateCurrentPage]);
  126. const onClickDuplicateMenuItem = useCallback((pageToDuplicate: IPageForPageDuplicateModal) => {
  127. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  128. const duplicatedHandler: OnDuplicatedFunction = (fromPath, toPath) => {
  129. toastSuccess(t('duplicated_pages', { fromPath }));
  130. mutatePageTree();
  131. mutateSearching();
  132. mutatePageList();
  133. };
  134. openDuplicateModal(pageToDuplicate, { onDuplicated: duplicatedHandler });
  135. }, [openDuplicateModal, t]);
  136. const onClickDeleteMenuItem = useCallback((pageToDelete: IPageToDeleteWithMeta) => {
  137. const onDeletedHandler: OnDeletedFunction = (pathOrPathsToDelete, isRecursively, isCompletely) => {
  138. if (typeof pathOrPathsToDelete !== 'string') {
  139. return;
  140. }
  141. if (isCompletely) {
  142. toastSuccess(t('deleted_pages_completely', { path: pathOrPathsToDelete }));
  143. }
  144. else {
  145. toastSuccess(t('deleted_pages', { path: pathOrPathsToDelete }));
  146. }
  147. mutatePageTree();
  148. mutateSearching();
  149. mutatePageList();
  150. mutateAllPageInfo();
  151. if (currentPagePath === pathOrPathsToDelete) {
  152. mutateCurrentPage();
  153. router.push(isCompletely ? path.dirname(pathOrPathsToDelete) : `/trash${pathOrPathsToDelete}`);
  154. }
  155. };
  156. openDeleteModal([pageToDelete], { onDeleted: onDeletedHandler });
  157. }, [currentPagePath, mutateCurrentPage, openDeleteModal, router, t]);
  158. if (error1 != null || error2 != null) {
  159. // TODO: improve message
  160. toastError('Error occurred while fetching pages to render PageTree');
  161. return <></>;
  162. }
  163. let initialItemNode;
  164. /*
  165. * Render second stage
  166. */
  167. if (isSecondStageRenderingCondition(renderingCondition)) {
  168. initialItemNode = generateInitialNodeAfterResponse(
  169. renderingCondition.ancestorsChildrenResult.ancestorsChildren,
  170. new ItemNode(renderingCondition.rootPageResult.rootPage),
  171. );
  172. }
  173. /*
  174. * Before swr response comes back
  175. */
  176. else if (targetAndAncestorsData != null) {
  177. initialItemNode = generateInitialNodeBeforeResponse(targetAndAncestorsData.targetAndAncestors);
  178. }
  179. if (initialItemNode != null) {
  180. return (
  181. <ul className={`${moduleClass} list-group py-4`}>
  182. <CustomTreeItem
  183. key={initialItemNode.page.path}
  184. targetPathOrId={targetPathOrId}
  185. itemNode={initialItemNode}
  186. isOpen
  187. isEnableActions={isEnableActions}
  188. isWipPageShown={isWipPageShown}
  189. isReadOnlyUser={isReadOnlyUser}
  190. onRenamed={onRenamed}
  191. onClickDuplicateMenuItem={onClickDuplicateMenuItem}
  192. onClickDeleteMenuItem={onClickDeleteMenuItem}
  193. onClick={onClickTreeItem}
  194. />
  195. </ul>
  196. );
  197. }
  198. return <ItemsTreeContentSkeleton />;
  199. };