Item.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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: () => {
  90. // in order to set d-none to dropped Item
  91. setShouldHide(true);
  92. },
  93. collect: monitor => ({
  94. isDragging: monitor.isDragging(),
  95. }),
  96. }));
  97. const pageItemDropHandler = async(item, monitor) => {
  98. if (page == null || page.path == null) {
  99. return;
  100. }
  101. const { page: droppedPage } = item;
  102. const pageTitle = nodePath.basename(droppedPage.path);
  103. const newParentPath = page.path;
  104. const newPagePath = nodePath.join(newParentPath, pageTitle);
  105. try {
  106. await apiv3Put('/pages/rename', {
  107. pageId: droppedPage._id,
  108. revisionId: droppedPage.revision,
  109. newPagePath,
  110. isRenameRedirect: false,
  111. isRemainMetadata: false,
  112. });
  113. await mutateChildren();
  114. // force open
  115. setIsOpen(true);
  116. toastSuccess('TODO: i18n Successfully moved pages.');
  117. }
  118. catch (err) {
  119. // display the dropped item
  120. displayDroppedItemByPageId(droppedPage._id);
  121. if (err.code === 'operation__blocked') {
  122. toastWarning('TODO: i18n You cannot move this page now.');
  123. }
  124. else {
  125. toastError('TODO: i18n Something went wrong with moving page.');
  126. }
  127. }
  128. };
  129. const [{ isOver }, drop] = useDrop(() => ({
  130. accept: 'PAGE_TREE',
  131. drop: pageItemDropHandler,
  132. hover: (item, monitor) => {
  133. // when a drag item is overlapped more than 1 sec, the drop target item will be opened.
  134. if (monitor.isOver()) {
  135. setTimeout(() => {
  136. if (monitor.isOver()) {
  137. setIsOpen(true);
  138. }
  139. }, 1000);
  140. }
  141. },
  142. collect: monitor => ({
  143. isOver: monitor.isOver(),
  144. }),
  145. }));
  146. const hasChildren = useCallback((): boolean => {
  147. return currentChildren != null && currentChildren.length > 0;
  148. }, [currentChildren]);
  149. const onClickLoadChildren = useCallback(async() => {
  150. setIsOpen(!isOpen);
  151. }, [isOpen]);
  152. const onClickPlusButton = useCallback(() => {
  153. setNewPageInputShown(true);
  154. }, []);
  155. const duplicateMenuItemClickHandler = useCallback((): void => {
  156. if (onClickDuplicateMenuItem == null) {
  157. return;
  158. }
  159. const { _id: pageId, path } = page;
  160. if (pageId == null || path == null) {
  161. throw Error('Any of _id and path must not be null.');
  162. }
  163. onClickDuplicateMenuItem(pageId, path);
  164. }, [onClickDuplicateMenuItem, page]);
  165. /*
  166. * Rename: TODO: rename page title on input form by #87757
  167. */
  168. // const onClickRenameButton = useCallback(async(_pageId: string): Promise<void> => {
  169. // setRenameInputShown(true);
  170. // }, []);
  171. // const onPressEnterForRenameHandler = async(inputText: string) => {
  172. // const parentPath = getParentPagePath(page.path as string)
  173. // const newPagePath = `${parentPath}/${inputText}`;
  174. // try {
  175. // setPageTitle(inputText);
  176. // setRenameInputShown(false);
  177. // await apiv3Put('/pages/rename', { newPagePath, pageId: page._id, revisionId: page.revision });
  178. // }
  179. // catch (err) {
  180. // // open ClosableInput and set pageTitle back to the previous title
  181. // setPageTitle(nodePath.basename(pageTitle as string));
  182. // setRenameInputShown(true);
  183. // toastError(err);
  184. // }
  185. // };
  186. const renameMenuItemClickHandler = useCallback((): void => {
  187. if (onClickRenameMenuItem == null) {
  188. return;
  189. }
  190. const { _id: pageId, revision: revisionId, path } = page;
  191. if (pageId == null || revisionId == null || path == null) {
  192. throw Error('Any of _id and revisionId and path must not be null.');
  193. }
  194. onClickRenameMenuItem(pageId, revisionId as string, path);
  195. }, [onClickRenameMenuItem, page]);
  196. const deleteMenuItemClickHandler = useCallback(async(_pageId: string): Promise<void> => {
  197. if (onClickDeleteMenuItem == null) {
  198. return;
  199. }
  200. const { _id: pageId, revision: revisionId, path } = page;
  201. if (pageId == null || revisionId == null || path == null) {
  202. throw Error('Any of _id, revision, and path must not be null.');
  203. }
  204. const pageToDelete: IPageForPageDeleteModal = {
  205. pageId,
  206. revisionId: revisionId as string,
  207. path,
  208. };
  209. const isAbleToDeleteCompletely = pageInfo?.isAbleToDeleteCompletely ?? false;
  210. onClickDeleteMenuItem(pageToDelete, isAbleToDeleteCompletely);
  211. }, [onClickDeleteMenuItem, page, pageInfo?.isAbleToDeleteCompletely]);
  212. const onPressEnterForCreateHandler = async(inputText: string) => {
  213. setNewPageInputShown(false);
  214. const parentPath = pathUtils.addTrailingSlash(page.path as string);
  215. const newPagePath = `${parentPath}${inputText}`;
  216. const isCreatable = pagePathUtils.isCreatablePage(newPagePath);
  217. if (!isCreatable) {
  218. toastWarning(t('you_can_not_create_page_with_this_name'));
  219. return;
  220. }
  221. // TODO 88261: Get the isEnabledAttachTitleHeader by SWR
  222. // const initBody = '';
  223. // const { isEnabledAttachTitleHeader } = props.appContainer.getConfig();
  224. // if (isEnabledAttachTitleHeader) {
  225. // initBody = pathUtils.attachTitleHeader(newPagePath);
  226. // }
  227. try {
  228. await apiv3Post('/pages/', {
  229. path: newPagePath,
  230. body: '',
  231. grant: page.grant,
  232. grantUserGroupId: page.grantedGroup,
  233. createFromPageTree: true,
  234. });
  235. mutateChildren();
  236. toastSuccess(t('successfully_saved_the_page'));
  237. }
  238. catch (err) {
  239. toastError(err);
  240. }
  241. };
  242. const inputValidator = (title: string | null): AlertInfo | null => {
  243. if (title == null || title === '' || title.trim() === '') {
  244. return {
  245. type: AlertType.WARNING,
  246. message: t('form_validation.title_required'),
  247. };
  248. }
  249. if (title.includes('/')) {
  250. return {
  251. type: AlertType.WARNING,
  252. message: t('form_validation.slashed_are_not_yet_supported'),
  253. };
  254. }
  255. return null;
  256. };
  257. // didMount
  258. useEffect(() => {
  259. if (hasChildren()) setIsOpen(true);
  260. }, [hasChildren]);
  261. /*
  262. * Make sure itemNode.children and currentChildren are synced
  263. */
  264. useEffect(() => {
  265. if (children.length > currentChildren.length) {
  266. markTarget(children, targetPathOrId);
  267. setCurrentChildren(children);
  268. }
  269. }, [children, currentChildren.length, targetPathOrId]);
  270. /*
  271. * When swr fetch succeeded
  272. */
  273. useEffect(() => {
  274. if (isOpen && data != null) {
  275. const newChildren = ItemNode.generateNodesFromPages(data.children);
  276. markTarget(newChildren, targetPathOrId);
  277. setCurrentChildren(newChildren);
  278. }
  279. }, [data, isOpen, targetPathOrId]);
  280. return (
  281. <div id={`pagetree-item-${page._id}`} className={`grw-pagetree-item-container ${isOver ? 'grw-pagetree-is-over' : ''} ${shouldHide ? 'd-none' : ''}`}>
  282. <li
  283. ref={(c) => { drag(c); drop(c) }}
  284. className={`list-group-item list-group-item-action border-0 py-1 d-flex align-items-center ${page.isTarget ? 'grw-pagetree-is-target' : ''}`}
  285. >
  286. <div className="grw-triangle-container d-flex justify-content-center">
  287. {hasDescendants && (
  288. <button
  289. type="button"
  290. className={`grw-pagetree-button btn ${isOpen ? 'grw-pagetree-open' : ''}`}
  291. onClick={onClickLoadChildren}
  292. >
  293. <div className="grw-triangle-icon d-flex justify-content-center">
  294. <TriangleIcon />
  295. </div>
  296. </button>
  297. )}
  298. </div>
  299. {/* TODO: rename page title on input form by 87757 */}
  300. {/* { isRenameInputShown && (
  301. <ClosableTextInput
  302. isShown
  303. value={nodePath.basename(pageTitle as string)}
  304. placeholder={t('Input page name')}
  305. onClickOutside={() => { setRenameInputShown(false) }}
  306. onPressEnter={onPressEnterForRenameHandler}
  307. inputValidator={inputValidator}
  308. />
  309. )}
  310. { !isRenameInputShown && ( */}
  311. <a href={page._id} className="grw-pagetree-title-anchor flex-grow-1">
  312. <p className={`text-truncate m-auto ${page.isEmpty && 'text-muted'}`}>{nodePath.basename(pageTitle as string) || '/'}</p>
  313. </a>
  314. {/* )} */}
  315. {(page.descendantCount != null && page.descendantCount > 0) && (
  316. <div className="grw-pagetree-count-wrapper">
  317. <ItemCount descendantCount={page.descendantCount} />
  318. </div>
  319. )}
  320. <div className="grw-pagetree-control d-none">
  321. <PageItemControl
  322. pageId={page._id}
  323. isEnableActions={isEnableActions}
  324. showBookmarkMenuItem
  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;