GrowiContextualSubNavigation.tsx 16 KB

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