GrowiContextualSubNavigation.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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 { DropdownItem } from 'reactstrap';
  6. import { exportAsMarkdown } from '~/client/services/page-operation';
  7. import { toastSuccess, toastError } from '~/client/util/apiNotification';
  8. import { apiPost } from '~/client/util/apiv1-client';
  9. import {
  10. IPageToRenameWithMeta, IPageWithMeta, IPageInfoForEntity,
  11. } from '~/interfaces/page';
  12. import { IResTagsUpdateApiv1 } from '~/interfaces/tag';
  13. import { OnDuplicatedFunction, OnRenamedFunction, OnDeletedFunction } from '~/interfaces/ui';
  14. import {
  15. useCurrentPageId, useCurrentPathname,
  16. useIsNotFound,
  17. useCurrentUser, useIsGuestUser, useIsSharedUser, useShareLinkId, useTemplateTagData,
  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 { Skelton } from '../Skelton';
  35. import { GrowiSubNavigation } from './GrowiSubNavigation';
  36. import { SubNavButtonsProps } from './SubNavButtons';
  37. import AuthorInfoStyles from './AuthorInfo.module.scss';
  38. import PageEditorModeManagerStyles from './PageEditorModeManager.module.scss';
  39. const AuthorInfoSkelton = () => <Skelton additionalClass={`${AuthorInfoStyles['grw-author-info-skelton']} py-1`} />;
  40. const PageEditorModeManager = dynamic(
  41. () => import('./PageEditorModeManager'),
  42. { ssr: false, loading: () => <Skelton additionalClass={`${PageEditorModeManagerStyles['grw-page-editor-mode-manager-skelton']}`} /> },
  43. );
  44. // TODO: If enable skeleton, we get hydration error when create a page from PageCreateModal
  45. // { ssr: false, loading: () => <Skelton additionalClass='btn-skelton py-2' /> },
  46. const SubNavButtons = dynamic<SubNavButtonsProps>(
  47. () => import('./SubNavButtons').then(mod => mod.SubNavButtons),
  48. { ssr: false, loading: () => <></> },
  49. );
  50. const AuthorInfo = dynamic(() => import('./AuthorInfo'), {
  51. ssr: false,
  52. loading: AuthorInfoSkelton,
  53. });
  54. type AdditionalMenuItemsProps = {
  55. pageId: string,
  56. revisionId: string,
  57. isLinkSharingDisabled?: boolean,
  58. onClickTemplateMenuItem: (isPageTemplateModalShown: boolean) => void,
  59. }
  60. const AdditionalMenuItems = (props: AdditionalMenuItemsProps): JSX.Element => {
  61. const { t } = useTranslation();
  62. const {
  63. pageId, revisionId, isLinkSharingDisabled, onClickTemplateMenuItem,
  64. } = props;
  65. const openPageTemplateModalHandler = () => {
  66. onClickTemplateMenuItem(true);
  67. };
  68. const { data: isGuestUser } = useIsGuestUser();
  69. const { data: isSharedUser } = useIsSharedUser();
  70. const { open: openPresentationModal } = usePagePresentationModal();
  71. const { open: openAccessoriesModal } = usePageAccessoriesModal();
  72. const hrefForPresentationModal = `${pageId}/?presentation=1`;
  73. return (
  74. <>
  75. {/* Presentation */}
  76. <DropdownItem
  77. onClick={() => openPresentationModal(hrefForPresentationModal)}
  78. data-testid="open-presentation-modal-btn"
  79. className="grw-page-control-dropdown-item"
  80. >
  81. <i className="icon-fw grw-page-control-dropdown-icon">
  82. <PresentationIcon />
  83. </i>
  84. { t('Presentation Mode') }
  85. </DropdownItem>
  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. <DropdownItem divider />
  132. {/* Create template */}
  133. <DropdownItem
  134. onClick={openPageTemplateModalHandler}
  135. className="grw-page-control-dropdown-item"
  136. data-testid="open-page-template-modal-btn"
  137. >
  138. <i className="icon-fw icon-magic-wand grw-page-control-dropdown-icon"></i>
  139. { t('template.option_label.create/edit') }
  140. </DropdownItem>
  141. </>
  142. );
  143. };
  144. type GrowiContextualSubNavigationProps = {
  145. isCompactMode?: boolean,
  146. isLinkSharingDisabled: boolean,
  147. };
  148. const GrowiContextualSubNavigation = (props: GrowiContextualSubNavigationProps): JSX.Element => {
  149. const { data: currentPage, mutate: mutateCurrentPage } = useSWRxCurrentPage();
  150. const path = currentPage?.path;
  151. const revision = currentPage?.revision;
  152. const revisionId = (revision != null && isPopulated(revision)) ? revision._id : undefined;
  153. const { data: isDrawerMode } = useDrawerMode();
  154. const { data: editorMode, mutate: mutateEditorMode } = useEditorMode();
  155. const { data: pageId } = useCurrentPageId();
  156. const { data: currentPathname } = useCurrentPathname();
  157. const { data: currentUser } = useCurrentUser();
  158. const { data: isNotFound } = useIsNotFound();
  159. const { data: isGuestUser } = useIsGuestUser();
  160. const { data: isSharedUser } = useIsSharedUser();
  161. const { data: shareLinkId } = useShareLinkId();
  162. const { data: isAbleToShowPageManagement } = useIsAbleToShowPageManagement();
  163. const { data: isAbleToShowTagLabel } = useIsAbleToShowTagLabel();
  164. const { data: isAbleToShowPageEditorModeManager } = useIsAbleToShowPageEditorModeManager();
  165. const { data: isAbleToShowPageAuthors } = useIsAbleToShowPageAuthors();
  166. const { mutate: mutateSWRTagsInfo, data: tagsInfoData } = useSWRxTagsInfo(currentPage?._id);
  167. const { data: tagsForEditors, mutate: mutatePageTagsForEditors, sync: syncPageTagsForEditors } = usePageTagsForEditors(currentPage?._id);
  168. const { open: openDuplicateModal } = usePageDuplicateModal();
  169. const { open: openRenameModal } = usePageRenameModal();
  170. const { open: openDeleteModal } = usePageDeleteModal();
  171. const { data: templateTagData } = useTemplateTagData();
  172. useEffect(() => {
  173. // Run only when tagsInfoData has been updated
  174. if (templateTagData == null) {
  175. syncPageTagsForEditors();
  176. }
  177. // eslint-disable-next-line react-hooks/exhaustive-deps
  178. }, [tagsInfoData?.tags]);
  179. useEffect(() => {
  180. if (pageId === null && templateTagData != null) {
  181. const tags = templateTagData.split(',').filter((str: string) => {
  182. return str !== ''; // filter empty values
  183. });
  184. mutatePageTagsForEditors(tags);
  185. }
  186. }, [pageId, mutatePageTagsForEditors, templateTagData, mutateSWRTagsInfo]);
  187. const [isPageTemplateModalShown, setIsPageTempleteModalShown] = useState(false);
  188. const { isCompactMode, isLinkSharingDisabled } = props;
  189. const isViewMode = editorMode === EditorMode.View;
  190. const tagsUpdatedHandlerForViewMode = useCallback(async(newTags: string[]) => {
  191. if (currentPage == null) {
  192. return;
  193. }
  194. const { _id: pageId, revision: revisionId } = currentPage;
  195. try {
  196. const res: IResTagsUpdateApiv1 = await apiPost('/tags.update', { pageId, revisionId, tags: newTags });
  197. mutateCurrentPage();
  198. // TODO: fix https://github.com/weseek/growi/pull/6478 without pageContainer
  199. // const lastUpdateUser = res.savedPage?.lastUpdateUser as IUser;
  200. // await pageContainer.setState({ lastUpdateUsername: lastUpdateUser.username });
  201. // revalidate SWRTagsInfo
  202. mutateSWRTagsInfo();
  203. mutatePageTagsForEditors(newTags);
  204. toastSuccess('updated tags successfully');
  205. }
  206. catch (err) {
  207. toastError(err, 'fail to update tags');
  208. }
  209. }, [currentPage, mutateCurrentPage, mutateSWRTagsInfo, mutatePageTagsForEditors]);
  210. const tagsUpdatedHandlerForEditMode = useCallback((newTags: string[]): void => {
  211. // It will not be reflected in the DB until the page is refreshed
  212. mutatePageTagsForEditors(newTags);
  213. return;
  214. }, [mutatePageTagsForEditors]);
  215. const duplicateItemClickedHandler = useCallback(async(page: IPageForPageDuplicateModal) => {
  216. const duplicatedHandler: OnDuplicatedFunction = (fromPath, toPath) => {
  217. window.location.href = toPath;
  218. };
  219. openDuplicateModal(page, { onDuplicated: duplicatedHandler });
  220. }, [openDuplicateModal]);
  221. const renameItemClickedHandler = useCallback(async(page: IPageToRenameWithMeta<IPageInfoForEntity>) => {
  222. const renamedHandler: OnRenamedFunction = () => {
  223. if (page.data._id !== null) {
  224. window.location.href = `/${page.data._id}`;
  225. return;
  226. }
  227. window.location.reload();
  228. };
  229. openRenameModal(page, { onRenamed: renamedHandler });
  230. }, [openRenameModal]);
  231. const onDeletedHandler: OnDeletedFunction = useCallback((pathOrPathsToDelete, isRecursively, isCompletely) => {
  232. if (typeof pathOrPathsToDelete !== 'string') {
  233. return;
  234. }
  235. const path = pathOrPathsToDelete;
  236. if (isCompletely) {
  237. // redirect to NotFound Page
  238. window.location.href = path;
  239. }
  240. else {
  241. window.location.reload();
  242. }
  243. }, []);
  244. const deleteItemClickedHandler = useCallback((pageWithMeta: IPageWithMeta) => {
  245. openDeleteModal([pageWithMeta], { onDeleted: onDeletedHandler });
  246. }, [onDeletedHandler, openDeleteModal]);
  247. const templateMenuItemClickHandler = useCallback(() => {
  248. setIsPageTempleteModalShown(true);
  249. }, []);
  250. const RightComponent = useCallback(() => {
  251. const additionalMenuItemsRenderer = () => {
  252. if (revisionId == null || pageId == null) {
  253. return <></>;
  254. }
  255. return (
  256. <AdditionalMenuItems
  257. pageId={pageId}
  258. revisionId={revisionId}
  259. isLinkSharingDisabled={isLinkSharingDisabled}
  260. onClickTemplateMenuItem={templateMenuItemClickHandler}
  261. />
  262. );
  263. };
  264. return (
  265. <>
  266. <div className="d-flex">
  267. <div className="d-flex flex-column align-items-end justify-content-center py-md-2" style={{ gap: `${isCompactMode ? '5px' : '7px'}` }}>
  268. { isViewMode && (
  269. <div className="h-50 w-100">
  270. { pageId != null && (
  271. <SubNavButtons
  272. isCompactMode={isCompactMode}
  273. pageId={pageId}
  274. revisionId={revisionId}
  275. shareLinkId={shareLinkId}
  276. path={path}
  277. disableSeenUserInfoPopover={isSharedUser}
  278. showPageControlDropdown={isAbleToShowPageManagement}
  279. additionalMenuItemRenderer={additionalMenuItemsRenderer}
  280. onClickDuplicateMenuItem={duplicateItemClickedHandler}
  281. onClickRenameMenuItem={renameItemClickedHandler}
  282. onClickDeleteMenuItem={deleteItemClickedHandler}
  283. />
  284. ) }
  285. </div>
  286. ) }
  287. {isAbleToShowPageEditorModeManager && (
  288. <PageEditorModeManager
  289. onPageEditorModeButtonClicked={viewType => mutateEditorMode(viewType)}
  290. isBtnDisabled={isGuestUser}
  291. editorMode={editorMode}
  292. />
  293. )}
  294. </div>
  295. { (isAbleToShowPageAuthors && !isCompactMode) && (
  296. <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`}>
  297. <li className="pb-1">
  298. { currentPage != null
  299. ? <AuthorInfo user={currentPage.creator as IUser} date={currentPage.createdAt} locate="subnav" />
  300. : <AuthorInfoSkelton />
  301. }
  302. </li>
  303. <li className="mt-1 pt-1 border-top">
  304. { currentPage != null
  305. ? <AuthorInfo user={currentPage.lastUpdateUser as IUser} date={currentPage.updatedAt} mode="update" locate="subnav" />
  306. : <AuthorInfoSkelton />
  307. }
  308. </li>
  309. </ul>
  310. ) }
  311. </div>
  312. {path != null && currentUser != null && (
  313. <CreateTemplateModal
  314. path={path}
  315. isOpen={isPageTemplateModalShown}
  316. onClose={() => setIsPageTempleteModalShown(false)}
  317. />
  318. )}
  319. </>
  320. );
  321. // eslint-disable-next-line max-len
  322. }, [isCompactMode, isViewMode, pageId, revisionId, shareLinkId, path, isSharedUser, isAbleToShowPageManagement, duplicateItemClickedHandler, renameItemClickedHandler, deleteItemClickedHandler, isAbleToShowPageEditorModeManager, isGuestUser, editorMode, isAbleToShowPageAuthors, currentPage, currentUser, isPageTemplateModalShown, isLinkSharingDisabled, templateMenuItemClickHandler, mutateEditorMode]);
  323. const pagePath = isNotFound
  324. ? currentPathname
  325. : currentPage?.path;
  326. return (
  327. <GrowiSubNavigation
  328. pagePath={pagePath}
  329. pageId={currentPage?._id}
  330. showDrawerToggler={isDrawerMode}
  331. showTagLabel={isAbleToShowTagLabel}
  332. isGuestUser={isGuestUser}
  333. isDrawerMode={isDrawerMode}
  334. isCompactMode={isCompactMode}
  335. tags={isViewMode ? tagsInfoData?.tags : tagsForEditors}
  336. tagsUpdatedHandler={isViewMode ? tagsUpdatedHandlerForViewMode : tagsUpdatedHandlerForEditMode}
  337. rightComponent={RightComponent}
  338. additionalClasses={['container-fluid']}
  339. />
  340. );
  341. };
  342. export default GrowiContextualSubNavigation;