Item.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. import React, {
  2. useCallback, useState, FC, useEffect,
  3. } from 'react';
  4. import nodePath from 'path';
  5. import { pathUtils, pagePathUtils } from '@growi/core';
  6. import { useDrag, useDrop } from 'react-dnd';
  7. import { useTranslation } from 'react-i18next';
  8. import { DropdownToggle } from 'reactstrap';
  9. import { bookmark, unbookmark } from '~/client/services/page-operation';
  10. import { toastWarning, toastError, toastSuccess } from '~/client/util/apiNotification';
  11. import { apiv3Put, apiv3Post } from '~/client/util/apiv3-client';
  12. import TriangleIcon from '~/components/Icons/TriangleIcon';
  13. import {
  14. IPageHasId, IPageInfoAll, IPageToDeleteWithMeta,
  15. } from '~/interfaces/page';
  16. import { IPageForPageDuplicateModal } from '~/stores/modal';
  17. import { useSWRxPageChildren } from '~/stores/page-listing';
  18. import { usePageTreeDescCountMap } from '~/stores/ui';
  19. import loggerFactory from '~/utils/logger';
  20. import ClosableTextInput, { AlertInfo, AlertType } from '../../Common/ClosableTextInput';
  21. import CountBadge from '../../Common/CountBadge';
  22. import { PageItemControl } from '../../Common/Dropdown/PageItemControl';
  23. import { ItemNode } from './ItemNode';
  24. const logger = loggerFactory('growi:cli:Item');
  25. interface ItemProps {
  26. isEnableActions: boolean
  27. itemNode: ItemNode
  28. targetPathOrId?: string
  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 isDroppable = (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) && !pagePathUtils.isUsersTopPage(newParentPage.path);
  77. };
  78. const Item: FC<ItemProps> = (props: ItemProps) => {
  79. const { t } = useTranslation();
  80. const {
  81. itemNode, targetPathOrId, isOpen: _isOpen = false, isEnabledAttachTitleHeader,
  82. onRenamed, onClickDuplicateMenuItem, onClickDeleteMenuItem, isEnableActions,
  83. } = props;
  84. const { page, children } = itemNode;
  85. const [currentChildren, setCurrentChildren] = useState(children);
  86. const [isOpen, setIsOpen] = useState(_isOpen);
  87. const [isNewPageInputShown, setNewPageInputShown] = useState(false);
  88. const [shouldHide, setShouldHide] = useState(false);
  89. const [isRenameInputShown, setRenameInputShown] = useState(false);
  90. const [isRenaming, setRenaming] = useState(false);
  91. const [isCreating, setCreating] = useState(false);
  92. const { data, mutate: mutateChildren } = useSWRxPageChildren(isOpen ? page._id : null);
  93. // descendantCount
  94. const { getDescCount } = usePageTreeDescCountMap();
  95. const descendantCount = getDescCount(page._id) || page.descendantCount || 0;
  96. // hasDescendants flag
  97. const isChildrenLoaded = currentChildren?.length > 0;
  98. const hasDescendants = descendantCount > 0 || isChildrenLoaded;
  99. // to re-show hidden item when useDrag end() callback
  100. const displayDroppedItemByPageId = useCallback((pageId) => {
  101. const target = document.getElementById(`pagetree-item-${pageId}`);
  102. if (target == null) {
  103. return;
  104. }
  105. // wait 500ms to avoid removing before d-none is set by useDrag end() callback
  106. setTimeout(() => {
  107. target.classList.remove('d-none');
  108. }, 500);
  109. }, []);
  110. const [, drag] = useDrag({
  111. type: 'PAGE_TREE',
  112. item: { page },
  113. canDrag: () => {
  114. if (page.path == null) {
  115. return false;
  116. }
  117. return !pagePathUtils.isUsersProtectedPages(page.path);
  118. },
  119. end: (item, monitor) => {
  120. // in order to set d-none to dropped Item
  121. const dropResult = monitor.getDropResult();
  122. if (dropResult != null) {
  123. setShouldHide(true);
  124. }
  125. },
  126. collect: monitor => ({
  127. isDragging: monitor.isDragging(),
  128. canDrag: monitor.canDrag(),
  129. }),
  130. });
  131. const pageItemDropHandler = async(item: ItemNode) => {
  132. const { page: droppedPage } = item;
  133. if (!isDroppable(droppedPage, page, true)) {
  134. return;
  135. }
  136. if (droppedPage.path == null || page.path == null) {
  137. return;
  138. }
  139. const newPagePath = getNewPathAfterMoved(droppedPage.path, page.path);
  140. try {
  141. await apiv3Put('/pages/rename', {
  142. pageId: droppedPage._id,
  143. revisionId: droppedPage.revision,
  144. newPagePath,
  145. isRenameRedirect: false,
  146. updateMetadata: true,
  147. });
  148. await mutateChildren();
  149. if (onRenamed != null) {
  150. onRenamed();
  151. }
  152. // force open
  153. setIsOpen(true);
  154. }
  155. catch (err) {
  156. // display the dropped item
  157. displayDroppedItemByPageId(droppedPage._id);
  158. if (err.code === 'operation__blocked') {
  159. toastWarning(t('pagetree.you_cannot_move_this_page_now'));
  160. }
  161. else {
  162. toastError(t('pagetree.something_went_wrong_with_moving_page'));
  163. }
  164. }
  165. };
  166. const [{ isOver }, drop] = useDrop<ItemNode, Promise<void>, { isOver: boolean }>(() => ({
  167. accept: 'PAGE_TREE',
  168. drop: pageItemDropHandler,
  169. hover: (item, monitor) => {
  170. // when a drag item is overlapped more than 1 sec, the drop target item will be opened.
  171. if (monitor.isOver()) {
  172. setTimeout(() => {
  173. if (monitor.isOver()) {
  174. setIsOpen(true);
  175. }
  176. }, 600);
  177. }
  178. },
  179. canDrop: (item) => {
  180. const { page: droppedPage } = item;
  181. return isDroppable(droppedPage, page);
  182. },
  183. collect: monitor => ({
  184. isOver: monitor.isOver(),
  185. }),
  186. }));
  187. const hasChildren = useCallback((): boolean => {
  188. return currentChildren != null && currentChildren.length > 0;
  189. }, [currentChildren]);
  190. const onClickLoadChildren = useCallback(async() => {
  191. setIsOpen(!isOpen);
  192. }, [isOpen]);
  193. const onClickPlusButton = useCallback(() => {
  194. setNewPageInputShown(true);
  195. if (hasDescendants) {
  196. setIsOpen(true);
  197. }
  198. }, [hasDescendants]);
  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. setRenaming(true);
  223. await apiv3Put('/pages/rename', {
  224. pageId: page._id,
  225. revisionId: page.revision,
  226. newPagePath,
  227. });
  228. if (onRenamed != null) {
  229. onRenamed();
  230. }
  231. toastSuccess(t('renamed_pages', { path: page.path }));
  232. }
  233. catch (err) {
  234. setRenameInputShown(true);
  235. toastError(err);
  236. }
  237. finally {
  238. setTimeout(() => {
  239. setRenaming(false);
  240. }, 1000);
  241. }
  242. };
  243. const deleteMenuItemClickHandler = useCallback(async(_pageId: string, pageInfo: IPageInfoAll | undefined): Promise<void> => {
  244. if (onClickDeleteMenuItem == null) {
  245. return;
  246. }
  247. if (page._id == null || page.revision == null || page.path == null) {
  248. throw Error('Any of _id, revision, and path must not be null.');
  249. }
  250. const pageToDelete: IPageToDeleteWithMeta = {
  251. data: {
  252. _id: page._id,
  253. revision: page.revision as string,
  254. path: page.path,
  255. },
  256. meta: pageInfo,
  257. };
  258. onClickDeleteMenuItem(pageToDelete);
  259. }, [onClickDeleteMenuItem, page]);
  260. const onPressEnterForCreateHandler = async(inputText: string) => {
  261. setNewPageInputShown(false);
  262. const parentPath = pathUtils.addTrailingSlash(page.path as string);
  263. const newPagePath = nodePath.resolve(parentPath, inputText);
  264. const isCreatable = pagePathUtils.isCreatablePage(newPagePath);
  265. if (!isCreatable) {
  266. toastWarning(t('you_can_not_create_page_with_this_name'));
  267. return;
  268. }
  269. let initBody = '';
  270. if (isEnabledAttachTitleHeader) {
  271. const pageTitle = nodePath.basename(newPagePath);
  272. initBody = pathUtils.attachTitleHeader(pageTitle);
  273. }
  274. try {
  275. setCreating(true);
  276. await apiv3Post('/pages/', {
  277. path: newPagePath,
  278. body: initBody,
  279. grant: page.grant,
  280. grantUserGroupId: page.grantedGroup,
  281. createFromPageTree: true,
  282. });
  283. mutateChildren();
  284. if (!hasDescendants) {
  285. setIsOpen(true);
  286. }
  287. toastSuccess(t('successfully_saved_the_page'));
  288. }
  289. catch (err) {
  290. toastError(err);
  291. }
  292. finally {
  293. setCreating(false);
  294. }
  295. };
  296. const inputValidator = (title: string | null): AlertInfo | null => {
  297. if (title == null || title === '' || title.trim() === '') {
  298. return {
  299. type: AlertType.WARNING,
  300. message: t('form_validation.title_required'),
  301. };
  302. }
  303. if (title.includes('/')) {
  304. return {
  305. type: AlertType.WARNING,
  306. message: t('form_validation.slashed_are_not_yet_supported'),
  307. };
  308. }
  309. return null;
  310. };
  311. // didMount
  312. useEffect(() => {
  313. if (hasChildren()) setIsOpen(true);
  314. }, [hasChildren]);
  315. /*
  316. * Make sure itemNode.children and currentChildren are synced
  317. */
  318. useEffect(() => {
  319. if (children.length > currentChildren.length) {
  320. markTarget(children, targetPathOrId);
  321. setCurrentChildren(children);
  322. }
  323. }, [children, currentChildren.length, targetPathOrId]);
  324. /*
  325. * When swr fetch succeeded
  326. */
  327. useEffect(() => {
  328. if (isOpen && data != null) {
  329. const newChildren = ItemNode.generateNodesFromPages(data.children);
  330. markTarget(newChildren, targetPathOrId);
  331. setCurrentChildren(newChildren);
  332. }
  333. }, [data, isOpen, targetPathOrId]);
  334. return (
  335. <div
  336. id={`pagetree-item-${page._id}`}
  337. className={`grw-pagetree-item-container ${isOver ? 'grw-pagetree-is-over' : ''}
  338. ${shouldHide ? 'd-none' : ''}`}
  339. >
  340. <li
  341. ref={(c) => { drag(c); drop(c) }}
  342. className={`list-group-item list-group-item-action border-0 py-0 pr-3 d-flex align-items-center
  343. ${page.isTarget ? 'grw-pagetree-current-page-item' : ''}`}
  344. id={page.isTarget ? 'grw-pagetree-current-page-item' : `grw-pagetree-list-${page._id}`}
  345. >
  346. <div className="grw-triangle-container d-flex justify-content-center">
  347. {hasDescendants && (
  348. <button
  349. type="button"
  350. className={`grw-pagetree-triangle-btn btn ${isOpen ? 'grw-pagetree-open' : ''}`}
  351. onClick={onClickLoadChildren}
  352. >
  353. <div className="d-flex justify-content-center">
  354. <TriangleIcon />
  355. </div>
  356. </button>
  357. )}
  358. </div>
  359. { isRenameInputShown
  360. ? (
  361. <ClosableTextInput
  362. value={nodePath.basename(page.path ?? '')}
  363. placeholder={t('Input page name')}
  364. onClickOutside={() => { setRenameInputShown(false) }}
  365. onPressEnter={onPressEnterForRenameHandler}
  366. inputValidator={inputValidator}
  367. />
  368. )
  369. : (
  370. <>
  371. { isRenaming && (
  372. <i className="fa fa-spinner fa-pulse mr-2 text-muted"></i>
  373. )}
  374. <a href={`/${page._id}`} className="grw-pagetree-title-anchor flex-grow-1">
  375. <p className={`text-truncate m-auto ${page.isEmpty && 'text-muted'}`}>{nodePath.basename(page.path ?? '') || '/'}</p>
  376. </a>
  377. </>
  378. )}
  379. {descendantCount > 0 && !isRenameInputShown && (
  380. <div className="grw-pagetree-count-wrapper">
  381. <CountBadge count={descendantCount} />
  382. </div>
  383. )}
  384. <div className="grw-pagetree-control d-flex">
  385. <PageItemControl
  386. pageId={page._id}
  387. isEnableActions={isEnableActions}
  388. onClickBookmarkMenuItem={bookmarkMenuItemClickHandler}
  389. onClickDuplicateMenuItem={duplicateMenuItemClickHandler}
  390. onClickRenameMenuItem={renameMenuItemClickHandler}
  391. onClickDeleteMenuItem={deleteMenuItemClickHandler}
  392. isInstantRename
  393. >
  394. {/* pass the color property to reactstrap dropdownToggle props. https://6-4-0--reactstrap.netlify.app/components/dropdowns/ */}
  395. <DropdownToggle color="transparent" className="border-0 rounded btn-page-item-control p-0 grw-visible-on-hover mr-1">
  396. <i className="icon-options fa fa-rotate-90 p-1"></i>
  397. </DropdownToggle>
  398. </PageItemControl>
  399. {!pagePathUtils.isUsersTopPage(page.path ?? '') && (
  400. <button
  401. type="button"
  402. className="border-0 rounded btn btn-page-item-control p-0 grw-visible-on-hover"
  403. onClick={onClickPlusButton}
  404. >
  405. <i className="icon-plus d-block p-0" />
  406. </button>
  407. )}
  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;