PageTreeItem.tsx 5.7 KB

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