GrowiContextualSubNavigation.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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 { useSWRxCurrentPage, 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 { NotAvailableForNow } from '../NotAvailableForNow';
  37. import { Skeleton } from '../Skeleton';
  38. import type { AuthorInfoProps } from './AuthorInfo';
  39. import { GrowiSubNavigation } from './GrowiSubNavigation';
  40. import type { SubNavButtonsProps } from './SubNavButtons';
  41. import AuthorInfoStyles from './AuthorInfo.module.scss';
  42. import PageEditorModeManagerStyles from './PageEditorModeManager.module.scss';
  43. const { isUsersHomePage } = pagePathUtils;
  44. const AuthorInfoSkeleton = () => <Skeleton additionalClass={`${AuthorInfoStyles['grw-author-info-skeleton']} py-1`} />;
  45. const PageEditorModeManager = dynamic(
  46. () => import('./PageEditorModeManager'),
  47. { ssr: false, loading: () => <Skeleton additionalClass={`${PageEditorModeManagerStyles['grw-page-editor-mode-manager-skeleton']}`} /> },
  48. );
  49. // TODO: If enable skeleton, we get hydration error when create a page from PageCreateModal
  50. // { ssr: false, loading: () => <Skeleton additionalClass='btn-skeleton py-2' /> },
  51. const SubNavButtons = dynamic<SubNavButtonsProps>(
  52. () => import('./SubNavButtons').then(mod => mod.SubNavButtons),
  53. { ssr: false, loading: () => <></> },
  54. );
  55. const AuthorInfo = dynamic<AuthorInfoProps>(() => import('./AuthorInfo').then(mod => mod.AuthorInfo), {
  56. ssr: false,
  57. loading: AuthorInfoSkeleton,
  58. });
  59. type PageOperationMenuItemsProps = {
  60. pageId: string,
  61. revisionId: string,
  62. isLinkSharingDisabled?: boolean,
  63. }
  64. const PageOperationMenuItems = (props: PageOperationMenuItemsProps): JSX.Element => {
  65. const { t } = useTranslation();
  66. const {
  67. pageId, revisionId, isLinkSharingDisabled,
  68. } = props;
  69. const { data: isGuestUser } = useIsGuestUser();
  70. const { data: isSharedUser } = useIsSharedUser();
  71. const { open: openPresentationModal } = usePagePresentationModal();
  72. const { open: openAccessoriesModal } = usePageAccessoriesModal();
  73. const hrefForPresentationModal = `${pageId}/?presentation=1`;
  74. return (
  75. <>
  76. {/* Presentation */}
  77. <NotAvailableForNow>
  78. <DropdownItem
  79. onClick={() => openPresentationModal(hrefForPresentationModal)}
  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. </NotAvailableForNow>
  89. {/* Export markdown */}
  90. <DropdownItem
  91. onClick={() => exportAsMarkdown(pageId, revisionId, 'md')}
  92. className="grw-page-control-dropdown-item"
  93. >
  94. <i className="icon-fw icon-cloud-download grw-page-control-dropdown-icon"></i>
  95. {t('export_bulk.export_page_markdown')}
  96. </DropdownItem>
  97. <DropdownItem divider />
  98. {/*
  99. TODO: show Tooltip when menu is disabled
  100. refs: PageAccessoriesModalControl
  101. */}
  102. <DropdownItem
  103. onClick={() => openAccessoriesModal(PageAccessoriesModalContents.PageHistory)}
  104. disabled={isGuestUser || isSharedUser}
  105. data-testid="open-page-accessories-modal-btn-with-history-tab"
  106. className="grw-page-control-dropdown-item"
  107. >
  108. <span className="grw-page-control-dropdown-icon">
  109. <HistoryIcon />
  110. </span>
  111. {t('History')}
  112. </DropdownItem>
  113. <DropdownItem
  114. onClick={() => openAccessoriesModal(PageAccessoriesModalContents.Attachment)}
  115. data-testid="open-page-accessories-modal-btn-with-attachment-data-tab"
  116. className="grw-page-control-dropdown-item"
  117. >
  118. <span className="grw-page-control-dropdown-icon">
  119. <AttachmentIcon />
  120. </span>
  121. {t('attachment_data')}
  122. </DropdownItem>
  123. { !isGuestUser && !isSharedUser && (
  124. <NotAvailable isDisabled={isLinkSharingDisabled ?? false} title="Disabled by admin">
  125. <DropdownItem
  126. onClick={() => openAccessoriesModal(PageAccessoriesModalContents.ShareLink)}
  127. data-testid="open-page-accessories-modal-btn-with-share-link-management-data-tab"
  128. className="grw-page-control-dropdown-item"
  129. >
  130. <span className="grw-page-control-dropdown-icon">
  131. <ShareLinkIcon />
  132. </span>
  133. {t('share_links.share_link_management')}
  134. </DropdownItem>
  135. </NotAvailable>
  136. ) }
  137. </>
  138. );
  139. };
  140. type CreateTemplateMenuItemsProps = {
  141. onClickTemplateMenuItem: (isPageTemplateModalShown: boolean) => void,
  142. }
  143. const CreateTemplateMenuItems = (props: CreateTemplateMenuItemsProps): JSX.Element => {
  144. const { t } = useTranslation();
  145. const { onClickTemplateMenuItem } = props;
  146. const openPageTemplateModalHandler = () => {
  147. onClickTemplateMenuItem(true);
  148. };
  149. return (
  150. <>
  151. {/* Create template */}
  152. <DropdownItem
  153. onClick={openPageTemplateModalHandler}
  154. className="grw-page-control-dropdown-item"
  155. data-testid="open-page-template-modal-btn"
  156. >
  157. <i className="icon-fw icon-magic-wand grw-page-control-dropdown-icon"></i>
  158. { t('template.option_label.create/edit') }
  159. </DropdownItem>
  160. </>
  161. );
  162. };
  163. type GrowiContextualSubNavigationProps = {
  164. currentPage?: IPagePopulatedToShowRevision | null,
  165. isCompactMode?: boolean,
  166. isLinkSharingDisabled: boolean,
  167. };
  168. const GrowiContextualSubNavigation = (props: GrowiContextualSubNavigationProps): JSX.Element => {
  169. const { currentPage } = props;
  170. const router = useRouter();
  171. const { data: shareLinkId } = useShareLinkId();
  172. const { mutate: mutateCurrentPage } = useSWRxCurrentPage();
  173. const { data: currentPathname } = useCurrentPathname();
  174. const isSharedPage = pagePathUtils.isSharedPage(currentPathname ?? '');
  175. const revision = currentPage?.revision;
  176. const revisionId = (revision != null && isPopulated(revision)) ? revision._id : undefined;
  177. const { data: isDrawerMode } = useDrawerMode();
  178. const { data: editorMode, mutate: mutateEditorMode } = useEditorMode();
  179. const { data: pageId } = useCurrentPageId();
  180. const { data: currentUser } = useCurrentUser();
  181. const { data: isNotFound } = useIsNotFound();
  182. const { data: isIdenticalPath } = useIsIdenticalPath();
  183. const { data: isGuestUser } = useIsGuestUser();
  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, 'fail to update tags');
  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. <CreateTemplateMenuItems
  281. onClickTemplateMenuItem={templateMenuItemClickHandler}
  282. />
  283. </>);
  284. }
  285. return (
  286. <>
  287. <PageOperationMenuItems
  288. pageId={pageId}
  289. revisionId={revisionId}
  290. isLinkSharingDisabled={isLinkSharingDisabled}
  291. />
  292. <DropdownItem divider />
  293. <CreateTemplateMenuItems
  294. onClickTemplateMenuItem={templateMenuItemClickHandler}
  295. />
  296. </>
  297. );
  298. };
  299. return (
  300. <>
  301. <div className="d-flex">
  302. <div className="d-flex flex-column align-items-end justify-content-center py-md-2" style={{ gap: `${isCompactMode ? '5px' : '7px'}` }}>
  303. { isViewMode && (
  304. <div className="h-50">
  305. { pageId != null && (
  306. <SubNavButtons
  307. isCompactMode={isCompactMode}
  308. pageId={pageId}
  309. revisionId={revisionId}
  310. shareLinkId={shareLinkId}
  311. path={path ?? currentPathname} // If the page is empty, "path" is undefined
  312. expandContentWidth={currentPage?.expandContentWidth ?? isContainerFluid}
  313. disableSeenUserInfoPopover={isSharedUser}
  314. showPageControlDropdown={isAbleToShowPageManagement}
  315. additionalMenuItemRenderer={additionalMenuItemsRenderer}
  316. onClickDuplicateMenuItem={duplicateItemClickedHandler}
  317. onClickRenameMenuItem={renameItemClickedHandler}
  318. onClickDeleteMenuItem={deleteItemClickedHandler}
  319. onClickSwitchContentWidth={switchContentWidthHandler}
  320. />
  321. ) }
  322. </div>
  323. ) }
  324. {isAbleToChangeEditorMode && (
  325. <PageEditorModeManager
  326. onPageEditorModeButtonClicked={viewType => mutateEditorMode(viewType)}
  327. isBtnDisabled={isGuestUser}
  328. editorMode={editorMode}
  329. />
  330. )}
  331. </div>
  332. { (isAbleToShowPageAuthors && !isCompactMode && !isUsersHomePage(path ?? '')) && (
  333. <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`}>
  334. <li className="pb-1">
  335. { currentPage != null
  336. ? <AuthorInfo user={currentPage.creator as IUser} date={currentPage.createdAt} mode="create" locate="subnav" />
  337. : <AuthorInfoSkeleton />
  338. }
  339. </li>
  340. <li className="mt-1 pt-1 border-top">
  341. { currentPage != null
  342. ? <AuthorInfo user={currentPage.lastUpdateUser as IUser} date={currentPage.updatedAt} mode="update" locate="subnav" />
  343. : <AuthorInfoSkeleton />
  344. }
  345. </li>
  346. </ul>
  347. ) }
  348. </div>
  349. {path != null && currentUser != null && (
  350. <CreateTemplateModal
  351. path={path}
  352. isOpen={isPageTemplateModalShown}
  353. onClose={() => setIsPageTempleteModalShown(false)}
  354. />
  355. )}
  356. </>
  357. );
  358. };
  359. const pagePath = isIdenticalPath || isNotFound
  360. ? currentPathname
  361. : currentPage?.path;
  362. return (
  363. <GrowiSubNavigation
  364. pagePath={pagePath}
  365. pageId={currentPage?._id}
  366. showDrawerToggler={isDrawerMode}
  367. showTagLabel={isAbleToShowTagLabel}
  368. isGuestUser={isGuestUser}
  369. isDrawerMode={isDrawerMode}
  370. isCompactMode={isCompactMode}
  371. tags={isViewMode ? tagsInfoData?.tags : tagsForEditors}
  372. tagsUpdatedHandler={isViewMode ? tagsUpdatedHandlerForViewMode : tagsUpdatedHandlerForEditMode}
  373. rightComponent={RightComponent}
  374. additionalClasses={['container-fluid']}
  375. />
  376. );
  377. };
  378. export default GrowiContextualSubNavigation;