@cometchat/chat-uikit-react-native 5.3.4 → 5.3.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/package.json +2 -1
  2. package/src/CometChatConversations/CometChatConversations.tsx +107 -18
  3. package/src/CometChatMessageList/CometChatMessageList.tsx +24 -5
  4. package/src/CometChatNotificationFeed/CometChatNotificationFeed.tsx +811 -0
  5. package/src/CometChatNotificationFeed/Skeleton.tsx +43 -0
  6. package/src/CometChatNotificationFeed/index.ts +19 -0
  7. package/src/CometChatNotificationFeed/style.ts +333 -0
  8. package/src/CometChatNotificationFeed/utils.ts +124 -0
  9. package/src/extensions/LinkPreview/LinkPreviewBubble.tsx +22 -18
  10. package/src/extensions/LinkPreview/LinkPreviewExtensionDecorator.tsx +1 -1
  11. package/src/extensions/ThumbnailGeneration/ThumbnailGenerationDecorator.tsx +5 -1
  12. package/src/index.ts +7 -0
  13. package/src/shared/icons/components/notification-empty.tsx +27 -0
  14. package/src/shared/resources/CometChatLocalizeNew/resources/de/translation.json +8 -1
  15. package/src/shared/resources/CometChatLocalizeNew/resources/en/translation.json +8 -1
  16. package/src/shared/resources/CometChatLocalizeNew/resources/es/translation.json +8 -1
  17. package/src/shared/resources/CometChatLocalizeNew/resources/fr/translation.json +8 -1
  18. package/src/shared/resources/CometChatLocalizeNew/resources/hi/translation.json +8 -1
  19. package/src/shared/resources/CometChatLocalizeNew/resources/hu/translation.json +8 -1
  20. package/src/shared/resources/CometChatLocalizeNew/resources/it/translation.json +8 -1
  21. package/src/shared/resources/CometChatLocalizeNew/resources/ja/translation.json +8 -1
  22. package/src/shared/resources/CometChatLocalizeNew/resources/ko/translation.json +8 -1
  23. package/src/shared/resources/CometChatLocalizeNew/resources/lt/translation.json +8 -1
  24. package/src/shared/resources/CometChatLocalizeNew/resources/ms/translation.json +8 -1
  25. package/src/shared/resources/CometChatLocalizeNew/resources/nl/translation.json +8 -1
  26. package/src/shared/resources/CometChatLocalizeNew/resources/pt/translation.json +8 -1
  27. package/src/shared/resources/CometChatLocalizeNew/resources/ru/translation.json +8 -1
  28. package/src/shared/resources/CometChatLocalizeNew/resources/sv/translation.json +8 -1
  29. package/src/shared/resources/CometChatLocalizeNew/resources/tr/translation.json +8 -1
  30. package/src/shared/resources/CometChatLocalizeNew/resources/zh/translation.json +8 -1
  31. package/src/shared/resources/CometChatLocalizeNew/resources/zh-tw/translation.json +8 -1
  32. package/src/shared/utils/MessageReceiptUtils.ts +0 -1
  33. package/src/shared/views/CometChatInlineAudioRecorder/useAudioRecorder.ts +53 -21
  34. package/src/shared/views/CometChatList/CometChatList.tsx +26 -15
  35. package/src/theme/default/default.ts +6 -0
  36. package/src/theme/type.ts +2 -0
@@ -0,0 +1,811 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * CometChatNotificationFeed.tsx
4
+ * ---------------------------------------------------------------------------
5
+ * Full-screen notification feed component displaying campaign/promotional
6
+ * notifications with category filtering, timestamp grouping, rich card
7
+ * rendering, real-time updates, and engagement reporting.
8
+ *
9
+ * Follows UIKit v5 component-centric architecture:
10
+ * - Arrow function component with co-located state and logic
11
+ * - useTheme() for style consumption
12
+ * - Event listener setup/cleanup in useEffect
13
+ * - No ViewModel class
14
+ * ---------------------------------------------------------------------------
15
+ */
16
+ import { CometChat } from "@cometchat/chat-sdk-react-native";
17
+ import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
18
+ import {
19
+ ActivityIndicator,
20
+ Pressable,
21
+ RefreshControl,
22
+ ScrollView,
23
+ SectionList,
24
+ Text,
25
+ View,
26
+ } from "react-native";
27
+ import { CometChatCardView } from "@cometchat/cards-react-native";
28
+ import type { CometChatCardThemeOverride } from "@cometchat/cards-react-native";
29
+
30
+ import { useTheme } from "../theme";
31
+ import { deepMerge } from "../shared/helper/helperFunctions";
32
+ import { DeepPartial } from "../shared/helper/types";
33
+ import { useLocalizedDate } from "../shared/helper/useLocalizedDateHook";
34
+ import { getCometChatTranslation } from "../shared/resources/CometChatLocalizeNew/LocalizationManager";
35
+ import { NotificationFeedStyle } from "./style";
36
+ import { groupFeedItemsByTimestamp } from "./utils";
37
+ import { Skeleton } from "./Skeleton";
38
+ import Header from "../shared/views/CometChatList/Header";
39
+ import { ErrorEmptyView } from "../shared/views/ErrorEmptyView/ErrorEmptyView";
40
+ import NotificationEmptyIcon from "../shared/icons/components/notification-empty";
41
+
42
+ // ───────────────────────────────────────────────────────────────
43
+ // Module-level constants (hoisted — no GC churn)
44
+ // ───────────────────────────────────────────────────────────────
45
+ const LISTENER_ID_PREFIX = "notification_feed_";
46
+ const UNREAD_POLL_INTERVAL_MS = 30_000;
47
+ const ALL_CATEGORY_ID = "__all__";
48
+ const t = getCometChatTranslation();
49
+
50
+ // ───────────────────────────────────────────────────────────────
51
+ // Types
52
+ // ───────────────────────────────────────────────────────────────
53
+
54
+ /** SDK types — these come from @cometchat/chat-sdk-react-native */
55
+ type NotificationFeedItem = any;
56
+ type NotificationCategory = any;
57
+ type NotificationFeedRequestBuilder = any;
58
+ type NotificationCategoriesRequestBuilder = any;
59
+
60
+ type ScreenState = "loading" | "loaded" | "empty" | "error";
61
+
62
+ interface CardAction {
63
+ type: string;
64
+ params: Record<string, any>;
65
+ elementId: string;
66
+ }
67
+
68
+ /**
69
+ * Props interface for CometChatNotificationFeed.
70
+ */
71
+ export interface CometChatNotificationFeedInterface {
72
+ // ─── Content Configuration ───────────────────────────────────
73
+ /** Feed title. Default: "Notifications" */
74
+ title?: string;
75
+ /** Show/hide the header. Default: true */
76
+ showHeader?: boolean;
77
+ /** Show/hide back button. Default: false */
78
+ showBackButton?: boolean;
79
+ /** Show/hide filter chips row. Default: true */
80
+ showFilterChips?: boolean;
81
+ /** Replace entire header with custom view */
82
+ HeaderView?: () => JSX.Element;
83
+ /** Deep link: scroll to a specific item by ID */
84
+ scrollToItemId?: string;
85
+
86
+ // ─── Data Configuration ──────────────────────────────────────
87
+ /** Custom request builder for feed items */
88
+ notificationFeedRequestBuilder?: NotificationFeedRequestBuilder;
89
+ /** Custom request builder for categories */
90
+ notificationCategoriesRequestBuilder?: NotificationCategoriesRequestBuilder;
91
+
92
+ // ─── Callbacks ───────────────────────────────────────────────
93
+ /** Called when a feed item card is tapped */
94
+ onItemClick?: (feedItem: NotificationFeedItem) => void;
95
+ /** Called when an action button inside a card is tapped */
96
+ onActionClick?: (feedItem: NotificationFeedItem, action: CardAction) => void;
97
+ /** Called on error */
98
+ onError?: (error: CometChat.CometChatException) => void;
99
+ /** Called when back button is pressed */
100
+ onBackPress?: () => void;
101
+
102
+ // ─── Custom State Views ──────────────────────────────────────
103
+ EmptyView?: () => JSX.Element;
104
+ ErrorView?: () => JSX.Element;
105
+ LoadingView?: () => JSX.Element;
106
+
107
+ // ─── Style ───────────────────────────────────────────────────
108
+ style?: DeepPartial<NotificationFeedStyle>;
109
+
110
+ // ─── CometChatCardsRenderer configuration ────────────────────
111
+ cardThemeMode?: "auto" | "light" | "dark";
112
+ cardThemeOverride?: CometChatCardThemeOverride;
113
+ }
114
+
115
+ // ───────────────────────────────────────────────────────────────
116
+ // Component
117
+ // ───────────────────────────────────────────────────────────────
118
+ export const CometChatNotificationFeed = (props: CometChatNotificationFeedInterface) => {
119
+ const {
120
+ title,
121
+ showHeader = true,
122
+ showBackButton = false,
123
+ showFilterChips = true,
124
+ HeaderView,
125
+ scrollToItemId,
126
+ notificationFeedRequestBuilder,
127
+ notificationCategoriesRequestBuilder,
128
+ onItemClick,
129
+ onActionClick,
130
+ onError,
131
+ onBackPress,
132
+ EmptyView,
133
+ ErrorView,
134
+ LoadingView,
135
+ style,
136
+ cardThemeMode = "auto",
137
+ cardThemeOverride,
138
+ } = props;
139
+
140
+ // ─── Theme & Styles ──────────────────────────────────────────
141
+ const theme = useTheme();
142
+ const { formatDate } = useLocalizedDate();
143
+ const mergedStyles = useMemo(
144
+ () => deepMerge(theme.notificationFeedStyles, style ?? {}) as NotificationFeedStyle,
145
+ [theme, style]
146
+ );
147
+
148
+ // ─── State ───────────────────────────────────────────────────
149
+ const [screenState, setScreenState] = useState<ScreenState>("loading");
150
+ const [feedItems, setFeedItems] = useState<NotificationFeedItem[]>([]);
151
+ const [categories, setCategories] = useState<NotificationCategory[]>([]);
152
+ const [activeCategory, setActiveCategory] = useState<string | null>(null);
153
+ const [totalUnreadCount, setTotalUnreadCount] = useState<number>(0);
154
+ /** Per-category unread counts — persists across category switches (Property 4) */
155
+ const [categoryUnreadCounts, setCategoryUnreadCounts] = useState<Map<string, number>>(new Map());
156
+ const [isRefreshing, setIsRefreshing] = useState(false);
157
+ const [isLoadingMore, setIsLoadingMore] = useState(false);
158
+ const [isFetchingItems, setIsFetchingItems] = useState(false);
159
+ const [hasMorePages, setHasMorePages] = useState(true);
160
+ const [loadMoreError, setLoadMoreError] = useState(false);
161
+
162
+ // ─── Refs ────────────────────────────────────────────────────
163
+ const feedRequestRef = useRef<any>(null);
164
+ const categoriesRequestRef = useRef<any>(null);
165
+ const listenerIdRef = useRef(LISTENER_ID_PREFIX + Date.now());
166
+ const unreadPollTimerRef = useRef<ReturnType<typeof setInterval> | null>(null);
167
+ const visibilityTimersRef = useRef<Map<string, ReturnType<typeof setTimeout>>>(new Map());
168
+ const deliveredItemsRef = useRef<Set<string>>(new Set());
169
+ const readItemsRef = useRef<Set<string>>(new Set());
170
+ const sectionListRef = useRef<SectionList>(null);
171
+
172
+ // ─── Computed ────────────────────────────────────────────────
173
+ const sections = useMemo(() => groupFeedItemsByTimestamp(feedItems),
174
+ [feedItems]
175
+ );
176
+
177
+ // ─── Request Builder Factory ─────────────────────────────────
178
+ const createFeedRequestBuilder = useCallback(
179
+ (category: string | null) => {
180
+ if (notificationFeedRequestBuilder) {
181
+ return notificationFeedRequestBuilder;
182
+ }
183
+ let builder = new CometChat.NotificationFeedRequestBuilder()
184
+ .setLimit(20);
185
+ if (category) {
186
+
187
+ builder = builder.setCategory(category);
188
+ }
189
+ return builder.build();
190
+ },
191
+ [notificationFeedRequestBuilder]
192
+ );
193
+
194
+ // ─── Mark as Delivered (batch) ───────────────────────────────
195
+ const markItemsAsDelivered = useCallback((items: NotificationFeedItem[]) => {
196
+ // Seed read/delivered refs for items already marked by server
197
+ items.forEach((item: any) => {
198
+ if (item.deliveredAt != null) {
199
+ deliveredItemsRef.current.add(item.id);
200
+ }
201
+ if (item.readAt != null) {
202
+ readItemsRef.current.add(item.id);
203
+ }
204
+ });
205
+ // Only call API for items not yet delivered
206
+ const undelivered = items.filter(
207
+ (item: any) => !deliveredItemsRef.current.has(item.id) && item.deliveredAt == null
208
+ );
209
+ if (undelivered.length === 0) return;
210
+ undelivered.forEach((item: any) => deliveredItemsRef.current.add(item.id));
211
+ CometChat.markFeedItemsAsDelivered(undelivered).catch((e) => { console.warn('[CometChatNotificationFeed]', e?.message || e); });
212
+ }, []);
213
+
214
+ // ─── Fetch Categories ────────────────────────────────────────
215
+ const fetchCategories = useCallback(async () => {
216
+ try {
217
+ const builder =
218
+ notificationCategoriesRequestBuilder ??
219
+ new CometChat.NotificationCategoriesRequestBuilder().setLimit(50).build();
220
+ categoriesRequestRef.current = builder;
221
+ const cats = await builder.fetchNext();
222
+ setCategories(cats ?? []);
223
+ } catch (err: any) {
224
+ setCategories([]);
225
+ }
226
+ }, [notificationCategoriesRequestBuilder]);
227
+
228
+ // ─── Fetch Feed Items ────────────────────────────────────────
229
+ const isInitialLoadRef = useRef(true);
230
+
231
+ const fetchInitialItems = useCallback(async () => {
232
+ // Only show full loading state on first load, not on category switch
233
+ if (isInitialLoadRef.current) {
234
+ setScreenState("loading");
235
+ } else {
236
+ setIsFetchingItems(true);
237
+ }
238
+ setFeedItems([]);
239
+ setHasMorePages(true);
240
+ hasMorePagesRef.current = true;
241
+
242
+ const builder = createFeedRequestBuilder(activeCategory);
243
+ feedRequestRef.current = builder;
244
+
245
+ try {
246
+ const items = await builder.fetchNext();
247
+
248
+ if (!items || items.length === 0) {
249
+ setScreenState("empty");
250
+ setFeedItems([]);
251
+ setHasMorePages(false);
252
+ } else {
253
+ setFeedItems(items);
254
+ setScreenState("loaded");
255
+ markItemsAsDelivered(items);
256
+ isInitialLoadRef.current = false;
257
+ // Initialize per-category unread counts from "All" fetch (Property 4)
258
+ // Only seed counts on the initial "All" load (no category filter)
259
+ if (activeCategory === null) {
260
+ const counts = new Map<string, number>();
261
+ let total = 0;
262
+ for (const item of items) {
263
+ if (item.readAt == null) {
264
+ total++;
265
+ const cat = item.category;
266
+ if (cat) {
267
+ counts.set(cat, (counts.get(cat) ?? 0) + 1);
268
+ }
269
+ }
270
+ }
271
+ setCategoryUnreadCounts(counts);
272
+ setTotalUnreadCount(total);
273
+ }
274
+ }
275
+ } catch (err: any) {
276
+ setScreenState("error");
277
+ onError?.(err);
278
+ } finally {
279
+ setIsFetchingItems(false);
280
+ }
281
+ }, [activeCategory, createFeedRequestBuilder, markItemsAsDelivered, onError]);
282
+
283
+ // ─── Fetch Next Page ─────────────────────────────────────────
284
+ const isLoadingMoreRef = useRef(false);
285
+ const hasMorePagesRef = useRef(true);
286
+
287
+ const fetchNextPage = useCallback(async () => {
288
+ if (isLoadingMoreRef.current || !hasMorePagesRef.current || !feedRequestRef.current) return;
289
+ isLoadingMoreRef.current = true;
290
+ setIsLoadingMore(true);
291
+ setLoadMoreError(false);
292
+ try {
293
+ const items = await feedRequestRef.current.fetchNext();
294
+
295
+ if (!items || items.length === 0) {
296
+ setHasMorePages(false);
297
+ hasMorePagesRef.current = false;
298
+ } else {
299
+ setFeedItems((prev) => [...prev, ...items]);
300
+ markItemsAsDelivered(items);
301
+ }
302
+ } catch (err: any) {
303
+ setLoadMoreError(true);
304
+ onError?.(err);
305
+ } finally {
306
+ isLoadingMoreRef.current = false;
307
+ setIsLoadingMore(false);
308
+ }
309
+ }, [markItemsAsDelivered, onError]);
310
+
311
+ // ─── Pull to Refresh ─────────────────────────────────────────
312
+ const handleRefresh = useCallback(async () => {
313
+ setIsRefreshing(true);
314
+ const builder = createFeedRequestBuilder(activeCategory);
315
+ feedRequestRef.current = builder;
316
+ try {
317
+ const items = await builder.fetchNext();
318
+ if (!items || items.length === 0) {
319
+ setFeedItems([]);
320
+ setScreenState("empty");
321
+ setHasMorePages(false);
322
+ } else {
323
+ setFeedItems(items);
324
+ setScreenState("loaded");
325
+ setHasMorePages(true);
326
+ hasMorePagesRef.current = true;
327
+ markItemsAsDelivered(items);
328
+ }
329
+ } catch (err: any) {
330
+ onError?.(err);
331
+ } finally {
332
+ setIsRefreshing(false);
333
+ }
334
+ }, [activeCategory, createFeedRequestBuilder, markItemsAsDelivered, onError]);
335
+
336
+ // ─── Unread Count ────────────────────────────────────────────
337
+ /** Fetches total unread count from API and per-category counts */
338
+ const fetchUnreadCount = useCallback(async () => {
339
+ try {
340
+ const result = await CometChat.getNotificationFeedUnreadCount();
341
+ const total = result?.count ?? 0;
342
+ setTotalUnreadCount(total);
343
+ } catch (err: any) {
344
+ // Silently fail — unread count is non-critical
345
+ }
346
+ }, []);
347
+
348
+ // ─── Category Switch ─────────────────────────────────────────
349
+ const handleCategorySwitch = useCallback(
350
+ (categoryId: string | null) => {
351
+ if (categoryId === activeCategory) return;
352
+ setActiveCategory(categoryId);
353
+ // Reset visibility tracking
354
+ visibilityTimersRef.current.forEach((timer) => clearTimeout(timer));
355
+ visibilityTimersRef.current.clear();
356
+ },
357
+ [activeCategory]
358
+ );
359
+
360
+ // ─── Engagement: Viewed ──────────────────────────────────────
361
+ const reportViewed = useCallback((item: NotificationFeedItem) => {
362
+ CometChat
363
+ .reportFeedEngagement(item, "viewed")
364
+ .catch((e) => { console.warn('[CometChatNotificationFeed]', e?.message || e); });
365
+ }, []);
366
+
367
+ // ─── Engagement: Mark as Read (immediately on viewport entry) ──────────
368
+ const markAsRead = useCallback(
369
+ (item: NotificationFeedItem) => {
370
+ const id = item.id;
371
+ if (!id) return;
372
+ if (item.readAt != null) return; // Already read (server state)
373
+ if (readItemsRef.current.has(id)) return; // Already marked read this session
374
+
375
+ readItemsRef.current.add(id);
376
+ CometChat.markFeedItemAsRead(item).then(() => {
377
+ setFeedItems((prev) =>
378
+ prev.map((fi: any) => {
379
+ if (fi.id === id) {
380
+ fi.readAt = Date.now() / 1000;
381
+ }
382
+ return fi;
383
+ })
384
+ );
385
+ setTotalUnreadCount((prev) => Math.max(0, prev - 1));
386
+ const itemCategory = item.category;
387
+ if (itemCategory) {
388
+ setCategoryUnreadCounts((prev) => {
389
+ const next = new Map(prev);
390
+ const current = next.get(itemCategory) ?? 0;
391
+ if (current > 0) {
392
+ next.set(itemCategory, current - 1);
393
+ }
394
+ return next;
395
+ });
396
+ }
397
+ }).catch((e) => {
398
+ console.warn('[CometChatNotificationFeed] markFeedItemAsRead failed:', e?.message || e);
399
+ readItemsRef.current.delete(id);
400
+ });
401
+ },
402
+ []
403
+ );
404
+
405
+ // ─── Engagement: Clicked ─────────────────────────────────────
406
+ const handleItemClick = useCallback(
407
+ (item: NotificationFeedItem) => {
408
+ CometChat.reportFeedEngagement(item, "clicked").catch((e) => { console.warn('[CometChatNotificationFeed]', e?.message || e); });
409
+ onItemClick?.(item);
410
+ },
411
+ [onItemClick]
412
+ );
413
+
414
+ // ─── Engagement: Interacted (button press) ─────────────────
415
+ const handleActionClick = useCallback(
416
+ (item: NotificationFeedItem, action: CardAction) => {
417
+ CometChat.reportFeedEngagement(item, "clicked").catch((e) => { console.warn('[CometChatNotificationFeed]', e?.message || e); });
418
+ onActionClick?.(item, action);
419
+ },
420
+ [onActionClick]
421
+ );
422
+
423
+ // ─── Viewability Config (for visibility tracking) ────────────
424
+ const previouslyVisibleRef = useRef<Set<string>>(new Set());
425
+
426
+ const onViewableItemsChanged = useCallback(
427
+ ({ viewableItems }: any) => {
428
+ const currentlyVisible = new Set<string>();
429
+
430
+ for (const viewable of viewableItems) {
431
+
432
+ if (viewable.item) {
433
+ const id = viewable.item.id;
434
+
435
+ currentlyVisible.add(id);
436
+ reportViewed(viewable.item);
437
+ markAsRead(viewable.item);
438
+ }
439
+ }
440
+
441
+ previouslyVisibleRef.current = currentlyVisible;
442
+ },
443
+ [reportViewed, markAsRead]
444
+ );
445
+
446
+ const viewabilityConfig = useRef({ itemVisiblePercentThreshold: 50 }).current;
447
+
448
+ // ─── Lifecycle: Init ─────────────────────────────────────────
449
+ useEffect(() => {
450
+ fetchCategories();
451
+ fetchUnreadCount();
452
+
453
+ // Start unread count polling
454
+ unreadPollTimerRef.current = setInterval(fetchUnreadCount, UNREAD_POLL_INTERVAL_MS);
455
+
456
+ return () => {
457
+ // Cleanup polling
458
+ if (unreadPollTimerRef.current) {
459
+ clearInterval(unreadPollTimerRef.current);
460
+ }
461
+ // Cleanup visibility timers
462
+ visibilityTimersRef.current.forEach((timer) => clearTimeout(timer));
463
+ visibilityTimersRef.current.clear();
464
+ };
465
+ }, []);
466
+
467
+ // ─── Lifecycle: Fetch on category change (also handles initial fetch) ──
468
+ useEffect(() => {
469
+ fetchInitialItems();
470
+ }, [activeCategory]);
471
+
472
+ // ─── Lifecycle: WebSocket Listener ───────────────────────────
473
+ useEffect(() => {
474
+ const listenerId = listenerIdRef.current;
475
+
476
+ CometChat.addNotificationFeedListener(listenerId, {
477
+ onFeedItemReceived: (feedItem: NotificationFeedItem) => {
478
+ // Ensure sentAt is set (WebSocket items may not have it populated)
479
+ if (!feedItem.sentAt) {
480
+ feedItem.sentAt = Math.floor(Date.now() / 1000);
481
+ }
482
+ // Insert at top
483
+ setFeedItems((prev) => [feedItem, ...prev]);
484
+ // Mark delivered
485
+ if (!deliveredItemsRef.current.has(feedItem.id)) {
486
+ deliveredItemsRef.current.add(feedItem.id);
487
+ CometChat.markFeedItemAsDelivered(feedItem).catch((e) => { console.warn('[CometChatNotificationFeed]', e?.message || e); });
488
+ }
489
+ // Increment total unread count
490
+ setTotalUnreadCount((prev) => prev + 1);
491
+ // Increment per-category unread count (Property 4)
492
+ const itemCategory = feedItem.category;
493
+ if (itemCategory) {
494
+ setCategoryUnreadCounts((prev) => {
495
+ const next = new Map(prev);
496
+ next.set(itemCategory, (next.get(itemCategory) ?? 0) + 1);
497
+ return next;
498
+ });
499
+ }
500
+ // Ensure we're in loaded state
501
+ setScreenState("loaded");
502
+ },
503
+ });
504
+
505
+ return () => {
506
+ CometChat.removeNotificationFeedListener(listenerId);
507
+ };
508
+ }, []);
509
+
510
+ // ─── Deep Link: scrollToItemId ───────────────────────────────
511
+ useEffect(() => {
512
+ if (!scrollToItemId) return;
513
+ const existingIndex = feedItems.findIndex(
514
+ (item: any) => item.id === scrollToItemId
515
+ );
516
+ if (existingIndex >= 0) {
517
+ // Item already in list — scroll to it
518
+ return;
519
+ }
520
+ // Fetch single item for deep linking
521
+ CometChat
522
+ .getNotificationFeedItem(scrollToItemId)
523
+ .then((item: NotificationFeedItem) => {
524
+ if (item) {
525
+ setFeedItems((prev) => [item, ...prev]);
526
+ setScreenState("loaded");
527
+ }
528
+ })
529
+ .catch((e) => { console.warn('[CometChatNotificationFeed]', e?.message || e); });
530
+ }, [scrollToItemId]);
531
+
532
+ // ─── Render: Header ──────────────────────────────────────────
533
+ const renderHeader = () => {
534
+ if (!showHeader) return null;
535
+ if (HeaderView) return <HeaderView />;
536
+
537
+ return (
538
+ <Header
539
+ title={title ?? t("NOTIFICATIONS")}
540
+ hideBackButton={!showBackButton}
541
+ onBack={onBackPress}
542
+ containerStyle={mergedStyles.headerContainerStyle}
543
+ titleStyle={mergedStyles.titleStyle}
544
+ backButtonIconStyle={mergedStyles.backButtonIconStyle}
545
+ backButtonIconContainerStyle={{ paddingRight: theme.spacing.spacing.s2 }}
546
+ hideSearch={true}
547
+ />
548
+ );
549
+ };
550
+
551
+ // ─── Render: Filter Chips ────────────────────────────────────
552
+ const renderFilterChips = () => {
553
+ if (!showFilterChips) return null;
554
+
555
+ const allChips = [
556
+ { id: ALL_CATEGORY_ID, label: "All", filterKey: null as string | null },
557
+ ...categories.map((cat: any, index: number) => ({
558
+ id: `chip_${index}_${cat.label ?? cat.id}`,
559
+ label: cat?.label || "",
560
+ filterKey: cat?.label || cat?.id,
561
+ })),
562
+ ];
563
+ return (
564
+ <View>
565
+ <ScrollView
566
+ horizontal
567
+ showsHorizontalScrollIndicator={false}
568
+ contentContainerStyle={{
569
+ alignItems: "center",
570
+ paddingHorizontal: theme.spacing.padding.p4,
571
+ paddingVertical: theme.spacing.padding.p2,
572
+ gap: theme.spacing.spacing.s2,
573
+ }}
574
+ >
575
+ {allChips.map((chip) => {
576
+ const isActive =
577
+ (chip.filterKey === null && activeCategory === null) ||
578
+ chip.filterKey === activeCategory;
579
+ const chipStyle = isActive
580
+ ? mergedStyles.chipActiveStyle
581
+ : mergedStyles.chipInactiveStyle;
582
+ // Property 4: "All" uses totalUnreadCount (from API), categories use persistent Map
583
+ const unreadCount =
584
+ chip.filterKey === null
585
+ ? totalUnreadCount
586
+ : (categoryUnreadCounts.get(chip.filterKey) ?? 0);
587
+
588
+ return (
589
+ <Pressable
590
+ key={chip.id}
591
+ onPress={() => handleCategorySwitch(chip.filterKey)}
592
+ style={chipStyle?.containerStyle}
593
+ >
594
+ <Text style={chipStyle?.textStyle}>{chip.label}</Text>
595
+ {!isActive && unreadCount > 0 && (
596
+ <View style={mergedStyles.chipInactiveBadgeStyle?.containerStyle}>
597
+ <Text style={mergedStyles.chipInactiveBadgeStyle?.textStyle}>
598
+ {unreadCount > 999 ? "999+" : unreadCount}
599
+ </Text>
600
+ </View>
601
+ )}
602
+ {isActive && unreadCount > 0 && (
603
+ <View style={mergedStyles.chipBadgeStyle?.containerStyle}>
604
+ <Text style={mergedStyles.chipBadgeStyle?.textStyle}>
605
+ {unreadCount > 999 ? "999+" : unreadCount}
606
+ </Text>
607
+ </View>
608
+ )}
609
+ </Pressable>
610
+ );
611
+ })}
612
+ </ScrollView>
613
+ </View>
614
+ );
615
+ };
616
+
617
+ // ─── Render: Feed Item ───────────────────────────────────────
618
+ const renderFeedItem = useCallback(
619
+ ({ item }: { item: NotificationFeedItem }) => {
620
+ const isUnread = item.readAt == null;
621
+ const cardJson = JSON.stringify(item.content);
622
+ const categoryLabel = item.category ?? "";
623
+ const sentAtSeconds = item.sentAt;
624
+ const relativeTime = sentAtSeconds
625
+ ? formatDate(sentAtSeconds * 1000, "conversationDate")
626
+ : "";
627
+
628
+ return (
629
+ <View>
630
+ {/* Per-item header: Category + Timestamp */}
631
+ <View style={mergedStyles.itemHeaderStyle?.containerStyle}>
632
+ <Text style={mergedStyles.itemHeaderStyle?.categoryTextStyle}>{categoryLabel}</Text>
633
+ <Text style={mergedStyles.itemHeaderStyle?.timestampTextStyle}>{relativeTime}</Text>
634
+ </View>
635
+ <Pressable onPress={() => handleItemClick(item)}>
636
+ <View
637
+ style={[
638
+ mergedStyles.cardContainerStyle,
639
+ {
640
+ borderColor: mergedStyles.cardBorderColor,
641
+ borderWidth: mergedStyles.cardBorderWidth,
642
+ },
643
+ ]}
644
+ >
645
+ {isUnread && (
646
+ <View
647
+ style={[
648
+ mergedStyles.unreadIndicatorStyle,
649
+ { backgroundColor: mergedStyles.unreadIndicatorColor },
650
+ ]}
651
+ />
652
+ )}
653
+ <CometChatCardView
654
+ cardJson={cardJson}
655
+ themeMode={cardThemeMode}
656
+ themeOverride={cardThemeOverride}
657
+ onAction={(actionEvent: any) => {
658
+ handleActionClick(item, {
659
+ type: actionEvent?.type ?? actionEvent?.action ?? "unknown",
660
+ params: actionEvent?.params ?? actionEvent?.data ?? {},
661
+ elementId: actionEvent?.elementId ?? actionEvent?.id ?? "",
662
+ });
663
+ }}
664
+ />
665
+ </View>
666
+ </Pressable>
667
+ </View>
668
+ );
669
+ },
670
+ [
671
+ mergedStyles,
672
+ cardThemeMode,
673
+ cardThemeOverride,
674
+ handleItemClick,
675
+ handleActionClick,
676
+ ]
677
+ );
678
+
679
+ // ─── Render: Footer (loading more) ──────────────────────────
680
+
681
+ const renderFooter = () => {
682
+ if (loadMoreError) {
683
+ return (
684
+ <View style={{ paddingVertical: theme.spacing.padding.p4, alignItems: "center" }}>
685
+ <ActivityIndicator size="small" color={theme.color.error} />
686
+ <Text style={{ color: theme.color.textSecondary, ...theme.typography.body.regular, marginTop: theme.spacing.margin.m2 }}>
687
+ {t("NOTIFICATION_FEED_LOAD_MORE_ERROR")}
688
+ </Text>
689
+ <Pressable onPress={() => { setLoadMoreError(false); fetchNextPage(); }}>
690
+ <Text style={{ color: theme.color.primary, ...theme.typography.body.medium, marginTop: theme.spacing.margin.m1 }}>
691
+ {t("NOTIFICATION_FEED_TAP_TO_RETRY")}
692
+ </Text>
693
+ </Pressable>
694
+ </View>
695
+ );
696
+ }
697
+ if (!isLoadingMore) return null;
698
+ return (
699
+ <View style={{ paddingVertical: theme.spacing.padding.p4, alignItems: "center" }}>
700
+ <ActivityIndicator size="small" color={theme.color.primary} />
701
+ <Text style={{ color: theme.color.textSecondary, ...theme.typography.body.regular, marginTop: theme.spacing.margin.m2 }}>
702
+ {t("NOTIFICATION_FEED_LOADING_MORE")}
703
+ </Text>
704
+ </View>
705
+ );
706
+ };
707
+
708
+ // ─── Render: State Views ─────────────────────────────────────
709
+ if (screenState === "loading") {
710
+ if (LoadingView) return <LoadingView />;
711
+ return (
712
+ <View style={mergedStyles.containerStyle}>
713
+ {renderHeader()}
714
+ <Skeleton />
715
+ </View>
716
+ );
717
+ }
718
+
719
+ if (screenState === "empty") {
720
+ if (EmptyView) {
721
+ return (
722
+ <View style={mergedStyles.containerStyle}>
723
+ {renderHeader()}
724
+ {renderFilterChips()}
725
+ <EmptyView />
726
+ </View>
727
+ );
728
+ }
729
+ return (
730
+ <View style={mergedStyles.containerStyle}>
731
+ {renderHeader()}
732
+ {renderFilterChips()}
733
+ <ErrorEmptyView
734
+ Icon={<NotificationEmptyIcon width={100} height={97} color={theme.color.iconSecondary} />}
735
+ title={t("NOTIFICATION_FEED_EMPTY_TITLE")}
736
+ subTitle={t("NOTIFICATION_FEED_EMPTY_SUBTITLE")}
737
+ containerStyle={mergedStyles.emptyStateStyle?.containerStyle}
738
+ titleStyle={mergedStyles.emptyStateStyle?.titleStyle}
739
+ subTitleStyle={mergedStyles.emptyStateStyle?.subTitleStyle}
740
+ />
741
+ </View>
742
+ );
743
+ }
744
+
745
+ if (screenState === "error") {
746
+ if (ErrorView) {
747
+ return (
748
+ <View style={mergedStyles.containerStyle}>
749
+ {renderHeader()}
750
+ <ErrorView />
751
+ </View>
752
+ );
753
+ }
754
+ return (
755
+ <View style={mergedStyles.containerStyle}>
756
+ {renderHeader()}
757
+ <ErrorEmptyView
758
+ title={t("NOTIFICATION_FEED_ERROR_TITLE")}
759
+ subTitle={t("NOTIFICATION_FEED_ERROR_SUBTITLE")}
760
+ containerStyle={mergedStyles.errorStateStyle?.containerStyle}
761
+ titleStyle={mergedStyles.errorStateStyle?.titleStyle}
762
+ subTitleStyle={mergedStyles.errorStateStyle?.subTitleStyle}
763
+ RetryView={
764
+ <Pressable onPress={fetchInitialItems} style={{ marginTop: theme.spacing.margin.m4 }}>
765
+ <Text style={{ color: theme.color.primary, ...theme.typography.button.medium }}>
766
+ {t("RETRY")}
767
+ </Text>
768
+ </Pressable>
769
+ }
770
+ />
771
+ </View>
772
+ );
773
+ }
774
+
775
+ // ─── Render: Loaded State ────────────────────────────────────
776
+ return (
777
+ <View style={mergedStyles.containerStyle}>
778
+ {renderHeader()}
779
+ {renderFilterChips()}
780
+ {isFetchingItems ? (
781
+ <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
782
+ <ActivityIndicator size="large" color={theme.color.primary} />
783
+ </View>
784
+ ) : (
785
+ <SectionList
786
+ ref={sectionListRef}
787
+ sections={sections}
788
+ keyExtractor={(item: any) => item.id}
789
+ renderItem={renderFeedItem}
790
+ onScroll={({ nativeEvent }) => {
791
+ const { layoutMeasurement, contentOffset, contentSize } = nativeEvent;
792
+ const paddingToBottom = 50;
793
+ const isCloseToBottom =
794
+ layoutMeasurement.height + contentOffset.y >= contentSize.height - paddingToBottom;
795
+ if (isCloseToBottom && contentOffset.y > 0) {
796
+ fetchNextPage();
797
+ }
798
+ }}
799
+ scrollEventThrottle={400}
800
+ ListFooterComponent={renderFooter}
801
+ onViewableItemsChanged={onViewableItemsChanged}
802
+ viewabilityConfig={viewabilityConfig}
803
+ refreshControl={
804
+ <RefreshControl refreshing={isRefreshing} onRefresh={handleRefresh} />
805
+ }
806
+ showsVerticalScrollIndicator={false}
807
+ />
808
+ )}
809
+ </View>
810
+ );
811
+ };