Item.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  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 { 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. mutateAfterRenamed?(): void
  30. onClickDuplicateMenuItem?(pageToDuplicate: IPageForPageDuplicateModal): 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. mutateAfterRenamed, 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 { data, mutate: mutateChildren } = useSWRxPageChildren(isOpen ? page._id : null);
  101. // descendantCount
  102. const { getDescCount } = usePageTreeDescCountMap();
  103. const descendantCount = getDescCount(page._id) || page.descendantCount || 0;
  104. // hasDescendants flag
  105. const isChildrenLoaded = currentChildren?.length > 0;
  106. const hasDescendants = descendantCount > 0 || isChildrenLoaded;
  107. // to re-show hidden item when useDrag end() callback
  108. const displayDroppedItemByPageId = useCallback((pageId) => {
  109. const target = document.getElementById(`pagetree-item-${pageId}`);
  110. if (target == null) {
  111. return;
  112. }
  113. // wait 500ms to avoid removing before d-none is set by useDrag end() callback
  114. setTimeout(() => {
  115. target.classList.remove('d-none');
  116. }, 500);
  117. }, []);
  118. const [, drag] = useDrag({
  119. type: 'PAGE_TREE',
  120. item: { page },
  121. canDrag: () => {
  122. const isDraggable = !pagePathUtils.isUserPage(page.path || '/');
  123. return isDraggable;
  124. },
  125. end: (item, monitor) => {
  126. // in order to set d-none to dropped Item
  127. const dropResult = monitor.getDropResult();
  128. if (dropResult != null) {
  129. setShouldHide(true);
  130. }
  131. },
  132. collect: monitor => ({
  133. isDragging: monitor.isDragging(),
  134. canDrag: monitor.canDrag(),
  135. }),
  136. });
  137. const pageItemDropHandler = async(item: ItemNode) => {
  138. const { page: droppedPage } = item;
  139. if (!canMoveUnderNewParent(droppedPage, page, true)) {
  140. return;
  141. }
  142. if (droppedPage.path == null || page.path == null) {
  143. return;
  144. }
  145. const newPagePath = getNewPathAfterMoved(droppedPage.path, page.path);
  146. try {
  147. await apiv3Put('/pages/rename', {
  148. pageId: droppedPage._id,
  149. revisionId: droppedPage.revision,
  150. newPagePath,
  151. isRenameRedirect: false,
  152. isRemainMetadata: false,
  153. });
  154. await mutateChildren();
  155. // force open
  156. setIsOpen(true);
  157. }
  158. catch (err) {
  159. // display the dropped item
  160. displayDroppedItemByPageId(droppedPage._id);
  161. if (err.code === 'operation__blocked') {
  162. toastWarning(t('pagetree.you_cannot_move_this_page_now'));
  163. }
  164. else {
  165. toastError(t('pagetree.something_went_wrong_with_moving_page'));
  166. }
  167. }
  168. };
  169. const [{ isOver }, drop] = useDrop<ItemNode, Promise<void>, { isOver: boolean }>(() => ({
  170. accept: 'PAGE_TREE',
  171. drop: pageItemDropHandler,
  172. hover: (item, monitor) => {
  173. // when a drag item is overlapped more than 1 sec, the drop target item will be opened.
  174. if (monitor.isOver()) {
  175. setTimeout(() => {
  176. if (monitor.isOver()) {
  177. setIsOpen(true);
  178. }
  179. }, 1000);
  180. }
  181. },
  182. canDrop: (item) => {
  183. const { page: droppedPage } = item;
  184. return canMoveUnderNewParent(droppedPage, page);
  185. },
  186. collect: monitor => ({
  187. isOver: monitor.isOver(),
  188. }),
  189. }));
  190. const hasChildren = useCallback((): boolean => {
  191. return currentChildren != null && currentChildren.length > 0;
  192. }, [currentChildren]);
  193. const onClickLoadChildren = useCallback(async() => {
  194. setIsOpen(!isOpen);
  195. }, [isOpen]);
  196. const onClickPlusButton = useCallback(() => {
  197. setNewPageInputShown(true);
  198. }, []);
  199. const duplicateMenuItemClickHandler = useCallback((): void => {
  200. if (onClickDuplicateMenuItem == null) {
  201. return;
  202. }
  203. const { _id: pageId, path } = page;
  204. if (pageId == null || path == null) {
  205. throw Error('Any of _id and path must not be null.');
  206. }
  207. const pageToDuplicate = { pageId, path };
  208. onClickDuplicateMenuItem(pageToDuplicate);
  209. }, [onClickDuplicateMenuItem, page]);
  210. const renameMenuItemClickHandler = useCallback(async(_pageId: string): Promise<void> => {
  211. setRenameInputShown(true);
  212. }, []);
  213. const onPressEnterForRenameHandler = async(inputText: string) => {
  214. const parentPath = pathUtils.addTrailingSlash(nodePath.dirname(page.path ?? ''));
  215. const newPagePath = `${parentPath}${inputText}`;
  216. try {
  217. setRenameInputShown(false);
  218. await apiv3Put('/pages/rename', {
  219. pageId: page._id,
  220. revisionId: page.revision,
  221. newPagePath,
  222. isRenameRedirect: false,
  223. isRemainMetadata: false,
  224. });
  225. if (mutateAfterRenamed != null) {
  226. mutateAfterRenamed();
  227. }
  228. toastSuccess(t('renamed_pages', { newPagePath }));
  229. }
  230. catch (err) {
  231. setRenameInputShown(true);
  232. toastError(err);
  233. }
  234. };
  235. const deleteMenuItemClickHandler = useCallback(async(_pageId: string, pageInfo: IPageInfoAll | undefined): Promise<void> => {
  236. if (page._id == null || page.revision == null || page.path == null) {
  237. throw Error('Any of _id, revision, and path must not be null.');
  238. }
  239. const pageToDelete: IPageToDeleteWithMeta = {
  240. data: {
  241. _id: page._id,
  242. revision: page.revision as string,
  243. path: page.path,
  244. },
  245. meta: pageInfo,
  246. };
  247. if (onClickDeleteMenuItem != null) {
  248. onClickDeleteMenuItem(pageToDelete);
  249. }
  250. }, [onClickDeleteMenuItem, page]);
  251. const onPressEnterForCreateHandler = async(inputText: string) => {
  252. setNewPageInputShown(false);
  253. const parentPath = pathUtils.addTrailingSlash(page.path as string);
  254. const newPagePath = `${parentPath}${inputText}`;
  255. const isCreatable = pagePathUtils.isCreatablePage(newPagePath);
  256. if (!isCreatable) {
  257. toastWarning(t('you_can_not_create_page_with_this_name'));
  258. return;
  259. }
  260. let initBody = '';
  261. if (isEnabledAttachTitleHeader) {
  262. const pageTitle = pathUtils.addHeadingSlash(nodePath.basename(newPagePath));
  263. initBody = pathUtils.attachTitleHeader(pageTitle);
  264. }
  265. try {
  266. await apiv3Post('/pages/', {
  267. path: newPagePath,
  268. body: initBody,
  269. grant: page.grant,
  270. grantUserGroupId: page.grantedGroup,
  271. createFromPageTree: true,
  272. });
  273. mutateChildren();
  274. toastSuccess(t('successfully_saved_the_page'));
  275. }
  276. catch (err) {
  277. toastError(err);
  278. }
  279. };
  280. const inputValidator = (title: string | null): AlertInfo | null => {
  281. if (title == null || title === '' || title.trim() === '') {
  282. return {
  283. type: AlertType.WARNING,
  284. message: t('form_validation.title_required'),
  285. };
  286. }
  287. if (title.includes('/')) {
  288. return {
  289. type: AlertType.WARNING,
  290. message: t('form_validation.slashed_are_not_yet_supported'),
  291. };
  292. }
  293. return null;
  294. };
  295. useEffect(() => {
  296. if (!props.isScrolled && page.isTarget) {
  297. document.dispatchEvent(new CustomEvent('targetItemRendered'));
  298. }
  299. }, [props.isScrolled, page.isTarget]);
  300. // didMount
  301. useEffect(() => {
  302. if (hasChildren()) setIsOpen(true);
  303. }, [hasChildren]);
  304. /*
  305. * Make sure itemNode.children and currentChildren are synced
  306. */
  307. useEffect(() => {
  308. if (children.length > currentChildren.length) {
  309. markTarget(children, targetPathOrId);
  310. setCurrentChildren(children);
  311. }
  312. }, [children, currentChildren.length, targetPathOrId]);
  313. /*
  314. * When swr fetch succeeded
  315. */
  316. useEffect(() => {
  317. if (isOpen && data != null) {
  318. const newChildren = ItemNode.generateNodesFromPages(data.children);
  319. markTarget(newChildren, targetPathOrId);
  320. setCurrentChildren(newChildren);
  321. }
  322. }, [data, isOpen, targetPathOrId]);
  323. return (
  324. <div
  325. id={`pagetree-item-${page._id}`}
  326. className={`grw-pagetree-item-container ${isOver ? 'grw-pagetree-is-over' : ''}
  327. ${shouldHide ? 'd-none' : ''}`}
  328. >
  329. <li
  330. ref={(c) => { drag(c); drop(c) }}
  331. className={`list-group-item list-group-item-action border-0 py-0 d-flex align-items-center ${page.isTarget ? 'grw-pagetree-is-target' : ''}`}
  332. id={page.isTarget ? 'grw-pagetree-is-target' : `grw-pagetree-list-${page._id}`}
  333. >
  334. <div className="grw-triangle-container d-flex justify-content-center">
  335. {hasDescendants && (
  336. <button
  337. type="button"
  338. className={`grw-pagetree-button btn ${isOpen ? 'grw-pagetree-open' : ''}`}
  339. onClick={onClickLoadChildren}
  340. >
  341. <div className="grw-triangle-icon d-flex justify-content-center">
  342. <TriangleIcon />
  343. </div>
  344. </button>
  345. )}
  346. </div>
  347. { isRenameInputShown && (
  348. <ClosableTextInput
  349. isShown
  350. value={nodePath.basename(page.path ?? '')}
  351. placeholder={t('Input page name')}
  352. onClickOutside={() => { setRenameInputShown(false) }}
  353. onPressEnter={onPressEnterForRenameHandler}
  354. inputValidator={inputValidator}
  355. />
  356. )}
  357. { !isRenameInputShown && (
  358. <a href={`/${page._id}`} className="grw-pagetree-title-anchor flex-grow-1">
  359. <p className={`text-truncate m-auto ${page.isEmpty && 'text-muted'}`}>{nodePath.basename(page.path ?? '') || '/'}</p>
  360. </a>
  361. )}
  362. {(descendantCount > 0) && (
  363. <div className="grw-pagetree-count-wrapper">
  364. <ItemCount descendantCount={descendantCount} />
  365. </div>
  366. )}
  367. <div className="grw-pagetree-control d-flex">
  368. <PageItemControl
  369. pageId={page._id}
  370. isEnableActions={isEnableActions}
  371. onClickBookmarkMenuItem={bookmarkMenuItemClickHandler}
  372. onClickDuplicateMenuItem={duplicateMenuItemClickHandler}
  373. onClickRenameMenuItem={renameMenuItemClickHandler}
  374. onClickDeleteMenuItem={deleteMenuItemClickHandler}
  375. >
  376. {/* pass the color property to reactstrap dropdownToggle props. https://6-4-0--reactstrap.netlify.app/components/dropdowns/ */}
  377. <DropdownToggle color="transparent" className="border-0 rounded btn-page-item-control p-0 grw-visible-on-hover">
  378. <i className="icon-options fa fa-rotate-90 text-muted p-1"></i>
  379. </DropdownToggle>
  380. </PageItemControl>
  381. <button
  382. type="button"
  383. className="border-0 rounded btn btn-page-item-control p-0 grw-visible-on-hover"
  384. onClick={onClickPlusButton}
  385. >
  386. <i className="icon-plus text-muted d-block p-1" />
  387. </button>
  388. </div>
  389. </li>
  390. {isEnableActions && (
  391. <ClosableTextInput
  392. isShown={isNewPageInputShown}
  393. placeholder={t('Input page name')}
  394. onClickOutside={() => { setNewPageInputShown(false) }}
  395. onPressEnter={onPressEnterForCreateHandler}
  396. inputValidator={inputValidator}
  397. />
  398. )}
  399. {
  400. isOpen && hasChildren() && currentChildren.map(node => (
  401. <div key={node.page._id} className="grw-pagetree-item-children">
  402. <Item
  403. isEnableActions={isEnableActions}
  404. itemNode={node}
  405. isOpen={false}
  406. isScrolled={props.isScrolled}
  407. targetPathOrId={targetPathOrId}
  408. isEnabledAttachTitleHeader={isEnabledAttachTitleHeader}
  409. mutateAfterRenamed={mutateAfterRenamed}
  410. onClickDuplicateMenuItem={onClickDuplicateMenuItem}
  411. onClickDeleteMenuItem={onClickDeleteMenuItem}
  412. />
  413. </div>
  414. ))
  415. }
  416. </div>
  417. );
  418. };
  419. export default Item;