Item.tsx 14 KB

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