SearchResultContent.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. import type { FC, JSX } from 'react';
  2. import { useCallback, useEffect, useRef } from 'react';
  3. import dynamic from 'next/dynamic';
  4. import type { IPageToDeleteWithMeta, IPageToRenameWithMeta } from '@growi/core';
  5. import { getIdStringForRef } from '@growi/core';
  6. import { useTranslation } from 'next-i18next';
  7. import { DropdownItem } from 'reactstrap';
  8. import { debounce } from 'throttle-debounce';
  9. import type {
  10. AdditionalMenuItemsRendererProps,
  11. ForceHideMenuItems,
  12. } from '~/client/components/Common/Dropdown/PageItemControl';
  13. import type { RevisionLoaderProps } from '~/client/components/Page/RevisionLoader';
  14. import { watchRenderingAndReScroll } from '~/client/hooks/use-content-auto-scroll/watch-rendering-and-rescroll';
  15. import { exportAsMarkdown } from '~/client/services/page-operation';
  16. import { scrollWithinContainer } from '~/client/util/smooth-scroll';
  17. import { toastSuccess } from '~/client/util/toastr';
  18. import { PagePathNav } from '~/components/Common/PagePathNav';
  19. import type { IPageWithSearchMeta } from '~/interfaces/search';
  20. import type {
  21. OnDeletedFunction,
  22. OnDuplicatedFunction,
  23. OnRenamedFunction,
  24. } from '~/interfaces/ui';
  25. import { useShouldExpandContent } from '~/services/layout/use-should-expand-content';
  26. import { useCurrentUser } from '~/states/global';
  27. import { usePageDeleteModalActions } from '~/states/ui/modal/page-delete';
  28. import { usePageDuplicateModalActions } from '~/states/ui/modal/page-duplicate';
  29. import { usePageRenameModalActions } from '~/states/ui/modal/page-rename';
  30. import {
  31. mutatePageList,
  32. mutatePageTree,
  33. mutateRecentlyUpdated,
  34. } from '~/stores/page-listing';
  35. import { useSearchResultOptions } from '~/stores/renderer';
  36. import { mutateSearching } from '~/stores/search';
  37. import styles from './SearchResultContent.module.scss';
  38. const moduleClass = styles['search-result-content'];
  39. const _fluidLayoutClass = styles['fluid-layout'];
  40. const PageControls = dynamic(
  41. () =>
  42. import('~/client/components/PageControls').then((mod) => mod.PageControls),
  43. { ssr: false },
  44. );
  45. const RevisionLoader = dynamic<RevisionLoaderProps>(
  46. () =>
  47. import('~/client/components/Page/RevisionLoader').then(
  48. (mod) => mod.RevisionLoader,
  49. ),
  50. { ssr: false },
  51. );
  52. const PageComment = dynamic(
  53. () =>
  54. import('~/client/components/PageComment').then((mod) => mod.PageComment),
  55. { ssr: false },
  56. );
  57. const PageContentFooter = dynamic(
  58. () =>
  59. import('~/components/PageView/PageContentFooter').then(
  60. (mod) => mod.PageContentFooter,
  61. ),
  62. { ssr: false },
  63. );
  64. type AdditionalMenuItemsProps = AdditionalMenuItemsRendererProps & {
  65. pageId: string;
  66. revisionId: string;
  67. };
  68. const AdditionalMenuItems = (props: AdditionalMenuItemsProps): JSX.Element => {
  69. const { t } = useTranslation();
  70. const { pageId, revisionId } = props;
  71. return (
  72. // Export markdown
  73. <DropdownItem
  74. onClick={() => exportAsMarkdown(pageId, revisionId, 'md')}
  75. className="grw-page-control-dropdown-item"
  76. >
  77. <span className="material-symbols-outlined me-1 grw-page-control-dropdown-icon">
  78. cloud_download
  79. </span>
  80. {t('page_export.export_page_markdown')}
  81. </DropdownItem>
  82. );
  83. };
  84. const SCROLL_OFFSET_TOP = 30;
  85. const MUTATION_OBSERVER_CONFIG = { childList: true, subtree: true }; // omit 'subtree: true'
  86. type Props = {
  87. pageWithMeta: IPageWithSearchMeta;
  88. highlightKeywords?: string[];
  89. showPageControlDropdown?: boolean;
  90. forceHideMenuItems?: ForceHideMenuItems;
  91. };
  92. const scrollToTargetWithinContainer = (
  93. target: HTMLElement,
  94. container: HTMLElement,
  95. ): void => {
  96. const distance =
  97. target.getBoundingClientRect().top -
  98. container.getBoundingClientRect().top -
  99. SCROLL_OFFSET_TOP;
  100. scrollWithinContainer(container, distance);
  101. };
  102. const scrollToFirstHighlightedKeyword = (scrollElement: HTMLElement): void => {
  103. // use querySelector to intentionally get the first element found
  104. const toElem = scrollElement.querySelector(
  105. '.highlighted-keyword',
  106. ) as HTMLElement | null;
  107. if (toElem == null) return;
  108. scrollToTargetWithinContainer(toElem, scrollElement);
  109. };
  110. const scrollToFirstHighlightedKeywordDebounced = debounce(
  111. 500,
  112. scrollToFirstHighlightedKeyword,
  113. );
  114. export const SearchResultContent: FC<Props> = (props: Props) => {
  115. const scrollElementRef = useRef<HTMLDivElement | null>(null);
  116. const { pageWithMeta } = props;
  117. const page = pageWithMeta.data;
  118. // *************************** Keyword Scroll ***************************
  119. // biome-ignore lint/correctness/useExhaustiveDependencies: page._id is a trigger dep: re-run this effect when the selected page changes
  120. useEffect(() => {
  121. const scrollElement = scrollElementRef.current;
  122. if (scrollElement == null) return;
  123. const scrollToKeyword = (): boolean => {
  124. const toElem = scrollElement.querySelector(
  125. '.highlighted-keyword',
  126. ) as HTMLElement | null;
  127. if (toElem == null) return false;
  128. scrollToTargetWithinContainer(toElem, scrollElement);
  129. return true;
  130. };
  131. const observer = new MutationObserver(() => {
  132. scrollToFirstHighlightedKeywordDebounced(scrollElement);
  133. });
  134. observer.observe(scrollElement, MUTATION_OBSERVER_CONFIG);
  135. // Re-scroll to keyword after async renderers (drawio/mermaid) cause layout shifts
  136. const cleanupWatch = watchRenderingAndReScroll(
  137. scrollElement,
  138. scrollToKeyword,
  139. );
  140. return cleanupWatch;
  141. }, [page._id]);
  142. // ******************************* end *******************************
  143. const { highlightKeywords, showPageControlDropdown, forceHideMenuItems } =
  144. props;
  145. const { t } = useTranslation();
  146. const { open: openDuplicateModal } = usePageDuplicateModalActions();
  147. const { open: openRenameModal } = usePageRenameModalActions();
  148. const { open: openDeleteModal } = usePageDeleteModalActions();
  149. const { data: rendererOptions } = useSearchResultOptions(
  150. pageWithMeta.data.path,
  151. highlightKeywords,
  152. );
  153. const currentUser = useCurrentUser();
  154. const shouldExpandContent = useShouldExpandContent(page);
  155. const duplicateItemClickedHandler = useCallback(
  156. async (pageToDuplicate) => {
  157. const duplicatedHandler: OnDuplicatedFunction = (fromPath, _toPath) => {
  158. toastSuccess(t('duplicated_pages', { fromPath }));
  159. mutatePageTree();
  160. mutateRecentlyUpdated();
  161. mutateSearching();
  162. mutatePageList();
  163. };
  164. openDuplicateModal(pageToDuplicate, { onDuplicated: duplicatedHandler });
  165. },
  166. [openDuplicateModal, t],
  167. );
  168. const renameItemClickedHandler = useCallback(
  169. (pageToRename: IPageToRenameWithMeta) => {
  170. const renamedHandler: OnRenamedFunction = (path) => {
  171. toastSuccess(t('renamed_pages', { path }));
  172. mutatePageTree();
  173. mutateRecentlyUpdated();
  174. mutateSearching();
  175. mutatePageList();
  176. };
  177. openRenameModal(pageToRename, { onRenamed: renamedHandler });
  178. },
  179. [openRenameModal, t],
  180. );
  181. const onDeletedHandler: OnDeletedFunction = useCallback(
  182. (pathOrPathsToDelete, isRecursively, isCompletely) => {
  183. if (typeof pathOrPathsToDelete !== 'string') {
  184. return;
  185. }
  186. const path = pathOrPathsToDelete;
  187. if (isCompletely) {
  188. toastSuccess(t('deleted_pages_completely', { path }));
  189. } else {
  190. toastSuccess(t('deleted_pages', { path }));
  191. }
  192. mutatePageTree();
  193. mutateRecentlyUpdated();
  194. mutateSearching();
  195. mutatePageList();
  196. },
  197. [t],
  198. );
  199. const deleteItemClickedHandler = useCallback(
  200. (pageToDelete: IPageToDeleteWithMeta) => {
  201. openDeleteModal([pageToDelete], { onDeleted: onDeletedHandler });
  202. },
  203. [onDeletedHandler, openDeleteModal],
  204. );
  205. const RightComponent = useCallback(() => {
  206. if (page == null) {
  207. return <></>;
  208. }
  209. const revisionId =
  210. page.revision != null ? getIdStringForRef(page.revision) : null;
  211. const additionalMenuItemRenderer =
  212. revisionId != null
  213. ? (props) => (
  214. <AdditionalMenuItems
  215. {...props}
  216. pageId={page._id}
  217. revisionId={revisionId}
  218. />
  219. )
  220. : undefined;
  221. return (
  222. <div className="d-flex flex-column flex-row-reverse flex px-2 py-1">
  223. <PageControls
  224. pageId={page._id}
  225. revisionId={revisionId}
  226. path={page.path}
  227. expandContentWidth={shouldExpandContent}
  228. showPageControlDropdown={showPageControlDropdown}
  229. forceHideMenuItems={forceHideMenuItems}
  230. additionalMenuItemRenderer={additionalMenuItemRenderer}
  231. onClickDuplicateMenuItem={duplicateItemClickedHandler}
  232. onClickRenameMenuItem={renameItemClickedHandler}
  233. onClickDeleteMenuItem={deleteItemClickedHandler}
  234. />
  235. </div>
  236. );
  237. }, [
  238. page,
  239. shouldExpandContent,
  240. showPageControlDropdown,
  241. forceHideMenuItems,
  242. duplicateItemClickedHandler,
  243. renameItemClickedHandler,
  244. deleteItemClickedHandler,
  245. ]);
  246. const fluidLayoutClass = shouldExpandContent ? _fluidLayoutClass : '';
  247. return (
  248. <div
  249. key={page._id}
  250. data-testid="search-result-content"
  251. className={`dynamic-layout-root ${moduleClass} ${fluidLayoutClass}`}
  252. >
  253. <RightComponent />
  254. <div className="container-lg grw-container-convertible pt-2 pb-2">
  255. <PagePathNav
  256. pageId={page._id}
  257. pagePath={page.path}
  258. isWipPage={page.wip}
  259. formerLinkClassName="small"
  260. latterLinkClassName="fs-3 text-truncate"
  261. />
  262. </div>
  263. <div
  264. id="search-result-content-body-container"
  265. ref={scrollElementRef}
  266. className="search-result-content-body-container container-lg grw-container-convertible overflow-y-scroll"
  267. >
  268. {page.revision != null && rendererOptions != null && (
  269. <RevisionLoader
  270. rendererOptions={rendererOptions}
  271. pageId={page._id}
  272. revisionId={page.revision}
  273. />
  274. )}
  275. {page.revision != null && (
  276. <PageComment
  277. rendererOptions={rendererOptions}
  278. pageId={page._id}
  279. pagePath={page.path}
  280. revision={page.revision}
  281. currentUser={currentUser}
  282. isReadOnly
  283. />
  284. )}
  285. <PageContentFooter page={page} />
  286. </div>
  287. </div>
  288. );
  289. };