Item.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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 { toastWarning, toastError } from '~/client/util/apiNotification';
  9. import { useSWRxPageChildren } from '~/stores/page-listing';
  10. import { IPageForPageDeleteModal } from '~/stores/ui';
  11. import { apiv3Put } from '~/client/util/apiv3-client';
  12. import TriangleIcon from '~/components/Icons/TriangleIcon';
  13. import { bookmark, unbookmark } from '~/client/services/page-operation';
  14. import ClosableTextInput, { AlertInfo, AlertType } from '../../Common/ClosableTextInput';
  15. import { AsyncPageItemControl } from '../../Common/Dropdown/PageItemControl';
  16. import { ItemNode } from './ItemNode';
  17. interface ItemProps {
  18. isEnableActions: boolean
  19. itemNode: ItemNode
  20. targetPathOrId?: string
  21. isOpen?: boolean
  22. onClickDuplicateMenuItem?(pageId: string, path: string): void
  23. onClickRenameMenuItem?(pageId: string, revisionId: string, path: string): void
  24. onClickDeleteByPage?(pageToDelete: IPageForPageDeleteModal | null): void
  25. }
  26. // Utility to mark target
  27. const markTarget = (children: ItemNode[], targetPathOrId?: string): void => {
  28. if (targetPathOrId == null) {
  29. return;
  30. }
  31. children.forEach((node) => {
  32. if (node.page._id === targetPathOrId || node.page.path === targetPathOrId) {
  33. node.page.isTarget = true;
  34. }
  35. return node;
  36. });
  37. };
  38. const bookmarkMenuItemClickHandler = async(_pageId: string, _newValue: boolean): Promise<void> => {
  39. const bookmarkOperation = _newValue ? bookmark : unbookmark;
  40. await bookmarkOperation(_pageId);
  41. };
  42. type ItemCountProps = {
  43. descendantCount: number
  44. }
  45. const ItemCount: FC<ItemCountProps> = (props:ItemCountProps) => {
  46. return (
  47. <>
  48. <span className="grw-pagetree-count badge badge-pill badge-light text-muted">
  49. {props.descendantCount}
  50. </span>
  51. </>
  52. );
  53. };
  54. const Item: FC<ItemProps> = (props: ItemProps) => {
  55. const { t } = useTranslation();
  56. const {
  57. itemNode, targetPathOrId, isOpen: _isOpen = false, onClickDuplicateMenuItem, onClickRenameMenuItem, onClickDeleteByPage, isEnableActions,
  58. } = props;
  59. const { page, children } = itemNode;
  60. const [pageTitle, setPageTitle] = useState(page.path);
  61. const [currentChildren, setCurrentChildren] = useState(children);
  62. const [isOpen, setIsOpen] = useState(_isOpen);
  63. const [isNewPageInputShown, setNewPageInputShown] = useState(false);
  64. const [isRenameInputShown, setRenameInputShown] = useState(false);
  65. const { data, error } = useSWRxPageChildren(isOpen ? page._id : null);
  66. const hasDescendants = (page.descendantCount != null && page?.descendantCount > 0);
  67. const [{ isDragging }, drag] = useDrag(() => ({
  68. type: 'PAGE_TREE',
  69. item: { page },
  70. collect: monitor => ({
  71. isDragging: monitor.isDragging(),
  72. }),
  73. }));
  74. const pageItemDropHandler = () => {
  75. // TODO: hit an api to rename the page by 85175
  76. // eslint-disable-next-line no-console
  77. console.log('pageItem was droped!!');
  78. };
  79. const [{ isOver }, drop] = useDrop(() => ({
  80. accept: 'PAGE_TREE',
  81. drop: pageItemDropHandler,
  82. hover: (item, monitor) => {
  83. // when a drag item is overlapped more than 1 sec, the drop target item will be opened.
  84. if (monitor.isOver()) {
  85. setTimeout(() => {
  86. if (monitor.isOver()) {
  87. setIsOpen(true);
  88. }
  89. }, 1000);
  90. }
  91. },
  92. collect: monitor => ({
  93. isOver: monitor.isOver(),
  94. }),
  95. }));
  96. const hasChildren = useCallback((): boolean => {
  97. return currentChildren != null && currentChildren.length > 0;
  98. }, [currentChildren]);
  99. const onClickLoadChildren = useCallback(async() => {
  100. setIsOpen(!isOpen);
  101. }, [isOpen]);
  102. const onClickPlusButton = useCallback(() => {
  103. setNewPageInputShown(true);
  104. }, []);
  105. const duplicateMenuItemClickHandler = useCallback((): void => {
  106. if (onClickDuplicateMenuItem == null) {
  107. return;
  108. }
  109. const { _id: pageId, path } = page;
  110. if (pageId == null || path == null) {
  111. throw Error('Any of _id and path must not be null.');
  112. }
  113. onClickDuplicateMenuItem(pageId, path);
  114. }, [onClickDuplicateMenuItem, page]);
  115. /*
  116. * Rename: TODO: rename page title on input form
  117. */
  118. // const onClickRenameButton = useCallback(async(_pageId: string): Promise<void> => {
  119. // setRenameInputShown(true);
  120. // }, []);
  121. const renameMenuItemClickHandler = useCallback((): void => {
  122. if (onClickRenameMenuItem == null) {
  123. return;
  124. }
  125. const { _id: pageId, revision: revisionId, path } = page;
  126. if (pageId == null || revisionId == null || path == null) {
  127. throw Error('Any of _id and revisionId and path must not be null.');
  128. }
  129. onClickRenameMenuItem(pageId, revisionId as string, path);
  130. }, [onClickRenameMenuItem, page]);
  131. const onClickDeleteButton = useCallback(async(_pageId: string): Promise<void> => {
  132. if (onClickDeleteByPage == null) {
  133. return;
  134. }
  135. const { _id: pageId, revision: revisionId, path } = page;
  136. if (pageId == null || revisionId == null || path == null) {
  137. throw Error('Any of _id, revision, and path must not be null.');
  138. }
  139. const pageToDelete: IPageForPageDeleteModal = {
  140. pageId,
  141. revisionId: revisionId as string,
  142. path,
  143. };
  144. onClickDeleteByPage(pageToDelete);
  145. }, [page, onClickDeleteByPage]);
  146. const onPressEnterForRenameHandler = async(inputText: string) => {
  147. if (inputText == null || inputText === '' || inputText.trim() === '' || inputText.includes('/')) {
  148. return;
  149. }
  150. const parentPath = nodePath.dirname(page.path as string);
  151. const newPagePath = `${parentPath}/${inputText}`;
  152. try {
  153. setPageTitle(inputText);
  154. setRenameInputShown(false);
  155. await apiv3Put('/pages/rename', { newPagePath, pageId: page._id, revisionId: page.revision });
  156. }
  157. catch (err) {
  158. // open ClosableInput and set pageTitle back to the previous title
  159. setPageTitle(nodePath.basename(pageTitle as string));
  160. setRenameInputShown(true);
  161. toastError(err);
  162. }
  163. };
  164. // TODO: go to create page page
  165. const onPressEnterForCreateHandler = () => {
  166. toastWarning(t('search_result.currently_not_implemented'));
  167. setNewPageInputShown(false);
  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. { isRenameInputShown && (
  227. <ClosableTextInput
  228. isShown
  229. value={nodePath.basename(pageTitle as string)}
  230. placeholder={t('Input page name')}
  231. onClickOutside={() => { setRenameInputShown(false) }}
  232. onPressEnter={onPressEnterForRenameHandler}
  233. inputValidator={inputValidator}
  234. />
  235. )}
  236. { !isRenameInputShown && (
  237. <a href={page._id} className="grw-pagetree-title-anchor flex-grow-1">
  238. <p className={`text-truncate m-auto ${page.isEmpty && 'text-muted'}`}>{nodePath.basename(pageTitle as string) || '/'}</p>
  239. </a>
  240. )}
  241. {(page.descendantCount != null && page.descendantCount > 0) && (
  242. <div className="grw-pagetree-count-wrapper">
  243. <ItemCount descendantCount={page.descendantCount} />
  244. </div>
  245. )}
  246. <div className="grw-pagetree-control d-none">
  247. <AsyncPageItemControl
  248. pageId={page._id}
  249. isEnableActions={isEnableActions}
  250. showBookmarkMenuItem
  251. onClickBookmarkMenuItem={bookmarkMenuItemClickHandler}
  252. onClickDuplicateMenuItem={duplicateMenuItemClickHandler}
  253. onClickDeleteMenuItem={onClickDeleteButton}
  254. onClickRenameMenuItem={renameMenuItemClickHandler}
  255. >
  256. <DropdownToggle color="transparent" className="border-0 rounded btn-page-item-control p-0">
  257. <i className="icon-options fa fa-rotate-90 text-muted p-1"></i>
  258. </DropdownToggle>
  259. </AsyncPageItemControl>
  260. <button
  261. type="button"
  262. className="border-0 rounded btn-page-item-control p-0"
  263. onClick={onClickPlusButton}
  264. >
  265. <i className="icon-plus text-muted d-block p-1" />
  266. </button>
  267. </div>
  268. </li>
  269. {isEnableActions && (
  270. <ClosableTextInput
  271. isShown={isNewPageInputShown}
  272. placeholder={t('Input page name')}
  273. onClickOutside={() => { setNewPageInputShown(false) }}
  274. onPressEnter={onPressEnterForCreateHandler}
  275. inputValidator={inputValidator}
  276. />
  277. )}
  278. {
  279. isOpen && hasChildren() && currentChildren.map(node => (
  280. <div key={node.page._id} className="grw-pagetree-item-children">
  281. <Item
  282. isEnableActions={isEnableActions}
  283. itemNode={node}
  284. isOpen={false}
  285. targetPathOrId={targetPathOrId}
  286. onClickDuplicateMenuItem={onClickDuplicateMenuItem}
  287. onClickRenameMenuItem={onClickRenameMenuItem}
  288. onClickDeleteByPage={onClickDeleteByPage}
  289. />
  290. </div>
  291. ))
  292. }
  293. </div>
  294. );
  295. };
  296. export default Item;