Item.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  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. onRenamed?(): 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. onRenamed, 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(() => {
  211. setRenameInputShown(true);
  212. }, []);
  213. const onPressEnterForRenameHandler = async(inputText: string) => {
  214. const parentPath = pathUtils.addTrailingSlash(nodePath.dirname(page.path ?? ''));
  215. const newPagePath = nodePath.resolve(parentPath, inputText);
  216. if (newPagePath === page.path) {
  217. setRenameInputShown(false);
  218. return;
  219. }
  220. try {
  221. setRenameInputShown(false);
  222. await apiv3Put('/pages/rename', {
  223. pageId: page._id,
  224. revisionId: page.revision,
  225. newPagePath,
  226. });
  227. if (onRenamed != null) {
  228. onRenamed();
  229. }
  230. toastSuccess(t('renamed_pages', { path: page.path }));
  231. }
  232. catch (err) {
  233. setRenameInputShown(true);
  234. toastError(err);
  235. }
  236. };
  237. const deleteMenuItemClickHandler = useCallback(async(_pageId: string, pageInfo: IPageInfoAll | undefined): Promise<void> => {
  238. if (page._id == null || page.revision == null || page.path == null) {
  239. throw Error('Any of _id, revision, and path must not be null.');
  240. }
  241. const pageToDelete: IPageToDeleteWithMeta = {
  242. data: {
  243. _id: page._id,
  244. revision: page.revision as string,
  245. path: page.path,
  246. },
  247. meta: pageInfo,
  248. };
  249. if (onClickDeleteMenuItem != null) {
  250. onClickDeleteMenuItem(pageToDelete);
  251. }
  252. }, [onClickDeleteMenuItem, page]);
  253. const onPressEnterForCreateHandler = async(inputText: string) => {
  254. setNewPageInputShown(false);
  255. const parentPath = pathUtils.addTrailingSlash(page.path as string);
  256. const newPagePath = `${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 = pathUtils.addHeadingSlash(nodePath.basename(newPagePath));
  265. initBody = pathUtils.attachTitleHeader(pageTitle);
  266. }
  267. try {
  268. await apiv3Post('/pages/', {
  269. path: newPagePath,
  270. body: initBody,
  271. grant: page.grant,
  272. grantUserGroupId: page.grantedGroup,
  273. createFromPageTree: true,
  274. });
  275. mutateChildren();
  276. toastSuccess(t('successfully_saved_the_page'));
  277. }
  278. catch (err) {
  279. toastError(err);
  280. }
  281. };
  282. const inputValidator = (title: string | null): AlertInfo | null => {
  283. if (title == null || title === '' || title.trim() === '') {
  284. return {
  285. type: AlertType.WARNING,
  286. message: t('form_validation.title_required'),
  287. };
  288. }
  289. if (title.includes('/')) {
  290. return {
  291. type: AlertType.WARNING,
  292. message: t('form_validation.slashed_are_not_yet_supported'),
  293. };
  294. }
  295. return null;
  296. };
  297. useEffect(() => {
  298. if (!props.isScrolled && page.isTarget) {
  299. document.dispatchEvent(new CustomEvent('targetItemRendered'));
  300. }
  301. }, [props.isScrolled, page.isTarget]);
  302. // didMount
  303. useEffect(() => {
  304. if (hasChildren()) setIsOpen(true);
  305. }, [hasChildren]);
  306. /*
  307. * Make sure itemNode.children and currentChildren are synced
  308. */
  309. useEffect(() => {
  310. if (children.length > currentChildren.length) {
  311. markTarget(children, targetPathOrId);
  312. setCurrentChildren(children);
  313. }
  314. }, [children, currentChildren.length, targetPathOrId]);
  315. /*
  316. * When swr fetch succeeded
  317. */
  318. useEffect(() => {
  319. if (isOpen && data != null) {
  320. const newChildren = ItemNode.generateNodesFromPages(data.children);
  321. markTarget(newChildren, targetPathOrId);
  322. setCurrentChildren(newChildren);
  323. }
  324. }, [data, isOpen, targetPathOrId]);
  325. return (
  326. <div
  327. id={`pagetree-item-${page._id}`}
  328. className={`grw-pagetree-item-container ${isOver ? 'grw-pagetree-is-over' : ''}
  329. ${shouldHide ? 'd-none' : ''}`}
  330. >
  331. <li
  332. ref={(c) => { drag(c); drop(c) }}
  333. className={`list-group-item list-group-item-action border-0 py-0 d-flex align-items-center ${page.isTarget ? 'grw-pagetree-is-target' : ''}`}
  334. id={page.isTarget ? 'grw-pagetree-is-target' : `grw-pagetree-list-${page._id}`}
  335. >
  336. <div className="grw-triangle-container d-flex justify-content-center">
  337. {hasDescendants && (
  338. <button
  339. type="button"
  340. className={`grw-pagetree-button btn ${isOpen ? 'grw-pagetree-open' : ''}`}
  341. onClick={onClickLoadChildren}
  342. >
  343. <div className="grw-triangle-icon d-flex justify-content-center">
  344. <TriangleIcon />
  345. </div>
  346. </button>
  347. )}
  348. </div>
  349. { isRenameInputShown && (
  350. <ClosableTextInput
  351. isShown
  352. value={nodePath.basename(page.path ?? '')}
  353. placeholder={t('Input page name')}
  354. onClickOutside={() => { setRenameInputShown(false) }}
  355. onPressEnter={onPressEnterForRenameHandler}
  356. inputValidator={inputValidator}
  357. />
  358. )}
  359. { !isRenameInputShown && (
  360. <a href={`/${page._id}`} className="grw-pagetree-title-anchor flex-grow-1">
  361. <p className={`text-truncate m-auto ${page.isEmpty && 'text-muted'}`}>{nodePath.basename(page.path ?? '') || '/'}</p>
  362. </a>
  363. )}
  364. {(descendantCount > 0) && (
  365. <div className="grw-pagetree-count-wrapper">
  366. <ItemCount descendantCount={descendantCount} />
  367. </div>
  368. )}
  369. <div className="grw-pagetree-control d-flex">
  370. <PageItemControl
  371. pageId={page._id}
  372. isEnableActions={isEnableActions}
  373. onClickBookmarkMenuItem={bookmarkMenuItemClickHandler}
  374. onClickDuplicateMenuItem={duplicateMenuItemClickHandler}
  375. onClickRenameMenuItem={renameMenuItemClickHandler}
  376. onClickDeleteMenuItem={deleteMenuItemClickHandler}
  377. >
  378. {/* pass the color property to reactstrap dropdownToggle props. https://6-4-0--reactstrap.netlify.app/components/dropdowns/ */}
  379. <DropdownToggle color="transparent" className="border-0 rounded btn-page-item-control p-0 grw-visible-on-hover">
  380. <i className="icon-options fa fa-rotate-90 text-muted p-1"></i>
  381. </DropdownToggle>
  382. </PageItemControl>
  383. <button
  384. type="button"
  385. className="border-0 rounded btn btn-page-item-control p-0 grw-visible-on-hover"
  386. onClick={onClickPlusButton}
  387. >
  388. <i className="icon-plus text-muted d-block p-1" />
  389. </button>
  390. </div>
  391. </li>
  392. {isEnableActions && (
  393. <ClosableTextInput
  394. isShown={isNewPageInputShown}
  395. placeholder={t('Input page name')}
  396. onClickOutside={() => { setNewPageInputShown(false) }}
  397. onPressEnter={onPressEnterForCreateHandler}
  398. inputValidator={inputValidator}
  399. />
  400. )}
  401. {
  402. isOpen && hasChildren() && currentChildren.map(node => (
  403. <div key={node.page._id} className="grw-pagetree-item-children">
  404. <Item
  405. isEnableActions={isEnableActions}
  406. itemNode={node}
  407. isOpen={false}
  408. isScrolled={props.isScrolled}
  409. targetPathOrId={targetPathOrId}
  410. isEnabledAttachTitleHeader={isEnabledAttachTitleHeader}
  411. onRenamed={onRenamed}
  412. onClickDuplicateMenuItem={onClickDuplicateMenuItem}
  413. onClickDeleteMenuItem={onClickDeleteMenuItem}
  414. />
  415. </div>
  416. ))
  417. }
  418. </div>
  419. );
  420. };
  421. export default Item;