PageTreeItem.tsx 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. import React, {
  2. useCallback, useState,
  3. type FC,
  4. } from 'react';
  5. import nodePath from 'path';
  6. import type { IPageHasId } from '@growi/core';
  7. import { pagePathUtils, pathUtils } from '@growi/core/dist/utils';
  8. import { useTranslation } from 'next-i18next';
  9. import { useRouter } from 'next/router';
  10. import { useDrag, useDrop } from 'react-dnd';
  11. import { apiv3Put } from '~/client/util/apiv3-client';
  12. import { toastWarning, toastError } from '~/client/util/toastr';
  13. import type { IPageForItem } from '~/interfaces/page';
  14. import { mutatePageTree, useSWRxPageChildren } from '~/stores/page-listing';
  15. import loggerFactory from '~/utils/logger';
  16. import type { ItemNode } from '../../TreeItem';
  17. import {
  18. TreeItemLayout, useNewPageInput, type TreeItemProps,
  19. } from '../../TreeItem';
  20. import { CountBadgeForPageTreeItem } from './CountBadgeForPageTreeItem';
  21. import { CreatingNewPageSpinner } from './CreatingNewPageSpinner';
  22. import { usePageItemControl } from './use-page-item-control';
  23. import styles from './PageTreeItem.module.scss';
  24. const moduleClass = styles['page-tree-item'] ?? '';
  25. const logger = loggerFactory('growi:cli:Item');
  26. export const PageTreeItem: FC<TreeItemProps> = (props) => {
  27. const router = useRouter();
  28. const getNewPathAfterMoved = (droppedPagePath: string, newParentPagePath: string): string => {
  29. const pageTitle = nodePath.basename(droppedPagePath);
  30. return nodePath.join(newParentPagePath, pageTitle);
  31. };
  32. const isDroppable = (fromPage?: Partial<IPageHasId>, newParentPage?: Partial<IPageHasId>, printLog = false): boolean => {
  33. if (fromPage == null || newParentPage == null || fromPage.path == null || newParentPage.path == null) {
  34. if (printLog) {
  35. logger.warn('Any of page, page.path or droppedPage.path is null');
  36. }
  37. return false;
  38. }
  39. const newPathAfterMoved = getNewPathAfterMoved(fromPage.path, newParentPage.path);
  40. return pagePathUtils.canMoveByPath(fromPage.path, newPathAfterMoved) && !pagePathUtils.isUsersTopPage(newParentPage.path);
  41. };
  42. const { t } = useTranslation();
  43. const {
  44. itemNode, targetPathOrId, isOpen: _isOpen = false, onRenamed,
  45. } = props;
  46. const { page } = itemNode;
  47. const [isOpen, setIsOpen] = useState(_isOpen);
  48. const { mutate: mutateChildren } = useSWRxPageChildren(isOpen ? page._id : null);
  49. const {
  50. showRenameInput, Control, RenameInput,
  51. } = usePageItemControl();
  52. const { isProcessingSubmission, Input: NewPageInput, CreateButton: NewPageCreateButton } = useNewPageInput();
  53. const itemSelectedHandler = useCallback((page: IPageForItem) => {
  54. if (page.path == null || page._id == null) {
  55. return;
  56. }
  57. const link = pathUtils.returnPathForURL(page.path, page._id);
  58. router.push(link);
  59. }, [router]);
  60. const itemSelectedByWheelClickHandler = useCallback((page: IPageForItem) => {
  61. if (page.path == null || page._id == null) {
  62. return;
  63. }
  64. const url = pathUtils.returnPathForURL(page.path, page._id);
  65. window.open(url, '_blank');
  66. }, []);
  67. const [, drag] = useDrag({
  68. type: 'PAGE_TREE',
  69. item: { page },
  70. canDrag: () => {
  71. if (page.path == null) {
  72. return false;
  73. }
  74. return !pagePathUtils.isUsersProtectedPages(page.path);
  75. },
  76. end: (item, monitor) => {
  77. // in order to set d-none to dropped Item
  78. const dropResult = monitor.getDropResult();
  79. },
  80. collect: monitor => ({
  81. isDragging: monitor.isDragging(),
  82. canDrag: monitor.canDrag(),
  83. }),
  84. });
  85. const pageItemDropHandler = async(item: ItemNode) => {
  86. const { page: droppedPage } = item;
  87. if (!isDroppable(droppedPage, page, true)) {
  88. return;
  89. }
  90. if (droppedPage.path == null || page.path == null) {
  91. return;
  92. }
  93. const newPagePath = getNewPathAfterMoved(droppedPage.path, page.path);
  94. try {
  95. await apiv3Put('/pages/rename', {
  96. pageId: droppedPage._id,
  97. revisionId: droppedPage.revision,
  98. newPagePath,
  99. isRenameRedirect: false,
  100. updateMetadata: true,
  101. });
  102. await mutatePageTree();
  103. await mutateChildren();
  104. if (onRenamed != null) {
  105. onRenamed(page.path, newPagePath);
  106. }
  107. // force open
  108. setIsOpen(true);
  109. }
  110. catch (err) {
  111. if (err.code === 'operation__blocked') {
  112. toastWarning(t('pagetree.you_cannot_move_this_page_now'));
  113. }
  114. else {
  115. toastError(t('pagetree.something_went_wrong_with_moving_page'));
  116. }
  117. }
  118. };
  119. const [{ isOver }, drop] = useDrop<ItemNode, Promise<void>, { isOver: boolean }>(
  120. () => ({
  121. accept: 'PAGE_TREE',
  122. drop: pageItemDropHandler,
  123. hover: (item, monitor) => {
  124. // when a drag item is overlapped more than 1 sec, the drop target item will be opened.
  125. if (monitor.isOver()) {
  126. setTimeout(() => {
  127. if (monitor.isOver()) {
  128. setIsOpen(true);
  129. }
  130. }, 600);
  131. }
  132. },
  133. canDrop: (item) => {
  134. const { page: droppedPage } = item;
  135. return isDroppable(droppedPage, page);
  136. },
  137. collect: monitor => ({
  138. isOver: monitor.isOver(),
  139. }),
  140. }),
  141. [page],
  142. );
  143. const itemRef = (c) => {
  144. // do not apply when RenameInput is shown
  145. if (showRenameInput) return;
  146. drag(c);
  147. drop(c);
  148. };
  149. const isSelected = page._id === targetPathOrId || page.path === targetPathOrId;
  150. const itemClassNames = [
  151. isOver ? 'drag-over' : '',
  152. page.path !== '/' && isSelected ? 'active' : '', // set 'active' except the root page
  153. ];
  154. return (
  155. <TreeItemLayout
  156. className={moduleClass}
  157. targetPathOrId={props.targetPathOrId}
  158. itemLevel={props.itemLevel}
  159. itemNode={props.itemNode}
  160. isOpen={isOpen}
  161. isEnableActions={props.isEnableActions}
  162. isReadOnlyUser={props.isReadOnlyUser}
  163. isWipPageShown={props.isWipPageShown}
  164. onClick={itemSelectedHandler}
  165. onClickDuplicateMenuItem={props.onClickDuplicateMenuItem}
  166. onClickDeleteMenuItem={props.onClickDeleteMenuItem}
  167. onWheelClick={itemSelectedByWheelClickHandler}
  168. onRenamed={props.onRenamed}
  169. itemRef={itemRef}
  170. itemClass={PageTreeItem}
  171. itemClassName={itemClassNames.join(' ')}
  172. customEndComponents={[CountBadgeForPageTreeItem]}
  173. customHoveredEndComponents={[Control, NewPageCreateButton]}
  174. customHeadOfChildrenComponents={[NewPageInput, () => <CreatingNewPageSpinner show={isProcessingSubmission} />]}
  175. showAlternativeContent={showRenameInput}
  176. customAlternativeComponents={[RenameInput]}
  177. />
  178. );
  179. };