PageTreeItem.tsx 5.3 KB

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