Item.tsx 18 KB

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