GrowiContextualSubNavigation.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. import React, { useState, useEffect, useCallback } from 'react';
  2. import { isPopulated } 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, IPageHasId,
  11. } from '~/interfaces/page';
  12. import { IResTagsUpdateApiv1 } from '~/interfaces/tag';
  13. import { OnDuplicatedFunction, OnRenamedFunction, OnDeletedFunction } from '~/interfaces/ui';
  14. import {
  15. useCurrentPageId,
  16. useCurrentPathname, 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 PageEditorModeManagerStyles from './PageEditorModeManager.module.scss';
  38. const PageEditorModeManager = dynamic(
  39. () => import('./PageEditorModeManager'),
  40. { ssr: false, loading: () => <Skelton additionalClass={`${PageEditorModeManagerStyles['grw-page-editor-mode-manager-skelton']}`} /> },
  41. );
  42. // TODO: If enable skeleton, we get hydration error when create a page from PageCreateModal
  43. // { ssr: false, loading: () => <Skelton additionalClass='btn-skelton py-2' /> },
  44. const SubNavButtons = dynamic<SubNavButtonsProps>(
  45. () => import('./SubNavButtons').then(mod => mod.SubNavButtons),
  46. { ssr: false, loading: () => <></> },
  47. );
  48. type AdditionalMenuItemsProps = {
  49. pageId: string,
  50. revisionId: string,
  51. isLinkSharingDisabled?: boolean,
  52. onClickTemplateMenuItem: (isPageTemplateModalShown: boolean) => void,
  53. }
  54. const AdditionalMenuItems = (props: AdditionalMenuItemsProps): JSX.Element => {
  55. const { t } = useTranslation();
  56. const {
  57. pageId, revisionId, isLinkSharingDisabled, onClickTemplateMenuItem,
  58. } = props;
  59. const openPageTemplateModalHandler = () => {
  60. onClickTemplateMenuItem(true);
  61. };
  62. const { data: isGuestUser } = useIsGuestUser();
  63. const { data: isSharedUser } = useIsSharedUser();
  64. const { open: openPresentationModal } = usePagePresentationModal();
  65. const { open: openAccessoriesModal } = usePageAccessoriesModal();
  66. const hrefForPresentationModal = `${pageId}/?presentation=1`;
  67. return (
  68. <>
  69. {/* Presentation */}
  70. <DropdownItem
  71. onClick={() => openPresentationModal(hrefForPresentationModal)}
  72. data-testid="open-presentation-modal-btn"
  73. className="grw-page-control-dropdown-item"
  74. >
  75. <i className="icon-fw grw-page-control-dropdown-icon">
  76. <PresentationIcon />
  77. </i>
  78. { t('Presentation Mode') }
  79. </DropdownItem>
  80. {/* Export markdown */}
  81. <DropdownItem
  82. onClick={() => exportAsMarkdown(pageId, revisionId, 'md')}
  83. className="grw-page-control-dropdown-item"
  84. >
  85. <i className="icon-fw icon-cloud-download grw-page-control-dropdown-icon"></i>
  86. {t('export_bulk.export_page_markdown')}
  87. </DropdownItem>
  88. <DropdownItem divider />
  89. {/*
  90. TODO: show Tooltip when menu is disabled
  91. refs: PageAccessoriesModalControl
  92. */}
  93. <DropdownItem
  94. onClick={() => openAccessoriesModal(PageAccessoriesModalContents.PageHistory)}
  95. disabled={isGuestUser || isSharedUser}
  96. data-testid="open-page-accessories-modal-btn-with-history-tab"
  97. className="grw-page-control-dropdown-item"
  98. >
  99. <span className="grw-page-control-dropdown-icon">
  100. <HistoryIcon />
  101. </span>
  102. {t('History')}
  103. </DropdownItem>
  104. <DropdownItem
  105. onClick={() => openAccessoriesModal(PageAccessoriesModalContents.Attachment)}
  106. data-testid="open-page-accessories-modal-btn-with-attachment-data-tab"
  107. className="grw-page-control-dropdown-item"
  108. >
  109. <span className="grw-page-control-dropdown-icon">
  110. <AttachmentIcon />
  111. </span>
  112. {t('attachment_data')}
  113. </DropdownItem>
  114. <DropdownItem
  115. onClick={() => openAccessoriesModal(PageAccessoriesModalContents.ShareLink)}
  116. disabled={isGuestUser || isSharedUser || isLinkSharingDisabled}
  117. data-testid="open-page-accessories-modal-btn-with-share-link-management-data-tab"
  118. className="grw-page-control-dropdown-item"
  119. >
  120. <span className="grw-page-control-dropdown-icon">
  121. <ShareLinkIcon />
  122. </span>
  123. {t('share_links.share_link_management')}
  124. </DropdownItem>
  125. <DropdownItem divider />
  126. {/* Create template */}
  127. <DropdownItem
  128. onClick={openPageTemplateModalHandler}
  129. className="grw-page-control-dropdown-item"
  130. data-testid="open-page-template-modal-btn"
  131. >
  132. <i className="icon-fw icon-magic-wand grw-page-control-dropdown-icon"></i>
  133. { t('template.option_label.create/edit') }
  134. </DropdownItem>
  135. </>
  136. );
  137. };
  138. type GrowiContextualSubNavigationProps = {
  139. isCompactMode?: boolean,
  140. isLinkSharingDisabled: boolean,
  141. };
  142. const GrowiContextualSubNavigation = (props: GrowiContextualSubNavigationProps): JSX.Element => {
  143. const { data: currentPage, mutate: mutateCurrentPage } = useSWRxCurrentPage();
  144. const path = currentPage?.path;
  145. const revision = currentPage?.revision;
  146. const revisionId = (revision != null && isPopulated(revision)) ? revision._id : undefined;
  147. const { data: isDrawerMode } = useDrawerMode();
  148. const { data: editorMode, mutate: mutateEditorMode } = useEditorMode();
  149. const { data: pageId } = useCurrentPageId();
  150. const { data: currentPathname } = useCurrentPathname();
  151. const { data: currentUser } = useCurrentUser();
  152. const { data: isGuestUser } = useIsGuestUser();
  153. const { data: isSharedUser } = useIsSharedUser();
  154. const { data: isNotFound } = useIsNotFound();
  155. const { data: shareLinkId } = useShareLinkId();
  156. const { data: isAbleToShowPageManagement } = useIsAbleToShowPageManagement();
  157. const { data: isAbleToShowTagLabel } = useIsAbleToShowTagLabel();
  158. const { data: isAbleToShowPageEditorModeManager } = useIsAbleToShowPageEditorModeManager();
  159. const { data: isAbleToShowPageAuthors } = useIsAbleToShowPageAuthors();
  160. const { mutate: mutateSWRTagsInfo, data: tagsInfoData } = useSWRxTagsInfo(currentPage?._id);
  161. const { data: tagsForEditors, mutate: mutatePageTagsForEditors, sync: syncPageTagsForEditors } = usePageTagsForEditors(currentPage?._id);
  162. const { open: openDuplicateModal } = usePageDuplicateModal();
  163. const { open: openRenameModal } = usePageRenameModal();
  164. const { open: openDeleteModal } = usePageDeleteModal();
  165. const { data: templateTagData } = useTemplateTagData();
  166. useEffect(() => {
  167. // Run only when tagsInfoData has been updated
  168. if (templateTagData == null) {
  169. syncPageTagsForEditors();
  170. }
  171. // eslint-disable-next-line react-hooks/exhaustive-deps
  172. }, [tagsInfoData?.tags]);
  173. useEffect(() => {
  174. if (pageId === null && templateTagData != null) {
  175. const tags = templateTagData.split(',').filter((str: string) => {
  176. return str !== ''; // filter empty values
  177. });
  178. mutatePageTagsForEditors(tags);
  179. }
  180. }, [pageId, mutatePageTagsForEditors, templateTagData, mutateSWRTagsInfo]);
  181. const [isPageTemplateModalShown, setIsPageTempleteModalShown] = useState(false);
  182. const { isCompactMode, isLinkSharingDisabled } = props;
  183. const isViewMode = editorMode === EditorMode.View;
  184. const tagsUpdatedHandlerForViewMode = useCallback(async(newTags: string[]) => {
  185. if (currentPage == null) {
  186. return;
  187. }
  188. const { _id: pageId, revision: revisionId } = currentPage;
  189. try {
  190. const res: IResTagsUpdateApiv1 = await apiPost('/tags.update', { pageId, revisionId, tags: newTags });
  191. mutateCurrentPage();
  192. // TODO: fix https://github.com/weseek/growi/pull/6478 without pageContainer
  193. // const lastUpdateUser = res.savedPage?.lastUpdateUser as IUser;
  194. // await pageContainer.setState({ lastUpdateUsername: lastUpdateUser.username });
  195. // revalidate SWRTagsInfo
  196. mutateSWRTagsInfo();
  197. mutatePageTagsForEditors(newTags);
  198. toastSuccess('updated tags successfully');
  199. }
  200. catch (err) {
  201. toastError(err, 'fail to update tags');
  202. }
  203. }, [currentPage, mutateCurrentPage, mutateSWRTagsInfo, mutatePageTagsForEditors]);
  204. const tagsUpdatedHandlerForEditMode = useCallback((newTags: string[]): void => {
  205. // It will not be reflected in the DB until the page is refreshed
  206. mutatePageTagsForEditors(newTags);
  207. return;
  208. }, [mutatePageTagsForEditors]);
  209. const duplicateItemClickedHandler = useCallback(async(page: IPageForPageDuplicateModal) => {
  210. const duplicatedHandler: OnDuplicatedFunction = (fromPath, toPath) => {
  211. window.location.href = toPath;
  212. };
  213. openDuplicateModal(page, { onDuplicated: duplicatedHandler });
  214. }, [openDuplicateModal]);
  215. const renameItemClickedHandler = useCallback(async(page: IPageToRenameWithMeta<IPageInfoForEntity>) => {
  216. const renamedHandler: OnRenamedFunction = () => {
  217. if (page.data._id !== null) {
  218. window.location.href = `/${page.data._id}`;
  219. return;
  220. }
  221. window.location.reload();
  222. };
  223. openRenameModal(page, { onRenamed: renamedHandler });
  224. }, [openRenameModal]);
  225. const onDeletedHandler: OnDeletedFunction = useCallback((pathOrPathsToDelete, isRecursively, isCompletely) => {
  226. if (typeof pathOrPathsToDelete !== 'string') {
  227. return;
  228. }
  229. const path = pathOrPathsToDelete;
  230. if (isCompletely) {
  231. // redirect to NotFound Page
  232. window.location.href = path;
  233. }
  234. else {
  235. window.location.reload();
  236. }
  237. }, []);
  238. const deleteItemClickedHandler = useCallback((pageWithMeta: IPageWithMeta) => {
  239. openDeleteModal([pageWithMeta], { onDeleted: onDeletedHandler });
  240. }, [onDeletedHandler, openDeleteModal]);
  241. const templateMenuItemClickHandler = useCallback(() => {
  242. setIsPageTempleteModalShown(true);
  243. }, []);
  244. const ControlComponents = useCallback(() => {
  245. const additionalMenuItemsRenderer = () => {
  246. if (revisionId == null || pageId == null) {
  247. return <></>;
  248. }
  249. return (
  250. <AdditionalMenuItems
  251. pageId={pageId}
  252. revisionId={revisionId}
  253. isLinkSharingDisabled={isLinkSharingDisabled}
  254. onClickTemplateMenuItem={templateMenuItemClickHandler}
  255. />
  256. );
  257. };
  258. return (
  259. <>
  260. <div className="d-flex flex-column align-items-end justify-content-center py-md-2" style={{ gap: `${isCompactMode ? '5px' : '7px'}` }}>
  261. { isViewMode && (
  262. <div className="h-50 w-100">
  263. { pageId != null && (
  264. <SubNavButtons
  265. isCompactMode={isCompactMode}
  266. pageId={pageId}
  267. revisionId={revisionId}
  268. shareLinkId={shareLinkId}
  269. path={path}
  270. disableSeenUserInfoPopover={isSharedUser}
  271. showPageControlDropdown={isAbleToShowPageManagement}
  272. additionalMenuItemRenderer={additionalMenuItemsRenderer}
  273. onClickDuplicateMenuItem={duplicateItemClickedHandler}
  274. onClickRenameMenuItem={renameItemClickedHandler}
  275. onClickDeleteMenuItem={deleteItemClickedHandler}
  276. />
  277. ) }
  278. </div>
  279. ) }
  280. {isAbleToShowPageEditorModeManager && (
  281. <PageEditorModeManager
  282. onPageEditorModeButtonClicked={viewType => mutateEditorMode(viewType)}
  283. isBtnDisabled={isGuestUser}
  284. editorMode={editorMode}
  285. />
  286. )}
  287. </div>
  288. {path != null && currentUser != null && (
  289. <CreateTemplateModal
  290. path={path}
  291. isOpen={isPageTemplateModalShown}
  292. onClose={() => setIsPageTempleteModalShown(false)}
  293. />
  294. )}
  295. </>
  296. );
  297. // eslint-disable-next-line max-len
  298. }, [currentUser, pageId, revisionId, shareLinkId, path, editorMode, isCompactMode, isViewMode, isSharedUser, isAbleToShowPageManagement, isAbleToShowPageEditorModeManager, isLinkSharingDisabled, isGuestUser, isPageTemplateModalShown, duplicateItemClickedHandler, renameItemClickedHandler, deleteItemClickedHandler, mutateEditorMode, templateMenuItemClickHandler]);
  299. if (currentPathname == null) {
  300. return <></>;
  301. }
  302. const notFoundPage: Partial<IPageHasId> = {
  303. path: currentPathname,
  304. };
  305. return (
  306. <GrowiSubNavigation
  307. page={currentPage ?? notFoundPage}
  308. showDrawerToggler={isDrawerMode}
  309. showTagLabel={isAbleToShowTagLabel}
  310. showPageAuthors={isAbleToShowPageAuthors}
  311. isGuestUser={isGuestUser}
  312. isDrawerMode={isDrawerMode}
  313. isCompactMode={isCompactMode}
  314. tags={isViewMode ? tagsInfoData?.tags : tagsForEditors}
  315. tagsUpdatedHandler={isViewMode ? tagsUpdatedHandlerForViewMode : tagsUpdatedHandlerForEditMode}
  316. controls={ControlComponents}
  317. additionalClasses={['container-fluid']}
  318. />
  319. );
  320. };
  321. export default GrowiContextualSubNavigation;