SimpleItem.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  1. import React, {
  2. useCallback, useState, FC, useEffect, ReactNode,
  3. } from 'react';
  4. import nodePath from 'path';
  5. import {
  6. pathUtils, pagePathUtils, Nullable,
  7. } from '@growi/core';
  8. import { useTranslation } from 'next-i18next';
  9. import Link from 'next/link';
  10. import { useRouter } from 'next/router';
  11. import { ConnectDragSource, useDrag, useDrop } from 'react-dnd';
  12. import { UncontrolledTooltip, DropdownToggle } from 'reactstrap';
  13. import { bookmark, unbookmark, resumeRenameOperation } from '~/client/services/page-operation';
  14. import { apiv3Put, apiv3Post } from '~/client/util/apiv3-client';
  15. import { ValidationTarget } from '~/client/util/input-validator';
  16. import { toastWarning, toastError, toastSuccess } from '~/client/util/toastr';
  17. import { TriangleIcon } from '~/components/Icons/TriangleIcon';
  18. import { NotAvailableForGuest } from '~/components/NotAvailableForGuest';
  19. import { NotAvailableForReadOnlyUser } from '~/components/NotAvailableForReadOnlyUser';
  20. import {
  21. IPageHasId, IPageInfoAll, IPageToDeleteWithMeta,
  22. } from '~/interfaces/page';
  23. import { useSWRMUTxCurrentUserBookmarks } from '~/stores/bookmark';
  24. import { IPageForPageDuplicateModal } from '~/stores/modal';
  25. import { useSWRMUTxPageInfo } from '~/stores/page';
  26. import { mutatePageTree, useSWRxPageChildren } from '~/stores/page-listing';
  27. import { usePageTreeDescCountMap } from '~/stores/ui';
  28. import loggerFactory from '~/utils/logger';
  29. import { shouldRecoverPagePaths } from '~/utils/page-operation';
  30. import ClosableTextInput from '../../Common/ClosableTextInput';
  31. import CountBadge from '../../Common/CountBadge';
  32. import { PageItemControl } from '../../Common/Dropdown/PageItemControl';
  33. import { ItemNode } from './ItemNode';
  34. const logger = loggerFactory('growi:cli:Item');
  35. interface ItemProps {
  36. isEnableActions: boolean
  37. isReadOnlyUser: boolean
  38. itemNode: ItemNode
  39. targetPathOrId?: Nullable<string>
  40. isOpen?: boolean
  41. onRenamed?(fromPath: string | undefined, toPath: string): void
  42. onClickDuplicateMenuItem?(pageToDuplicate: IPageForPageDuplicateModal): void
  43. onClickDeleteMenuItem?(pageToDelete: IPageToDeleteWithMeta): void
  44. itemRef?
  45. }
  46. // Utility to mark target
  47. const markTarget = (children: ItemNode[], targetPathOrId?: Nullable<string>): void => {
  48. if (targetPathOrId == null) {
  49. return;
  50. }
  51. children.forEach((node) => {
  52. if (node.page._id === targetPathOrId || node.page.path === targetPathOrId) {
  53. node.page.isTarget = true;
  54. }
  55. else {
  56. node.page.isTarget = false;
  57. }
  58. return node;
  59. });
  60. };
  61. /**
  62. * Return new page path after the droppedPagePath is moved under the newParentPagePath
  63. * @param droppedPagePath
  64. * @param newParentPagePath
  65. * @returns
  66. */
  67. //
  68. const getNewPathAfterMoved = (droppedPagePath: string, newParentPagePath: string): string => {
  69. const pageTitle = nodePath.basename(droppedPagePath);
  70. return nodePath.join(newParentPagePath, pageTitle);
  71. };
  72. //
  73. /**
  74. * Return whether the fromPage could be moved under the newParentPage
  75. * @param fromPage
  76. * @param newParentPage
  77. * @param printLog
  78. * @returns
  79. */
  80. //
  81. const isDroppable = (fromPage?: Partial<IPageHasId>, newParentPage?: Partial<IPageHasId>, printLog = false): boolean => {
  82. if (fromPage == null || newParentPage == null || fromPage.path == null || newParentPage.path == null) {
  83. if (printLog) {
  84. logger.warn('Any of page, page.path or droppedPage.path is null');
  85. }
  86. return false;
  87. }
  88. const newPathAfterMoved = getNewPathAfterMoved(fromPage.path, newParentPage.path);
  89. return pagePathUtils.canMoveByPath(fromPage.path, newPathAfterMoved) && !pagePathUtils.isUsersTopPage(newParentPage.path);
  90. };
  91. //
  92. // Component wrapper to make a child element not draggable
  93. // https://github.com/react-dnd/react-dnd/issues/335
  94. type NotDraggableProps = {
  95. children: ReactNode,
  96. };
  97. const NotDraggableForClosableTextInput = (props: NotDraggableProps): JSX.Element => {
  98. return <div draggable onDragStart={e => e.preventDefault()}>{props.children}</div>;
  99. };
  100. const SimpleItem: FC<ItemProps> = (props: ItemProps) => {
  101. const { t } = useTranslation();
  102. const router = useRouter();
  103. const {
  104. itemNode, targetPathOrId, isOpen: _isOpen = false,
  105. onRenamed, onClickDuplicateMenuItem, onClickDeleteMenuItem, isEnableActions, isReadOnlyUser,
  106. } = props;
  107. const { page, children } = itemNode;
  108. const [currentChildren, setCurrentChildren] = useState(children);
  109. const [isOpen, setIsOpen] = useState(_isOpen);
  110. const [isNewPageInputShown, setNewPageInputShown] = useState(false);
  111. const [shouldHide, setShouldHide] = useState(false);
  112. const [isRenameInputShown, setRenameInputShown] = useState(false);
  113. const [isCreating, setCreating] = useState(false);
  114. const { data, mutate: mutateChildren } = useSWRxPageChildren(isOpen ? page._id : null);
  115. const { trigger: mutateCurrentUserBookmarks } = useSWRMUTxCurrentUserBookmarks();
  116. const { trigger: mutatePageInfo } = useSWRMUTxPageInfo(page._id ?? null);
  117. // descendantCount
  118. const { getDescCount } = usePageTreeDescCountMap();
  119. const descendantCount = getDescCount(page._id) || page.descendantCount || 0;
  120. // hasDescendants flag
  121. const isChildrenLoaded = currentChildren?.length > 0;
  122. const hasDescendants = descendantCount > 0 || isChildrenLoaded;
  123. //
  124. // to re-show hidden item when useDrag end() callback
  125. const displayDroppedItemByPageId = useCallback((pageId) => {
  126. const target = document.getElementById(`pagetree-item-${pageId}`);
  127. if (target == null) {
  128. return;
  129. }
  130. // // wait 500ms to avoid removing before d-none is set by useDrag end() callback
  131. setTimeout(() => {
  132. target.classList.remove('d-none');
  133. }, 500);
  134. }, []);
  135. //
  136. // ここから切り分け開始
  137. // const [, drag] = useDrag({
  138. // type: 'PAGE_TREE',
  139. // item: { page },
  140. // canDrag: () => {
  141. // if (page.path == null) {
  142. // return false;
  143. // }
  144. // return !pagePathUtils.isUsersProtectedPages(page.path);
  145. // },
  146. // end: (item, monitor) => {
  147. // // in order to set d-none to dropped Item
  148. // const dropResult = monitor.getDropResult();
  149. // if (dropResult != null) {
  150. // setShouldHide(true);
  151. // }
  152. // },
  153. // collect: monitor => ({
  154. // isDragging: monitor.isDragging(),
  155. // canDrag: monitor.canDrag(),
  156. // }),
  157. // });
  158. //
  159. //
  160. const pageItemDropHandler = async(item: ItemNode) => {
  161. const { page: droppedPage } = item;
  162. if (!isDroppable(droppedPage, page, true)) {
  163. return;
  164. }
  165. if (droppedPage.path == null || page.path == null) {
  166. return;
  167. }
  168. const newPagePath = getNewPathAfterMoved(droppedPage.path, page.path);
  169. try {
  170. await apiv3Put('/pages/rename', {
  171. pageId: droppedPage._id,
  172. revisionId: droppedPage.revision,
  173. newPagePath,
  174. isRenameRedirect: false,
  175. updateMetadata: true,
  176. });
  177. await mutatePageTree();
  178. await mutateChildren();
  179. if (onRenamed != null) {
  180. onRenamed(page.path, newPagePath);
  181. }
  182. // force open
  183. setIsOpen(true);
  184. }
  185. catch (err) {
  186. // display the dropped item
  187. displayDroppedItemByPageId(droppedPage._id);
  188. if (err.code === 'operation__blocked') {
  189. toastWarning(t('pagetree.you_cannot_move_this_page_now'));
  190. }
  191. else {
  192. toastError(t('pagetree.something_went_wrong_with_moving_page'));
  193. }
  194. }
  195. };
  196. //
  197. //
  198. // const [{ isOver }, drop] = useDrop<ItemNode, Promise<void>, { isOver: boolean }>(
  199. // () => ({
  200. // accept: 'PAGE_TREE',
  201. // drop: pageItemDropHandler,
  202. // hover: (item, monitor) => {
  203. // // when a drag item is overlapped more than 1 sec, the drop target item will be opened.
  204. // if (monitor.isOver()) {
  205. // setTimeout(() => {
  206. // if (monitor.isOver()) {
  207. // setIsOpen(true);
  208. // }
  209. // }, 600);
  210. // }
  211. // },
  212. // canDrop: (item) => {
  213. // const { page: droppedPage } = item;
  214. // return isDroppable(droppedPage, page);
  215. // },
  216. // collect: monitor => ({
  217. // isOver: monitor.isOver(),
  218. // }),
  219. // }),
  220. // [page],
  221. // );
  222. //
  223. const hasChildren = useCallback((): boolean => {
  224. return currentChildren != null && currentChildren.length > 0;
  225. }, [currentChildren]);
  226. const onClickLoadChildren = useCallback(async() => {
  227. setIsOpen(!isOpen);
  228. }, [isOpen]);
  229. const onClickPlusButton = useCallback(() => {
  230. setNewPageInputShown(true);
  231. if (hasDescendants) {
  232. setIsOpen(true);
  233. }
  234. }, [hasDescendants]);
  235. const bookmarkMenuItemClickHandler = async(_pageId: string, _newValue: boolean): Promise<void> => {
  236. const bookmarkOperation = _newValue ? bookmark : unbookmark;
  237. await bookmarkOperation(_pageId);
  238. mutateCurrentUserBookmarks();
  239. mutatePageInfo();
  240. };
  241. const duplicateMenuItemClickHandler = useCallback((): void => {
  242. if (onClickDuplicateMenuItem == null) {
  243. return;
  244. }
  245. const { _id: pageId, path } = page;
  246. if (pageId == null || path == null) {
  247. throw Error('Any of _id and path must not be null.');
  248. }
  249. const pageToDuplicate = { pageId, path };
  250. onClickDuplicateMenuItem(pageToDuplicate);
  251. }, [onClickDuplicateMenuItem, page]);
  252. const renameMenuItemClickHandler = useCallback(() => {
  253. setRenameInputShown(true);
  254. }, []);
  255. const onPressEnterForRenameHandler = async(inputText: string) => {
  256. const parentPath = pathUtils.addTrailingSlash(nodePath.dirname(page.path ?? ''));
  257. const newPagePath = nodePath.resolve(parentPath, inputText);
  258. if (newPagePath === page.path) {
  259. setRenameInputShown(false);
  260. return;
  261. }
  262. try {
  263. setRenameInputShown(false);
  264. await apiv3Put('/pages/rename', {
  265. pageId: page._id,
  266. revisionId: page.revision,
  267. newPagePath,
  268. });
  269. if (onRenamed != null) {
  270. onRenamed(page.path, newPagePath);
  271. }
  272. toastSuccess(t('renamed_pages', { path: page.path }));
  273. }
  274. catch (err) {
  275. setRenameInputShown(true);
  276. toastError(err);
  277. }
  278. };
  279. const deleteMenuItemClickHandler = useCallback(async(_pageId: string, pageInfo: IPageInfoAll | undefined): Promise<void> => {
  280. if (onClickDeleteMenuItem == null) {
  281. return;
  282. }
  283. if (page._id == null || page.path == null) {
  284. throw Error('_id and path must not be null.');
  285. }
  286. const pageToDelete: IPageToDeleteWithMeta = {
  287. data: {
  288. _id: page._id,
  289. revision: page.revision as string,
  290. path: page.path,
  291. },
  292. meta: pageInfo,
  293. };
  294. onClickDeleteMenuItem(pageToDelete);
  295. }, [onClickDeleteMenuItem, page]);
  296. const onPressEnterForCreateHandler = async(inputText: string) => {
  297. setNewPageInputShown(false);
  298. const parentPath = pathUtils.addTrailingSlash(page.path as string);
  299. const newPagePath = nodePath.resolve(parentPath, inputText);
  300. const isCreatable = pagePathUtils.isCreatablePage(newPagePath);
  301. if (!isCreatable) {
  302. toastWarning(t('you_can_not_create_page_with_this_name'));
  303. return;
  304. }
  305. try {
  306. setCreating(true);
  307. await apiv3Post('/pages/', {
  308. path: newPagePath,
  309. body: undefined,
  310. grant: page.grant,
  311. grantUserGroupId: page.grantedGroup,
  312. });
  313. mutateChildren();
  314. if (!hasDescendants) {
  315. setIsOpen(true);
  316. }
  317. toastSuccess(t('successfully_saved_the_page'));
  318. }
  319. catch (err) {
  320. toastError(err);
  321. }
  322. finally {
  323. setCreating(false);
  324. }
  325. };
  326. /**
  327. * Users do not need to know if all pages have been renamed.
  328. * Make resuming rename operation appears to be working fine to allow users for a seamless operation.
  329. */
  330. const pathRecoveryMenuItemClickHandler = async(pageId: string): Promise<void> => {
  331. try {
  332. await resumeRenameOperation(pageId);
  333. toastSuccess(t('page_operation.paths_recovered'));
  334. }
  335. catch {
  336. toastError(t('page_operation.path_recovery_failed'));
  337. }
  338. };
  339. const pageTreeItemClickHandler = (e) => {
  340. e.preventDefault();
  341. if (page.path == null || page._id == null) {
  342. return;
  343. }
  344. const link = pathUtils.returnPathForURL(page.path, page._id);
  345. router.push(link);
  346. };
  347. // didMount
  348. useEffect(() => {
  349. if (hasChildren()) setIsOpen(true);
  350. }, [hasChildren]);
  351. /*
  352. * Make sure itemNode.children and currentChildren are synced
  353. */
  354. useEffect(() => {
  355. if (children.length > currentChildren.length) {
  356. markTarget(children, targetPathOrId);
  357. setCurrentChildren(children);
  358. }
  359. }, [children, currentChildren.length, targetPathOrId]);
  360. /*
  361. * When swr fetch succeeded
  362. */
  363. useEffect(() => {
  364. if (isOpen && data != null) {
  365. const newChildren = ItemNode.generateNodesFromPages(data.children);
  366. markTarget(newChildren, targetPathOrId);
  367. setCurrentChildren(newChildren);
  368. }
  369. }, [data, isOpen, targetPathOrId]);
  370. // Rename process
  371. // Icon that draw attention from users for some actions
  372. const shouldShowAttentionIcon = page.processData != null ? shouldRecoverPagePaths(page.processData) : false;
  373. const pageName = nodePath.basename(page.path ?? '') || '/';
  374. const itemRef = props.itemRef;
  375. console.log(itemRef);
  376. // const [isLoading, setIsLoading] = useState(true);
  377. // useEffect(() => {
  378. // // someProp が非同期で設定されるまで待機
  379. // if (itemRef !== undefined) {
  380. // setIsLoading(false);
  381. // }
  382. // }, [itemRef]);
  383. // if (isLoading) {
  384. // return <div>Loading...</div>;
  385. // }
  386. // 上のやり方だと、意識的にitemRefを設定しなかった場合におかしくなる
  387. return (
  388. <div
  389. id={`pagetree-item-${page._id}`}
  390. data-testid="grw-pagetree-item-container"
  391. className={`grw-pagetree-item-container ${shouldHide ? 'd-none' : ''}`}
  392. >
  393. <li
  394. ref={itemRef}
  395. className={`list-group-item list-group-item-action border-0 py-0 pr-3 d-flex align-items-center
  396. ${page.isTarget ? 'grw-pagetree-current-page-item' : ''}`}
  397. id={page.isTarget ? 'grw-pagetree-current-page-item' : `grw-pagetree-list-${page._id}`}
  398. >
  399. <div className="grw-triangle-container d-flex justify-content-center">
  400. {hasDescendants && (
  401. <button
  402. type="button"
  403. className={`grw-pagetree-triangle-btn btn ${isOpen ? 'grw-pagetree-open' : ''}`}
  404. onClick={onClickLoadChildren}
  405. >
  406. <div className="d-flex justify-content-center">
  407. <TriangleIcon />
  408. </div>
  409. </button>
  410. )}
  411. </div>
  412. {isRenameInputShown
  413. ? (
  414. <div className="flex-fill">
  415. <NotDraggableForClosableTextInput>
  416. <ClosableTextInput
  417. value={nodePath.basename(page.path ?? '')}
  418. placeholder={t('Input page name')}
  419. onClickOutside={() => { setRenameInputShown(false) }}
  420. onPressEnter={onPressEnterForRenameHandler}
  421. validationTarget={ValidationTarget.PAGE}
  422. />
  423. </NotDraggableForClosableTextInput>
  424. </div>
  425. )
  426. : (
  427. <>
  428. {shouldShowAttentionIcon && (
  429. <>
  430. <i id="path-recovery" className="fa fa-warning mr-2 text-warning"></i>
  431. <UncontrolledTooltip placement="top" target="path-recovery" fade={false}>
  432. {t('tooltip.operation.attention.rename')}
  433. </UncontrolledTooltip>
  434. </>
  435. )}
  436. {page != null && page.path != null && page._id != null && (
  437. <div className="grw-pagetree-title-anchor flex-grow-1">
  438. <p onClick={pageTreeItemClickHandler} className={`text-truncate m-auto ${page.isEmpty && 'grw-sidebar-text-muted'}`}>{pageName}</p>
  439. </div>
  440. )}
  441. </>
  442. )}
  443. {descendantCount > 0 && !isRenameInputShown && (
  444. <div className="grw-pagetree-count-wrapper">
  445. <CountBadge count={descendantCount} />
  446. </div>
  447. )}
  448. <NotAvailableForGuest>
  449. <div className="grw-pagetree-control d-flex">
  450. <PageItemControl
  451. pageId={page._id}
  452. isEnableActions={isEnableActions}
  453. isReadOnlyUser={isReadOnlyUser}
  454. onClickBookmarkMenuItem={bookmarkMenuItemClickHandler}
  455. onClickDuplicateMenuItem={duplicateMenuItemClickHandler}
  456. onClickRenameMenuItem={renameMenuItemClickHandler}
  457. onClickDeleteMenuItem={deleteMenuItemClickHandler}
  458. onClickPathRecoveryMenuItem={pathRecoveryMenuItemClickHandler}
  459. isInstantRename
  460. // Todo: It is wanted to find a better way to pass operationProcessData to PageItemControl
  461. operationProcessData={page.processData}
  462. >
  463. {/* pass the color property to reactstrap dropdownToggle props. https://6-4-0--reactstrap.netlify.app/components/dropdowns/ */}
  464. <DropdownToggle color="transparent" className="border-0 rounded btn-page-item-control p-0 grw-visible-on-hover mr-1">
  465. <i id='option-button-in-page-tree' className="icon-options fa fa-rotate-90 p-1"></i>
  466. </DropdownToggle>
  467. </PageItemControl>
  468. </div>
  469. </NotAvailableForGuest>
  470. {!pagePathUtils.isUsersTopPage(page.path ?? '') && (
  471. <NotAvailableForGuest>
  472. <NotAvailableForReadOnlyUser>
  473. <button
  474. id='page-create-button-in-page-tree'
  475. type="button"
  476. className="border-0 rounded btn btn-page-item-control p-0 grw-visible-on-hover"
  477. onClick={onClickPlusButton}
  478. >
  479. <i className="icon-plus d-block p-0" />
  480. </button>
  481. </NotAvailableForReadOnlyUser>
  482. </NotAvailableForGuest>
  483. )}
  484. </li>
  485. {isEnableActions && isNewPageInputShown && (
  486. <div className="flex-fill">
  487. <NotDraggableForClosableTextInput>
  488. <ClosableTextInput
  489. placeholder={t('Input page name')}
  490. onClickOutside={() => { setNewPageInputShown(false) }}
  491. onPressEnter={onPressEnterForCreateHandler}
  492. validationTarget={ValidationTarget.PAGE}
  493. />
  494. </NotDraggableForClosableTextInput>
  495. </div>
  496. )}
  497. {
  498. isOpen && hasChildren() && currentChildren.map((node, index) => (
  499. <div key={node.page._id} className="grw-pagetree-item-children">
  500. <SimpleItem
  501. isEnableActions={isEnableActions}
  502. isReadOnlyUser={isReadOnlyUser}
  503. itemNode={node}
  504. isOpen={false}
  505. targetPathOrId={targetPathOrId}
  506. onRenamed={onRenamed}
  507. onClickDuplicateMenuItem={onClickDuplicateMenuItem}
  508. onClickDeleteMenuItem={onClickDeleteMenuItem}
  509. itemRef={itemRef}
  510. />
  511. {isCreating && (currentChildren.length - 1 === index) && (
  512. <div className="text-muted text-center">
  513. <i className="fa fa-spinner fa-pulse mr-1"></i>
  514. </div>
  515. )}
  516. </div>
  517. ))
  518. }
  519. </div>
  520. );
  521. };
  522. export default SimpleItem;