GrowiContextualSubNavigation.tsx 17 KB

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