Item.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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 { toastWarning, toastError, toastSuccess } from '~/client/util/apiNotification';
  10. import { useSWRxPageChildren } from '~/stores/page-listing';
  11. import { useSWRxPageInfo } from '~/stores/page';
  12. import { apiv3Put, apiv3Post } from '~/client/util/apiv3-client';
  13. import { useShareLinkId, useIsEnabledAttachTitleHeader } from '~/stores/context';
  14. import { IPageForPageDeleteModal } from '~/stores/modal';
  15. import TriangleIcon from '~/components/Icons/TriangleIcon';
  16. import { bookmark, unbookmark } from '~/client/services/page-operation';
  17. import ClosableTextInput, { AlertInfo, AlertType } from '../../Common/ClosableTextInput';
  18. import { PageItemControl } from '../../Common/Dropdown/PageItemControl';
  19. import { ItemNode } from './ItemNode';
  20. interface ItemProps {
  21. isEnableActions: boolean
  22. itemNode: ItemNode
  23. targetPathOrId?: string
  24. isOpen?: boolean
  25. onClickDuplicateMenuItem?(pageId: string, path: string): void
  26. onClickRenameMenuItem?(pageId: string, revisionId: string, path: string): void
  27. onClickDeleteMenuItem?(pageToDelete: IPageForPageDeleteModal | null, isAbleToDeleteCompletely: boolean, callback: VoidFunction): void
  28. mutateSiblings?: VoidFunction
  29. }
  30. // Utility to mark target
  31. const markTarget = (children: ItemNode[], targetPathOrId?: string): void => {
  32. if (targetPathOrId == null) {
  33. return;
  34. }
  35. children.forEach((node) => {
  36. if (node.page._id === targetPathOrId || node.page.path === targetPathOrId) {
  37. node.page.isTarget = true;
  38. }
  39. return node;
  40. });
  41. };
  42. const bookmarkMenuItemClickHandler = async(_pageId: string, _newValue: boolean): Promise<void> => {
  43. const bookmarkOperation = _newValue ? bookmark : unbookmark;
  44. await bookmarkOperation(_pageId);
  45. };
  46. type ItemCountProps = {
  47. descendantCount: number
  48. }
  49. const ItemCount: FC<ItemCountProps> = (props:ItemCountProps) => {
  50. return (
  51. <>
  52. <span className="grw-pagetree-count badge badge-pill badge-light text-muted">
  53. {props.descendantCount}
  54. </span>
  55. </>
  56. );
  57. };
  58. const Item: FC<ItemProps> = (props: ItemProps) => {
  59. const { t } = useTranslation();
  60. const {
  61. itemNode, targetPathOrId, isOpen: _isOpen = false, onClickDuplicateMenuItem, onClickRenameMenuItem, onClickDeleteMenuItem, isEnableActions,
  62. mutateSiblings,
  63. } = props;
  64. const { page, children } = itemNode;
  65. const [pageTitle, setPageTitle] = useState(page.path);
  66. const { data: shareLinkId } = useShareLinkId();
  67. const { data: pageInfo } = useSWRxPageInfo(page._id ?? null, shareLinkId);
  68. const [currentChildren, setCurrentChildren] = useState(children);
  69. const [isOpen, setIsOpen] = useState(_isOpen);
  70. const [isNewPageInputShown, setNewPageInputShown] = useState(false);
  71. const [shouldHide, setShouldHide] = useState(false);
  72. // const [isRenameInputShown, setRenameInputShown] = useState(false);
  73. const { data, mutate: mutateChildren } = useSWRxPageChildren(isOpen ? page._id : null);
  74. const { data: isEnabledAttachTitleHeader } = useIsEnabledAttachTitleHeader();
  75. // hasDescendants flag
  76. const isChildrenLoaded = currentChildren?.length > 0;
  77. const hasDescendants = (page.descendantCount != null && page?.descendantCount > 0) || isChildrenLoaded;
  78. // to re-show hidden item when useDrag end() callback
  79. const displayDroppedItemByPageId = useCallback((pageId) => {
  80. const target = document.getElementById(`pagetree-item-${pageId}`);
  81. if (target == null) {
  82. return;
  83. }
  84. // wait 500ms to avoid removing before d-none is set by useDrag end() callback
  85. setTimeout(() => {
  86. target.classList.remove('d-none');
  87. }, 500);
  88. }, []);
  89. const [{ isDragging }, drag] = useDrag(() => ({
  90. type: 'PAGE_TREE',
  91. item: { page },
  92. end: (item, monitor) => {
  93. // in order to set d-none to dropped Item
  94. const dropResult = monitor.getDropResult();
  95. if (dropResult != null) {
  96. setShouldHide(true);
  97. }
  98. },
  99. collect: monitor => ({
  100. isDragging: monitor.isDragging(),
  101. }),
  102. }));
  103. const pageItemDropHandler = async(item, monitor) => {
  104. if (page == null || page.path == null) {
  105. return;
  106. }
  107. const { page: droppedPage } = item;
  108. const pageTitle = nodePath.basename(droppedPage.path);
  109. const newParentPath = page.path;
  110. const newPagePath = nodePath.join(newParentPath, pageTitle);
  111. try {
  112. await apiv3Put('/pages/rename', {
  113. pageId: droppedPage._id,
  114. revisionId: droppedPage.revision,
  115. newPagePath,
  116. isRenameRedirect: false,
  117. isRemainMetadata: false,
  118. });
  119. await mutateChildren();
  120. // force open
  121. setIsOpen(true);
  122. }
  123. catch (err) {
  124. // display the dropped item
  125. displayDroppedItemByPageId(droppedPage._id);
  126. if (err.code === 'operation__blocked') {
  127. toastWarning(t('pagetree.you_cannot_move_this_page_now'));
  128. }
  129. else {
  130. toastError(t('pagetree.something_went_wrong_with_moving_page'));
  131. }
  132. }
  133. };
  134. const [{ isOver }, drop] = useDrop(() => ({
  135. accept: 'PAGE_TREE',
  136. drop: pageItemDropHandler,
  137. hover: (item, monitor) => {
  138. // when a drag item is overlapped more than 1 sec, the drop target item will be opened.
  139. if (monitor.isOver()) {
  140. setTimeout(() => {
  141. if (monitor.isOver()) {
  142. setIsOpen(true);
  143. }
  144. }, 1000);
  145. }
  146. },
  147. collect: monitor => ({
  148. isOver: monitor.isOver(),
  149. }),
  150. }));
  151. const hasChildren = useCallback((): boolean => {
  152. return currentChildren != null && currentChildren.length > 0;
  153. }, [currentChildren]);
  154. const onClickLoadChildren = useCallback(async() => {
  155. setIsOpen(!isOpen);
  156. }, [isOpen]);
  157. const onClickPlusButton = useCallback(() => {
  158. setNewPageInputShown(true);
  159. }, []);
  160. const duplicateMenuItemClickHandler = useCallback((): void => {
  161. if (onClickDuplicateMenuItem == null) {
  162. return;
  163. }
  164. const { _id: pageId, path } = page;
  165. if (pageId == null || path == null) {
  166. throw Error('Any of _id and path must not be null.');
  167. }
  168. onClickDuplicateMenuItem(pageId, path);
  169. }, [onClickDuplicateMenuItem, page]);
  170. /*
  171. * Rename: TODO: rename page title on input form by #87757
  172. */
  173. // const onClickRenameButton = useCallback(async(_pageId: string): Promise<void> => {
  174. // setRenameInputShown(true);
  175. // }, []);
  176. // const onPressEnterForRenameHandler = async(inputText: string) => {
  177. // const parentPath = getParentPagePath(page.path as string)
  178. // const newPagePath = `${parentPath}/${inputText}`;
  179. // try {
  180. // setPageTitle(inputText);
  181. // setRenameInputShown(false);
  182. // await apiv3Put('/pages/rename', { newPagePath, pageId: page._id, revisionId: page.revision });
  183. // }
  184. // catch (err) {
  185. // // open ClosableInput and set pageTitle back to the previous title
  186. // setPageTitle(nodePath.basename(pageTitle as string));
  187. // setRenameInputShown(true);
  188. // toastError(err);
  189. // }
  190. // };
  191. const renameMenuItemClickHandler = useCallback((): void => {
  192. if (onClickRenameMenuItem == null) {
  193. return;
  194. }
  195. const { _id: pageId, revision: revisionId, path } = page;
  196. if (pageId == null || revisionId == null || path == null) {
  197. throw Error('Any of _id and revisionId and path must not be null.');
  198. }
  199. onClickRenameMenuItem(pageId, revisionId as string, path);
  200. }, [onClickRenameMenuItem, page]);
  201. const deleteMenuItemClickHandler = useCallback(async(_pageId: string): Promise<void> => {
  202. if (onClickDeleteMenuItem == null) {
  203. return;
  204. }
  205. const { _id: pageId, revision: revisionId, path } = page;
  206. if (pageId == null || revisionId == null || path == null) {
  207. throw Error('Any of _id, revision, and path must not be null.');
  208. }
  209. const pageToDelete: IPageForPageDeleteModal = {
  210. pageId,
  211. revisionId: revisionId as string,
  212. path,
  213. };
  214. const isAbleToDeleteCompletely = pageInfo?.isAbleToDeleteCompletely ?? false;
  215. onClickDeleteMenuItem(pageToDelete, isAbleToDeleteCompletely, async() => {
  216. if (mutateSiblings != null) await mutateSiblings();
  217. });
  218. }, [onClickDeleteMenuItem, page, pageInfo?.isAbleToDeleteCompletely, mutateSiblings]);
  219. const onPressEnterForCreateHandler = async(inputText: string) => {
  220. setNewPageInputShown(false);
  221. const parentPath = pathUtils.addTrailingSlash(page.path as string);
  222. const newPagePath = `${parentPath}${inputText}`;
  223. const isCreatable = pagePathUtils.isCreatablePage(newPagePath);
  224. if (!isCreatable) {
  225. toastWarning(t('you_can_not_create_page_with_this_name'));
  226. return;
  227. }
  228. let initBody = '';
  229. if (isEnabledAttachTitleHeader) {
  230. initBody = pathUtils.attachTitleHeader(newPagePath);
  231. }
  232. try {
  233. await apiv3Post('/pages/', {
  234. path: newPagePath,
  235. body: initBody,
  236. grant: page.grant,
  237. grantUserGroupId: page.grantedGroup,
  238. createFromPageTree: true,
  239. });
  240. mutateChildren();
  241. toastSuccess(t('successfully_saved_the_page'));
  242. }
  243. catch (err) {
  244. toastError(err);
  245. }
  246. };
  247. const inputValidator = (title: string | null): AlertInfo | null => {
  248. if (title == null || title === '' || title.trim() === '') {
  249. return {
  250. type: AlertType.WARNING,
  251. message: t('form_validation.title_required'),
  252. };
  253. }
  254. if (title.includes('/')) {
  255. return {
  256. type: AlertType.WARNING,
  257. message: t('form_validation.slashed_are_not_yet_supported'),
  258. };
  259. }
  260. return null;
  261. };
  262. // didMount
  263. useEffect(() => {
  264. if (hasChildren()) setIsOpen(true);
  265. }, [hasChildren]);
  266. /*
  267. * Make sure itemNode.children and currentChildren are synced
  268. */
  269. useEffect(() => {
  270. if (children.length > currentChildren.length) {
  271. markTarget(children, targetPathOrId);
  272. setCurrentChildren(children);
  273. }
  274. }, [children, currentChildren.length, targetPathOrId]);
  275. /*
  276. * When swr fetch succeeded
  277. */
  278. useEffect(() => {
  279. if (isOpen && data != null) {
  280. const newChildren = ItemNode.generateNodesFromPages(data.children);
  281. markTarget(newChildren, targetPathOrId);
  282. setCurrentChildren(newChildren);
  283. }
  284. }, [data, isOpen, targetPathOrId]);
  285. return (
  286. <div id={`pagetree-item-${page._id}`} className={`grw-pagetree-item-container ${isOver ? 'grw-pagetree-is-over' : ''} ${shouldHide ? 'd-none' : ''}`}>
  287. <li
  288. ref={(c) => { drag(c); drop(c) }}
  289. className={`list-group-item list-group-item-action border-0 py-1 d-flex align-items-center ${page.isTarget ? 'grw-pagetree-is-target' : ''}`}
  290. >
  291. <div className="grw-triangle-container d-flex justify-content-center">
  292. {hasDescendants && (
  293. <button
  294. type="button"
  295. className={`grw-pagetree-button btn ${isOpen ? 'grw-pagetree-open' : ''}`}
  296. onClick={onClickLoadChildren}
  297. >
  298. <div className="grw-triangle-icon d-flex justify-content-center">
  299. <TriangleIcon />
  300. </div>
  301. </button>
  302. )}
  303. </div>
  304. {/* TODO: rename page title on input form by 87757 */}
  305. {/* { isRenameInputShown && (
  306. <ClosableTextInput
  307. isShown
  308. value={nodePath.basename(pageTitle as string)}
  309. placeholder={t('Input page name')}
  310. onClickOutside={() => { setRenameInputShown(false) }}
  311. onPressEnter={onPressEnterForRenameHandler}
  312. inputValidator={inputValidator}
  313. />
  314. )}
  315. { !isRenameInputShown && ( */}
  316. <a href={`/${page._id}`} className="grw-pagetree-title-anchor flex-grow-1">
  317. <p className={`text-truncate m-auto ${page.isEmpty && 'text-muted'}`}>{nodePath.basename(pageTitle as string) || '/'}</p>
  318. </a>
  319. {/* )} */}
  320. {(page.descendantCount != null && page.descendantCount > 0) && (
  321. <div className="grw-pagetree-count-wrapper">
  322. <ItemCount descendantCount={page.descendantCount} />
  323. </div>
  324. )}
  325. <div className="grw-pagetree-control d-none">
  326. <PageItemControl
  327. pageId={page._id}
  328. isEnableActions={isEnableActions}
  329. onClickBookmarkMenuItem={bookmarkMenuItemClickHandler}
  330. onClickDuplicateMenuItem={duplicateMenuItemClickHandler}
  331. onClickDeleteMenuItem={deleteMenuItemClickHandler}
  332. onClickRenameMenuItem={renameMenuItemClickHandler}
  333. >
  334. <DropdownToggle color="transparent" className="border-0 rounded btn-page-item-control p-0">
  335. <i className="icon-options fa fa-rotate-90 text-muted p-1"></i>
  336. </DropdownToggle>
  337. </PageItemControl>
  338. <button
  339. type="button"
  340. className="border-0 rounded btn-page-item-control p-0"
  341. onClick={onClickPlusButton}
  342. >
  343. <i className="icon-plus text-muted d-block p-1" />
  344. </button>
  345. </div>
  346. </li>
  347. {isEnableActions && (
  348. <ClosableTextInput
  349. isShown={isNewPageInputShown}
  350. placeholder={t('Input page name')}
  351. onClickOutside={() => { setNewPageInputShown(false) }}
  352. onPressEnter={onPressEnterForCreateHandler}
  353. inputValidator={inputValidator}
  354. />
  355. )}
  356. {
  357. isOpen && hasChildren() && currentChildren.map(node => (
  358. <div key={node.page._id} className="grw-pagetree-item-children">
  359. <Item
  360. isEnableActions={isEnableActions}
  361. itemNode={node}
  362. isOpen={false}
  363. targetPathOrId={targetPathOrId}
  364. onClickDuplicateMenuItem={onClickDuplicateMenuItem}
  365. onClickRenameMenuItem={onClickRenameMenuItem}
  366. onClickDeleteMenuItem={onClickDeleteMenuItem}
  367. mutateSiblings={async() => { await mutateChildren() }}
  368. />
  369. </div>
  370. ))
  371. }
  372. </div>
  373. );
  374. };
  375. export default Item;