SearchResultContent.tsx 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. import type { FC } from 'react';
  2. import React, {
  3. useCallback, useEffect, useRef, useState,
  4. } from 'react';
  5. import { getIdForRef } from '@growi/core';
  6. import type { IPageToDeleteWithMeta, IPageToRenameWithMeta } from '@growi/core';
  7. import { useTranslation } from 'next-i18next';
  8. import dynamic from 'next/dynamic';
  9. import { animateScroll } from 'react-scroll';
  10. import { DropdownItem } from 'reactstrap';
  11. import { debounce } from 'throttle-debounce';
  12. import { useShouldExpandContent } from '~/client/services/layout';
  13. import { exportAsMarkdown, updateContentWidth } from '~/client/services/page-operation';
  14. import { toastSuccess } from '~/client/util/toastr';
  15. import type { IPageWithSearchMeta } from '~/interfaces/search';
  16. import type { OnDuplicatedFunction, OnRenamedFunction, OnDeletedFunction } from '~/interfaces/ui';
  17. import { useCurrentUser } from '~/stores/context';
  18. import {
  19. usePageDuplicateModal, usePageRenameModal, usePageDeleteModal,
  20. } from '~/stores/modal';
  21. import { mutatePageList, mutatePageTree } from '~/stores/page-listing';
  22. import { useSearchResultOptions } from '~/stores/renderer';
  23. import { mutateSearching } from '~/stores/search';
  24. import type { AdditionalMenuItemsRendererProps, ForceHideMenuItems } from '../Common/Dropdown/PageItemControl';
  25. import { PagePathNav } from '../Common/PagePathNav';
  26. import { type RevisionLoaderProps } from '../Page/RevisionLoader';
  27. import { type PageCommentProps } from '../PageComment';
  28. import type { PageContentFooterProps } from '../PageContentFooter';
  29. import styles from './SearchResultContent.module.scss';
  30. const moduleClass = styles['search-result-content'];
  31. const _fluidLayoutClass = styles['fluid-layout'];
  32. const PageControls = dynamic(() => import('../PageControls').then(mod => mod.PageControls), { ssr: false });
  33. const RevisionLoader = dynamic<RevisionLoaderProps>(() => import('../Page/RevisionLoader').then(mod => mod.RevisionLoader), { ssr: false });
  34. const PageComment = dynamic<PageCommentProps>(() => import('../PageComment').then(mod => mod.PageComment), { ssr: false });
  35. const PageContentFooter = dynamic<PageContentFooterProps>(() => import('../PageContentFooter').then(mod => mod.PageContentFooter), { ssr: false });
  36. type AdditionalMenuItemsProps = AdditionalMenuItemsRendererProps & {
  37. pageId: string,
  38. revisionId: string,
  39. }
  40. const AdditionalMenuItems = (props: AdditionalMenuItemsProps): JSX.Element => {
  41. const { t } = useTranslation();
  42. const { pageId, revisionId } = props;
  43. return (
  44. // Export markdown
  45. <DropdownItem
  46. onClick={() => exportAsMarkdown(pageId, revisionId, 'md')}
  47. className="grw-page-control-dropdown-item"
  48. >
  49. <span className="material-symbols-outlined me-1 grw-page-control-dropdown-icon">cloud_download</span>
  50. {t('export_bulk.export_page_markdown')}
  51. </DropdownItem>
  52. );
  53. };
  54. const SCROLL_OFFSET_TOP = 30;
  55. const MUTATION_OBSERVER_CONFIG = { childList: true, subtree: true }; // omit 'subtree: true'
  56. type Props ={
  57. pageWithMeta : IPageWithSearchMeta,
  58. highlightKeywords?: string[],
  59. showPageControlDropdown?: boolean,
  60. forceHideMenuItems?: ForceHideMenuItems,
  61. }
  62. const scrollToFirstHighlightedKeyword = (scrollElement: HTMLElement): void => {
  63. // use querySelector to intentionally get the first element found
  64. const toElem = scrollElement.querySelector('.highlighted-keyword') as HTMLElement | null;
  65. if (toElem == null) {
  66. return;
  67. }
  68. const distance = toElem.getBoundingClientRect().top - scrollElement.getBoundingClientRect().top - SCROLL_OFFSET_TOP;
  69. animateScroll.scrollMore(distance, {
  70. containerId: scrollElement.id,
  71. duration: 200,
  72. });
  73. };
  74. const scrollToFirstHighlightedKeywordDebounced = debounce(500, scrollToFirstHighlightedKeyword);
  75. export const SearchResultContent: FC<Props> = (props: Props) => {
  76. const scrollElementRef = useRef<HTMLDivElement|null>(null);
  77. // *************************** Auto Scroll ***************************
  78. useEffect(() => {
  79. const scrollElement = scrollElementRef.current;
  80. if (scrollElement == null) return;
  81. const observer = new MutationObserver(() => {
  82. scrollToFirstHighlightedKeywordDebounced(scrollElement);
  83. });
  84. observer.observe(scrollElement, MUTATION_OBSERVER_CONFIG);
  85. // no cleanup function -- 2023.07.31 Yuki Takei
  86. // see: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver/observe
  87. // > You can call observe() multiple times on the same MutationObserver
  88. // > to watch for changes to different parts of the DOM tree and/or different types of changes.
  89. });
  90. // ******************************* end *******************************
  91. const {
  92. pageWithMeta,
  93. highlightKeywords,
  94. showPageControlDropdown,
  95. forceHideMenuItems,
  96. } = props;
  97. const { t } = useTranslation();
  98. const page = pageWithMeta.data;
  99. const { open: openDuplicateModal } = usePageDuplicateModal();
  100. const { open: openRenameModal } = usePageRenameModal();
  101. const { open: openDeleteModal } = usePageDeleteModal();
  102. const { data: rendererOptions } = useSearchResultOptions(pageWithMeta.data.path, highlightKeywords);
  103. const { data: currentUser } = useCurrentUser();
  104. const shouldExpandContent = useShouldExpandContent(page);
  105. const duplicateItemClickedHandler = useCallback(async(pageToDuplicate) => {
  106. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  107. const duplicatedHandler: OnDuplicatedFunction = (fromPath, toPath) => {
  108. toastSuccess(t('duplicated_pages', { fromPath }));
  109. mutatePageTree();
  110. mutateSearching();
  111. mutatePageList();
  112. };
  113. openDuplicateModal(pageToDuplicate, { onDuplicated: duplicatedHandler });
  114. }, [openDuplicateModal, t]);
  115. const renameItemClickedHandler = useCallback((pageToRename: IPageToRenameWithMeta) => {
  116. const renamedHandler: OnRenamedFunction = (path) => {
  117. toastSuccess(t('renamed_pages', { path }));
  118. mutatePageTree();
  119. mutateSearching();
  120. mutatePageList();
  121. };
  122. openRenameModal(pageToRename, { onRenamed: renamedHandler });
  123. }, [openRenameModal, t]);
  124. const onDeletedHandler: OnDeletedFunction = useCallback((pathOrPathsToDelete, isRecursively, isCompletely) => {
  125. if (typeof pathOrPathsToDelete !== 'string') {
  126. return;
  127. }
  128. const path = pathOrPathsToDelete;
  129. if (isCompletely) {
  130. toastSuccess(t('deleted_pages_completely', { path }));
  131. }
  132. else {
  133. toastSuccess(t('deleted_pages', { path }));
  134. }
  135. mutatePageTree();
  136. mutateSearching();
  137. mutatePageList();
  138. }, [t]);
  139. const deleteItemClickedHandler = useCallback((pageToDelete: IPageToDeleteWithMeta) => {
  140. openDeleteModal([pageToDelete], { onDeleted: onDeletedHandler });
  141. }, [onDeletedHandler, openDeleteModal]);
  142. const switchContentWidthHandler = useCallback(async(pageId: string, value: boolean) => {
  143. await updateContentWidth(pageId, value);
  144. // TODO: revalidate page data and update shouldExpandContent
  145. }, []);
  146. const RightComponent = useCallback(() => {
  147. if (page == null) {
  148. return <></>;
  149. }
  150. const revisionId = page.revision != null ? getIdForRef(page.revision) : null;
  151. const additionalMenuItemRenderer = revisionId != null
  152. ? props => <AdditionalMenuItems {...props} pageId={page._id} revisionId={revisionId} />
  153. : undefined;
  154. return (
  155. <div className="d-flex flex-column align-items-end justify-content-center px-2 py-1">
  156. <PageControls
  157. pageId={page._id}
  158. revisionId={revisionId}
  159. path={page.path}
  160. expandContentWidth={shouldExpandContent}
  161. showPageControlDropdown={showPageControlDropdown}
  162. forceHideMenuItems={forceHideMenuItems}
  163. additionalMenuItemRenderer={additionalMenuItemRenderer}
  164. onClickDuplicateMenuItem={duplicateItemClickedHandler}
  165. onClickRenameMenuItem={renameItemClickedHandler}
  166. onClickDeleteMenuItem={deleteItemClickedHandler}
  167. onClickSwitchContentWidth={switchContentWidthHandler}
  168. />
  169. </div>
  170. );
  171. }, [page, shouldExpandContent, showPageControlDropdown, forceHideMenuItems,
  172. duplicateItemClickedHandler, renameItemClickedHandler, deleteItemClickedHandler, switchContentWidthHandler]);
  173. const fluidLayoutClass = shouldExpandContent ? _fluidLayoutClass : '';
  174. return (
  175. <div
  176. key={page._id}
  177. data-testid="search-result-content"
  178. className={`dynamic-layout-root ${moduleClass} ${fluidLayoutClass}`}
  179. >
  180. <RightComponent />
  181. <div className="container-lg grw-container-convertible pt-2 pb-2">
  182. <PagePathNav pageId={page._id} pagePath={page.path} formerLinkClassName="small" latterLinkClassName="fs-3" />
  183. </div>
  184. <div
  185. id="search-result-content-body-container"
  186. ref={scrollElementRef}
  187. className="search-result-content-body-container container-lg grw-container-convertible overflow-y-scroll"
  188. >
  189. { page.revision != null && rendererOptions != null && (
  190. <RevisionLoader
  191. rendererOptions={rendererOptions}
  192. pageId={page._id}
  193. revisionId={page.revision}
  194. />
  195. )}
  196. { page.revision != null && (
  197. <PageComment
  198. rendererOptions={rendererOptions}
  199. pageId={page._id}
  200. pagePath={page.path}
  201. revision={page.revision}
  202. currentUser={currentUser}
  203. isReadOnly
  204. />
  205. )}
  206. <PageContentFooter
  207. page={page}
  208. />
  209. </div>
  210. </div>
  211. );
  212. };