Item.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  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 { 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?(pageId: string, path: string): void
  25. onClickRenameMenuItem?(pageId: string, revisionId: string, path: string): void
  26. onClickDeleteMenuItem?(pageToDelete: IPageForPageDeleteModal, callback?: VoidFunction): void
  27. onSelfDeleted?: VoidFunction
  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, onSelfDeleted,
  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. onClickDuplicateMenuItem(pageId, path);
  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. onClickRenameMenuItem(pageId, revisionId as string, path);
  196. }, [onClickRenameMenuItem, page]);
  197. const deleteMenuItemClickHandler = useCallback(async(_pageId: string, pageInfo): Promise<void> => {
  198. if (onClickDeleteMenuItem == null) {
  199. return;
  200. }
  201. const { _id: pageId, revision: revisionId, path } = page;
  202. if (pageId == null || revisionId == null || path == null) {
  203. throw Error('Any of _id, revision, and path must not be null.');
  204. }
  205. const pageToDelete: IPageForPageDeleteModal = {
  206. pageId,
  207. revisionId: revisionId as string,
  208. path,
  209. isAbleToDeleteCompletely: pageInfo?.isAbleToDeleteCompletely,
  210. };
  211. onClickDeleteMenuItem(pageToDelete, async() => {
  212. if (onSelfDeleted != null) await onSelfDeleted();
  213. });
  214. }, [onClickDeleteMenuItem, page, onSelfDeleted]);
  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. onClickRenameMenuItem={renameMenuItemClickHandler}
  328. onClickDeleteMenuItem={deleteMenuItemClickHandler}
  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. isEnabledAttachTitleHeader={isEnabledAttachTitleHeader}
  361. onClickDuplicateMenuItem={onClickDuplicateMenuItem}
  362. onClickRenameMenuItem={onClickRenameMenuItem}
  363. onClickDeleteMenuItem={onClickDeleteMenuItem}
  364. onSelfDeleted={async() => { await mutateChildren() }}
  365. />
  366. </div>
  367. ))
  368. }
  369. </div>
  370. );
  371. };
  372. export default Item;