GrowiContextualSubNavigation.tsx 16 KB

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