Item.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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 { apiv3Put, apiv3Post } from '~/client/util/apiv3-client';
  12. import { IPageForPageRenameModal, IPageForPageDuplicateModal, IPageForPageDeleteModal } from '~/stores/modal';
  13. import TriangleIcon from '~/components/Icons/TriangleIcon';
  14. import { bookmark, unbookmark } from '~/client/services/page-operation';
  15. import ClosableTextInput, { AlertInfo, AlertType } from '../../Common/ClosableTextInput';
  16. import { PageItemControl } from '../../Common/Dropdown/PageItemControl';
  17. import { ItemNode } from './ItemNode';
  18. interface ItemProps {
  19. isEnableActions: boolean
  20. itemNode: ItemNode
  21. targetPathOrId?: string
  22. isScrolled: boolean,
  23. isOpen?: boolean
  24. isEnabledAttachTitleHeader?: boolean
  25. onClickDuplicateMenuItem?(pageToDuplicate: IPageForPageDuplicateModal): void
  26. onClickRenameMenuItem?(pageToRename: IPageForPageRenameModal): void
  27. onClickDeleteMenuItem?(pageToDelete: IPageForPageDeleteModal): 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, isEnabledAttachTitleHeader,
  61. onClickDuplicateMenuItem, onClickRenameMenuItem, onClickDeleteMenuItem, isEnableActions,
  62. } = props;
  63. const { page, children } = itemNode;
  64. const [pageTitle, setPageTitle] = useState(page.path);
  65. const [currentChildren, setCurrentChildren] = useState(children);
  66. const [isOpen, setIsOpen] = useState(_isOpen);
  67. const [isNewPageInputShown, setNewPageInputShown] = useState(false);
  68. const [shouldHide, setShouldHide] = useState(false);
  69. // const [isRenameInputShown, setRenameInputShown] = useState(false);
  70. const { data, mutate: mutateChildren } = useSWRxPageChildren(isOpen ? page._id : null);
  71. // hasDescendants flag
  72. const isChildrenLoaded = currentChildren?.length > 0;
  73. const hasDescendants = (page.descendantCount != null && page?.descendantCount > 0) || isChildrenLoaded;
  74. // to re-show hidden item when useDrag end() callback
  75. const displayDroppedItemByPageId = useCallback((pageId) => {
  76. const target = document.getElementById(`pagetree-item-${pageId}`);
  77. if (target == null) {
  78. return;
  79. }
  80. // wait 500ms to avoid removing before d-none is set by useDrag end() callback
  81. setTimeout(() => {
  82. target.classList.remove('d-none');
  83. }, 500);
  84. }, []);
  85. const [{ isDragging }, drag] = useDrag(() => ({
  86. type: 'PAGE_TREE',
  87. item: { page },
  88. end: (item, monitor) => {
  89. // in order to set d-none to dropped Item
  90. const dropResult = monitor.getDropResult();
  91. if (dropResult != null) {
  92. setShouldHide(true);
  93. }
  94. },
  95. collect: monitor => ({
  96. isDragging: monitor.isDragging(),
  97. }),
  98. }));
  99. const pageItemDropHandler = async(item, monitor) => {
  100. if (page == null || page.path == null) {
  101. return;
  102. }
  103. const { page: droppedPage } = item;
  104. const pageTitle = nodePath.basename(droppedPage.path);
  105. const newParentPath = page.path;
  106. const newPagePath = nodePath.join(newParentPath, pageTitle);
  107. try {
  108. await apiv3Put('/pages/rename', {
  109. pageId: droppedPage._id,
  110. revisionId: droppedPage.revision,
  111. newPagePath,
  112. isRenameRedirect: false,
  113. isRemainMetadata: false,
  114. });
  115. await mutateChildren();
  116. // force open
  117. setIsOpen(true);
  118. }
  119. catch (err) {
  120. // display the dropped item
  121. displayDroppedItemByPageId(droppedPage._id);
  122. if (err.code === 'operation__blocked') {
  123. toastWarning(t('pagetree.you_cannot_move_this_page_now'));
  124. }
  125. else {
  126. toastError(t('pagetree.something_went_wrong_with_moving_page'));
  127. }
  128. }
  129. };
  130. const [{ isOver }, drop] = useDrop(() => ({
  131. accept: 'PAGE_TREE',
  132. drop: pageItemDropHandler,
  133. hover: (item, monitor) => {
  134. // when a drag item is overlapped more than 1 sec, the drop target item will be opened.
  135. if (monitor.isOver()) {
  136. setTimeout(() => {
  137. if (monitor.isOver()) {
  138. setIsOpen(true);
  139. }
  140. }, 1000);
  141. }
  142. },
  143. collect: monitor => ({
  144. isOver: monitor.isOver(),
  145. }),
  146. }));
  147. const hasChildren = useCallback((): boolean => {
  148. return currentChildren != null && currentChildren.length > 0;
  149. }, [currentChildren]);
  150. const onClickLoadChildren = useCallback(async() => {
  151. setIsOpen(!isOpen);
  152. }, [isOpen]);
  153. const onClickPlusButton = useCallback(() => {
  154. setNewPageInputShown(true);
  155. }, []);
  156. const duplicateMenuItemClickHandler = useCallback((): void => {
  157. if (onClickDuplicateMenuItem == null) {
  158. return;
  159. }
  160. const { _id: pageId, path } = page;
  161. if (pageId == null || path == null) {
  162. throw Error('Any of _id and path must not be null.');
  163. }
  164. const pageToDuplicate = { pageId, path };
  165. onClickDuplicateMenuItem(pageToDuplicate);
  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. const pageToRename: IPageForPageRenameModal = {
  197. pageId,
  198. revisionId: revisionId as string,
  199. path,
  200. };
  201. onClickRenameMenuItem(pageToRename);
  202. }, [onClickRenameMenuItem, page]);
  203. const deleteMenuItemClickHandler = useCallback(async(_pageId: string, pageInfo): Promise<void> => {
  204. const { _id: pageId, revision: revisionId, path } = page;
  205. if (pageId == null || revisionId == null || path == null) {
  206. throw Error('Any of _id, revision, and path must not be null.');
  207. }
  208. const pageToDelete: IPageForPageDeleteModal = {
  209. pageId,
  210. revisionId: revisionId as string,
  211. path,
  212. isAbleToDeleteCompletely: pageInfo?.isAbleToDeleteCompletely,
  213. };
  214. if (onClickDeleteMenuItem != null) {
  215. onClickDeleteMenuItem(pageToDelete);
  216. }
  217. }, [onClickDeleteMenuItem, page]);
  218. const onPressEnterForCreateHandler = async(inputText: string) => {
  219. setNewPageInputShown(false);
  220. const parentPath = pathUtils.addTrailingSlash(page.path as string);
  221. const newPagePath = `${parentPath}${inputText}`;
  222. const isCreatable = pagePathUtils.isCreatablePage(newPagePath);
  223. if (!isCreatable) {
  224. toastWarning(t('you_can_not_create_page_with_this_name'));
  225. return;
  226. }
  227. let initBody = '';
  228. if (isEnabledAttachTitleHeader) {
  229. const pageTitle = pathUtils.addHeadingSlash(nodePath.basename(newPagePath));
  230. initBody = pathUtils.attachTitleHeader(pageTitle);
  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. useEffect(() => {
  263. if (!props.isScrolled && page.isTarget) {
  264. document.dispatchEvent(new CustomEvent('targetItemRendered'));
  265. }
  266. }, [props.isScrolled, page.isTarget]);
  267. // didMount
  268. useEffect(() => {
  269. if (hasChildren()) setIsOpen(true);
  270. }, [hasChildren]);
  271. /*
  272. * Make sure itemNode.children and currentChildren are synced
  273. */
  274. useEffect(() => {
  275. if (children.length > currentChildren.length) {
  276. markTarget(children, targetPathOrId);
  277. setCurrentChildren(children);
  278. }
  279. }, [children, currentChildren.length, targetPathOrId]);
  280. /*
  281. * When swr fetch succeeded
  282. */
  283. useEffect(() => {
  284. if (isOpen && data != null) {
  285. const newChildren = ItemNode.generateNodesFromPages(data.children);
  286. markTarget(newChildren, targetPathOrId);
  287. setCurrentChildren(newChildren);
  288. }
  289. }, [data, isOpen, targetPathOrId]);
  290. return (
  291. <div id={`pagetree-item-${page._id}`} className={`grw-pagetree-item-container ${isOver ? 'grw-pagetree-is-over' : ''} ${shouldHide ? 'd-none' : ''}`}>
  292. <li
  293. ref={(c) => { drag(c); drop(c) }}
  294. className={`list-group-item list-group-item-action border-0 py-0 d-flex align-items-center ${page.isTarget ? 'grw-pagetree-is-target' : ''}`}
  295. id={page.isTarget ? 'grw-pagetree-is-target' : `grw-pagetree-list-${page._id}`}
  296. >
  297. <div className="grw-triangle-container d-flex justify-content-center">
  298. {hasDescendants && (
  299. <button
  300. type="button"
  301. className={`grw-pagetree-button btn ${isOpen ? 'grw-pagetree-open' : ''}`}
  302. onClick={onClickLoadChildren}
  303. >
  304. <div className="grw-triangle-icon d-flex justify-content-center">
  305. <TriangleIcon />
  306. </div>
  307. </button>
  308. )}
  309. </div>
  310. {/* TODO: rename page title on input form by 87757 */}
  311. {/* { isRenameInputShown && (
  312. <ClosableTextInput
  313. isShown
  314. value={nodePath.basename(pageTitle as string)}
  315. placeholder={t('Input page name')}
  316. onClickOutside={() => { setRenameInputShown(false) }}
  317. onPressEnter={onPressEnterForRenameHandler}
  318. inputValidator={inputValidator}
  319. />
  320. )}
  321. { !isRenameInputShown && ( */}
  322. <a href={`/${page._id}`} className="grw-pagetree-title-anchor flex-grow-1">
  323. <p className={`text-truncate m-auto ${page.isEmpty && 'text-muted'}`}>{nodePath.basename(pageTitle as string) || '/'}</p>
  324. </a>
  325. {/* )} */}
  326. {(page.descendantCount != null && page.descendantCount > 0) && (
  327. <div className="grw-pagetree-count-wrapper">
  328. <ItemCount descendantCount={page.descendantCount} />
  329. </div>
  330. )}
  331. <div className="grw-pagetree-control d-flex">
  332. <PageItemControl
  333. pageId={page._id}
  334. isEnableActions={isEnableActions}
  335. onClickBookmarkMenuItem={bookmarkMenuItemClickHandler}
  336. onClickDuplicateMenuItem={duplicateMenuItemClickHandler}
  337. onClickRenameMenuItem={renameMenuItemClickHandler}
  338. onClickDeleteMenuItem={deleteMenuItemClickHandler}
  339. >
  340. <DropdownToggle color="transparent" className="border-0 rounded btn-page-item-control p-0 grw-visible-on-hover">
  341. <i className="icon-options fa fa-rotate-90 text-muted p-1"></i>
  342. </DropdownToggle>
  343. </PageItemControl>
  344. <button
  345. type="button"
  346. className="border-0 rounded btn-page-item-control p-0 grw-visible-on-hover"
  347. onClick={onClickPlusButton}
  348. >
  349. <i className="icon-plus text-muted d-block p-1" />
  350. </button>
  351. </div>
  352. </li>
  353. {isEnableActions && (
  354. <ClosableTextInput
  355. isShown={isNewPageInputShown}
  356. placeholder={t('Input page name')}
  357. onClickOutside={() => { setNewPageInputShown(false) }}
  358. onPressEnter={onPressEnterForCreateHandler}
  359. inputValidator={inputValidator}
  360. />
  361. )}
  362. {
  363. isOpen && hasChildren() && currentChildren.map(node => (
  364. <div key={node.page._id} className="grw-pagetree-item-children">
  365. <Item
  366. isEnableActions={isEnableActions}
  367. itemNode={node}
  368. isOpen={false}
  369. isScrolled={props.isScrolled}
  370. targetPathOrId={targetPathOrId}
  371. isEnabledAttachTitleHeader={isEnabledAttachTitleHeader}
  372. onClickDuplicateMenuItem={onClickDuplicateMenuItem}
  373. onClickRenameMenuItem={onClickRenameMenuItem}
  374. onClickDeleteMenuItem={onClickDeleteMenuItem}
  375. />
  376. </div>
  377. ))
  378. }
  379. </div>
  380. );
  381. };
  382. export default Item;