Item.tsx 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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. onClickDeleteButtonHandler?(): void
  41. onClickRenameButtonHandler?(): void
  42. onClickPlusButtonHandler?(): void
  43. }
  44. const ItemControl: FC<ItemControlProps> = memo((props: ItemControlProps) => {
  45. const onClickPlusButton = () => {
  46. if (props.onClickPlusButtonHandler == null) {
  47. return;
  48. }
  49. props.onClickPlusButtonHandler();
  50. };
  51. const onClickDeleteButton = () => {
  52. if (props.onClickDeleteButtonHandler == null) {
  53. return;
  54. }
  55. props.onClickDeleteButtonHandler();
  56. };
  57. const onClickRenameButton = () => {
  58. if (props.onClickRenameButtonHandler == null) {
  59. return;
  60. }
  61. props.onClickRenameButtonHandler();
  62. };
  63. if (props.page == null) {
  64. return <></>;
  65. }
  66. return (
  67. <>
  68. <PageItemControl
  69. page={props.page}
  70. onClickDeleteButton={onClickDeleteButton}
  71. isEnableActions={props.isEnableActions}
  72. isDeletable={props.isDeletable}
  73. onClickRenameButton={onClickRenameButton}
  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 [isInputForRenameOpen, setIsInputForRenameOpen] = useState(false);
  104. const [isNewPageInputShown, setNewPageInputShown] = useState(false);
  105. const { data, error } = useSWRxPageChildren(isOpen ? page._id : null);
  106. const [{ isDragging }, drag] = useDrag(() => ({
  107. type: 'PAGE_TREE',
  108. item: { page },
  109. collect: monitor => ({
  110. isDragging: monitor.isDragging(),
  111. }),
  112. }));
  113. const pageItemDropHandler = () => {
  114. // TODO: hit an api to rename the page by 85175
  115. // eslint-disable-next-line no-console
  116. console.log('pageItem was droped!!');
  117. };
  118. const [{ isOver }, drop] = useDrop(() => ({
  119. accept: 'PAGE_TREE',
  120. drop: pageItemDropHandler,
  121. hover: (item, monitor) => {
  122. // when a drag item is overlapped more than 1 sec, the drop target item will be opened.
  123. if (monitor.isOver()) {
  124. setTimeout(() => {
  125. if (monitor.isOver()) {
  126. setIsOpen(true);
  127. }
  128. }, 1000);
  129. }
  130. },
  131. collect: monitor => ({
  132. isOver: monitor.isOver(),
  133. }),
  134. }));
  135. const hasChildren = useCallback((): boolean => {
  136. return currentChildren != null && currentChildren.length > 0;
  137. }, [currentChildren]);
  138. const onClickLoadChildren = useCallback(async() => {
  139. setIsOpen(!isOpen);
  140. }, [isOpen]);
  141. const onClickDeleteButtonHandler = useCallback(() => {
  142. if (onClickDeleteByPage == null) {
  143. return;
  144. }
  145. const { _id: pageId, revision: revisionId, path } = page;
  146. if (pageId == null || revisionId == null || path == null) {
  147. throw Error('Any of _id, revision, and path must not be null.');
  148. }
  149. const pageToDelete: IPageForPageDeleteModal = {
  150. pageId,
  151. revisionId: revisionId as string,
  152. path,
  153. };
  154. onClickDeleteByPage(pageToDelete);
  155. }, [page, onClickDeleteByPage]);
  156. const onClickRenameButtonHandler = useCallback(() => {
  157. setIsInputForRenameOpen(true);
  158. }, []);
  159. const onPressEnterHandlerForRename = () => {
  160. console.log('Page path has been renamed!!');
  161. setIsInputForRenameOpen(false);
  162. };
  163. const inputValidator = (title: string | null): AlertInfo | null => {
  164. if (title == null || title === '') {
  165. return {
  166. type: AlertType.WARNING,
  167. message: t('form_validation.title_required'),
  168. };
  169. }
  170. return null;
  171. };
  172. // TODO: go to create page page
  173. const onPressEnterHandler = () => {
  174. toastWarning(t('search_result.currently_not_implemented'));
  175. };
  176. // didMount
  177. useEffect(() => {
  178. if (hasChildren()) setIsOpen(true);
  179. }, []);
  180. /*
  181. * Make sure itemNode.children and currentChildren are synced
  182. */
  183. useEffect(() => {
  184. if (children.length > currentChildren.length) {
  185. markTarget(children, targetPathOrId);
  186. setCurrentChildren(children);
  187. }
  188. }, []);
  189. /*
  190. * When swr fetch succeeded
  191. */
  192. useEffect(() => {
  193. if (isOpen && error == null && data != null) {
  194. const newChildren = ItemNode.generateNodesFromPages(data.children);
  195. markTarget(newChildren, targetPathOrId);
  196. setCurrentChildren(newChildren);
  197. }
  198. }, [data, isOpen]);
  199. return (
  200. <div className={`grw-pagetree-item-container ${isOver ? 'grw-pagetree-is-over' : ''}`}>
  201. <li
  202. ref={(c) => { drag(c); drop(c) }}
  203. className={`list-group-item list-group-item-action border-0 py-1 d-flex align-items-center ${page.isTarget ? 'grw-pagetree-is-target' : ''}`}
  204. >
  205. <button
  206. type="button"
  207. className={`grw-pagetree-button btn ${isOpen ? 'grw-pagetree-open' : ''}`}
  208. onClick={onClickLoadChildren}
  209. >
  210. <div className="grw-triangle-icon">
  211. <TriangleIcon />
  212. </div>
  213. </button>
  214. { isInputForRenameOpen && (
  215. <ClosableTextInput
  216. isShown
  217. placeholder={page.path}
  218. onClickOutside={() => { setIsInputForRenameOpen(false) }}
  219. onPressEnter={onPressEnterHandlerForRename}
  220. />
  221. )}
  222. { !isInputForRenameOpen && (
  223. <a href={page._id} className="grw-pagetree-title-anchor flex-grow-1">
  224. <p className={`text-truncate m-auto ${page.isEmpty && 'text-muted'}`}>{nodePath.basename(page.path as string) || '/'}</p>
  225. </a>
  226. )}
  227. <div className="grw-pagetree-count-wrapper">
  228. <ItemCount />
  229. </div>
  230. <div className="grw-pagetree-control d-none">
  231. <ItemControl
  232. page={page}
  233. onClickDeleteButtonHandler={onClickDeleteButtonHandler}
  234. onClickRenameButtonHandler={onClickRenameButtonHandler}
  235. onClickPlusButtonHandler={() => { setNewPageInputShown(true) }}
  236. isEnableActions={isEnableActions}
  237. isDeletable={!page.isEmpty && !isTopPage(page.path as string)}
  238. />
  239. </div>
  240. </li>
  241. {isEnableActions && (
  242. <ClosableTextInput
  243. isShown={isNewPageInputShown}
  244. placeholder={t('Input page name')}
  245. onClickOutside={() => { setNewPageInputShown(false) }}
  246. onPressEnter={onPressEnterHandler}
  247. inputValidator={inputValidator}
  248. />
  249. )}
  250. {
  251. isOpen && hasChildren() && currentChildren.map(node => (
  252. <div key={node.page._id} className="grw-pagetree-item-children">
  253. <Item
  254. isEnableActions={isEnableActions}
  255. itemNode={node}
  256. isOpen={false}
  257. targetPathOrId={targetPathOrId}
  258. onClickDeleteByPage={onClickDeleteByPage}
  259. />
  260. </div>
  261. ))
  262. }
  263. </div>
  264. );
  265. };
  266. export default Item;