Item.tsx 15 KB

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