Item.tsx 16 KB

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