Item.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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 } from '@growi/core';
  9. import { toastWarning, toastError, toastSuccess } from '~/client/util/apiNotification';
  10. import { useSWRxPageChildren } from '~/stores/page-listing';
  11. import { IPageForPageDeleteModal } from '~/stores/modal';
  12. import { apiv3Put } from '~/client/util/apiv3-client';
  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 = (inputText: string) => {
  208. setNewPageInputShown(false);
  209. const parentPath = pathUtils.addTrailingSlash(page.path as string);
  210. const newPagePath = `${parentPath}${inputText}`;
  211. console.log(newPagePath);
  212. // TODO: https://redmine.weseek.co.jp/issues/87943
  213. };
  214. const inputValidator = (title: string | null): AlertInfo | null => {
  215. if (title == null || title === '' || title.trim() === '') {
  216. return {
  217. type: AlertType.WARNING,
  218. message: t('form_validation.title_required'),
  219. };
  220. }
  221. if (title.includes('/')) {
  222. return {
  223. type: AlertType.WARNING,
  224. message: t('form_validation.slashed_are_not_yet_supported'),
  225. };
  226. }
  227. return null;
  228. };
  229. // didMount
  230. useEffect(() => {
  231. if (hasChildren()) setIsOpen(true);
  232. }, [hasChildren]);
  233. /*
  234. * Make sure itemNode.children and currentChildren are synced
  235. */
  236. useEffect(() => {
  237. if (children.length > currentChildren.length) {
  238. markTarget(children, targetPathOrId);
  239. setCurrentChildren(children);
  240. }
  241. }, [children, currentChildren.length, targetPathOrId]);
  242. /*
  243. * When swr fetch succeeded
  244. */
  245. useEffect(() => {
  246. if (isOpen && data != null) {
  247. const newChildren = ItemNode.generateNodesFromPages(data.children);
  248. markTarget(newChildren, targetPathOrId);
  249. setCurrentChildren(newChildren);
  250. }
  251. }, [data, isOpen, targetPathOrId]);
  252. return (
  253. <div id={`pagetree-item-${page._id}`} className={`grw-pagetree-item-container ${isOver ? 'grw-pagetree-is-over' : ''} ${shouldHide ? 'd-none' : ''}`}>
  254. <li
  255. ref={(c) => { drag(c); drop(c) }}
  256. className={`list-group-item list-group-item-action border-0 py-1 d-flex align-items-center ${page.isTarget ? 'grw-pagetree-is-target' : ''}`}
  257. >
  258. <div className="grw-triangle-container d-flex justify-content-center">
  259. {hasDescendants && (
  260. <button
  261. type="button"
  262. className={`grw-pagetree-button btn ${isOpen ? 'grw-pagetree-open' : ''}`}
  263. onClick={onClickLoadChildren}
  264. >
  265. <div className="grw-triangle-icon d-flex justify-content-center">
  266. <TriangleIcon />
  267. </div>
  268. </button>
  269. )}
  270. </div>
  271. {/* TODO: rename page title on input form by 87757 */}
  272. {/* { isRenameInputShown && (
  273. <ClosableTextInput
  274. isShown
  275. value={nodePath.basename(pageTitle as string)}
  276. placeholder={t('Input page name')}
  277. onClickOutside={() => { setRenameInputShown(false) }}
  278. onPressEnter={onPressEnterForRenameHandler}
  279. inputValidator={inputValidator}
  280. />
  281. )}
  282. { !isRenameInputShown && ( */}
  283. <a href={page._id} className="grw-pagetree-title-anchor flex-grow-1">
  284. <p className={`text-truncate m-auto ${page.isEmpty && 'text-muted'}`}>{nodePath.basename(pageTitle as string) || '/'}</p>
  285. </a>
  286. {/* )} */}
  287. {(page.descendantCount != null && page.descendantCount > 0) && (
  288. <div className="grw-pagetree-count-wrapper">
  289. <ItemCount descendantCount={page.descendantCount} />
  290. </div>
  291. )}
  292. <div className="grw-pagetree-control d-none">
  293. <PageItemControl
  294. pageId={page._id}
  295. isEnableActions={isEnableActions}
  296. showBookmarkMenuItem
  297. onClickBookmarkMenuItem={bookmarkMenuItemClickHandler}
  298. onClickDuplicateMenuItem={duplicateMenuItemClickHandler}
  299. onClickDeleteMenuItem={onClickDeleteButton}
  300. onClickRenameMenuItem={renameMenuItemClickHandler}
  301. >
  302. <DropdownToggle color="transparent" className="border-0 rounded btn-page-item-control p-0">
  303. <i className="icon-options fa fa-rotate-90 text-muted p-1"></i>
  304. </DropdownToggle>
  305. </PageItemControl>
  306. <button
  307. type="button"
  308. className="border-0 rounded btn-page-item-control p-0"
  309. onClick={onClickPlusButton}
  310. >
  311. <i className="icon-plus text-muted d-block p-1" />
  312. </button>
  313. </div>
  314. </li>
  315. {isEnableActions && (
  316. <ClosableTextInput
  317. isShown={isNewPageInputShown}
  318. placeholder={t('Input page name')}
  319. onClickOutside={() => { setNewPageInputShown(false) }}
  320. onPressEnter={onPressEnterForCreateHandler}
  321. inputValidator={inputValidator}
  322. />
  323. )}
  324. {
  325. isOpen && hasChildren() && currentChildren.map(node => (
  326. <div key={node.page._id} className="grw-pagetree-item-children">
  327. <Item
  328. isEnableActions={isEnableActions}
  329. itemNode={node}
  330. isOpen={false}
  331. targetPathOrId={targetPathOrId}
  332. onClickDuplicateMenuItem={onClickDuplicateMenuItem}
  333. onClickRenameMenuItem={onClickRenameMenuItem}
  334. onClickDeleteMenuItem={onClickDeleteMenuItem}
  335. />
  336. </div>
  337. ))
  338. }
  339. </div>
  340. );
  341. };
  342. export default Item;