GrowiContextualSubNavigation.tsx 16 KB

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