Item.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  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. isOpen?: boolean
  29. isEnabledAttachTitleHeader?: boolean
  30. onRenamed?(): void
  31. onClickDuplicateMenuItem?(pageToDuplicate: IPageForPageDuplicateModal): void
  32. onClickDeleteMenuItem?(pageToDelete: IPageToDeleteWithMeta): void
  33. }
  34. // Utility to mark target
  35. const markTarget = (children: ItemNode[], targetPathOrId?: string): void => {
  36. if (targetPathOrId == null) {
  37. return;
  38. }
  39. children.forEach((node) => {
  40. if (node.page._id === targetPathOrId || node.page.path === targetPathOrId) {
  41. node.page.isTarget = true;
  42. }
  43. return node;
  44. });
  45. };
  46. const bookmarkMenuItemClickHandler = async(_pageId: string, _newValue: boolean): Promise<void> => {
  47. const bookmarkOperation = _newValue ? bookmark : unbookmark;
  48. await bookmarkOperation(_pageId);
  49. };
  50. /**
  51. * Return new page path after the droppedPagePath is moved under the newParentPagePath
  52. * @param droppedPagePath
  53. * @param newParentPagePath
  54. * @returns
  55. */
  56. const getNewPathAfterMoved = (droppedPagePath: string, newParentPagePath: string): string => {
  57. const pageTitle = nodePath.basename(droppedPagePath);
  58. return nodePath.join(newParentPagePath, pageTitle);
  59. };
  60. /**
  61. * Return whether the fromPage could be moved under the newParentPage
  62. * @param fromPage
  63. * @param newParentPage
  64. * @param printLog
  65. * @returns
  66. */
  67. const canMoveUnderNewParent = (fromPage?: Partial<IPageHasId>, newParentPage?: Partial<IPageHasId>, printLog = false): boolean => {
  68. if (fromPage == null || newParentPage == null || fromPage.path == null || newParentPage.path == null) {
  69. if (printLog) {
  70. logger.warn('Any of page, page.path or droppedPage.path is null');
  71. }
  72. return false;
  73. }
  74. const newPathAfterMoved = getNewPathAfterMoved(fromPage.path, newParentPage.path);
  75. return pagePathUtils.canMoveByPath(fromPage.path, newPathAfterMoved);
  76. };
  77. type ItemCountProps = {
  78. descendantCount: number
  79. }
  80. const ItemCount: FC<ItemCountProps> = (props:ItemCountProps) => {
  81. return (
  82. <>
  83. <span className="grw-pagetree-count px-0 badge badge-pill badge-light">
  84. {props.descendantCount}
  85. </span>
  86. </>
  87. );
  88. };
  89. const Item: FC<ItemProps> = (props: ItemProps) => {
  90. const { t } = useTranslation();
  91. const {
  92. itemNode, targetPathOrId, isOpen: _isOpen = false, isEnabledAttachTitleHeader,
  93. onRenamed, onClickDuplicateMenuItem, onClickDeleteMenuItem, isEnableActions,
  94. } = props;
  95. const { page, children } = itemNode;
  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 [isRenameInputShown, setRenameInputShown] = useState(false);
  101. const [isRenaming, setRenaming] = useState(false);
  102. const [isCreating, setCreating] = useState(false);
  103. const { data, mutate: mutateChildren } = useSWRxPageChildren(isOpen ? page._id : null);
  104. // descendantCount
  105. const { getDescCount } = usePageTreeDescCountMap();
  106. const descendantCount = getDescCount(page._id) || page.descendantCount || 0;
  107. // hasDescendants flag
  108. const isChildrenLoaded = currentChildren?.length > 0;
  109. const hasDescendants = descendantCount > 0 || isChildrenLoaded;
  110. // to re-show hidden item when useDrag end() callback
  111. const displayDroppedItemByPageId = useCallback((pageId) => {
  112. const target = document.getElementById(`pagetree-item-${pageId}`);
  113. if (target == null) {
  114. return;
  115. }
  116. // wait 500ms to avoid removing before d-none is set by useDrag end() callback
  117. setTimeout(() => {
  118. target.classList.remove('d-none');
  119. }, 500);
  120. }, []);
  121. const [, drag] = useDrag({
  122. type: 'PAGE_TREE',
  123. item: { page },
  124. canDrag: () => {
  125. const isDraggable = !pagePathUtils.isUserPage(page.path || '/');
  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. updateMetadata: true,
  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. }, 600);
  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. const renameMenuItemClickHandler = useCallback(() => {
  214. setRenameInputShown(true);
  215. }, []);
  216. const onPressEnterForRenameHandler = async(inputText: string) => {
  217. const parentPath = pathUtils.addTrailingSlash(nodePath.dirname(page.path ?? ''));
  218. const newPagePath = nodePath.resolve(parentPath, inputText);
  219. if (newPagePath === page.path) {
  220. setRenameInputShown(false);
  221. return;
  222. }
  223. try {
  224. setRenameInputShown(false);
  225. setRenaming(true);
  226. await apiv3Put('/pages/rename', {
  227. pageId: page._id,
  228. revisionId: page.revision,
  229. newPagePath,
  230. });
  231. if (onRenamed != null) {
  232. onRenamed();
  233. }
  234. toastSuccess(t('renamed_pages', { path: page.path }));
  235. }
  236. catch (err) {
  237. setRenameInputShown(true);
  238. toastError(err);
  239. }
  240. finally {
  241. setTimeout(() => {
  242. setRenaming(false);
  243. }, 1000);
  244. }
  245. };
  246. const deleteMenuItemClickHandler = useCallback(async(_pageId: string, pageInfo: IPageInfoAll | undefined): Promise<void> => {
  247. if (onClickDeleteMenuItem == null) {
  248. return;
  249. }
  250. if (page._id == null || page.revision == null || page.path == null) {
  251. throw Error('Any of _id, revision, and path must not be null.');
  252. }
  253. const pageToDelete: IPageToDeleteWithMeta = {
  254. data: {
  255. _id: page._id,
  256. revision: page.revision as string,
  257. path: page.path,
  258. },
  259. meta: pageInfo,
  260. };
  261. onClickDeleteMenuItem(pageToDelete);
  262. }, [onClickDeleteMenuItem, page]);
  263. const onPressEnterForCreateHandler = async(inputText: string) => {
  264. setNewPageInputShown(false);
  265. const parentPath = pathUtils.addTrailingSlash(page.path as string);
  266. const newPagePath = nodePath.resolve(parentPath, inputText);
  267. const isCreatable = pagePathUtils.isCreatablePage(newPagePath);
  268. if (!isCreatable) {
  269. toastWarning(t('you_can_not_create_page_with_this_name'));
  270. return;
  271. }
  272. let initBody = '';
  273. if (isEnabledAttachTitleHeader) {
  274. const pageTitle = nodePath.basename(newPagePath);
  275. initBody = pathUtils.attachTitleHeader(pageTitle);
  276. }
  277. try {
  278. // force open
  279. setIsOpen(true);
  280. setCreating(true);
  281. await apiv3Post('/pages/', {
  282. path: newPagePath,
  283. body: initBody,
  284. grant: page.grant,
  285. grantUserGroupId: page.grantedGroup,
  286. createFromPageTree: true,
  287. });
  288. toastSuccess(t('successfully_saved_the_page'));
  289. }
  290. catch (err) {
  291. toastError(err);
  292. }
  293. finally {
  294. setTimeout(() => {
  295. setCreating(false);
  296. }, 500);
  297. }
  298. };
  299. const inputValidator = (title: string | null): AlertInfo | null => {
  300. if (title == null || title === '' || title.trim() === '') {
  301. return {
  302. type: AlertType.WARNING,
  303. message: t('form_validation.title_required'),
  304. };
  305. }
  306. if (title.includes('/')) {
  307. return {
  308. type: AlertType.WARNING,
  309. message: t('form_validation.slashed_are_not_yet_supported'),
  310. };
  311. }
  312. return null;
  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. return (
  338. <div
  339. id={`pagetree-item-${page._id}`}
  340. className={`grw-pagetree-item-container ${isOver ? 'grw-pagetree-is-over' : ''}
  341. ${shouldHide ? 'd-none' : ''}`}
  342. >
  343. <li
  344. ref={(c) => { drag(c); drop(c) }}
  345. className={`list-group-item list-group-item-action border-0 py-0 pr-3 d-flex align-items-center
  346. ${page.isTarget ? 'grw-pagetree-current-page-item' : ''}`}
  347. id={page.isTarget ? 'grw-pagetree-current-page-item' : `grw-pagetree-list-${page._id}`}
  348. >
  349. <div className="grw-triangle-container d-flex justify-content-center">
  350. {hasDescendants && (
  351. <button
  352. type="button"
  353. className={`grw-pagetree-triangle-btn btn ${isOpen ? 'grw-pagetree-open' : ''}`}
  354. onClick={onClickLoadChildren}
  355. >
  356. <div className="d-flex justify-content-center">
  357. <TriangleIcon />
  358. </div>
  359. </button>
  360. )}
  361. </div>
  362. { isRenameInputShown
  363. ? (
  364. <ClosableTextInput
  365. value={nodePath.basename(page.path ?? '')}
  366. placeholder={t('Input page name')}
  367. onClickOutside={() => { setRenameInputShown(false) }}
  368. onPressEnter={onPressEnterForRenameHandler}
  369. inputValidator={inputValidator}
  370. />
  371. )
  372. : (
  373. <>
  374. { isRenaming && (
  375. <i className="fa fa-spinner fa-pulse mr-2 text-muted"></i>
  376. )}
  377. <a href={`/${page._id}`} className="grw-pagetree-title-anchor flex-grow-1">
  378. <p className={`text-truncate m-auto ${page.isEmpty && 'text-muted'}`}>{nodePath.basename(page.path ?? '') || '/'}</p>
  379. </a>
  380. </>
  381. )}
  382. {descendantCount > 0 && !isRenameInputShown && (
  383. <div className="grw-pagetree-count-wrapper">
  384. <ItemCount descendantCount={descendantCount} />
  385. </div>
  386. )}
  387. <div className="grw-pagetree-control d-flex">
  388. <PageItemControl
  389. pageId={page._id}
  390. isEnableActions={isEnableActions}
  391. onClickBookmarkMenuItem={bookmarkMenuItemClickHandler}
  392. onClickDuplicateMenuItem={duplicateMenuItemClickHandler}
  393. onClickRenameMenuItem={renameMenuItemClickHandler}
  394. onClickDeleteMenuItem={deleteMenuItemClickHandler}
  395. >
  396. {/* pass the color property to reactstrap dropdownToggle props. https://6-4-0--reactstrap.netlify.app/components/dropdowns/ */}
  397. <DropdownToggle color="transparent" className="border-0 rounded btn-page-item-control p-0 grw-visible-on-hover mr-1">
  398. <i className="icon-options fa fa-rotate-90 p-1"></i>
  399. </DropdownToggle>
  400. </PageItemControl>
  401. <button
  402. type="button"
  403. className="border-0 rounded btn btn-page-item-control p-0 grw-visible-on-hover"
  404. onClick={onClickPlusButton}
  405. >
  406. <i className="icon-plus d-block p-0" />
  407. </button>
  408. </div>
  409. </li>
  410. {isEnableActions && isNewPageInputShown && (
  411. <ClosableTextInput
  412. placeholder={t('Input page name')}
  413. onClickOutside={() => { setNewPageInputShown(false) }}
  414. onPressEnter={onPressEnterForCreateHandler}
  415. inputValidator={inputValidator}
  416. />
  417. )}
  418. {
  419. isOpen && hasChildren() && currentChildren.map((node, index) => (
  420. <div key={node.page._id} className="grw-pagetree-item-children">
  421. <Item
  422. isEnableActions={isEnableActions}
  423. itemNode={node}
  424. isOpen={false}
  425. targetPathOrId={targetPathOrId}
  426. isEnabledAttachTitleHeader={isEnabledAttachTitleHeader}
  427. onRenamed={onRenamed}
  428. onClickDuplicateMenuItem={onClickDuplicateMenuItem}
  429. onClickDeleteMenuItem={onClickDeleteMenuItem}
  430. />
  431. { isCreating && (currentChildren.length - 1 === index) && (
  432. <div className="text-muted text-center">
  433. <i className="fa fa-spinner fa-pulse mr-1"></i>
  434. </div>
  435. )}
  436. </div>
  437. ))
  438. }
  439. </div>
  440. );
  441. };
  442. export default Item;