PageTreeItem.tsx 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  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 {
  17. SimpleItem, useNewPageInput, ItemNode, type TreeItemProps,
  18. } from '../../TreeItem';
  19. import { Ellipsis } from './Ellipsis';
  20. const logger = loggerFactory('growi:cli:Item');
  21. export const PageTreeItem: FC<TreeItemProps> = (props) => {
  22. const router = useRouter();
  23. const getNewPathAfterMoved = (droppedPagePath: string, newParentPagePath: string): string => {
  24. const pageTitle = nodePath.basename(droppedPagePath);
  25. return nodePath.join(newParentPagePath, pageTitle);
  26. };
  27. const isDroppable = (fromPage?: Partial<IPageHasId>, newParentPage?: Partial<IPageHasId>, printLog = false): boolean => {
  28. if (fromPage == null || newParentPage == null || fromPage.path == null || newParentPage.path == null) {
  29. if (printLog) {
  30. logger.warn('Any of page, page.path or droppedPage.path is null');
  31. }
  32. return false;
  33. }
  34. const newPathAfterMoved = getNewPathAfterMoved(fromPage.path, newParentPage.path);
  35. return pagePathUtils.canMoveByPath(fromPage.path, newPathAfterMoved) && !pagePathUtils.isUsersTopPage(newParentPage.path);
  36. };
  37. const { t } = useTranslation();
  38. const {
  39. itemNode, isOpen: _isOpen = false, onRenamed,
  40. } = props;
  41. const { page } = itemNode;
  42. const [isOpen, setIsOpen] = useState(_isOpen);
  43. const [shouldHide, setShouldHide] = useState(false);
  44. const { mutate: mutateChildren } = useSWRxPageChildren(isOpen ? page._id : null);
  45. const itemSelectedHandler = useCallback((page: IPageForItem) => {
  46. if (page.path == null || page._id == null) {
  47. return;
  48. }
  49. const link = pathUtils.returnPathForURL(page.path, page._id);
  50. router.push(link);
  51. }, [router]);
  52. const displayDroppedItemByPageId = useCallback((pageId) => {
  53. const target = document.getElementById(`pagetree-item-${pageId}`);
  54. if (target == null) {
  55. return;
  56. }
  57. // // wait 500ms to avoid removing before d-none is set by useDrag end() callback
  58. setTimeout(() => {
  59. target.classList.remove('d-none');
  60. }, 500);
  61. }, []);
  62. const [, drag] = useDrag({
  63. type: 'PAGE_TREE',
  64. item: { page },
  65. canDrag: () => {
  66. if (page.path == null) {
  67. return false;
  68. }
  69. return !pagePathUtils.isUsersProtectedPages(page.path);
  70. },
  71. end: (item, monitor) => {
  72. // in order to set d-none to dropped Item
  73. const dropResult = monitor.getDropResult();
  74. if (dropResult != null) {
  75. setShouldHide(true);
  76. }
  77. },
  78. collect: monitor => ({
  79. isDragging: monitor.isDragging(),
  80. canDrag: monitor.canDrag(),
  81. }),
  82. });
  83. const pageItemDropHandler = async(item: ItemNode) => {
  84. const { page: droppedPage } = item;
  85. if (!isDroppable(droppedPage, page, true)) {
  86. return;
  87. }
  88. if (droppedPage.path == null || page.path == null) {
  89. return;
  90. }
  91. const newPagePath = getNewPathAfterMoved(droppedPage.path, page.path);
  92. try {
  93. await apiv3Put('/pages/rename', {
  94. pageId: droppedPage._id,
  95. revisionId: droppedPage.revision,
  96. newPagePath,
  97. isRenameRedirect: false,
  98. updateMetadata: true,
  99. });
  100. await mutatePageTree();
  101. await mutateChildren();
  102. if (onRenamed != null) {
  103. onRenamed(page.path, newPagePath);
  104. }
  105. // force open
  106. setIsOpen(true);
  107. }
  108. catch (err) {
  109. // display the dropped item
  110. displayDroppedItemByPageId(droppedPage._id);
  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) => { drag(c); drop(c) };
  144. const mainClassName = `${isOver ? 'grw-pagetree-is-over' : ''} ${shouldHide ? 'd-none' : ''}`;
  145. const { Input: NewPageInput, CreateButton: NewPageCreateButton } = useNewPageInput();
  146. return (
  147. <SimpleItem
  148. targetPathOrId={props.targetPathOrId}
  149. itemNode={props.itemNode}
  150. isOpen={isOpen}
  151. isEnableActions={props.isEnableActions}
  152. isReadOnlyUser={props.isReadOnlyUser}
  153. onClick={itemSelectedHandler}
  154. onClickDuplicateMenuItem={props.onClickDuplicateMenuItem}
  155. onClickDeleteMenuItem={props.onClickDeleteMenuItem}
  156. onRenamed={props.onRenamed}
  157. itemRef={itemRef}
  158. itemClass={PageTreeItem}
  159. mainClassName={mainClassName}
  160. customEndComponents={[Ellipsis, NewPageCreateButton]}
  161. customNextComponents={[NewPageInput]}
  162. />
  163. );
  164. };