PageTreeItem.tsx 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  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. SimpleItem, useNewPageInput, type TreeItemProps,
  19. } from '../../TreeItem';
  20. import { Ellipsis } from './Ellipsis';
  21. import styles from './PageTreeItem.module.scss';
  22. const logger = loggerFactory('growi:cli:Item');
  23. export const PageTreeItem: FC<TreeItemProps> = (props) => {
  24. const router = useRouter();
  25. const getNewPathAfterMoved = (droppedPagePath: string, newParentPagePath: string): string => {
  26. const pageTitle = nodePath.basename(droppedPagePath);
  27. return nodePath.join(newParentPagePath, pageTitle);
  28. };
  29. const isDroppable = (fromPage?: Partial<IPageHasId>, newParentPage?: Partial<IPageHasId>, printLog = false): boolean => {
  30. if (fromPage == null || newParentPage == null || fromPage.path == null || newParentPage.path == null) {
  31. if (printLog) {
  32. logger.warn('Any of page, page.path or droppedPage.path is null');
  33. }
  34. return false;
  35. }
  36. const newPathAfterMoved = getNewPathAfterMoved(fromPage.path, newParentPage.path);
  37. return pagePathUtils.canMoveByPath(fromPage.path, newPathAfterMoved) && !pagePathUtils.isUsersTopPage(newParentPage.path);
  38. };
  39. const { t } = useTranslation();
  40. const {
  41. itemNode, isOpen: _isOpen = false, onRenamed,
  42. } = props;
  43. const { page } = itemNode;
  44. const [isOpen, setIsOpen] = useState(_isOpen);
  45. const [shouldHide, setShouldHide] = useState(false);
  46. const { mutate: mutateChildren } = useSWRxPageChildren(isOpen ? page._id : null);
  47. const itemSelectedHandler = useCallback((page: IPageForItem) => {
  48. if (page.path == null || page._id == null) {
  49. return;
  50. }
  51. const link = pathUtils.returnPathForURL(page.path, page._id);
  52. router.push(link);
  53. }, [router]);
  54. const displayDroppedItemByPageId = useCallback((pageId) => {
  55. const target = document.getElementById(`pagetree-item-${pageId}`);
  56. if (target == null) {
  57. return;
  58. }
  59. // // wait 500ms to avoid removing before d-none is set by useDrag end() callback
  60. setTimeout(() => {
  61. target.classList.remove('d-none');
  62. }, 500);
  63. }, []);
  64. const [, drag] = useDrag({
  65. type: 'PAGE_TREE',
  66. item: { page },
  67. canDrag: () => {
  68. if (page.path == null) {
  69. return false;
  70. }
  71. return !pagePathUtils.isUsersProtectedPages(page.path);
  72. },
  73. end: (item, monitor) => {
  74. // in order to set d-none to dropped Item
  75. const dropResult = monitor.getDropResult();
  76. if (dropResult != null) {
  77. setShouldHide(true);
  78. }
  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. // display the dropped item
  112. displayDroppedItemByPageId(droppedPage._id);
  113. if (err.code === 'operation__blocked') {
  114. toastWarning(t('pagetree.you_cannot_move_this_page_now'));
  115. }
  116. else {
  117. toastError(t('pagetree.something_went_wrong_with_moving_page'));
  118. }
  119. }
  120. };
  121. const [{ isOver }, drop] = useDrop<ItemNode, Promise<void>, { isOver: boolean }>(
  122. () => ({
  123. accept: 'PAGE_TREE',
  124. drop: pageItemDropHandler,
  125. hover: (item, monitor) => {
  126. // when a drag item is overlapped more than 1 sec, the drop target item will be opened.
  127. if (monitor.isOver()) {
  128. setTimeout(() => {
  129. if (monitor.isOver()) {
  130. setIsOpen(true);
  131. }
  132. }, 600);
  133. }
  134. },
  135. canDrop: (item) => {
  136. const { page: droppedPage } = item;
  137. return isDroppable(droppedPage, page);
  138. },
  139. collect: monitor => ({
  140. isOver: monitor.isOver(),
  141. }),
  142. }),
  143. [page],
  144. );
  145. const itemRef = (c) => { drag(c); drop(c) };
  146. const mainClassName = `${isOver ? 'grw-pagetree-is-over' : ''} ${shouldHide ? 'd-none' : ''}`;
  147. const { Input: NewPageInput, CreateButton: NewPageCreateButton } = useNewPageInput();
  148. return (
  149. <SimpleItem
  150. targetPathOrId={props.targetPathOrId}
  151. itemNode={props.itemNode}
  152. isOpen={isOpen}
  153. isEnableActions={props.isEnableActions}
  154. isReadOnlyUser={props.isReadOnlyUser}
  155. isWipPageShown={props.isWipPageShown}
  156. onClick={itemSelectedHandler}
  157. onClickDuplicateMenuItem={props.onClickDuplicateMenuItem}
  158. onClickDeleteMenuItem={props.onClickDeleteMenuItem}
  159. onRenamed={props.onRenamed}
  160. itemRef={itemRef}
  161. itemClass={PageTreeItem}
  162. mainClassName={mainClassName}
  163. customEndComponents={[Ellipsis, NewPageCreateButton]}
  164. customNextComponents={[NewPageInput]}
  165. />
  166. );
  167. };