SimpleItem.tsx 18 KB

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