Item.tsx 17 KB

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