Item.tsx 13 KB

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