Item.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. import React, {
  2. useCallback, useState, FC, useEffect,
  3. } from 'react';
  4. import { DropdownToggle } from 'reactstrap';
  5. import { useTranslation } from 'react-i18next';
  6. import { useDrag, useDrop } from 'react-dnd';
  7. import nodePath from 'path';
  8. import { pathUtils, pagePathUtils } from '@growi/core';
  9. import loggerFactory from '~/utils/logger';
  10. import { toastWarning, toastError, toastSuccess } from '~/client/util/apiNotification';
  11. import { useSWRxPageChildren } from '~/stores/page-listing';
  12. import { apiv3Put, apiv3Post } from '~/client/util/apiv3-client';
  13. import { IPageForPageRenameModal, IPageForPageDuplicateModal } from '~/stores/modal';
  14. import TriangleIcon from '~/components/Icons/TriangleIcon';
  15. import { bookmark, unbookmark } from '~/client/services/page-operation';
  16. import ClosableTextInput, { AlertInfo, AlertType } from '../../Common/ClosableTextInput';
  17. import { PageItemControl } from '../../Common/Dropdown/PageItemControl';
  18. import { ItemNode } from './ItemNode';
  19. import { usePageTreeDescCountMap } from '~/stores/ui';
  20. import { IPageHasId, IPageInfoAll, IPageToDeleteWithMeta } from '~/interfaces/page';
  21. const logger = loggerFactory('growi:cli:Item');
  22. interface ItemProps {
  23. isEnableActions: boolean
  24. itemNode: ItemNode
  25. targetPathOrId?: string
  26. isScrolled: boolean,
  27. isOpen?: boolean
  28. isEnabledAttachTitleHeader?: boolean
  29. onClickDuplicateMenuItem?(pageToDuplicate: IPageForPageDuplicateModal): void
  30. onClickRenameMenuItem?(pageToRename: IPageForPageRenameModal): void
  31. onClickDeleteMenuItem?(pageToDelete: IPageToDeleteWithMeta): void
  32. }
  33. // Utility to mark target
  34. const markTarget = (children: ItemNode[], targetPathOrId?: string): void => {
  35. if (targetPathOrId == null) {
  36. return;
  37. }
  38. children.forEach((node) => {
  39. if (node.page._id === targetPathOrId || node.page.path === targetPathOrId) {
  40. node.page.isTarget = true;
  41. }
  42. return node;
  43. });
  44. };
  45. const bookmarkMenuItemClickHandler = async(_pageId: string, _newValue: boolean): Promise<void> => {
  46. const bookmarkOperation = _newValue ? bookmark : unbookmark;
  47. await bookmarkOperation(_pageId);
  48. };
  49. /**
  50. * Return new page path after the droppedPagePath is moved under the newParentPagePath
  51. * @param droppedPagePath
  52. * @param newParentPagePath
  53. * @returns
  54. */
  55. const getNewPathAfterMoved = (droppedPagePath: string, newParentPagePath: string): string => {
  56. const pageTitle = nodePath.basename(droppedPagePath);
  57. return nodePath.join(newParentPagePath, pageTitle);
  58. };
  59. /**
  60. * Return whether the fromPage could be moved under the newParentPage
  61. * @param fromPage
  62. * @param newParentPage
  63. * @param printLog
  64. * @returns
  65. */
  66. const canMoveUnderNewParent = (fromPage?: Partial<IPageHasId>, newParentPage?: Partial<IPageHasId>, printLog = false): boolean => {
  67. if (fromPage == null || newParentPage == null || fromPage.path == null || newParentPage.path == null) {
  68. if (printLog) {
  69. logger.warn('Any of page, page.path or droppedPage.path is null');
  70. }
  71. return false;
  72. }
  73. const newPathAfterMoved = getNewPathAfterMoved(fromPage.path, newParentPage.path);
  74. return pagePathUtils.canMoveByPath(fromPage.path, newPathAfterMoved);
  75. };
  76. type ItemCountProps = {
  77. descendantCount: number
  78. }
  79. const ItemCount: FC<ItemCountProps> = (props:ItemCountProps) => {
  80. return (
  81. <>
  82. <span className="grw-pagetree-count badge badge-pill badge-light text-muted">
  83. {props.descendantCount}
  84. </span>
  85. </>
  86. );
  87. };
  88. const Item: FC<ItemProps> = (props: ItemProps) => {
  89. const { t } = useTranslation();
  90. const {
  91. itemNode, targetPathOrId, isOpen: _isOpen = false, isEnabledAttachTitleHeader,
  92. onClickDuplicateMenuItem, onClickRenameMenuItem, onClickDeleteMenuItem, isEnableActions,
  93. } = props;
  94. const { page, children } = itemNode;
  95. const [pageTitle, setPageTitle] = useState(page.path);
  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 [isDraggable, setIsDraggable] = useState(false);
  101. // const [isRenameInputShown, setRenameInputShown] = 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. const canDragItem = !pagePathUtils.isUserPage(page.path || '/');
  125. setIsDraggable(canDragItem);
  126. return isDraggable;
  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 (!canMoveUnderNewParent(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. isRemainMetadata: false,
  156. });
  157. await mutateChildren();
  158. // force open
  159. setIsOpen(true);
  160. }
  161. catch (err) {
  162. // display the dropped item
  163. displayDroppedItemByPageId(droppedPage._id);
  164. if (err.code === 'operation__blocked') {
  165. toastWarning(t('pagetree.you_cannot_move_this_page_now'));
  166. }
  167. else {
  168. toastError(t('pagetree.something_went_wrong_with_moving_page'));
  169. }
  170. }
  171. };
  172. const [{ isOver }, drop] = useDrop<ItemNode, Promise<void>, { isOver: boolean }>(() => ({
  173. accept: 'PAGE_TREE',
  174. drop: pageItemDropHandler,
  175. hover: (item, monitor) => {
  176. // when a drag item is overlapped more than 1 sec, the drop target item will be opened.
  177. if (monitor.isOver()) {
  178. setTimeout(() => {
  179. if (monitor.isOver()) {
  180. setIsOpen(true);
  181. }
  182. }, 1000);
  183. }
  184. },
  185. canDrop: (item) => {
  186. const { page: droppedPage } = item;
  187. return canMoveUnderNewParent(droppedPage, page);
  188. },
  189. collect: monitor => ({
  190. isOver: monitor.isOver(),
  191. }),
  192. }));
  193. const hasChildren = useCallback((): boolean => {
  194. return currentChildren != null && currentChildren.length > 0;
  195. }, [currentChildren]);
  196. const onClickLoadChildren = useCallback(async() => {
  197. setIsOpen(!isOpen);
  198. }, [isOpen]);
  199. const onClickPlusButton = useCallback(() => {
  200. setNewPageInputShown(true);
  201. }, []);
  202. const duplicateMenuItemClickHandler = useCallback((): void => {
  203. if (onClickDuplicateMenuItem == null) {
  204. return;
  205. }
  206. const { _id: pageId, path } = page;
  207. if (pageId == null || path == null) {
  208. throw Error('Any of _id and path must not be null.');
  209. }
  210. const pageToDuplicate = { pageId, path };
  211. onClickDuplicateMenuItem(pageToDuplicate);
  212. }, [onClickDuplicateMenuItem, page]);
  213. /*
  214. * Rename: TODO: rename page title on input form by #87757
  215. */
  216. // const onClickRenameButton = useCallback(async(_pageId: string): Promise<void> => {
  217. // setRenameInputShown(true);
  218. // }, []);
  219. // const onPressEnterForRenameHandler = async(inputText: string) => {
  220. // const parentPath = getParentPagePath(page.path as string)
  221. // const newPagePath = `${parentPath}/${inputText}`;
  222. // try {
  223. // setPageTitle(inputText);
  224. // setRenameInputShown(false);
  225. // await apiv3Put('/pages/rename', { newPagePath, pageId: page._id, revisionId: page.revision });
  226. // }
  227. // catch (err) {
  228. // // open ClosableInput and set pageTitle back to the previous title
  229. // setPageTitle(nodePath.basename(pageTitle as string));
  230. // setRenameInputShown(true);
  231. // toastError(err);
  232. // }
  233. // };
  234. const renameMenuItemClickHandler = useCallback((): void => {
  235. if (onClickRenameMenuItem == null) {
  236. return;
  237. }
  238. const { _id: pageId, revision: revisionId, path } = page;
  239. if (!page.isEmpty && revisionId == null) {
  240. throw Error('Existing page should have revisionId');
  241. }
  242. if (pageId == null || path == null) {
  243. throw Error('Any of _id and revisionId and path must not be null.');
  244. }
  245. const pageToRename: IPageForPageRenameModal = {
  246. pageId,
  247. revisionId: revisionId as string,
  248. path,
  249. };
  250. onClickRenameMenuItem(pageToRename);
  251. }, [onClickRenameMenuItem, page]);
  252. const deleteMenuItemClickHandler = useCallback(async(_pageId: string, pageInfo: IPageInfoAll | undefined): Promise<void> => {
  253. if (page._id == null || page.revision == null || page.path == null) {
  254. throw Error('Any of _id, revision, and path must not be null.');
  255. }
  256. const pageToDelete: IPageToDeleteWithMeta = {
  257. data: {
  258. _id: page._id,
  259. revision: page.revision as string,
  260. path: page.path,
  261. },
  262. meta: pageInfo,
  263. };
  264. if (onClickDeleteMenuItem != null) {
  265. onClickDeleteMenuItem(pageToDelete);
  266. }
  267. }, [onClickDeleteMenuItem, page]);
  268. const onPressEnterForCreateHandler = async(inputText: string) => {
  269. setNewPageInputShown(false);
  270. const parentPath = pathUtils.addTrailingSlash(page.path as string);
  271. const newPagePath = `${parentPath}${inputText}`;
  272. const isCreatable = pagePathUtils.isCreatablePage(newPagePath);
  273. if (!isCreatable) {
  274. toastWarning(t('you_can_not_create_page_with_this_name'));
  275. return;
  276. }
  277. let initBody = '';
  278. if (isEnabledAttachTitleHeader) {
  279. const pageTitle = pathUtils.addHeadingSlash(nodePath.basename(newPagePath));
  280. initBody = pathUtils.attachTitleHeader(pageTitle);
  281. }
  282. try {
  283. await apiv3Post('/pages/', {
  284. path: newPagePath,
  285. body: initBody,
  286. grant: page.grant,
  287. grantUserGroupId: page.grantedGroup,
  288. createFromPageTree: true,
  289. });
  290. mutateChildren();
  291. toastSuccess(t('successfully_saved_the_page'));
  292. }
  293. catch (err) {
  294. toastError(err);
  295. }
  296. };
  297. const inputValidator = (title: string | null): AlertInfo | null => {
  298. if (title == null || title === '' || title.trim() === '') {
  299. return {
  300. type: AlertType.WARNING,
  301. message: t('form_validation.title_required'),
  302. };
  303. }
  304. if (title.includes('/')) {
  305. return {
  306. type: AlertType.WARNING,
  307. message: t('form_validation.slashed_are_not_yet_supported'),
  308. };
  309. }
  310. return null;
  311. };
  312. useEffect(() => {
  313. if (!props.isScrolled && page.isTarget) {
  314. document.dispatchEvent(new CustomEvent('targetItemRendered'));
  315. }
  316. }, [props.isScrolled, page.isTarget]);
  317. // didMount
  318. useEffect(() => {
  319. if (hasChildren()) setIsOpen(true);
  320. }, [hasChildren]);
  321. /*
  322. * Make sure itemNode.children and currentChildren are synced
  323. */
  324. useEffect(() => {
  325. if (children.length > currentChildren.length) {
  326. markTarget(children, targetPathOrId);
  327. setCurrentChildren(children);
  328. }
  329. }, [children, currentChildren.length, targetPathOrId]);
  330. /*
  331. * When swr fetch succeeded
  332. */
  333. useEffect(() => {
  334. if (isOpen && data != null) {
  335. const newChildren = ItemNode.generateNodesFromPages(data.children);
  336. markTarget(newChildren, targetPathOrId);
  337. setCurrentChildren(newChildren);
  338. }
  339. }, [data, isOpen, targetPathOrId]);
  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 d-flex align-items-center ${page.isTarget ? 'grw-pagetree-is-target' : ''}`}
  349. id={page.isTarget ? 'grw-pagetree-is-target' : `grw-pagetree-list-${page._id}`}
  350. >
  351. <div className="grw-triangle-container d-flex justify-content-center">
  352. {hasDescendants && (
  353. <button
  354. type="button"
  355. className={`grw-pagetree-button btn ${isOpen ? 'grw-pagetree-open' : ''}`}
  356. onClick={onClickLoadChildren}
  357. >
  358. <div className="grw-triangle-icon d-flex justify-content-center">
  359. <TriangleIcon />
  360. </div>
  361. </button>
  362. )}
  363. </div>
  364. {/* TODO: rename page title on input form by 87757 */}
  365. {/* { isRenameInputShown && (
  366. <ClosableTextInput
  367. isShown
  368. value={nodePath.basename(pageTitle as string)}
  369. placeholder={t('Input page name')}
  370. onClickOutside={() => { setRenameInputShown(false) }}
  371. onPressEnter={onPressEnterForRenameHandler}
  372. inputValidator={inputValidator}
  373. />
  374. )}
  375. { !isRenameInputShown && ( */}
  376. <a href={`/${page._id}`} className="grw-pagetree-title-anchor flex-grow-1">
  377. <p className={`text-truncate m-auto ${page.isEmpty && 'text-muted'}`}>{nodePath.basename(pageTitle as string) || '/'}</p>
  378. </a>
  379. {/* )} */}
  380. {(descendantCount > 0) && (
  381. <div className="grw-pagetree-count-wrapper">
  382. <ItemCount descendantCount={descendantCount} />
  383. </div>
  384. )}
  385. <div className="grw-pagetree-control d-flex">
  386. <PageItemControl
  387. pageId={page._id}
  388. isEnableActions={isEnableActions}
  389. onClickBookmarkMenuItem={bookmarkMenuItemClickHandler}
  390. onClickDuplicateMenuItem={duplicateMenuItemClickHandler}
  391. onClickRenameMenuItem={renameMenuItemClickHandler}
  392. onClickDeleteMenuItem={deleteMenuItemClickHandler}
  393. >
  394. {/* pass the color property to reactstrap dropdownToggle props. https://6-4-0--reactstrap.netlify.app/components/dropdowns/ */}
  395. <DropdownToggle color="transparent" className="border-0 rounded btn-page-item-control p-0 grw-visible-on-hover">
  396. <i className="icon-options fa fa-rotate-90 text-muted p-1"></i>
  397. </DropdownToggle>
  398. </PageItemControl>
  399. <button
  400. type="button"
  401. className="border-0 rounded btn btn-page-item-control p-0 grw-visible-on-hover"
  402. onClick={onClickPlusButton}
  403. >
  404. <i className="icon-plus text-muted d-block p-1" />
  405. </button>
  406. </div>
  407. </li>
  408. {isEnableActions && (
  409. <ClosableTextInput
  410. isShown={isNewPageInputShown}
  411. placeholder={t('Input page name')}
  412. onClickOutside={() => { setNewPageInputShown(false) }}
  413. onPressEnter={onPressEnterForCreateHandler}
  414. inputValidator={inputValidator}
  415. />
  416. )}
  417. {
  418. isOpen && hasChildren() && currentChildren.map(node => (
  419. <div key={node.page._id} className="grw-pagetree-item-children">
  420. <Item
  421. isEnableActions={isEnableActions}
  422. itemNode={node}
  423. isOpen={false}
  424. isScrolled={props.isScrolled}
  425. targetPathOrId={targetPathOrId}
  426. isEnabledAttachTitleHeader={isEnabledAttachTitleHeader}
  427. onClickDuplicateMenuItem={onClickDuplicateMenuItem}
  428. onClickRenameMenuItem={onClickRenameMenuItem}
  429. onClickDeleteMenuItem={onClickDeleteMenuItem}
  430. />
  431. </div>
  432. ))
  433. }
  434. </div>
  435. );
  436. };
  437. export default Item;