Item.tsx 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. import React, {
  2. useCallback, useState, FC, useEffect, memo,
  3. } from 'react';
  4. import nodePath from 'path';
  5. import { useTranslation } from 'react-i18next';
  6. import { pagePathUtils } from '@growi/core';
  7. import { useDrag, useDrop } from 'react-dnd';
  8. import { toastWarning, toastError } from '~/client/util/apiNotification';
  9. import { ItemNode } from './ItemNode';
  10. import { IPageHasId } from '~/interfaces/page';
  11. import { useSWRxPageChildren } from '../../../stores/page-listing';
  12. import ClosableTextInput, { AlertInfo, AlertType } from '../../Common/ClosableTextInput';
  13. import PageItemControl from '../../Common/Dropdown/PageItemControl';
  14. import { IPageForPageDeleteModal } from '~/components/PageDeleteModal';
  15. import { apiv3Put } from '~/client/util/apiv3-client';
  16. import TriangleIcon from '~/components/Icons/TriangleIcon';
  17. const { isTopPage } = pagePathUtils;
  18. interface ItemProps {
  19. isEnableActions: boolean
  20. itemNode: ItemNode
  21. targetPathOrId?: string
  22. isOpen?: boolean
  23. onClickDeleteByPage?(page: IPageForPageDeleteModal): void
  24. }
  25. // Utility to mark target
  26. const markTarget = (children: ItemNode[], targetPathOrId?: string): void => {
  27. if (targetPathOrId == null) {
  28. return;
  29. }
  30. children.forEach((node) => {
  31. if (node.page._id === targetPathOrId || node.page.path === targetPathOrId) {
  32. node.page.isTarget = true;
  33. }
  34. return node;
  35. });
  36. };
  37. type ItemControlProps = {
  38. page: Partial<IPageHasId>
  39. isEnableActions: boolean
  40. isDeletable: boolean
  41. onClickPlusButton?(): void
  42. onClickDeleteButton?(): void
  43. onClickRenameButton?(): void
  44. }
  45. const ItemControl: FC<ItemControlProps> = memo((props: ItemControlProps) => {
  46. const onClickPlusButton = () => {
  47. if (props.onClickPlusButton == null) {
  48. return;
  49. }
  50. props.onClickPlusButton();
  51. };
  52. const onClickDeleteButtonHandler = () => {
  53. if (props.onClickDeleteButton == null) {
  54. return;
  55. }
  56. props.onClickDeleteButton();
  57. };
  58. const onClickRenameButtonHandler = () => {
  59. if (props.onClickRenameButton == null) {
  60. return;
  61. }
  62. props.onClickRenameButton();
  63. };
  64. if (props.page == null) {
  65. return <></>;
  66. }
  67. return (
  68. <>
  69. <PageItemControl
  70. page={props.page}
  71. onClickDeleteButtonHandler={onClickDeleteButtonHandler}
  72. isEnableActions={props.isEnableActions}
  73. isDeletable={props.isDeletable}
  74. onClickRenameButtonHandler={onClickRenameButtonHandler}
  75. />
  76. <button
  77. type="button"
  78. className="border-0 rounded grw-btn-page-management p-0"
  79. onClick={onClickPlusButton}
  80. >
  81. <i className="icon-plus text-muted d-block p-1" />
  82. </button>
  83. </>
  84. );
  85. });
  86. const ItemCount: FC = () => {
  87. return (
  88. <>
  89. <span className="grw-pagetree-count badge badge-pill badge-light text-muted">
  90. {/* TODO: consider to show the number of children pages */}
  91. 00
  92. </span>
  93. </>
  94. );
  95. };
  96. const Item: FC<ItemProps> = (props: ItemProps) => {
  97. const { t } = useTranslation();
  98. const {
  99. itemNode, targetPathOrId, isOpen: _isOpen = false, onClickDeleteByPage, isEnableActions,
  100. } = props;
  101. const { page, children } = itemNode;
  102. const [pageTitle, setPageTitle] = useState(page.path);
  103. const [currentChildren, setCurrentChildren] = useState(children);
  104. const [isOpen, setIsOpen] = useState(_isOpen);
  105. const [isNewPageInputShown, setNewPageInputShown] = useState(false);
  106. const [isRenameInputShown, setRenameInputShown] = useState(false);
  107. const { data, error } = useSWRxPageChildren(isOpen ? page._id : null);
  108. const [{ isDragging }, drag] = useDrag(() => ({
  109. type: 'PAGE_TREE',
  110. item: { page },
  111. collect: monitor => ({
  112. isDragging: monitor.isDragging(),
  113. }),
  114. }));
  115. const pageItemDropHandler = () => {
  116. // TODO: hit an api to rename the page by 85175
  117. // eslint-disable-next-line no-console
  118. console.log('pageItem was droped!!');
  119. };
  120. const [{ isOver }, drop] = useDrop(() => ({
  121. accept: 'PAGE_TREE',
  122. drop: pageItemDropHandler,
  123. hover: (item, monitor) => {
  124. // when a drag item is overlapped more than 1 sec, the drop target item will be opened.
  125. if (monitor.isOver()) {
  126. setTimeout(() => {
  127. if (monitor.isOver()) {
  128. setIsOpen(true);
  129. }
  130. }, 1000);
  131. }
  132. },
  133. collect: monitor => ({
  134. isOver: monitor.isOver(),
  135. }),
  136. }));
  137. const hasChildren = useCallback((): boolean => {
  138. return currentChildren != null && currentChildren.length > 0;
  139. }, [currentChildren]);
  140. const onClickLoadChildren = useCallback(async() => {
  141. setIsOpen(!isOpen);
  142. }, [isOpen]);
  143. const onClickPlusButton = useCallback(() => {
  144. setNewPageInputShown(true);
  145. }, []);
  146. const onClickDeleteButton = useCallback(() => {
  147. if (onClickDeleteByPage == null) {
  148. return;
  149. }
  150. const { _id: pageId, revision: revisionId, path } = page;
  151. if (pageId == null || revisionId == null || path == null) {
  152. throw Error('Any of _id, revision, and path must not be null.');
  153. }
  154. const pageToDelete: IPageForPageDeleteModal = {
  155. pageId,
  156. revisionId: revisionId as string,
  157. path,
  158. };
  159. onClickDeleteByPage(pageToDelete);
  160. }, [page, onClickDeleteByPage]);
  161. const onClickRenameButton = useCallback(() => {
  162. setRenameInputShown(true);
  163. }, []);
  164. // TODO: make a put request to pages/title
  165. const onPressEnterForRenameHandler = async(inputText: string) => {
  166. if (inputText.includes('/')) {
  167. toastWarning('Cannot rename a title that contains "/"');
  168. return;
  169. }
  170. const parentPath = nodePath.dirname(page.path as string || '/');
  171. const childPath = nodePath.basename(inputText);
  172. const newPagePath = `${parentPath}/${childPath}`;
  173. try {
  174. const res = await apiv3Put('pages/rename', { newPagePath, pageId: page._id, revisionId: page.revision });
  175. const title = nodePath.basename(res.data.page.path);
  176. setPageTitle(title);
  177. }
  178. catch (err) {
  179. toastError(err);
  180. }
  181. finally {
  182. setRenameInputShown(false);
  183. }
  184. };
  185. // TODO: go to create page page
  186. const onPressEnterForCreateHandler = () => {
  187. toastWarning(t('search_result.currently_not_implemented'));
  188. setNewPageInputShown(false);
  189. };
  190. const inputValidator = (title: string | null): AlertInfo | null => {
  191. if (title == null || title === '') {
  192. return {
  193. type: AlertType.WARNING,
  194. message: t('form_validation.title_required'),
  195. };
  196. }
  197. return null;
  198. };
  199. // didMount
  200. useEffect(() => {
  201. if (hasChildren()) setIsOpen(true);
  202. }, []);
  203. /*
  204. * Make sure itemNode.children and currentChildren are synced
  205. */
  206. useEffect(() => {
  207. if (children.length > currentChildren.length) {
  208. markTarget(children, targetPathOrId);
  209. setCurrentChildren(children);
  210. }
  211. }, []);
  212. /*
  213. * When swr fetch succeeded
  214. */
  215. useEffect(() => {
  216. if (isOpen && error == null && data != null) {
  217. const newChildren = ItemNode.generateNodesFromPages(data.children);
  218. markTarget(newChildren, targetPathOrId);
  219. setCurrentChildren(newChildren);
  220. }
  221. }, [data, isOpen]);
  222. return (
  223. <div className={`grw-pagetree-item-container ${isOver ? 'grw-pagetree-is-over' : ''}`}>
  224. <li
  225. ref={(c) => { drag(c); drop(c) }}
  226. className={`list-group-item list-group-item-action border-0 py-1 d-flex align-items-center ${page.isTarget ? 'grw-pagetree-is-target' : ''}`}
  227. >
  228. <button
  229. type="button"
  230. className={`grw-pagetree-button btn ${isOpen ? 'grw-pagetree-open' : ''}`}
  231. onClick={onClickLoadChildren}
  232. >
  233. <div className="grw-triangle-icon">
  234. <TriangleIcon />
  235. </div>
  236. </button>
  237. { isRenameInputShown && (
  238. <ClosableTextInput
  239. isShown
  240. placeholder={t('Input page name')}
  241. onClickOutside={() => { setRenameInputShown(false) }}
  242. onPressEnter={onPressEnterForRenameHandler}
  243. inputValidator={inputValidator}
  244. />
  245. )}
  246. { !isRenameInputShown && (
  247. <a href={page._id} className="grw-pagetree-title-anchor flex-grow-1">
  248. <p className={`text-truncate m-auto ${page.isEmpty && 'text-muted'}`}>{nodePath.basename(pageTitle as string) || '/'}</p>
  249. </a>
  250. )}
  251. <div className="grw-pagetree-count-wrapper">
  252. <ItemCount />
  253. </div>
  254. <div className="grw-pagetree-control d-none">
  255. <ItemControl
  256. page={page}
  257. onClickPlusButton={onClickPlusButton}
  258. onClickDeleteButton={onClickDeleteButton}
  259. onClickRenameButton={onClickRenameButton}
  260. isEnableActions={isEnableActions}
  261. isDeletable={!page.isEmpty && !isTopPage(page.path as string)}
  262. />
  263. </div>
  264. </li>
  265. {isEnableActions && (
  266. <ClosableTextInput
  267. isShown={isNewPageInputShown}
  268. placeholder={t('Input page name')}
  269. onClickOutside={() => { setNewPageInputShown(false) }}
  270. onPressEnter={onPressEnterForCreateHandler}
  271. inputValidator={inputValidator}
  272. />
  273. )}
  274. {
  275. isOpen && hasChildren() && currentChildren.map(node => (
  276. <div key={node.page._id} className="grw-pagetree-item-children">
  277. <Item
  278. isEnableActions={isEnableActions}
  279. itemNode={node}
  280. isOpen={false}
  281. targetPathOrId={targetPathOrId}
  282. onClickDeleteByPage={onClickDeleteByPage}
  283. />
  284. </div>
  285. ))
  286. }
  287. </div>
  288. );
  289. };
  290. export default Item;