GrowiContextualSubNavigation.tsx 16 KB

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