Item.tsx 14 KB

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