PageListItemL.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. import React, {
  2. forwardRef, useState,
  3. ForwardRefRenderFunction, memo, useCallback, useImperativeHandle, useRef, useEffect,
  4. } from 'react';
  5. import type {
  6. IPageInfoAll, IPageWithMeta, IPageInfoForListing,
  7. } from '@growi/core';
  8. import { isIPageInfoForListing, isIPageInfoForEntity } from '@growi/core';
  9. import { DevidedPagePath } from '@growi/core/dist/models';
  10. import { pathUtils } from '@growi/core/dist/utils';
  11. import { UserPicture } from '@growi/ui/dist/components';
  12. import { PageListMeta } from '@growi/ui/dist/components/PagePath';
  13. import { format } from 'date-fns';
  14. import { useTranslation } from 'next-i18next';
  15. import Link from 'next/link';
  16. import Clamp from 'react-multiline-clamp';
  17. import { Input } from 'reactstrap';
  18. import { ISelectable } from '~/client/interfaces/selectable-all';
  19. import { unlink, bookmark, unbookmark } from '~/client/services/page-operation';
  20. import { toastError } from '~/client/util/toastr';
  21. import { IPageSearchMeta, IPageWithSearchMeta, isIPageSearchMeta } from '~/interfaces/search';
  22. import {
  23. OnDuplicatedFunction, OnRenamedFunction, OnDeletedFunction, OnPutBackedFunction,
  24. } from '~/interfaces/ui';
  25. import LinkedPagePath from '~/models/linked-page-path';
  26. import { useSWRMUTxCurrentUserBookmarks } from '~/stores/bookmark';
  27. import {
  28. usePageRenameModal, usePageDuplicateModal, usePageDeleteModal, usePutBackPageModal,
  29. } from '~/stores/modal';
  30. import { useIsDeviceSmallerThanLg } from '~/stores/ui';
  31. import { useSWRMUTxPageInfo, useSWRxPageInfo } from '../../stores/page';
  32. import { ForceHideMenuItems, PageItemControl } from '../Common/Dropdown/PageItemControl';
  33. import { PagePathHierarchicalLink } from '../Common/PagePathHierarchicalLink';
  34. type Props = {
  35. page: IPageWithSearchMeta | IPageWithMeta<IPageInfoForListing & IPageSearchMeta>,
  36. isSelected?: boolean, // is item selected(focused)
  37. isEnableActions?: boolean,
  38. isReadOnlyUser: boolean,
  39. forceHideMenuItems?: ForceHideMenuItems,
  40. showPageUpdatedTime?: boolean, // whether to show page's updated time at the top-right corner of item
  41. onCheckboxChanged?: (isChecked: boolean, pageId: string) => void,
  42. onClickItem?: (pageId: string) => void,
  43. onPageDuplicated?: OnDuplicatedFunction,
  44. onPageRenamed?: OnRenamedFunction,
  45. onPageDeleted?: OnDeletedFunction,
  46. onPagePutBacked?: OnPutBackedFunction,
  47. }
  48. const PageListItemLSubstance: ForwardRefRenderFunction<ISelectable, Props> = (props: Props, ref): JSX.Element => {
  49. const {
  50. page: { data: pageData, meta: pageMeta }, isSelected, isEnableActions, isReadOnlyUser,
  51. forceHideMenuItems,
  52. showPageUpdatedTime,
  53. onClickItem, onCheckboxChanged, onPageDuplicated, onPageRenamed, onPageDeleted, onPagePutBacked,
  54. } = props;
  55. const { returnPathForURL } = pathUtils;
  56. const [likerCount, setLikerCount] = useState(pageData.liker.length);
  57. const [bookmarkCount, setBookmarkCount] = useState(pageMeta && pageMeta.bookmarkCount ? pageMeta.bookmarkCount : 0);
  58. const { t } = useTranslation();
  59. const inputRef = useRef<HTMLInputElement>(null);
  60. // publish ISelectable methods
  61. useImperativeHandle(ref, () => ({
  62. select: () => {
  63. const input = inputRef.current;
  64. if (input != null) {
  65. input.checked = true;
  66. }
  67. },
  68. deselect: () => {
  69. const input = inputRef.current;
  70. if (input != null) {
  71. input.checked = false;
  72. }
  73. },
  74. }));
  75. const { data: isDeviceSmallerThanLg } = useIsDeviceSmallerThanLg();
  76. const { open: openDuplicateModal } = usePageDuplicateModal();
  77. const { open: openRenameModal } = usePageRenameModal();
  78. const { open: openDeleteModal } = usePageDeleteModal();
  79. const { open: openPutBackPageModal } = usePutBackPageModal();
  80. const shouldFetch = isSelected && (pageData != null || pageMeta != null);
  81. const { data: pageInfo } = useSWRxPageInfo(shouldFetch ? pageData?._id : null);
  82. const { trigger: mutatePageInfo } = useSWRMUTxPageInfo(pageData?._id ?? null);
  83. const { trigger: mutateCurrentUserBookmarks } = useSWRMUTxCurrentUserBookmarks();
  84. const elasticSearchResult = isIPageSearchMeta(pageMeta) ? pageMeta.elasticSearchResult : null;
  85. const revisionShortBody = isIPageInfoForListing(pageMeta) ? pageMeta.revisionShortBody : null;
  86. const dPagePath: DevidedPagePath = new DevidedPagePath(pageData.path, false);
  87. const linkedPagePathFormer = new LinkedPagePath(dPagePath.former);
  88. const dPagePathHighlighted: DevidedPagePath = new DevidedPagePath(elasticSearchResult?.highlightedPath || pageData.path, true);
  89. const linkedPagePathHighlightedFormer = new LinkedPagePath(dPagePathHighlighted.former);
  90. const linkedPagePathHighlightedLatter = new LinkedPagePath(dPagePathHighlighted.latter);
  91. const lastUpdateDate = format(new Date(pageData.updatedAt), 'yyyy/MM/dd HH:mm:ss');
  92. useEffect(() => {
  93. if (isIPageInfoForEntity(pageInfo)) {
  94. // likerCount
  95. setLikerCount(pageInfo.likerIds?.length ?? 0);
  96. // bookmarkCount
  97. setBookmarkCount(pageInfo.bookmarkCount ?? 0);
  98. }
  99. }, [pageInfo]);
  100. // click event handler
  101. const clickHandler = useCallback(() => {
  102. // do nothing if mobile
  103. if (isDeviceSmallerThanLg) {
  104. return;
  105. }
  106. if (onClickItem != null) {
  107. onClickItem(pageData._id);
  108. }
  109. }, [isDeviceSmallerThanLg, onClickItem, pageData._id]);
  110. const bookmarkMenuItemClickHandler = async(_pageId: string, _newValue: boolean): Promise<void> => {
  111. const bookmarkOperation = _newValue ? bookmark : unbookmark;
  112. await bookmarkOperation(_pageId);
  113. mutateCurrentUserBookmarks();
  114. mutatePageInfo();
  115. };
  116. const duplicateMenuItemClickHandler = useCallback(() => {
  117. const page = {
  118. pageId: pageData._id,
  119. path: pageData.path,
  120. };
  121. openDuplicateModal(page, { onDuplicated: onPageDuplicated });
  122. }, [onPageDuplicated, openDuplicateModal, pageData._id, pageData.path]);
  123. const renameMenuItemClickHandler = useCallback((_id: string, pageInfo: IPageInfoAll | undefined) => {
  124. const page = { data: pageData, meta: pageInfo };
  125. openRenameModal(page, { onRenamed: onPageRenamed });
  126. }, [pageData, onPageRenamed, openRenameModal]);
  127. const deleteMenuItemClickHandler = useCallback((_id: string, pageInfo: IPageInfoAll | undefined) => {
  128. const pageToDelete = { data: pageData, meta: pageInfo };
  129. // open modal
  130. openDeleteModal([pageToDelete], { onDeleted: onPageDeleted });
  131. }, [pageData, openDeleteModal, onPageDeleted]);
  132. const revertMenuItemClickHandler = useCallback(async() => {
  133. const { _id: pageId, path } = pageData;
  134. const putBackedHandler = async(path) => {
  135. try {
  136. // pageData path should be `/trash/fuga` (`/trash` should be included to the prefix)
  137. await unlink(pageData.path);
  138. }
  139. catch (err) {
  140. toastError(err);
  141. }
  142. if (onPagePutBacked != null) {
  143. // This path should be `/fuga` ( `/trash` is not included to the prefix)
  144. onPagePutBacked(path);
  145. }
  146. };
  147. openPutBackPageModal({ pageId, path }, { onPutBacked: putBackedHandler });
  148. }, [onPagePutBacked, openPutBackPageModal, pageData]);
  149. const styleListGroupItem = (!isDeviceSmallerThanLg && onClickItem != null) ? 'list-group-item-action' : '';
  150. // background color of list item changes when class "active" exists under 'list-group-item'
  151. const styleActive = !isDeviceSmallerThanLg && isSelected ? 'active' : '';
  152. const shouldDangerouslySetInnerHTMLForPaths = elasticSearchResult != null && elasticSearchResult.highlightedPath != null;
  153. const canRenderESSnippet = elasticSearchResult != null && elasticSearchResult.snippet != null;
  154. const canRenderRevisionSnippet = revisionShortBody != null;
  155. const hasBrowsingRights = canRenderESSnippet || canRenderRevisionSnippet;
  156. return (
  157. <li
  158. key={pageData._id}
  159. className={`list-group-item d-flex align-items-center px-3 px-md-1 ${styleListGroupItem} ${styleActive}`}
  160. data-testid="page-list-item-L"
  161. onClick={clickHandler}
  162. >
  163. <div className="text-break w-100">
  164. <div className="d-flex">
  165. {/* checkbox */}
  166. {onCheckboxChanged != null && (
  167. <div className="d-flex align-items-center justify-content-center">
  168. <Input
  169. type="checkbox"
  170. id={`cbSelect-${pageData._id}`}
  171. data-testid="cb-select"
  172. innerRef={inputRef}
  173. onChange={(e) => { onCheckboxChanged(e.target.checked, pageData._id) }}
  174. />
  175. </div>
  176. )}
  177. <div className="flex-grow-1 px-2 px-md-4">
  178. <div className="d-flex justify-content-between">
  179. {/* page path */}
  180. <PagePathHierarchicalLink
  181. linkedPagePath={linkedPagePathFormer}
  182. linkedPagePathByHtml={linkedPagePathHighlightedFormer}
  183. />
  184. {showPageUpdatedTime && (
  185. <span className="page-list-updated-at text-muted">Last update: {lastUpdateDate}</span>
  186. )}
  187. </div>
  188. <div className="d-flex align-items-center mb-1">
  189. {/* Picture */}
  190. <span className="me-2 d-none d-md-block">
  191. <UserPicture user={pageData.lastUpdateUser} size="md" />
  192. </span>
  193. {/* page title */}
  194. <Clamp lines={1}>
  195. <span className="h5 mb-0">
  196. {/* Use permanent links to care for pages with the same name (Cannot use page path url) */}
  197. <span className="grw-page-path-hierarchical-link text-break">
  198. <Link
  199. legacyBehavior
  200. href={returnPathForURL(pageData.path, pageData._id)}
  201. prefetch={false}
  202. >
  203. {shouldDangerouslySetInnerHTMLForPaths
  204. ? (
  205. <a
  206. className="page-segment"
  207. // eslint-disable-next-line react/no-danger
  208. dangerouslySetInnerHTML={{ __html: linkedPagePathHighlightedLatter.pathName }}
  209. >
  210. </a>
  211. )
  212. : <a className="page-segment">{linkedPagePathHighlightedLatter.pathName}</a>
  213. }
  214. </Link>
  215. </span>
  216. </span>
  217. </Clamp>
  218. {/* page meta */}
  219. <div className="d-none d-md-flex py-0 px-1 ms-2 text-nowrap">
  220. <PageListMeta page={pageData} likerCount={likerCount} bookmarkCount={bookmarkCount} shouldSpaceOutIcon />
  221. </div>
  222. {/* doropdown icon includes page control buttons */}
  223. {hasBrowsingRights
  224. && (
  225. <div className="ms-auto">
  226. <PageItemControl
  227. alignEnd
  228. pageId={pageData._id}
  229. pageInfo={isIPageInfoForListing(pageMeta) ? pageMeta : undefined}
  230. isEnableActions={isEnableActions}
  231. isReadOnlyUser={isReadOnlyUser}
  232. forceHideMenuItems={forceHideMenuItems}
  233. onClickBookmarkMenuItem={bookmarkMenuItemClickHandler}
  234. onClickRenameMenuItem={renameMenuItemClickHandler}
  235. onClickDuplicateMenuItem={duplicateMenuItemClickHandler}
  236. onClickDeleteMenuItem={deleteMenuItemClickHandler}
  237. onClickRevertMenuItem={revertMenuItemClickHandler}
  238. />
  239. </div>
  240. )
  241. }
  242. </div>
  243. <div className="page-list-snippet py-1">
  244. <Clamp lines={2}>
  245. {elasticSearchResult != null && elasticSearchResult.snippet != null && (
  246. // eslint-disable-next-line react/no-danger
  247. <div dangerouslySetInnerHTML={{ __html: elasticSearchResult.snippet }}></div>
  248. )}
  249. {revisionShortBody != null && (
  250. <div data-testid="revision-short-body-in-page-list-item-L">{revisionShortBody}</div>
  251. )}
  252. {
  253. !hasBrowsingRights && (
  254. <>
  255. <i className="icon-exclamation p-1"></i>
  256. {t('not_allowed_to_see_this_page')}
  257. </>
  258. )
  259. }
  260. </Clamp>
  261. </div>
  262. </div>
  263. </div>
  264. {/* TODO: adjust snippet position */}
  265. </div>
  266. </li>
  267. );
  268. };
  269. export const PageListItemL = memo(forwardRef(PageListItemLSubstance));