GrowiContextualSubNavigation.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. import React, { useState, useEffect, useCallback } from 'react';
  2. import { isPopulated, IUser, pagePathUtils } 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, useUpdateStateAfterSave } 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 { OnDuplicatedFunction, OnRenamedFunction, OnDeletedFunction } from '~/interfaces/ui';
  14. import {
  15. useCurrentPageId, useCurrentPathname, useIsNotFound,
  16. useCurrentUser, useIsGuestUser, useIsSharedUser, useShareLinkId, useTemplateTagData, useIsContainerFluid, useIsIdenticalPath,
  17. } from '~/stores/context';
  18. import { usePageTagsForEditors } from '~/stores/editor';
  19. import {
  20. usePageAccessoriesModal, PageAccessoriesModalContents, IPageForPageDuplicateModal,
  21. usePageDuplicateModal, usePageRenameModal, usePageDeleteModal, usePagePresentationModal,
  22. } from '~/stores/modal';
  23. import { useSWRxCurrentPage, useSWRxTagsInfo } from '~/stores/page';
  24. import {
  25. EditorMode, useDrawerMode, useEditorMode, useIsAbleToShowPageManagement, useIsAbleToShowTagLabel,
  26. useIsAbleToShowPageEditorModeManager, useIsAbleToShowPageAuthors,
  27. } from '~/stores/ui';
  28. import CreateTemplateModal from '../CreateTemplateModal';
  29. import AttachmentIcon from '../Icons/AttachmentIcon';
  30. import HistoryIcon from '../Icons/HistoryIcon';
  31. import PresentationIcon from '../Icons/PresentationIcon';
  32. import ShareLinkIcon from '../Icons/ShareLinkIcon';
  33. import { NotAvailableForNow } from '../NotAvailableForNow';
  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 { isUsersHomePage } = pagePathUtils;
  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. <NotAvailableForNow>
  75. <DropdownItem
  76. onClick={() => openPresentationModal(hrefForPresentationModal)}
  77. data-testid="open-presentation-modal-btn"
  78. className="grw-page-control-dropdown-item"
  79. >
  80. <i className="icon-fw grw-page-control-dropdown-icon">
  81. <PresentationIcon />
  82. </i>
  83. { t('Presentation Mode') }
  84. </DropdownItem>
  85. </NotAvailableForNow>
  86. {/* Export markdown */}
  87. <DropdownItem
  88. onClick={() => exportAsMarkdown(pageId, revisionId, 'md')}
  89. className="grw-page-control-dropdown-item"
  90. >
  91. <i className="icon-fw icon-cloud-download grw-page-control-dropdown-icon"></i>
  92. {t('export_bulk.export_page_markdown')}
  93. </DropdownItem>
  94. <DropdownItem divider />
  95. {/*
  96. TODO: show Tooltip when menu is disabled
  97. refs: PageAccessoriesModalControl
  98. */}
  99. <DropdownItem
  100. onClick={() => openAccessoriesModal(PageAccessoriesModalContents.PageHistory)}
  101. disabled={isGuestUser || isSharedUser}
  102. data-testid="open-page-accessories-modal-btn-with-history-tab"
  103. className="grw-page-control-dropdown-item"
  104. >
  105. <span className="grw-page-control-dropdown-icon">
  106. <HistoryIcon />
  107. </span>
  108. {t('History')}
  109. </DropdownItem>
  110. <DropdownItem
  111. onClick={() => openAccessoriesModal(PageAccessoriesModalContents.Attachment)}
  112. data-testid="open-page-accessories-modal-btn-with-attachment-data-tab"
  113. className="grw-page-control-dropdown-item"
  114. >
  115. <span className="grw-page-control-dropdown-icon">
  116. <AttachmentIcon />
  117. </span>
  118. {t('attachment_data')}
  119. </DropdownItem>
  120. <DropdownItem
  121. onClick={() => openAccessoriesModal(PageAccessoriesModalContents.ShareLink)}
  122. disabled={isGuestUser || isSharedUser || isLinkSharingDisabled}
  123. data-testid="open-page-accessories-modal-btn-with-share-link-management-data-tab"
  124. className="grw-page-control-dropdown-item"
  125. >
  126. <span className="grw-page-control-dropdown-icon">
  127. <ShareLinkIcon />
  128. </span>
  129. {t('share_links.share_link_management')}
  130. </DropdownItem>
  131. </>
  132. );
  133. };
  134. type CreateTemplateMenuItemsProps = {
  135. onClickTemplateMenuItem: (isPageTemplateModalShown: boolean) => void,
  136. }
  137. const CreateTemplateMenuItems = (props: CreateTemplateMenuItemsProps): JSX.Element => {
  138. const { t } = useTranslation();
  139. const { onClickTemplateMenuItem } = props;
  140. const openPageTemplateModalHandler = () => {
  141. onClickTemplateMenuItem(true);
  142. };
  143. return (
  144. <>
  145. {/* Create template */}
  146. <DropdownItem
  147. onClick={openPageTemplateModalHandler}
  148. className="grw-page-control-dropdown-item"
  149. data-testid="open-page-template-modal-btn"
  150. >
  151. <i className="icon-fw icon-magic-wand grw-page-control-dropdown-icon"></i>
  152. { t('template.option_label.create/edit') }
  153. </DropdownItem>
  154. </>
  155. );
  156. };
  157. type GrowiContextualSubNavigationProps = {
  158. isCompactMode?: boolean,
  159. isLinkSharingDisabled: boolean,
  160. };
  161. const GrowiContextualSubNavigation = (props: GrowiContextualSubNavigationProps): JSX.Element => {
  162. const router = useRouter();
  163. const { data: shareLinkId } = useShareLinkId();
  164. const { data: currentPage, mutate: mutateCurrentPage } = useSWRxCurrentPage(shareLinkId ?? undefined);
  165. const { data: currentPathname } = useCurrentPathname();
  166. const isSharedPage = pagePathUtils.isSharedPage(currentPathname ?? '');
  167. const revision = currentPage?.revision;
  168. const revisionId = (revision != null && isPopulated(revision)) ? revision._id : undefined;
  169. const { data: isDrawerMode } = useDrawerMode();
  170. const { data: editorMode, mutate: mutateEditorMode } = useEditorMode();
  171. const { data: pageId } = useCurrentPageId();
  172. const { data: currentUser } = useCurrentUser();
  173. const { data: isNotFound } = useIsNotFound();
  174. const { data: isIdenticalPath } = useIsIdenticalPath();
  175. const { data: isGuestUser } = useIsGuestUser();
  176. const { data: isSharedUser } = useIsSharedUser();
  177. const { data: isContainerFluid } = useIsContainerFluid();
  178. const { data: isAbleToShowPageManagement } = useIsAbleToShowPageManagement();
  179. const { data: isAbleToShowTagLabel } = useIsAbleToShowTagLabel();
  180. const { data: isAbleToShowPageEditorModeManager } = useIsAbleToShowPageEditorModeManager();
  181. const { data: isAbleToShowPageAuthors } = useIsAbleToShowPageAuthors();
  182. const { mutate: mutateSWRTagsInfo, data: tagsInfoData } = useSWRxTagsInfo(!isSharedPage ? currentPage?._id : undefined);
  183. // eslint-disable-next-line max-len
  184. const { data: tagsForEditors, mutate: mutatePageTagsForEditors, sync: syncPageTagsForEditors } = usePageTagsForEditors(!isSharedPage ? currentPage?._id : undefined);
  185. const { open: openDuplicateModal } = usePageDuplicateModal();
  186. const { open: openRenameModal } = usePageRenameModal();
  187. const { open: openDeleteModal } = usePageDeleteModal();
  188. const { data: templateTagData } = useTemplateTagData();
  189. const updateStateAfterSave = useUpdateStateAfterSave(pageId);
  190. const path = currentPage?.path ?? currentPathname;
  191. useEffect(() => {
  192. // Run only when tagsInfoData has been updated
  193. if (templateTagData == null) {
  194. syncPageTagsForEditors();
  195. }
  196. // eslint-disable-next-line react-hooks/exhaustive-deps
  197. }, [tagsInfoData?.tags]);
  198. useEffect(() => {
  199. if (pageId === null && templateTagData != null) {
  200. mutatePageTagsForEditors(templateTagData);
  201. }
  202. }, [pageId, mutatePageTagsForEditors, templateTagData, mutateSWRTagsInfo]);
  203. const [isPageTemplateModalShown, setIsPageTempleteModalShown] = useState(false);
  204. const { isCompactMode, isLinkSharingDisabled } = props;
  205. const isViewMode = editorMode === EditorMode.View;
  206. const tagsUpdatedHandlerForViewMode = useCallback(async(newTags: string[]) => {
  207. if (currentPage == null) {
  208. return;
  209. }
  210. const { _id: pageId, revision: revisionId } = currentPage;
  211. try {
  212. await apiPost('/tags.update', { pageId, revisionId, tags: newTags });
  213. updateStateAfterSave?.();
  214. toastSuccess('updated tags successfully');
  215. }
  216. catch (err) {
  217. toastError(err, 'fail to update tags');
  218. }
  219. }, [currentPage, updateStateAfterSave]);
  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 if (currentPathname != null) {
  253. router.push(currentPathname);
  254. }
  255. };
  256. openDeleteModal([pageWithMeta], { onDeleted: deletedHandler });
  257. }, [currentPathname, openDeleteModal, 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 = () => {
  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 && !isUsersHomePage(path ?? '')) && (
  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. };
  349. const pagePath = isIdenticalPath || isNotFound
  350. ? currentPathname
  351. : currentPage?.path;
  352. return (
  353. <div data-testid="grw-contextual-sub-nav">
  354. <GrowiSubNavigation
  355. pagePath={pagePath}
  356. pageId={currentPage?._id}
  357. showDrawerToggler={isDrawerMode}
  358. showTagLabel={isAbleToShowTagLabel}
  359. isGuestUser={isGuestUser}
  360. isDrawerMode={isDrawerMode}
  361. isCompactMode={isCompactMode}
  362. tags={isViewMode ? tagsInfoData?.tags : tagsForEditors}
  363. tagsUpdatedHandler={isViewMode ? tagsUpdatedHandlerForViewMode : tagsUpdatedHandlerForEditMode}
  364. rightComponent={RightComponent}
  365. additionalClasses={['container-fluid']}
  366. />
  367. </div>
  368. );
  369. };
  370. export default GrowiContextualSubNavigation;