InAppNotificationSubstance.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. import { type JSX, useId, useMemo } from 'react';
  2. import { useTranslation } from 'next-i18next';
  3. import type { SWRInfiniteResponse } from 'swr/infinite';
  4. import InAppNotificationElm from '~/client/components/InAppNotification/InAppNotificationElm';
  5. import InfiniteScroll from '~/client/components/InfiniteScroll';
  6. import { NewsItem } from '~/features/news/client/components/NewsItem';
  7. import {
  8. useSWRINFxNews,
  9. useSWRxNewsUnreadCount,
  10. } from '~/features/news/client/hooks/use-news';
  11. import type { INewsItemWithReadStatus } from '~/features/news/interfaces/news-item';
  12. import type {
  13. IInAppNotificationHasId,
  14. PaginateResult,
  15. } from '~/interfaces/in-app-notification';
  16. import { InAppNotificationStatuses } from '~/interfaces/in-app-notification';
  17. import { useSidebarMode } from '~/states/ui/sidebar';
  18. import { useSWRINFxInAppNotifications } from '~/stores/in-app-notification';
  19. import type { FilterType } from './InAppNotification';
  20. const NEWS_PER_PAGE = 10;
  21. type InAppNotificationFormsProps = {
  22. isUnopendNotificationsVisible: boolean;
  23. onChangeUnopendNotificationsVisible: () => void;
  24. activeFilter: FilterType;
  25. onChangeFilter: (filter: FilterType) => void;
  26. };
  27. export const InAppNotificationForms = (
  28. props: InAppNotificationFormsProps,
  29. ): JSX.Element => {
  30. const {
  31. isUnopendNotificationsVisible,
  32. onChangeUnopendNotificationsVisible,
  33. activeFilter,
  34. onChangeFilter,
  35. } = props;
  36. const { t } = useTranslation('commons');
  37. const toggleId = useId();
  38. return (
  39. <div className="my-2">
  40. {/* Filter tabs */}
  41. <fieldset className="btn-group w-100 mb-2">
  42. <button
  43. type="button"
  44. className={`btn btn-sm ${activeFilter === 'all' ? 'btn-primary' : 'btn-outline-secondary'}`}
  45. onClick={() => onChangeFilter('all')}
  46. >
  47. {t('in_app_notification.filter_all')}
  48. </button>
  49. <button
  50. type="button"
  51. className={`btn btn-sm ${activeFilter === 'notifications' ? 'btn-primary' : 'btn-outline-secondary'}`}
  52. onClick={() => onChangeFilter('notifications')}
  53. >
  54. {t('in_app_notification.notifications')}
  55. </button>
  56. <button
  57. type="button"
  58. className={`btn btn-sm ${activeFilter === 'news' ? 'btn-primary' : 'btn-outline-secondary'}`}
  59. onClick={() => onChangeFilter('news')}
  60. >
  61. {t('in_app_notification.news')}
  62. </button>
  63. </fieldset>
  64. {/* Unread-only toggle */}
  65. <div className="form-check form-switch">
  66. <label className="form-check-label" htmlFor={toggleId}>
  67. {t('in_app_notification.only_unread')}
  68. </label>
  69. <input
  70. id={toggleId}
  71. className="form-check-input"
  72. type="checkbox"
  73. role="switch"
  74. aria-checked={isUnopendNotificationsVisible}
  75. checked={isUnopendNotificationsVisible}
  76. onChange={onChangeUnopendNotificationsVisible}
  77. />
  78. </div>
  79. </div>
  80. );
  81. };
  82. type InAppNotificationContentProps = {
  83. isUnopendNotificationsVisible: boolean;
  84. activeFilter: FilterType;
  85. };
  86. type MergedItem =
  87. | { type: 'news'; item: INewsItemWithReadStatus; sortKey: Date }
  88. | {
  89. type: 'notification';
  90. item: IInAppNotificationHasId;
  91. sortKey: Date;
  92. };
  93. export const InAppNotificationContent = (
  94. props: InAppNotificationContentProps,
  95. ): JSX.Element => {
  96. const { isUnopendNotificationsVisible, activeFilter } = props;
  97. const { t } = useTranslation('commons');
  98. const { isCollapsedMode } = useSidebarMode();
  99. // In collapsed mode (hover panel): constrain height + own scrollbar
  100. // In dock/drawer mode: no constraints — outer SimpleBar handles all scrolling
  101. const collapsed = isCollapsedMode();
  102. const scrollAreaClassName = collapsed ? 'overflow-auto' : undefined;
  103. const scrollAreaStyle = collapsed ? { maxHeight: '60vh' } : undefined;
  104. const notificationStatus = isUnopendNotificationsVisible
  105. ? InAppNotificationStatuses.STATUS_UNOPENED
  106. : undefined;
  107. // Always call both hooks (React rules of hooks)
  108. const newsResponse = useSWRINFxNews(
  109. NEWS_PER_PAGE,
  110. { onlyUnread: isUnopendNotificationsVisible },
  111. { keepPreviousData: true },
  112. );
  113. const { mutate: mutateNewsUnreadCount } = useSWRxNewsUnreadCount();
  114. const notificationResponse = useSWRINFxInAppNotifications(
  115. NEWS_PER_PAGE,
  116. { status: notificationStatus },
  117. { keepPreviousData: true },
  118. );
  119. const allNewsItems: INewsItemWithReadStatus[] = useMemo(() => {
  120. if (!newsResponse.data) return [];
  121. return newsResponse.data.flatMap((page) => page.docs);
  122. }, [newsResponse.data]);
  123. const allNotificationItems: IInAppNotificationHasId[] = useMemo(() => {
  124. if (!notificationResponse.data) return [];
  125. return notificationResponse.data.flatMap((page) => page.docs);
  126. }, [notificationResponse.data]);
  127. // Determine if each stream has exhausted its pages
  128. const newsExhausted = useMemo(
  129. () =>
  130. newsResponse.data != null &&
  131. newsResponse.data.length > 0 &&
  132. !newsResponse.data[newsResponse.data.length - 1].hasNextPage,
  133. [newsResponse.data],
  134. );
  135. const notifExhausted = useMemo(
  136. () =>
  137. notificationResponse.data != null &&
  138. notificationResponse.data.length > 0 &&
  139. !notificationResponse.data[notificationResponse.data.length - 1]
  140. .hasNextPage,
  141. [notificationResponse.data],
  142. );
  143. // Synthetic SWRInfiniteResponse for InfiniteScroll in 'all' mode.
  144. // Typed to match newsResponse's shape so InfiniteScroll<E> receives a
  145. // well-typed response without `as unknown as` casts.
  146. const allModeSWRResponse = useMemo<
  147. SWRInfiniteResponse<PaginateResult<INewsItemWithReadStatus>, Error>
  148. >(
  149. () => ({
  150. data: newsResponse.data,
  151. error: newsResponse.error ?? notificationResponse.error,
  152. isValidating:
  153. newsResponse.isValidating || notificationResponse.isValidating,
  154. isLoading: newsResponse.isLoading || notificationResponse.isLoading,
  155. mutate: newsResponse.mutate,
  156. setSize: async (updater) => {
  157. const nextNewsSize =
  158. typeof updater === 'function' ? updater(newsResponse.size) : updater;
  159. const nextNotifSize =
  160. typeof updater === 'function'
  161. ? updater(notificationResponse.size)
  162. : updater;
  163. const [newsResult] = await Promise.all([
  164. newsExhausted
  165. ? Promise.resolve(newsResponse.data)
  166. : newsResponse.setSize(nextNewsSize),
  167. notifExhausted
  168. ? Promise.resolve(notificationResponse.data)
  169. : notificationResponse.setSize(nextNotifSize),
  170. ]);
  171. return newsResult;
  172. },
  173. size: Math.max(newsResponse.size, notificationResponse.size),
  174. }),
  175. [newsResponse, notificationResponse, newsExhausted, notifExhausted],
  176. );
  177. // Merged and sorted items for 'all' filter
  178. const mergedItems: MergedItem[] = useMemo(() => {
  179. const newsEntries: MergedItem[] = allNewsItems.map((item) => ({
  180. type: 'news',
  181. item,
  182. sortKey:
  183. item.publishedAt instanceof Date
  184. ? item.publishedAt
  185. : new Date(item.publishedAt),
  186. }));
  187. const notifEntries: MergedItem[] = allNotificationItems.map((item) => ({
  188. type: 'notification',
  189. item,
  190. sortKey:
  191. item.createdAt instanceof Date
  192. ? item.createdAt
  193. : new Date(item.createdAt),
  194. }));
  195. return [...newsEntries, ...notifEntries].sort(
  196. (a, b) => b.sortKey.getTime() - a.sortKey.getTime(),
  197. );
  198. }, [allNewsItems, allNotificationItems]);
  199. const handleReadMutate = () => {
  200. newsResponse.mutate();
  201. mutateNewsUnreadCount();
  202. };
  203. // SWR-idiomatic optimistic update: rewrite the per-page cache in place and
  204. // suppress revalidation so the dot stays removed across unmount/remount.
  205. // The useSWRInfinite cache is held in the global SWR provider keyed by the
  206. // composite list key, so subsequent mounts read this updated cache directly.
  207. const handleNotificationRead = (notificationId: string) => {
  208. notificationResponse.mutate(
  209. (pages) =>
  210. pages?.map((page) => ({
  211. ...page,
  212. docs: page.docs.map((doc) =>
  213. doc._id.toString() === notificationId
  214. ? { ...doc, status: InAppNotificationStatuses.STATUS_OPENED }
  215. : doc,
  216. ),
  217. })),
  218. { revalidate: false },
  219. );
  220. };
  221. if (activeFilter === 'news') {
  222. if (allNewsItems.length === 0 && !newsResponse.isValidating) {
  223. return <>{t('in_app_notification.no_news')}</>;
  224. }
  225. return (
  226. <div className={scrollAreaClassName} style={scrollAreaStyle}>
  227. <InfiniteScroll
  228. swrInifiniteResponse={newsResponse}
  229. isReachingEnd={newsExhausted}
  230. >
  231. <div className="list-group">
  232. {allNewsItems.map((item) => (
  233. <NewsItem
  234. key={item._id.toString()}
  235. item={item}
  236. onReadMutate={handleReadMutate}
  237. />
  238. ))}
  239. </div>
  240. </InfiniteScroll>
  241. </div>
  242. );
  243. }
  244. if (activeFilter === 'notifications') {
  245. if (
  246. allNotificationItems.length === 0 &&
  247. !notificationResponse.isValidating
  248. ) {
  249. return <>{t('in_app_notification.no_notification')}</>;
  250. }
  251. return (
  252. <div className={scrollAreaClassName} style={scrollAreaStyle}>
  253. <InfiniteScroll
  254. swrInifiniteResponse={notificationResponse}
  255. isReachingEnd={notifExhausted}
  256. >
  257. <div className="list-group">
  258. {allNotificationItems.map((notification) => {
  259. const id = notification._id.toString();
  260. return (
  261. <InAppNotificationElm
  262. key={id}
  263. notification={notification}
  264. onUnopenedNotificationOpend={() => handleNotificationRead(id)}
  265. />
  266. );
  267. })}
  268. </div>
  269. </InfiniteScroll>
  270. </div>
  271. );
  272. }
  273. // 'all' filter: merged view
  274. if (
  275. mergedItems.length === 0 &&
  276. !newsResponse.isValidating &&
  277. !notificationResponse.isValidating
  278. ) {
  279. return <>{t('in_app_notification.no_notification')}</>;
  280. }
  281. return (
  282. <div className={scrollAreaClassName} style={scrollAreaStyle}>
  283. <InfiniteScroll
  284. swrInifiniteResponse={allModeSWRResponse}
  285. isReachingEnd={newsExhausted && notifExhausted}
  286. >
  287. <div className="list-group">
  288. {mergedItems.map((entry) => {
  289. if (entry.type === 'news') {
  290. return (
  291. <NewsItem
  292. key={`news-${entry.item._id.toString()}`}
  293. item={entry.item}
  294. onReadMutate={handleReadMutate}
  295. />
  296. );
  297. }
  298. const id = entry.item._id.toString();
  299. return (
  300. <InAppNotificationElm
  301. key={`notif-${id}`}
  302. notification={entry.item}
  303. onUnopenedNotificationOpend={() => handleNotificationRead(id)}
  304. />
  305. );
  306. })}
  307. </div>
  308. </InfiniteScroll>
  309. </div>
  310. );
  311. };