Item.tsx 9.0 KB

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