PageTreeItem.tsx 5.4 KB

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