Item.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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 } from '~/client/util/apiNotification';
  10. import { useSWRxPageChildren } from '~/stores/page-listing';
  11. import { IPageForPageDeleteModal } from '~/stores/ui';
  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 { AsyncPageItemControl } 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. onClickDeleteByPage?(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, onClickDeleteByPage, 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 [isRenameInputShown, setRenameInputShown] = useState(false);
  66. const { data, error } = useSWRxPageChildren(isOpen ? page._id : null);
  67. const hasDescendants = (page.descendantCount != null && page?.descendantCount > 0);
  68. const [{ isDragging }, drag] = useDrag(() => ({
  69. type: 'PAGE_TREE',
  70. item: { page },
  71. collect: monitor => ({
  72. isDragging: monitor.isDragging(),
  73. }),
  74. }));
  75. const pageItemDropHandler = () => {
  76. // TODO: hit an api to rename the page by 85175
  77. // eslint-disable-next-line no-console
  78. console.log('pageItem was droped!!');
  79. };
  80. const [{ isOver }, drop] = useDrop(() => ({
  81. accept: 'PAGE_TREE',
  82. drop: pageItemDropHandler,
  83. hover: (item, monitor) => {
  84. // when a drag item is overlapped more than 1 sec, the drop target item will be opened.
  85. if (monitor.isOver()) {
  86. setTimeout(() => {
  87. if (monitor.isOver()) {
  88. setIsOpen(true);
  89. }
  90. }, 1000);
  91. }
  92. },
  93. collect: monitor => ({
  94. isOver: monitor.isOver(),
  95. }),
  96. }));
  97. const hasChildren = useCallback((): boolean => {
  98. return currentChildren != null && currentChildren.length > 0;
  99. }, [currentChildren]);
  100. const onClickLoadChildren = useCallback(async() => {
  101. setIsOpen(!isOpen);
  102. }, [isOpen]);
  103. const onClickPlusButton = useCallback(() => {
  104. setNewPageInputShown(true);
  105. }, []);
  106. const duplicateMenuItemClickHandler = useCallback((): void => {
  107. if (onClickDuplicateMenuItem == null) {
  108. return;
  109. }
  110. const { _id: pageId, path } = page;
  111. if (pageId == null || path == null) {
  112. throw Error('Any of _id and path must not be null.');
  113. }
  114. onClickDuplicateMenuItem(pageId, path);
  115. }, [onClickDuplicateMenuItem, page]);
  116. /*
  117. * Rename: TODO: rename page title on input form by #87757
  118. */
  119. // const onClickRenameButton = useCallback(async(_pageId: string): Promise<void> => {
  120. // setRenameInputShown(true);
  121. // }, []);
  122. // const onPressEnterForRenameHandler = async(inputText: string) => {
  123. // const parentPath = getParentPagePath(page.path as string)
  124. // const newPagePath = `${parentPath}/${inputText}`;
  125. // try {
  126. // setPageTitle(inputText);
  127. // setRenameInputShown(false);
  128. // await apiv3Put('/pages/rename', { newPagePath, pageId: page._id, revisionId: page.revision });
  129. // }
  130. // catch (err) {
  131. // // open ClosableInput and set pageTitle back to the previous title
  132. // setPageTitle(nodePath.basename(pageTitle as string));
  133. // setRenameInputShown(true);
  134. // toastError(err);
  135. // }
  136. // };
  137. const renameMenuItemClickHandler = useCallback((): void => {
  138. if (onClickRenameMenuItem == null) {
  139. return;
  140. }
  141. const { _id: pageId, revision: revisionId, path } = page;
  142. if (pageId == null || revisionId == null || path == null) {
  143. throw Error('Any of _id and revisionId and path must not be null.');
  144. }
  145. onClickRenameMenuItem(pageId, revisionId as string, path);
  146. }, [onClickRenameMenuItem, page]);
  147. const onClickDeleteButton = useCallback(async(_pageId: string): Promise<void> => {
  148. if (onClickDeleteByPage == null) {
  149. return;
  150. }
  151. const { _id: pageId, revision: revisionId, path } = page;
  152. if (pageId == null || revisionId == null || path == null) {
  153. throw Error('Any of _id, revision, and path must not be null.');
  154. }
  155. const pageToDelete: IPageForPageDeleteModal = {
  156. pageId,
  157. revisionId: revisionId as string,
  158. path,
  159. };
  160. onClickDeleteByPage(pageToDelete);
  161. }, [page, onClickDeleteByPage]);
  162. const onPressEnterForCreateHandler = (inputText: string) => {
  163. setNewPageInputShown(false);
  164. const parentPath = pathUtils.addTrailingSlash(page.path as string);
  165. const newPagePath = `${parentPath}${inputText}`;
  166. console.log(newPagePath);
  167. // TODO: https://redmine.weseek.co.jp/issues/87943
  168. };
  169. const inputValidator = (title: string | null): AlertInfo | null => {
  170. if (title == null || title === '' || title.trim() === '') {
  171. return {
  172. type: AlertType.WARNING,
  173. message: t('form_validation.title_required'),
  174. };
  175. }
  176. if (title.includes('/')) {
  177. return {
  178. type: AlertType.WARNING,
  179. message: t('form_validation.slashed_are_not_yet_supported'),
  180. };
  181. }
  182. return null;
  183. };
  184. // didMount
  185. useEffect(() => {
  186. if (hasChildren()) setIsOpen(true);
  187. }, [hasChildren]);
  188. /*
  189. * Make sure itemNode.children and currentChildren are synced
  190. */
  191. useEffect(() => {
  192. if (children.length > currentChildren.length) {
  193. markTarget(children, targetPathOrId);
  194. setCurrentChildren(children);
  195. }
  196. }, [children, currentChildren.length, targetPathOrId]);
  197. /*
  198. * When swr fetch succeeded
  199. */
  200. useEffect(() => {
  201. if (isOpen && error == null && data != null) {
  202. const newChildren = ItemNode.generateNodesFromPages(data.children);
  203. markTarget(newChildren, targetPathOrId);
  204. setCurrentChildren(newChildren);
  205. }
  206. }, [data, error, isOpen, targetPathOrId]);
  207. return (
  208. <div className={`grw-pagetree-item-container ${isOver ? 'grw-pagetree-is-over' : ''}`}>
  209. <li
  210. ref={(c) => { drag(c); drop(c) }}
  211. className={`list-group-item list-group-item-action border-0 py-1 d-flex align-items-center ${page.isTarget ? 'grw-pagetree-is-target' : ''}`}
  212. >
  213. <div className="grw-triangle-container d-flex justify-content-center">
  214. {hasDescendants && (
  215. <button
  216. type="button"
  217. className={`grw-pagetree-button btn ${isOpen ? 'grw-pagetree-open' : ''}`}
  218. onClick={onClickLoadChildren}
  219. >
  220. <div className="grw-triangle-icon d-flex justify-content-center">
  221. <TriangleIcon />
  222. </div>
  223. </button>
  224. )}
  225. </div>
  226. {/* TODO: rename page title on input form by 87757 */}
  227. {/* { isRenameInputShown && (
  228. <ClosableTextInput
  229. isShown
  230. value={nodePath.basename(pageTitle as string)}
  231. placeholder={t('Input page name')}
  232. onClickOutside={() => { setRenameInputShown(false) }}
  233. onPressEnter={onPressEnterForRenameHandler}
  234. inputValidator={inputValidator}
  235. />
  236. )}
  237. { !isRenameInputShown && ( */}
  238. <a href={page._id} className="grw-pagetree-title-anchor flex-grow-1">
  239. <p className={`text-truncate m-auto ${page.isEmpty && 'text-muted'}`}>{nodePath.basename(pageTitle as string) || '/'}</p>
  240. </a>
  241. {/* )} */}
  242. {(page.descendantCount != null && page.descendantCount > 0) && (
  243. <div className="grw-pagetree-count-wrapper">
  244. <ItemCount descendantCount={page.descendantCount} />
  245. </div>
  246. )}
  247. <div className="grw-pagetree-control d-none">
  248. <AsyncPageItemControl
  249. pageId={page._id}
  250. isEnableActions={isEnableActions}
  251. showBookmarkMenuItem
  252. onClickBookmarkMenuItem={bookmarkMenuItemClickHandler}
  253. onClickDuplicateMenuItem={duplicateMenuItemClickHandler}
  254. onClickDeleteMenuItem={onClickDeleteButton}
  255. onClickRenameMenuItem={renameMenuItemClickHandler}
  256. >
  257. <DropdownToggle color="transparent" className="border-0 rounded btn-page-item-control p-0">
  258. <i className="icon-options fa fa-rotate-90 text-muted p-1"></i>
  259. </DropdownToggle>
  260. </AsyncPageItemControl>
  261. <button
  262. type="button"
  263. className="border-0 rounded btn-page-item-control p-0"
  264. onClick={onClickPlusButton}
  265. >
  266. <i className="icon-plus text-muted d-block p-1" />
  267. </button>
  268. </div>
  269. </li>
  270. {isEnableActions && (
  271. <ClosableTextInput
  272. isShown={isNewPageInputShown}
  273. placeholder={t('Input page name')}
  274. onClickOutside={() => { setNewPageInputShown(false) }}
  275. onPressEnter={onPressEnterForCreateHandler}
  276. inputValidator={inputValidator}
  277. />
  278. )}
  279. {
  280. isOpen && hasChildren() && currentChildren.map(node => (
  281. <div key={node.page._id} className="grw-pagetree-item-children">
  282. <Item
  283. isEnableActions={isEnableActions}
  284. itemNode={node}
  285. isOpen={false}
  286. targetPathOrId={targetPathOrId}
  287. onClickDuplicateMenuItem={onClickDuplicateMenuItem}
  288. onClickRenameMenuItem={onClickRenameMenuItem}
  289. onClickDeleteByPage={onClickDeleteByPage}
  290. />
  291. </div>
  292. ))
  293. }
  294. </div>
  295. );
  296. };
  297. export default Item;