Item.tsx 14 KB

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