GrowiContextualSubNavigation.tsx 16 KB

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