Item.tsx 16 KB

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