Item.tsx 14 KB

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