Item.tsx 17 KB

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