Item.tsx 18 KB

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