Item.tsx 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  1. import React, {
  2. useCallback, useState, FC, useEffect, ReactNode,
  3. } from 'react';
  4. import nodePath from 'path';
  5. import {
  6. pathUtils, pagePathUtils, Nullable, DevidedPagePath,
  7. } from '@growi/core';
  8. import { useTranslation } from 'next-i18next';
  9. import Link from 'next/link';
  10. import { useDrag, useDrop } from 'react-dnd';
  11. import { UncontrolledTooltip, DropdownToggle } from 'reactstrap';
  12. import { bookmark, unbookmark, resumeRenameOperation } from '~/client/services/page-operation';
  13. import { apiv3Put, apiv3Post } from '~/client/util/apiv3-client';
  14. import { ValidationTarget } from '~/client/util/input-validator';
  15. import { toastWarning, toastError, toastSuccess } from '~/client/util/toastr';
  16. import { TriangleIcon } from '~/components/Icons/TriangleIcon';
  17. import { NotAvailableForGuest } from '~/components/NotAvailableForGuest';
  18. import { NotAvailableForReadOnlyUser } from '~/components/NotAvailableForReadOnlyUser';
  19. import {
  20. IPageHasId, IPageInfoAll, IPageToDeleteWithMeta,
  21. } from '~/interfaces/page';
  22. import { useSWRBookmarkInfo, useSWRxUserBookmarks } from '~/stores/bookmark';
  23. import { IPageForPageDuplicateModal } from '~/stores/modal';
  24. import { mutatePageTree, useSWRxPageChildren } from '~/stores/page-listing';
  25. import { usePageTreeDescCountMap } from '~/stores/ui';
  26. import loggerFactory from '~/utils/logger';
  27. import { shouldRecoverPagePaths } from '~/utils/page-operation';
  28. import ClosableTextInput from '../../Common/ClosableTextInput';
  29. import CountBadge from '../../Common/CountBadge';
  30. import { PageItemControl } from '../../Common/Dropdown/PageItemControl';
  31. import { ItemNode } from './ItemNode';
  32. const logger = loggerFactory('growi:cli:Item');
  33. interface ItemProps {
  34. isEnableActions: boolean
  35. isReadOnlyUser: boolean
  36. itemNode: ItemNode
  37. targetPathOrId?: Nullable<string>
  38. isOpen?: boolean
  39. onRenamed?(fromPath: string | undefined, toPath: string): void
  40. onClickDuplicateMenuItem?(pageToDuplicate: IPageForPageDuplicateModal): void
  41. onClickDeleteMenuItem?(pageToDelete: IPageToDeleteWithMeta): void
  42. }
  43. // Utility to mark target
  44. const markTarget = (children: ItemNode[], targetPathOrId?: Nullable<string>): void => {
  45. if (targetPathOrId == null) {
  46. return;
  47. }
  48. children.forEach((node) => {
  49. if (node.page._id === targetPathOrId || node.page.path === targetPathOrId) {
  50. node.page.isTarget = true;
  51. }
  52. else {
  53. node.page.isTarget = false;
  54. }
  55. return node;
  56. });
  57. };
  58. /**
  59. * Return new page path after the droppedPagePath is moved under the newParentPagePath
  60. * @param droppedPagePath
  61. * @param newParentPagePath
  62. * @returns
  63. */
  64. const getNewPathAfterMoved = (droppedPagePath: string, newParentPagePath: string): string => {
  65. const pageTitle = nodePath.basename(droppedPagePath);
  66. return nodePath.join(newParentPagePath, pageTitle);
  67. };
  68. /**
  69. * Return whether the fromPage could be moved under the newParentPage
  70. * @param fromPage
  71. * @param newParentPage
  72. * @param printLog
  73. * @returns
  74. */
  75. const isDroppable = (fromPage?: Partial<IPageHasId>, newParentPage?: Partial<IPageHasId>, printLog = false): boolean => {
  76. if (fromPage == null || newParentPage == null || fromPage.path == null || newParentPage.path == null) {
  77. if (printLog) {
  78. logger.warn('Any of page, page.path or droppedPage.path is null');
  79. }
  80. return false;
  81. }
  82. const newPathAfterMoved = getNewPathAfterMoved(fromPage.path, newParentPage.path);
  83. return pagePathUtils.canMoveByPath(fromPage.path, newPathAfterMoved) && !pagePathUtils.isUsersTopPage(newParentPage.path);
  84. };
  85. // Component wrapper to make a child element not draggable
  86. // https://github.com/react-dnd/react-dnd/issues/335
  87. type NotDraggableProps = {
  88. children: ReactNode,
  89. };
  90. const NotDraggableForClosableTextInput = (props: NotDraggableProps): JSX.Element => {
  91. return <div draggable onDragStart={e => e.preventDefault()}>{props.children}</div>;
  92. };
  93. const Item: FC<ItemProps> = (props: ItemProps) => {
  94. const { t } = useTranslation();
  95. const {
  96. itemNode, targetPathOrId, isOpen: _isOpen = false,
  97. onRenamed, onClickDuplicateMenuItem, onClickDeleteMenuItem, isEnableActions, isReadOnlyUser,
  98. } = props;
  99. const { page, children } = itemNode;
  100. const [currentChildren, setCurrentChildren] = useState(children);
  101. const [isOpen, setIsOpen] = useState(_isOpen);
  102. const [isNewPageInputShown, setNewPageInputShown] = useState(false);
  103. const [shouldHide, setShouldHide] = useState(false);
  104. const [isRenameInputShown, setRenameInputShown] = useState(false);
  105. const [isCreating, setCreating] = useState(false);
  106. const { data, mutate: mutateChildren } = useSWRxPageChildren(isOpen ? page._id : null);
  107. const { mutate: mutateUserBookmarks } = useSWRxUserBookmarks();
  108. const { mutate: mutateBookmarkInfo } = useSWRBookmarkInfo(page._id);
  109. // descendantCount
  110. const { getDescCount } = usePageTreeDescCountMap();
  111. const descendantCount = getDescCount(page._id) || page.descendantCount || 0;
  112. // hasDescendants flag
  113. const isChildrenLoaded = currentChildren?.length > 0;
  114. const hasDescendants = descendantCount > 0 || isChildrenLoaded;
  115. // to re-show hidden item when useDrag end() callback
  116. const displayDroppedItemByPageId = useCallback((pageId) => {
  117. const target = document.getElementById(`pagetree-item-${pageId}`);
  118. if (target == null) {
  119. return;
  120. }
  121. // wait 500ms to avoid removing before d-none is set by useDrag end() callback
  122. setTimeout(() => {
  123. target.classList.remove('d-none');
  124. }, 500);
  125. }, []);
  126. const [, drag] = useDrag({
  127. type: 'PAGE_TREE',
  128. item: { page },
  129. canDrag: () => {
  130. if (page.path == null) {
  131. return false;
  132. }
  133. return !pagePathUtils.isUsersProtectedPages(page.path);
  134. },
  135. end: (item, monitor) => {
  136. // in order to set d-none to dropped Item
  137. const dropResult = monitor.getDropResult();
  138. if (dropResult != null) {
  139. setShouldHide(true);
  140. }
  141. },
  142. collect: monitor => ({
  143. isDragging: monitor.isDragging(),
  144. canDrag: monitor.canDrag(),
  145. }),
  146. });
  147. const pageItemDropHandler = async(item: ItemNode) => {
  148. const { page: droppedPage } = item;
  149. if (!isDroppable(droppedPage, page, true)) {
  150. return;
  151. }
  152. if (droppedPage.path == null || page.path == null) {
  153. return;
  154. }
  155. const newPagePath = getNewPathAfterMoved(droppedPage.path, page.path);
  156. try {
  157. await apiv3Put('/pages/rename', {
  158. pageId: droppedPage._id,
  159. revisionId: droppedPage.revision,
  160. newPagePath,
  161. isRenameRedirect: false,
  162. updateMetadata: true,
  163. });
  164. await mutatePageTree();
  165. await mutateChildren();
  166. if (onRenamed != null) {
  167. onRenamed(page.path, newPagePath);
  168. }
  169. // force open
  170. setIsOpen(true);
  171. }
  172. catch (err) {
  173. // display the dropped item
  174. displayDroppedItemByPageId(droppedPage._id);
  175. if (err.code === 'operation__blocked') {
  176. toastWarning(t('pagetree.you_cannot_move_this_page_now'));
  177. }
  178. else {
  179. toastError(t('pagetree.something_went_wrong_with_moving_page'));
  180. }
  181. }
  182. };
  183. const [{ isOver }, drop] = useDrop<ItemNode, Promise<void>, { isOver: boolean }>(
  184. () => ({
  185. accept: 'PAGE_TREE',
  186. drop: pageItemDropHandler,
  187. hover: (item, monitor) => {
  188. // when a drag item is overlapped more than 1 sec, the drop target item will be opened.
  189. if (monitor.isOver()) {
  190. setTimeout(() => {
  191. if (monitor.isOver()) {
  192. setIsOpen(true);
  193. }
  194. }, 600);
  195. }
  196. },
  197. canDrop: (item) => {
  198. const { page: droppedPage } = item;
  199. return isDroppable(droppedPage, page);
  200. },
  201. collect: monitor => ({
  202. isOver: monitor.isOver(),
  203. }),
  204. }),
  205. [page],
  206. );
  207. const hasChildren = useCallback((): boolean => {
  208. return currentChildren != null && currentChildren.length > 0;
  209. }, [currentChildren]);
  210. const onClickLoadChildren = useCallback(async() => {
  211. setIsOpen(!isOpen);
  212. }, [isOpen]);
  213. const onClickPlusButton = useCallback(() => {
  214. setNewPageInputShown(true);
  215. if (hasDescendants) {
  216. setIsOpen(true);
  217. }
  218. }, [hasDescendants]);
  219. const bookmarkMenuItemClickHandler = async(_pageId: string, _newValue: boolean): Promise<void> => {
  220. const bookmarkOperation = _newValue ? bookmark : unbookmark;
  221. await bookmarkOperation(_pageId);
  222. mutateUserBookmarks();
  223. mutateBookmarkInfo();
  224. };
  225. const duplicateMenuItemClickHandler = useCallback((): void => {
  226. if (onClickDuplicateMenuItem == null) {
  227. return;
  228. }
  229. const { _id: pageId, path } = page;
  230. if (pageId == null || path == null) {
  231. throw Error('Any of _id and path must not be null.');
  232. }
  233. const pageToDuplicate = { pageId, path };
  234. onClickDuplicateMenuItem(pageToDuplicate);
  235. }, [onClickDuplicateMenuItem, page]);
  236. const renameMenuItemClickHandler = useCallback(() => {
  237. setRenameInputShown(true);
  238. }, []);
  239. const onPressEnterForRenameHandler = async(inputText: string) => {
  240. const parentPath = pathUtils.addTrailingSlash(nodePath.dirname(page.path ?? ''));
  241. const newPagePath = nodePath.resolve(parentPath, inputText);
  242. if (newPagePath === page.path) {
  243. setRenameInputShown(false);
  244. return;
  245. }
  246. try {
  247. setRenameInputShown(false);
  248. await apiv3Put('/pages/rename', {
  249. pageId: page._id,
  250. revisionId: page.revision,
  251. newPagePath,
  252. });
  253. if (onRenamed != null) {
  254. onRenamed(page.path, newPagePath);
  255. }
  256. toastSuccess(t('renamed_pages', { path: page.path }));
  257. }
  258. catch (err) {
  259. setRenameInputShown(true);
  260. toastError(err);
  261. }
  262. };
  263. const deleteMenuItemClickHandler = useCallback(async(_pageId: string, pageInfo: IPageInfoAll | undefined): Promise<void> => {
  264. if (onClickDeleteMenuItem == null) {
  265. return;
  266. }
  267. if (page._id == null || page.path == null) {
  268. throw Error('_id and path must not be null.');
  269. }
  270. const pageToDelete: IPageToDeleteWithMeta = {
  271. data: {
  272. _id: page._id,
  273. revision: page.revision as string,
  274. path: page.path,
  275. },
  276. meta: pageInfo,
  277. };
  278. onClickDeleteMenuItem(pageToDelete);
  279. }, [onClickDeleteMenuItem, page]);
  280. const onPressEnterForCreateHandler = async(inputText: string) => {
  281. setNewPageInputShown(false);
  282. const parentPath = pathUtils.addTrailingSlash(page.path as string);
  283. const newPagePath = nodePath.resolve(parentPath, inputText);
  284. const isCreatable = pagePathUtils.isCreatablePage(newPagePath);
  285. if (!isCreatable) {
  286. toastWarning(t('you_can_not_create_page_with_this_name'));
  287. return;
  288. }
  289. try {
  290. setCreating(true);
  291. await apiv3Post('/pages/', {
  292. path: newPagePath,
  293. body: undefined,
  294. grant: page.grant,
  295. grantUserGroupId: page.grantedGroup,
  296. });
  297. mutateChildren();
  298. if (!hasDescendants) {
  299. setIsOpen(true);
  300. }
  301. toastSuccess(t('successfully_saved_the_page'));
  302. }
  303. catch (err) {
  304. toastError(err);
  305. }
  306. finally {
  307. setCreating(false);
  308. }
  309. };
  310. /**
  311. * Users do not need to know if all pages have been renamed.
  312. * Make resuming rename operation appears to be working fine to allow users for a seamless operation.
  313. */
  314. const pathRecoveryMenuItemClickHandler = async(pageId: string): Promise<void> => {
  315. try {
  316. await resumeRenameOperation(pageId);
  317. toastSuccess(t('page_operation.paths_recovered'));
  318. }
  319. catch {
  320. toastError(t('page_operation.path_recovery_failed'));
  321. }
  322. };
  323. // didMount
  324. useEffect(() => {
  325. if (hasChildren()) setIsOpen(true);
  326. }, [hasChildren]);
  327. /*
  328. * Make sure itemNode.children and currentChildren are synced
  329. */
  330. useEffect(() => {
  331. if (children.length > currentChildren.length) {
  332. markTarget(children, targetPathOrId);
  333. setCurrentChildren(children);
  334. }
  335. }, [children, currentChildren.length, targetPathOrId]);
  336. /*
  337. * When swr fetch succeeded
  338. */
  339. useEffect(() => {
  340. if (isOpen && data != null) {
  341. const newChildren = ItemNode.generateNodesFromPages(data.children);
  342. markTarget(newChildren, targetPathOrId);
  343. setCurrentChildren(newChildren);
  344. }
  345. }, [data, isOpen, targetPathOrId]);
  346. // Rename process
  347. // Icon that draw attention from users for some actions
  348. const shouldShowAttentionIcon = page.processData != null ? shouldRecoverPagePaths(page.processData) : false;
  349. return (
  350. <div
  351. id={`pagetree-item-${page._id}`}
  352. data-testid="grw-pagetree-item-container"
  353. className={`grw-pagetree-item-container ${isOver ? 'grw-pagetree-is-over' : ''}
  354. ${shouldHide ? 'd-none' : ''}`}
  355. >
  356. <li
  357. ref={(c) => { drag(c); drop(c) }}
  358. className={`list-group-item list-group-item-action border-0 py-0 pr-3 d-flex align-items-center
  359. ${page.isTarget ? 'grw-pagetree-current-page-item' : ''}`}
  360. id={page.isTarget ? 'grw-pagetree-current-page-item' : `grw-pagetree-list-${page._id}`}
  361. >
  362. <div className="grw-triangle-container d-flex justify-content-center">
  363. {hasDescendants && (
  364. <button
  365. type="button"
  366. className={`grw-pagetree-triangle-btn btn ${isOpen ? 'grw-pagetree-open' : ''}`}
  367. onClick={onClickLoadChildren}
  368. >
  369. <div className="d-flex justify-content-center">
  370. <TriangleIcon />
  371. </div>
  372. </button>
  373. )}
  374. </div>
  375. {isRenameInputShown
  376. ? (
  377. <div className="flex-fill">
  378. <NotDraggableForClosableTextInput>
  379. <ClosableTextInput
  380. value={nodePath.basename(page.path ?? '')}
  381. placeholder={t('Input page name')}
  382. onClickOutside={() => { setRenameInputShown(false) }}
  383. onPressEnter={onPressEnterForRenameHandler}
  384. validationTarget={ValidationTarget.PAGE}
  385. />
  386. </NotDraggableForClosableTextInput>
  387. </div>
  388. )
  389. : (
  390. <>
  391. {shouldShowAttentionIcon && (
  392. <>
  393. <i id="path-recovery" className="fa fa-warning mr-2 text-warning"></i>
  394. <UncontrolledTooltip placement="top" target="path-recovery" fade={false}>
  395. {t('tooltip.operation.attention.rename')}
  396. </UncontrolledTooltip>
  397. </>
  398. )}
  399. {page != null && page.path != null && page._id != null && (
  400. <Link
  401. href={pathUtils.returnPathForURL(page.path, page._id)}
  402. className="grw-pagetree-title-anchor flex-grow-1"
  403. prefetch={false}
  404. >
  405. <p className={`text-truncate m-auto ${page.isEmpty && 'grw-sidebar-text-muted'}`}>{nodePath.basename(page.path ?? '') || '/'}</p>
  406. </Link>
  407. )}
  408. </>
  409. )}
  410. {descendantCount > 0 && !isRenameInputShown && (
  411. <div className="grw-pagetree-count-wrapper">
  412. <CountBadge count={descendantCount} />
  413. </div>
  414. )}
  415. <NotAvailableForGuest>
  416. <div className="grw-pagetree-control d-flex">
  417. <PageItemControl
  418. pageId={page._id}
  419. isEnableActions={isEnableActions}
  420. isReadOnlyUser={isReadOnlyUser}
  421. onClickBookmarkMenuItem={bookmarkMenuItemClickHandler}
  422. onClickDuplicateMenuItem={duplicateMenuItemClickHandler}
  423. onClickRenameMenuItem={renameMenuItemClickHandler}
  424. onClickDeleteMenuItem={deleteMenuItemClickHandler}
  425. onClickPathRecoveryMenuItem={pathRecoveryMenuItemClickHandler}
  426. isInstantRename
  427. // Todo: It is wanted to find a better way to pass operationProcessData to PageItemControl
  428. operationProcessData={page.processData}
  429. >
  430. {/* pass the color property to reactstrap dropdownToggle props. https://6-4-0--reactstrap.netlify.app/components/dropdowns/ */}
  431. <DropdownToggle color="transparent" className="border-0 rounded btn-page-item-control p-0 grw-visible-on-hover mr-1">
  432. <i id='option-button-in-page-tree' className="icon-options fa fa-rotate-90 p-1"></i>
  433. </DropdownToggle>
  434. </PageItemControl>
  435. </div>
  436. </NotAvailableForGuest>
  437. {!pagePathUtils.isUsersTopPage(page.path ?? '') && (
  438. <NotAvailableForGuest>
  439. <NotAvailableForReadOnlyUser>
  440. <button
  441. id='page-create-button-in-page-tree'
  442. type="button"
  443. className="border-0 rounded btn btn-page-item-control p-0 grw-visible-on-hover"
  444. onClick={onClickPlusButton}
  445. >
  446. <i className="icon-plus d-block p-0" />
  447. </button>
  448. </NotAvailableForReadOnlyUser>
  449. </NotAvailableForGuest>
  450. )}
  451. </li>
  452. {isEnableActions && isNewPageInputShown && (
  453. <div className="flex-fill">
  454. <NotDraggableForClosableTextInput>
  455. <ClosableTextInput
  456. placeholder={t('Input page name')}
  457. onClickOutside={() => { setNewPageInputShown(false) }}
  458. onPressEnter={onPressEnterForCreateHandler}
  459. validationTarget={ValidationTarget.PAGE}
  460. />
  461. </NotDraggableForClosableTextInput>
  462. </div>
  463. )}
  464. {
  465. isOpen && hasChildren() && currentChildren.map((node, index) => (
  466. <div key={node.page._id} className="grw-pagetree-item-children">
  467. <Item
  468. isEnableActions={isEnableActions}
  469. isReadOnlyUser={isReadOnlyUser}
  470. itemNode={node}
  471. isOpen={false}
  472. targetPathOrId={targetPathOrId}
  473. onRenamed={onRenamed}
  474. onClickDuplicateMenuItem={onClickDuplicateMenuItem}
  475. onClickDeleteMenuItem={onClickDeleteMenuItem}
  476. />
  477. {isCreating && (currentChildren.length - 1 === index) && (
  478. <div className="text-muted text-center">
  479. <i className="fa fa-spinner fa-pulse mr-1"></i>
  480. </div>
  481. )}
  482. </div>
  483. ))
  484. }
  485. </div>
  486. );
  487. };
  488. export default Item;