PageTreeItem.tsx 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  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 [, drag] = useDrag({
  61. type: 'PAGE_TREE',
  62. item: { page },
  63. canDrag: () => {
  64. if (page.path == null) {
  65. return false;
  66. }
  67. return !pagePathUtils.isUsersProtectedPages(page.path);
  68. },
  69. end: (item, monitor) => {
  70. // in order to set d-none to dropped Item
  71. const dropResult = monitor.getDropResult();
  72. },
  73. collect: monitor => ({
  74. isDragging: monitor.isDragging(),
  75. canDrag: monitor.canDrag(),
  76. }),
  77. });
  78. const pageItemDropHandler = async(item: ItemNode) => {
  79. const { page: droppedPage } = item;
  80. if (!isDroppable(droppedPage, page, true)) {
  81. return;
  82. }
  83. if (droppedPage.path == null || page.path == null) {
  84. return;
  85. }
  86. const newPagePath = getNewPathAfterMoved(droppedPage.path, page.path);
  87. try {
  88. await apiv3Put('/pages/rename', {
  89. pageId: droppedPage._id,
  90. revisionId: droppedPage.revision,
  91. newPagePath,
  92. isRenameRedirect: false,
  93. updateMetadata: true,
  94. });
  95. await mutatePageTree();
  96. await mutateChildren();
  97. if (onRenamed != null) {
  98. onRenamed(page.path, newPagePath);
  99. }
  100. // force open
  101. setIsOpen(true);
  102. }
  103. catch (err) {
  104. if (err.code === 'operation__blocked') {
  105. toastWarning(t('pagetree.you_cannot_move_this_page_now'));
  106. }
  107. else {
  108. toastError(t('pagetree.something_went_wrong_with_moving_page'));
  109. }
  110. }
  111. };
  112. const [{ isOver }, drop] = useDrop<ItemNode, Promise<void>, { isOver: boolean }>(
  113. () => ({
  114. accept: 'PAGE_TREE',
  115. drop: pageItemDropHandler,
  116. hover: (item, monitor) => {
  117. // when a drag item is overlapped more than 1 sec, the drop target item will be opened.
  118. if (monitor.isOver()) {
  119. setTimeout(() => {
  120. if (monitor.isOver()) {
  121. setIsOpen(true);
  122. }
  123. }, 600);
  124. }
  125. },
  126. canDrop: (item) => {
  127. const { page: droppedPage } = item;
  128. return isDroppable(droppedPage, page);
  129. },
  130. collect: monitor => ({
  131. isOver: monitor.isOver(),
  132. }),
  133. }),
  134. [page],
  135. );
  136. const itemRef = (c) => {
  137. // do not apply when RenameInput is shown
  138. if (showRenameInput) return;
  139. drag(c);
  140. drop(c);
  141. };
  142. const isSelected = page._id === targetPathOrId || page.path === targetPathOrId;
  143. const itemClassNames = [
  144. isOver ? 'drag-over' : '',
  145. page.path !== '/' && isSelected ? 'active' : '', // set 'active' except the root page
  146. ];
  147. return (
  148. <TreeItemLayout
  149. className={moduleClass}
  150. targetPathOrId={props.targetPathOrId}
  151. itemLevel={props.itemLevel}
  152. itemNode={props.itemNode}
  153. isOpen={isOpen}
  154. isEnableActions={props.isEnableActions}
  155. isReadOnlyUser={props.isReadOnlyUser}
  156. isWipPageShown={props.isWipPageShown}
  157. onClick={itemSelectedHandler}
  158. onClickDuplicateMenuItem={props.onClickDuplicateMenuItem}
  159. onClickDeleteMenuItem={props.onClickDeleteMenuItem}
  160. onRenamed={props.onRenamed}
  161. itemRef={itemRef}
  162. itemClass={PageTreeItem}
  163. itemClassName={itemClassNames.join(' ')}
  164. customEndComponents={[CountBadgeForPageTreeItem]}
  165. customHoveredEndComponents={[Control, NewPageCreateButton]}
  166. customHeadOfChildrenComponents={[NewPageInput, () => <CreatingNewPageSpinner show={isProcessingSubmission} />]}
  167. showAlternativeContent={showRenameInput}
  168. customAlternativeComponents={[RenameInput]}
  169. />
  170. );
  171. };