PageTreeItem.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. import React, {
  2. useCallback, useState, FC,
  3. } from 'react';
  4. import nodePath from 'path';
  5. import { pathUtils, pagePathUtils } from '@growi/core';
  6. import { useTranslation } from 'next-i18next';
  7. import { useDrag, useDrop } from 'react-dnd';
  8. import { DropdownToggle } from 'reactstrap';
  9. import { bookmark, unbookmark, resumeRenameOperation } from '~/client/services/page-operation';
  10. import { apiv3Put } from '~/client/util/apiv3-client';
  11. import { ValidationTarget } from '~/client/util/input-validator';
  12. import { toastWarning, toastError, toastSuccess } from '~/client/util/toastr';
  13. import { NotAvailableForGuest } from '~/components/NotAvailableForGuest';
  14. import {
  15. IPageHasId,
  16. IPageInfoAll, IPageToDeleteWithMeta,
  17. } from '~/interfaces/page';
  18. import { useSWRMUTxCurrentUserBookmarks } from '~/stores/bookmark';
  19. import { useSWRMUTxPageInfo } from '~/stores/page';
  20. import { mutatePageTree, useSWRxPageChildren } from '~/stores/page-listing';
  21. import loggerFactory from '~/utils/logger';
  22. import ClosableTextInput from '../../Common/ClosableTextInput';
  23. import { PageItemControl } from '../../Common/Dropdown/PageItemControl';
  24. import { ItemNode } from './ItemNode';
  25. import SimpleItem, { SimpleItemProps, NotDraggableForClosableTextInput, SimpleItemTool } from './SimpleItem';
  26. const logger = loggerFactory('growi:cli:Item');
  27. type PageTreeItemPropsOptional = 'itemRef' | 'itemClass' | 'mainClassName';
  28. type PageTreeItemProps = Omit<SimpleItemProps, PageTreeItemPropsOptional> & {key};
  29. type EllipsisPropsOptional = 'itemNode' | 'targetPathOrId' | 'isOpen' | 'itemRef' | 'itemClass' | 'mainClassName';
  30. type EllipsisProps = Omit<SimpleItemProps, EllipsisPropsOptional> & {page};
  31. const Ellipsis: FC<EllipsisProps> = (props: EllipsisProps) => {
  32. const [isRenameInputShown, setRenameInputShown] = useState(false);
  33. const { t } = useTranslation();
  34. const {
  35. page, onRenamed, onClickDuplicateMenuItem,
  36. onClickDeleteMenuItem, isEnableActions, isReadOnlyUser,
  37. } = props;
  38. const { trigger: mutateCurrentUserBookmarks } = useSWRMUTxCurrentUserBookmarks();
  39. const { trigger: mutatePageInfo } = useSWRMUTxPageInfo(page._id ?? null);
  40. const bookmarkMenuItemClickHandler = async(_pageId: string, _newValue: boolean): Promise<void> => {
  41. const bookmarkOperation = _newValue ? bookmark : unbookmark;
  42. await bookmarkOperation(_pageId);
  43. mutateCurrentUserBookmarks();
  44. mutatePageInfo();
  45. };
  46. const duplicateMenuItemClickHandler = useCallback((): void => {
  47. if (onClickDuplicateMenuItem == null) {
  48. return;
  49. }
  50. const { _id: pageId, path } = page;
  51. if (pageId == null || path == null) {
  52. throw Error('Any of _id and path must not be null.');
  53. }
  54. const pageToDuplicate = { pageId, path };
  55. onClickDuplicateMenuItem(pageToDuplicate);
  56. }, [onClickDuplicateMenuItem, page]);
  57. const renameMenuItemClickHandler = useCallback(() => {
  58. setRenameInputShown(true);
  59. }, []);
  60. const onPressEnterForRenameHandler = async(inputText: string) => {
  61. const parentPath = pathUtils.addTrailingSlash(nodePath.dirname(page.path ?? ''));
  62. const newPagePath = nodePath.resolve(parentPath, inputText);
  63. if (newPagePath === page.path) {
  64. setRenameInputShown(false);
  65. return;
  66. }
  67. try {
  68. setRenameInputShown(false);
  69. await apiv3Put('/pages/rename', {
  70. pageId: page._id,
  71. revisionId: page.revision,
  72. newPagePath,
  73. });
  74. if (onRenamed != null) {
  75. onRenamed(page.path, newPagePath);
  76. }
  77. toastSuccess(t('renamed_pages', { path: page.path }));
  78. }
  79. catch (err) {
  80. setRenameInputShown(true);
  81. toastError(err);
  82. }
  83. };
  84. const deleteMenuItemClickHandler = useCallback(async(_pageId: string, pageInfo: IPageInfoAll | undefined): Promise<void> => {
  85. if (onClickDeleteMenuItem == null) {
  86. return;
  87. }
  88. if (page._id == null || page.path == null) {
  89. throw Error('_id and path must not be null.');
  90. }
  91. const pageToDelete: IPageToDeleteWithMeta = {
  92. data: {
  93. _id: page._id,
  94. revision: page.revision as string,
  95. path: page.path,
  96. },
  97. meta: pageInfo,
  98. };
  99. onClickDeleteMenuItem(pageToDelete);
  100. }, [onClickDeleteMenuItem, page]);
  101. const pathRecoveryMenuItemClickHandler = async(pageId: string): Promise<void> => {
  102. try {
  103. await resumeRenameOperation(pageId);
  104. toastSuccess(t('page_operation.paths_recovered'));
  105. }
  106. catch {
  107. toastError(t('page_operation.path_recovery_failed'));
  108. }
  109. };
  110. return (
  111. <>
  112. {isRenameInputShown ? (
  113. <div className="flex-fill">
  114. <NotDraggableForClosableTextInput>
  115. <ClosableTextInput
  116. value={nodePath.basename(page.path ?? '')}
  117. placeholder={t('Input page name')}
  118. onClickOutside={() => { setRenameInputShown(false) }}
  119. onPressEnter={onPressEnterForRenameHandler}
  120. validationTarget={ValidationTarget.PAGE}
  121. />
  122. </NotDraggableForClosableTextInput>
  123. </div>
  124. ) : (
  125. <SimpleItemTool page={page}/>
  126. )}
  127. <NotAvailableForGuest>
  128. <div className="grw-pagetree-control d-flex">
  129. <PageItemControl
  130. pageId={page._id}
  131. isEnableActions={isEnableActions}
  132. isReadOnlyUser={isReadOnlyUser}
  133. onClickBookmarkMenuItem={bookmarkMenuItemClickHandler}
  134. onClickDuplicateMenuItem={duplicateMenuItemClickHandler}
  135. onClickRenameMenuItem={renameMenuItemClickHandler}
  136. onClickDeleteMenuItem={deleteMenuItemClickHandler}
  137. onClickPathRecoveryMenuItem={pathRecoveryMenuItemClickHandler}
  138. isInstantRename
  139. // Todo: It is wanted to find a better way to pass operationProcessData to PageItemControl
  140. operationProcessData={page.processData}
  141. >
  142. {/* pass the color property to reactstrap dropdownToggle props. https://6-4-0--reactstrap.netlify.app/components/dropdowns/ */}
  143. <DropdownToggle color="transparent" className="border-0 rounded btn-page-item-control p-0 grw-visible-on-hover mr-1">
  144. <i id='option-button-in-page-tree' className="icon-options fa fa-rotate-90 p-1"></i>
  145. </DropdownToggle>
  146. </PageItemControl>
  147. </div>
  148. </NotAvailableForGuest>
  149. </>
  150. );
  151. };
  152. export const PageTreeItem: FC<PageTreeItemProps> = (props: PageTreeItemProps) => {
  153. const getNewPathAfterMoved = (droppedPagePath: string, newParentPagePath: string): string => {
  154. const pageTitle = nodePath.basename(droppedPagePath);
  155. return nodePath.join(newParentPagePath, pageTitle);
  156. };
  157. const isDroppable = (fromPage?: Partial<IPageHasId>, newParentPage?: Partial<IPageHasId>, printLog = false): boolean => {
  158. if (fromPage == null || newParentPage == null || fromPage.path == null || newParentPage.path == null) {
  159. if (printLog) {
  160. logger.warn('Any of page, page.path or droppedPage.path is null');
  161. }
  162. return false;
  163. }
  164. const newPathAfterMoved = getNewPathAfterMoved(fromPage.path, newParentPage.path);
  165. return pagePathUtils.canMoveByPath(fromPage.path, newPathAfterMoved) && !pagePathUtils.isUsersTopPage(newParentPage.path);
  166. };
  167. const { t } = useTranslation();
  168. const {
  169. itemNode, isOpen: _isOpen = false, onRenamed,
  170. } = props;
  171. const { page } = itemNode;
  172. const [isOpen, setIsOpen] = useState(_isOpen);
  173. const [shouldHide, setShouldHide] = useState(false);
  174. const { mutate: mutateChildren } = useSWRxPageChildren(isOpen ? page._id : null);
  175. const displayDroppedItemByPageId = useCallback((pageId) => {
  176. const target = document.getElementById(`pagetree-item-${pageId}`);
  177. if (target == null) {
  178. return;
  179. }
  180. // // wait 500ms to avoid removing before d-none is set by useDrag end() callback
  181. setTimeout(() => {
  182. target.classList.remove('d-none');
  183. }, 500);
  184. }, []);
  185. const [, drag] = useDrag({
  186. type: 'PAGE_TREE',
  187. item: { page },
  188. canDrag: () => {
  189. if (page.path == null) {
  190. return false;
  191. }
  192. return !pagePathUtils.isUsersProtectedPages(page.path);
  193. },
  194. end: (item, monitor) => {
  195. // in order to set d-none to dropped Item
  196. const dropResult = monitor.getDropResult();
  197. if (dropResult != null) {
  198. setShouldHide(true);
  199. }
  200. },
  201. collect: monitor => ({
  202. isDragging: monitor.isDragging(),
  203. canDrag: monitor.canDrag(),
  204. }),
  205. });
  206. const pageItemDropHandler = async(item: ItemNode) => {
  207. const { page: droppedPage } = item;
  208. if (!isDroppable(droppedPage, page, true)) {
  209. return;
  210. }
  211. if (droppedPage.path == null || page.path == null) {
  212. return;
  213. }
  214. const newPagePath = getNewPathAfterMoved(droppedPage.path, page.path);
  215. try {
  216. await apiv3Put('/pages/rename', {
  217. pageId: droppedPage._id,
  218. revisionId: droppedPage.revision,
  219. newPagePath,
  220. isRenameRedirect: false,
  221. updateMetadata: true,
  222. });
  223. await mutatePageTree();
  224. await mutateChildren();
  225. if (onRenamed != null) {
  226. onRenamed(page.path, newPagePath);
  227. }
  228. // force open
  229. setIsOpen(true);
  230. }
  231. catch (err) {
  232. // display the dropped item
  233. displayDroppedItemByPageId(droppedPage._id);
  234. if (err.code === 'operation__blocked') {
  235. toastWarning(t('pagetree.you_cannot_move_this_page_now'));
  236. }
  237. else {
  238. toastError(t('pagetree.something_went_wrong_with_moving_page'));
  239. }
  240. }
  241. };
  242. const [{ isOver }, drop] = useDrop<ItemNode, Promise<void>, { isOver: boolean }>(
  243. () => ({
  244. accept: 'PAGE_TREE',
  245. drop: pageItemDropHandler,
  246. hover: (item, monitor) => {
  247. // when a drag item is overlapped more than 1 sec, the drop target item will be opened.
  248. if (monitor.isOver()) {
  249. setTimeout(() => {
  250. if (monitor.isOver()) {
  251. setIsOpen(true);
  252. }
  253. }, 600);
  254. }
  255. },
  256. canDrop: (item) => {
  257. const { page: droppedPage } = item;
  258. return isDroppable(droppedPage, page);
  259. },
  260. collect: monitor => ({
  261. isOver: monitor.isOver(),
  262. }),
  263. }),
  264. [page],
  265. );
  266. const itemRef = (c) => { drag(c); drop(c) };
  267. const mainClassName = `${isOver ? 'grw-pagetree-is-over' : ''} ${shouldHide ? 'd-none' : ''}`;
  268. return (
  269. <SimpleItem
  270. key={props.key}
  271. targetPathOrId={props.targetPathOrId}
  272. itemNode={props.itemNode}
  273. isOpen
  274. isEnableActions={props.isEnableActions}
  275. isReadOnlyUser={props.isReadOnlyUser}
  276. onRenamed={props.onRenamed}
  277. onClickDuplicateMenuItem={props.onClickDuplicateMenuItem}
  278. onClickDeleteMenuItem={props.onClickDeleteMenuItem}
  279. itemRef={itemRef}
  280. itemClass={PageTreeItem}
  281. mainClassName={mainClassName}
  282. customComponent={Ellipsis}
  283. />
  284. );
  285. };