Item.tsx 16 KB

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