GrowiContextualSubNavigation.tsx 16 KB

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