SimpleItem.tsx 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. import React, {
  2. useCallback, useState, FC, useEffect, ReactNode,
  3. } from 'react';
  4. import nodePath from 'path';
  5. import type { Nullable, IPageToDeleteWithMeta } from '@growi/core';
  6. import { pathUtils } from '@growi/core/dist/utils';
  7. import { useTranslation } from 'next-i18next';
  8. import { useRouter } from 'next/router';
  9. import { UncontrolledTooltip } from 'reactstrap';
  10. import { IPageForItem } from '~/interfaces/page';
  11. import { IPageForPageDuplicateModal } from '~/stores/modal';
  12. import { useSWRxPageChildren } from '~/stores/page-listing';
  13. import { usePageTreeDescCountMap } from '~/stores/ui';
  14. import { shouldRecoverPagePaths } from '~/utils/page-operation';
  15. import CountBadge from '../Common/CountBadge';
  16. import { ItemNode } from './ItemNode';
  17. export type SimpleItemProps = {
  18. isEnableActions: boolean
  19. isReadOnlyUser: boolean
  20. itemNode: ItemNode
  21. targetPathOrId?: Nullable<string>
  22. isOpen?: boolean
  23. onRenamed?(fromPath: string | undefined, toPath: string): void
  24. onClickDuplicateMenuItem?(pageToDuplicate: IPageForPageDuplicateModal): void
  25. onClickDeleteMenuItem?(pageToDelete: IPageToDeleteWithMeta): void
  26. itemRef?
  27. itemClass?: React.FunctionComponent<SimpleItemProps>
  28. mainClassName?: string
  29. customEndComponents?: Array<React.FunctionComponent<SimpleItemToolProps>>
  30. customNextComponents?: Array<React.FunctionComponent<SimpleItemToolProps>>
  31. };
  32. // Utility to mark target
  33. const markTarget = (children: ItemNode[], targetPathOrId?: Nullable<string>): void => {
  34. if (targetPathOrId == null) {
  35. return;
  36. }
  37. children.forEach((node) => {
  38. if (node.page._id === targetPathOrId || node.page.path === targetPathOrId) {
  39. node.page.isTarget = true;
  40. }
  41. else {
  42. node.page.isTarget = false;
  43. }
  44. return node;
  45. });
  46. };
  47. /**
  48. * Return new page path after the droppedPagePath is moved under the newParentPagePath
  49. * @param droppedPagePath
  50. * @param newParentPagePath
  51. * @returns
  52. */
  53. /**
  54. * Return whether the fromPage could be moved under the newParentPage
  55. * @param fromPage
  56. * @param newParentPage
  57. * @param printLog
  58. * @returns
  59. */
  60. // Component wrapper to make a child element not draggable
  61. // https://github.com/react-dnd/react-dnd/issues/335
  62. type NotDraggableProps = {
  63. children: ReactNode,
  64. };
  65. export const NotDraggableForClosableTextInput = (props: NotDraggableProps): JSX.Element => {
  66. return <div draggable onDragStart={e => e.preventDefault()}>{props.children}</div>;
  67. };
  68. type SimpleItemToolPropsOptional = 'itemNode' | 'targetPathOrId' | 'isOpen' | 'itemRef' | 'itemClass' | 'mainClassName';
  69. export type SimpleItemToolProps = Omit<SimpleItemProps, SimpleItemToolPropsOptional> & {page: IPageForItem};
  70. export const SimpleItemTool: FC<SimpleItemToolProps> = (props) => {
  71. const { t } = useTranslation();
  72. const router = useRouter();
  73. const { getDescCount } = usePageTreeDescCountMap();
  74. const page = props.page;
  75. const pageName = nodePath.basename(page.path ?? '') || '/';
  76. const shouldShowAttentionIcon = page.processData != null ? shouldRecoverPagePaths(page.processData) : false;
  77. const descendantCount = getDescCount(page._id) || page.descendantCount || 0;
  78. const pageTreeItemClickHandler = (e) => {
  79. e.preventDefault();
  80. if (page.path == null || page._id == null) {
  81. return;
  82. }
  83. const link = pathUtils.returnPathForURL(page.path, page._id);
  84. router.push(link);
  85. };
  86. return (
  87. <>
  88. {shouldShowAttentionIcon && (
  89. <>
  90. <i id="path-recovery" className="fa fa-warning mr-2 text-warning"></i>
  91. <UncontrolledTooltip placement="top" target="path-recovery" fade={false}>
  92. {t('tooltip.operation.attention.rename')}
  93. </UncontrolledTooltip>
  94. </>
  95. )}
  96. {page != null && page.path != null && page._id != null && (
  97. <div className="grw-pagetree-title-anchor flex-grow-1">
  98. <p onClick={pageTreeItemClickHandler} className={`text-truncate m-auto ${page.isEmpty && 'grw-sidebar-text-muted'}`}>{pageName}</p>
  99. </div>
  100. )}
  101. {descendantCount > 0 && (
  102. <div className="grw-pagetree-count-wrapper">
  103. <CountBadge count={descendantCount} />
  104. </div>
  105. )}
  106. </>
  107. );
  108. };
  109. export const SimpleItem: FC<SimpleItemProps> = (props) => {
  110. const {
  111. itemNode, targetPathOrId, isOpen: _isOpen = false,
  112. onRenamed, onClickDuplicateMenuItem, onClickDeleteMenuItem, isEnableActions, isReadOnlyUser,
  113. itemRef, itemClass, mainClassName,
  114. } = props;
  115. const { page, children } = itemNode;
  116. const [currentChildren, setCurrentChildren] = useState(children);
  117. const [isOpen, setIsOpen] = useState(_isOpen);
  118. const [isCreating, setCreating] = useState(false);
  119. const { data } = useSWRxPageChildren(isOpen ? page._id : null);
  120. const stateHandlers = {
  121. isOpen,
  122. setIsOpen,
  123. isCreating,
  124. setCreating,
  125. };
  126. // descendantCount
  127. const { getDescCount } = usePageTreeDescCountMap();
  128. const descendantCount = getDescCount(page._id) || page.descendantCount || 0;
  129. // hasDescendants flag
  130. const isChildrenLoaded = currentChildren?.length > 0;
  131. const hasDescendants = descendantCount > 0 || isChildrenLoaded;
  132. const hasChildren = useCallback((): boolean => {
  133. return currentChildren != null && currentChildren.length > 0;
  134. }, [currentChildren]);
  135. const onClickLoadChildren = useCallback(async() => {
  136. setIsOpen(!isOpen);
  137. }, [isOpen]);
  138. // didMount
  139. useEffect(() => {
  140. if (hasChildren()) setIsOpen(true);
  141. }, [hasChildren]);
  142. /*
  143. * Make sure itemNode.children and currentChildren are synced
  144. */
  145. useEffect(() => {
  146. if (children.length > currentChildren.length) {
  147. markTarget(children, targetPathOrId);
  148. setCurrentChildren(children);
  149. }
  150. }, [children, currentChildren.length, targetPathOrId]);
  151. /*
  152. * When swr fetch succeeded
  153. */
  154. useEffect(() => {
  155. if (isOpen && data != null) {
  156. const newChildren = ItemNode.generateNodesFromPages(data.children);
  157. markTarget(newChildren, targetPathOrId);
  158. setCurrentChildren(newChildren);
  159. }
  160. }, [data, isOpen, targetPathOrId]);
  161. const ItemClassFixed = itemClass ?? SimpleItem;
  162. const commonProps = {
  163. isEnableActions,
  164. isReadOnlyUser,
  165. isOpen: false,
  166. targetPathOrId,
  167. onRenamed,
  168. onClickDuplicateMenuItem,
  169. onClickDeleteMenuItem,
  170. stateHandlers,
  171. };
  172. const CustomEndComponents = props.customEndComponents;
  173. const SimpleItemContent = CustomEndComponents ?? [SimpleItemTool];
  174. const SimpleItemContentProps = {
  175. itemNode,
  176. page,
  177. onRenamed,
  178. onClickDuplicateMenuItem,
  179. onClickDeleteMenuItem,
  180. isEnableActions,
  181. isReadOnlyUser,
  182. children,
  183. stateHandlers,
  184. };
  185. const CustomNextComponents = props.customNextComponents;
  186. return (
  187. <div
  188. id={`pagetree-item-${page._id}`}
  189. data-testid="grw-pagetree-item-container"
  190. className={`grw-pagetree-item-container ${mainClassName}`}
  191. >
  192. <li
  193. ref={itemRef}
  194. className={`list-group-item list-group-item-action border-0 py-0 pr-3 d-flex align-items-center
  195. ${page.isTarget ? 'grw-pagetree-current-page-item' : ''}`}
  196. id={page.isTarget ? 'grw-pagetree-current-page-item' : `grw-pagetree-list-${page._id}`}
  197. >
  198. <div className="grw-triangle-container d-flex justify-content-center">
  199. {hasDescendants && (
  200. <button
  201. type="button"
  202. className={`grw-pagetree-triangle-btn btn ${isOpen ? 'grw-pagetree-open' : ''}`}
  203. onClick={onClickLoadChildren}
  204. >
  205. <div className="d-flex justify-content-center">
  206. <span className="material-symbols-outlined">arrow_right</span>
  207. </div>
  208. </button>
  209. )}
  210. </div>
  211. {SimpleItemContent.map((ItemContent, index) => (
  212. // eslint-disable-next-line react/no-array-index-key
  213. <ItemContent key={index} {...SimpleItemContentProps} />
  214. ))}
  215. </li>
  216. {CustomNextComponents?.map((UnderItemContent, index) => (
  217. // eslint-disable-next-line react/no-array-index-key
  218. <UnderItemContent key={index} {...SimpleItemContentProps} />
  219. ))}
  220. {
  221. isOpen && hasChildren() && currentChildren.map((node, index) => (
  222. <div key={node.page._id} className="grw-pagetree-item-children">
  223. <ItemClassFixed itemNode={node} {...commonProps} />
  224. {isCreating && (currentChildren.length - 1 === index) && (
  225. <div className="text-muted text-center">
  226. <i className="fa fa-spinner fa-pulse mr-1"></i>
  227. </div>
  228. )}
  229. </div>
  230. ))
  231. }
  232. </div>
  233. );
  234. };