GrowiContextualSubNavigation.tsx 16 KB

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