GrowiContextualSubNavigation.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. import React, { useState, useEffect, useCallback } from 'react';
  2. import {
  3. isPopulated, IUser, pagePathUtils, IPagePopulatedToShowRevision,
  4. } from '@growi/core';
  5. import { useTranslation } from 'next-i18next';
  6. import dynamic from 'next/dynamic';
  7. import { useRouter } from 'next/router';
  8. import { DropdownItem } from 'reactstrap';
  9. import { exportAsMarkdown, updateContentWidth, useUpdateStateAfterSave } from '~/client/services/page-operation';
  10. import { apiPost } from '~/client/util/apiv1-client';
  11. import { toastSuccess, toastError } from '~/client/util/toastr';
  12. import {
  13. IPageToRenameWithMeta, IPageWithMeta, IPageInfoForEntity,
  14. } from '~/interfaces/page';
  15. import { OnDuplicatedFunction, OnRenamedFunction, OnDeletedFunction } from '~/interfaces/ui';
  16. import {
  17. useCurrentPathname,
  18. useCurrentUser, useIsGuestUser, useIsReadOnlyUser, useIsSharedUser, useShareLinkId, useIsContainerFluid, useIsIdenticalPath,
  19. } from '~/stores/context';
  20. import { usePageTagsForEditors } from '~/stores/editor';
  21. import {
  22. usePageAccessoriesModal, PageAccessoriesModalContents, IPageForPageDuplicateModal,
  23. usePageDuplicateModal, usePageRenameModal, usePageDeleteModal, usePagePresentationModal,
  24. } from '~/stores/modal';
  25. import {
  26. useSWRMUTxCurrentPage, useSWRxTagsInfo, useCurrentPageId, useIsNotFound, useTemplateTagData, useSWRxPageInfo,
  27. } from '~/stores/page';
  28. import {
  29. EditorMode, useDrawerMode, useEditorMode, useIsAbleToShowPageManagement, useIsAbleToShowTagLabel,
  30. useIsAbleToChangeEditorMode, useIsAbleToShowPageAuthors,
  31. } from '~/stores/ui';
  32. import CreateTemplateModal from '../CreateTemplateModal';
  33. import AttachmentIcon from '../Icons/AttachmentIcon';
  34. import HistoryIcon from '../Icons/HistoryIcon';
  35. import PresentationIcon from '../Icons/PresentationIcon';
  36. import ShareLinkIcon from '../Icons/ShareLinkIcon';
  37. import { NotAvailable } from '../NotAvailable';
  38. import { Skeleton } from '../Skeleton';
  39. import type { AuthorInfoProps } from './AuthorInfo';
  40. import { GrowiSubNavigation } from './GrowiSubNavigation';
  41. import type { SubNavButtonsProps } from './SubNavButtons';
  42. import AuthorInfoStyles from './AuthorInfo.module.scss';
  43. import PageEditorModeManagerStyles from './PageEditorModeManager.module.scss';
  44. import { useSWRxBookmarkFolderAndChild } from '~/stores/bookmark-folder';
  45. import { useSWRxUserBookmarks } from '~/stores/bookmark';
  46. const { isUsersHomePage } = pagePathUtils;
  47. const AuthorInfoSkeleton = () => <Skeleton additionalClass={`${AuthorInfoStyles['grw-author-info-skeleton']} py-1`} />;
  48. const PageEditorModeManager = dynamic(
  49. () => import('./PageEditorModeManager'),
  50. { ssr: false, loading: () => <Skeleton additionalClass={`${PageEditorModeManagerStyles['grw-page-editor-mode-manager-skeleton']}`} /> },
  51. );
  52. // TODO: If enable skeleton, we get hydration error when create a page from PageCreateModal
  53. // { ssr: false, loading: () => <Skeleton additionalClass='btn-skeleton py-2' /> },
  54. const SubNavButtons = dynamic<SubNavButtonsProps>(
  55. () => import('./SubNavButtons').then(mod => mod.SubNavButtons),
  56. { ssr: false, loading: () => <></> },
  57. );
  58. const AuthorInfo = dynamic<AuthorInfoProps>(() => import('./AuthorInfo').then(mod => mod.AuthorInfo), {
  59. ssr: false,
  60. loading: AuthorInfoSkeleton,
  61. });
  62. type PageOperationMenuItemsProps = {
  63. pageId: string,
  64. revisionId: string,
  65. isLinkSharingDisabled?: boolean,
  66. }
  67. const PageOperationMenuItems = (props: PageOperationMenuItemsProps): JSX.Element => {
  68. const { t } = useTranslation();
  69. const {
  70. pageId, revisionId, isLinkSharingDisabled,
  71. } = props;
  72. const { data: isGuestUser } = useIsGuestUser();
  73. const { data: isReadOnlyUser } = useIsReadOnlyUser();
  74. const { data: isSharedUser } = useIsSharedUser();
  75. const { open: openPresentationModal } = usePagePresentationModal();
  76. const { open: openAccessoriesModal } = usePageAccessoriesModal();
  77. return (
  78. <>
  79. {/* Presentation */}
  80. <DropdownItem
  81. onClick={() => openPresentationModal()}
  82. data-testid="open-presentation-modal-btn"
  83. className="grw-page-control-dropdown-item"
  84. >
  85. <i className="icon-fw grw-page-control-dropdown-icon">
  86. <PresentationIcon />
  87. </i>
  88. {t('Presentation Mode')}
  89. </DropdownItem>
  90. {/* Export markdown */}
  91. <DropdownItem
  92. onClick={() => exportAsMarkdown(pageId, revisionId, 'md')}
  93. className="grw-page-control-dropdown-item"
  94. >
  95. <i className="icon-fw icon-cloud-download grw-page-control-dropdown-icon"></i>
  96. {t('export_bulk.export_page_markdown')}
  97. </DropdownItem>
  98. <DropdownItem divider />
  99. {/*
  100. TODO: show Tooltip when menu is disabled
  101. refs: PageAccessoriesModalControl
  102. */}
  103. <DropdownItem
  104. onClick={() => openAccessoriesModal(PageAccessoriesModalContents.PageHistory)}
  105. disabled={!!isGuestUser || !!isSharedUser}
  106. data-testid="open-page-accessories-modal-btn-with-history-tab"
  107. className="grw-page-control-dropdown-item"
  108. >
  109. <span className="grw-page-control-dropdown-icon">
  110. <HistoryIcon />
  111. </span>
  112. {t('History')}
  113. </DropdownItem>
  114. <DropdownItem
  115. onClick={() => openAccessoriesModal(PageAccessoriesModalContents.Attachment)}
  116. data-testid="open-page-accessories-modal-btn-with-attachment-data-tab"
  117. className="grw-page-control-dropdown-item"
  118. >
  119. <span className="grw-page-control-dropdown-icon">
  120. <AttachmentIcon />
  121. </span>
  122. {t('attachment_data')}
  123. </DropdownItem>
  124. {!isGuestUser && !isReadOnlyUser && !isSharedUser && (
  125. <NotAvailable isDisabled={isLinkSharingDisabled ?? false} title="Disabled by admin">
  126. <DropdownItem
  127. onClick={() => openAccessoriesModal(PageAccessoriesModalContents.ShareLink)}
  128. data-testid="open-page-accessories-modal-btn-with-share-link-management-data-tab"
  129. className="grw-page-control-dropdown-item"
  130. >
  131. <span className="grw-page-control-dropdown-icon">
  132. <ShareLinkIcon />
  133. </span>
  134. {t('share_links.share_link_management')}
  135. </DropdownItem>
  136. </NotAvailable>
  137. )}
  138. </>
  139. );
  140. };
  141. type CreateTemplateMenuItemsProps = {
  142. onClickTemplateMenuItem: (isPageTemplateModalShown: boolean) => void,
  143. }
  144. const CreateTemplateMenuItems = (props: CreateTemplateMenuItemsProps): JSX.Element => {
  145. const { t } = useTranslation();
  146. const { onClickTemplateMenuItem } = props;
  147. const openPageTemplateModalHandler = () => {
  148. onClickTemplateMenuItem(true);
  149. };
  150. return (
  151. <>
  152. {/* Create template */}
  153. <DropdownItem
  154. onClick={openPageTemplateModalHandler}
  155. className="grw-page-control-dropdown-item"
  156. data-testid="open-page-template-modal-btn"
  157. >
  158. <i className="icon-fw icon-magic-wand grw-page-control-dropdown-icon"></i>
  159. {t('template.option_label.create/edit')}
  160. </DropdownItem>
  161. </>
  162. );
  163. };
  164. type GrowiContextualSubNavigationProps = {
  165. currentPage?: IPagePopulatedToShowRevision | null,
  166. isCompactMode?: boolean,
  167. isLinkSharingDisabled: boolean,
  168. };
  169. const GrowiContextualSubNavigation = (props: GrowiContextualSubNavigationProps): JSX.Element => {
  170. const { currentPage } = props;
  171. const router = useRouter();
  172. const { data: shareLinkId } = useShareLinkId();
  173. const { trigger: mutateCurrentPage } = useSWRMUTxCurrentPage();
  174. const { data: currentPathname } = useCurrentPathname();
  175. const isSharedPage = pagePathUtils.isSharedPage(currentPathname ?? '');
  176. const revision = currentPage?.revision;
  177. const revisionId = (revision != null && isPopulated(revision)) ? revision._id : undefined;
  178. const { data: isDrawerMode } = useDrawerMode();
  179. const { data: editorMode, mutate: mutateEditorMode } = useEditorMode();
  180. const { data: pageId } = useCurrentPageId();
  181. const { data: currentUser } = useCurrentUser();
  182. const { data: isNotFound } = useIsNotFound();
  183. const { data: isIdenticalPath } = useIsIdenticalPath();
  184. const { data: isGuestUser } = useIsGuestUser();
  185. const { data: isReadOnlyUser } = useIsReadOnlyUser();
  186. const { data: isSharedUser } = useIsSharedUser();
  187. const { data: isContainerFluid } = useIsContainerFluid();
  188. const { data: isAbleToShowPageManagement } = useIsAbleToShowPageManagement();
  189. const { data: isAbleToShowTagLabel } = useIsAbleToShowTagLabel();
  190. const { data: isAbleToChangeEditorMode } = useIsAbleToChangeEditorMode();
  191. const { data: isAbleToShowPageAuthors } = useIsAbleToShowPageAuthors();
  192. const { mutate: mutateSWRTagsInfo, data: tagsInfoData } = useSWRxTagsInfo(currentPage?._id);
  193. const { mutate: mutateBookmarkFolders } = useSWRxBookmarkFolderAndChild(currentUser?._id);
  194. const { mutate: mutateUserBookmarks } = useSWRxUserBookmarks(currentUser?._id);
  195. // eslint-disable-next-line max-len
  196. const { data: tagsForEditors, mutate: mutatePageTagsForEditors, sync: syncPageTagsForEditors } = usePageTagsForEditors(!isSharedPage ? currentPage?._id : undefined);
  197. const { open: openDuplicateModal } = usePageDuplicateModal();
  198. const { open: openRenameModal } = usePageRenameModal();
  199. const { open: openDeleteModal } = usePageDeleteModal();
  200. const { data: templateTagData } = useTemplateTagData();
  201. const { mutate: mutatePageInfo } = useSWRxPageInfo(pageId);
  202. const updateStateAfterSave = useUpdateStateAfterSave(pageId);
  203. const path = currentPage?.path ?? currentPathname;
  204. useEffect(() => {
  205. // Run only when tagsInfoData has been updated
  206. if (templateTagData == null) {
  207. syncPageTagsForEditors();
  208. }
  209. // eslint-disable-next-line react-hooks/exhaustive-deps
  210. }, [tagsInfoData?.tags]);
  211. useEffect(() => {
  212. if (pageId === null && templateTagData != null) {
  213. mutatePageTagsForEditors(templateTagData);
  214. }
  215. }, [pageId, mutatePageTagsForEditors, templateTagData, mutateSWRTagsInfo]);
  216. const [isPageTemplateModalShown, setIsPageTempleteModalShown] = useState(false);
  217. const { isCompactMode, isLinkSharingDisabled } = props;
  218. const isViewMode = editorMode === EditorMode.View;
  219. const tagsUpdatedHandlerForViewMode = useCallback(async (newTags: string[]) => {
  220. if (currentPage == null) {
  221. return;
  222. }
  223. const { _id: pageId, revision: revisionId } = currentPage;
  224. try {
  225. await apiPost('/tags.update', { pageId, revisionId, tags: newTags });
  226. updateStateAfterSave?.();
  227. toastSuccess('updated tags successfully');
  228. }
  229. catch (err) {
  230. toastError(err);
  231. }
  232. }, [currentPage, updateStateAfterSave]);
  233. const tagsUpdatedHandlerForEditMode = useCallback((newTags: string[]): void => {
  234. // It will not be reflected in the DB until the page is refreshed
  235. mutatePageTagsForEditors(newTags);
  236. return;
  237. }, [mutatePageTagsForEditors]);
  238. const reload = useCallback(() => {
  239. if (currentPathname != null) {
  240. router.push(currentPathname);
  241. }
  242. }, [currentPathname, router]);
  243. const duplicateItemClickedHandler = useCallback(async (page: IPageForPageDuplicateModal) => {
  244. const duplicatedHandler: OnDuplicatedFunction = (fromPath, toPath) => {
  245. router.push(toPath);
  246. };
  247. openDuplicateModal(page, { onDuplicated: duplicatedHandler });
  248. }, [openDuplicateModal, router]);
  249. const renameItemClickedHandler = useCallback(async (page: IPageToRenameWithMeta<IPageInfoForEntity>) => {
  250. const renamedHandler: OnRenamedFunction = () => {
  251. reload();
  252. };
  253. openRenameModal(page, { onRenamed: renamedHandler });
  254. }, [openRenameModal, reload]);
  255. const deleteItemClickedHandler = useCallback((pageWithMeta: IPageWithMeta) => {
  256. const deletedHandler: OnDeletedFunction = (pathOrPathsToDelete, isRecursively, isCompletely) => {
  257. if (typeof pathOrPathsToDelete !== 'string') {
  258. return;
  259. }
  260. const path = pathOrPathsToDelete;
  261. if (isCompletely) {
  262. // redirect to NotFound Page
  263. router.push(path);
  264. }
  265. else if (currentPathname != null) {
  266. router.push(currentPathname);
  267. }
  268. mutateCurrentPage();
  269. };
  270. openDeleteModal([pageWithMeta], { onDeleted: deletedHandler });
  271. }, [currentPathname, mutateCurrentPage, openDeleteModal, router]);
  272. const switchContentWidthHandler = useCallback(async (pageId: string, value: boolean) => {
  273. if (!isSharedPage) {
  274. await updateContentWidth(pageId, value);
  275. mutateCurrentPage();
  276. }
  277. }, [isSharedPage, mutateCurrentPage]);
  278. const templateMenuItemClickHandler = useCallback(() => {
  279. setIsPageTempleteModalShown(true);
  280. }, []);
  281. const RightComponent = () => {
  282. const additionalMenuItemsRenderer = () => {
  283. if (revisionId == null || pageId == null) {
  284. return (
  285. <>
  286. {!isReadOnlyUser
  287. && <CreateTemplateMenuItems
  288. onClickTemplateMenuItem={templateMenuItemClickHandler}
  289. />
  290. }
  291. </>);
  292. }
  293. return (
  294. <>
  295. <PageOperationMenuItems
  296. pageId={pageId}
  297. revisionId={revisionId}
  298. isLinkSharingDisabled={isLinkSharingDisabled}
  299. />
  300. {!isReadOnlyUser && <>
  301. <DropdownItem divider />
  302. <CreateTemplateMenuItems
  303. onClickTemplateMenuItem={templateMenuItemClickHandler}
  304. /></>
  305. }
  306. </>
  307. );
  308. };
  309. return (
  310. <>
  311. <div className="d-flex">
  312. <div className="d-flex flex-column align-items-end justify-content-center py-md-2" style={{ gap: `${isCompactMode ? '5px' : '7px'}` }}>
  313. {isViewMode && (
  314. <div className="h-50">
  315. {pageId != null && (
  316. <SubNavButtons
  317. isCompactMode={isCompactMode}
  318. pageId={pageId}
  319. revisionId={revisionId}
  320. shareLinkId={shareLinkId}
  321. path={path ?? currentPathname} // If the page is empty, "path" is undefined
  322. expandContentWidth={currentPage?.expandContentWidth ?? isContainerFluid}
  323. disableSeenUserInfoPopover={isSharedUser}
  324. showPageControlDropdown={isAbleToShowPageManagement}
  325. additionalMenuItemRenderer={additionalMenuItemsRenderer}
  326. onClickDuplicateMenuItem={duplicateItemClickedHandler}
  327. onClickRenameMenuItem={renameItemClickedHandler}
  328. onClickDeleteMenuItem={deleteItemClickedHandler}
  329. onClickSwitchContentWidth={switchContentWidthHandler}
  330. />
  331. )}
  332. </div>
  333. )}
  334. {isAbleToChangeEditorMode && (
  335. <PageEditorModeManager
  336. onPageEditorModeButtonClicked={viewType => mutateEditorMode(viewType)}
  337. isBtnDisabled={!!isGuestUser || !!isReadOnlyUser}
  338. editorMode={editorMode}
  339. />
  340. )}
  341. </div>
  342. {(isAbleToShowPageAuthors && !isCompactMode && !isUsersHomePage(path ?? '')) && (
  343. <ul className={`${AuthorInfoStyles['grw-author-info']} text-nowrap border-left d-none d-lg-block d-edit-none py-2 pl-4 mb-0 ml-3`}>
  344. <li className="pb-1">
  345. {currentPage != null
  346. ? <AuthorInfo user={currentPage.creator as IUser} date={currentPage.createdAt} mode="create" locate="subnav" />
  347. : <AuthorInfoSkeleton />
  348. }
  349. </li>
  350. <li className="mt-1 pt-1 border-top">
  351. {currentPage != null
  352. ? <AuthorInfo user={currentPage.lastUpdateUser as IUser} date={currentPage.updatedAt} mode="update" locate="subnav" />
  353. : <AuthorInfoSkeleton />
  354. }
  355. </li>
  356. </ul>
  357. )}
  358. </div>
  359. {path != null && currentUser != null && !isReadOnlyUser && (
  360. <CreateTemplateModal
  361. path={path}
  362. isOpen={isPageTemplateModalShown}
  363. onClose={() => setIsPageTempleteModalShown(false)}
  364. />
  365. )}
  366. </>
  367. );
  368. };
  369. const pagePath = isIdenticalPath || isNotFound
  370. ? currentPathname
  371. : currentPage?.path;
  372. return (
  373. <GrowiSubNavigation
  374. pagePath={pagePath}
  375. pageId={currentPage?._id}
  376. showDrawerToggler={isDrawerMode}
  377. showTagLabel={isAbleToShowTagLabel}
  378. isTagLabelsDisabled={!!isGuestUser || !!isReadOnlyUser}
  379. isDrawerMode={isDrawerMode}
  380. isCompactMode={isCompactMode}
  381. tags={isViewMode ? tagsInfoData?.tags : tagsForEditors}
  382. tagsUpdatedHandler={isViewMode ? tagsUpdatedHandlerForViewMode : tagsUpdatedHandlerForEditMode}
  383. rightComponent={RightComponent}
  384. additionalClasses={['container-fluid']}
  385. />
  386. );
  387. };
  388. export default GrowiContextualSubNavigation;