-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathPredictFeedView.tsx
More file actions
418 lines (384 loc) · 12.5 KB
/
Copy pathPredictFeedView.tsx
File metadata and controls
418 lines (384 loc) · 12.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
import React, { useCallback, useEffect, useMemo, useRef } from 'react';
import {
useNavigation,
useRoute,
RouteProp,
useFocusEffect,
} from '@react-navigation/native';
import { FlashList } from '@shopify/flash-list';
import { useTailwind } from '@metamask/design-system-twrnc-preset';
import {
Box,
HeaderStandard,
IconName,
Text,
TextColor,
TextVariant,
} from '@metamask/design-system-react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { strings } from '../../../../../../locales/i18n';
import Routes from '../../../../../constants/navigation/Routes';
import Engine from '../../../../../core/Engine';
import {
TabItem,
TabsBar,
} from '../../../../../component-library/components-temp/Tabs';
import { PredictEventValues } from '../../constants/eventNames';
import PredictMarket from '../../components/PredictMarket';
import PredictMarketSkeleton from '../../components/PredictMarketSkeleton';
import PredictOffline from '../../components/PredictOffline';
import PredictChipList from '../../components/PredictChipList';
import PredictSearchOverlay from '../../components/PredictSearchOverlay';
import { usePredictFeedConfig } from '../../hooks/usePredictFeedConfig';
import { usePredictMarketList } from '../../hooks/usePredictMarketList';
import { usePredictSearch } from '../../hooks/usePredictSearch';
import {
PredictFeedViewSelectorsIDs,
getPredictFeedViewSelector,
PredictMarketListSelectorsIDs,
PredictSearchSelectorsIDs,
} from '../../Predict.testIds';
import type { PredictNavigationParamList } from '../../types/navigation';
import type { PredictMarket as PredictMarketType } from '../../types';
const INITIAL_SKELETON_COUNT = 4;
/**
* Generic, config-driven Predict feed screen.
*
* Powers every configured feed (Sports / Politics / Crypto / Live / Trending /
* Popular Today) from one component. Presentational: it consumes
* `usePredictFeedConfig` for the render-ready config + tab/filter selection
* state and `usePredictMarketList` for the active tab/filter's market data —
* it owns no hydration/dedup/fallback logic itself.
*/
const PredictFeedView: React.FC = () => {
const tw = useTailwind();
const navigation = useNavigation();
const route =
useRoute<RouteProp<PredictNavigationParamList, 'PredictFeed'>>();
const { feedId, initialTabId, initialFilterId, entryPoint } =
route.params ?? {};
const transactionActiveAbTests = route.params?.transactionActiveAbTests;
const {
status,
titleKey,
header,
tabs,
showTabBar,
showFilterBar,
activeTabId,
setActiveTabId,
filters,
dynamicFilters,
activeFilterId,
setActiveFilterId,
activeFilter,
} = usePredictFeedConfig(feedId, { initialTabId, initialFilterId });
const isReady = status === 'ready';
// True once the active filter state is stable enough to log.
// - No initialFilterId → settled immediately.
// - Otherwise block while dynamic filters are still loading.
// - Once loading is done, check whether the requested filter actually
// appeared in the resolved list:
// • If it did appear, wait for activeFilterId to catch up (usePredictFeedConfig
// applies the pending filter one render after the fetch settles).
// • If it never appeared (chip absent from the API response), fire with
// the current fallback filter rather than blocking forever.
const isFilterSettled =
!initialFilterId ||
(dynamicFilters.status !== 'loading' &&
(!filters.some((f) => f.id === initialFilterId) ||
activeFilterId === initialFilterId));
const {
isSearchVisible,
searchQuery,
setSearchQuery,
showSearch,
clearSearchAndClose,
} = usePredictSearch();
const {
markets,
isLoading,
isFetchingNextPage,
error,
hasNextPage,
refetch,
fetchNextPage,
} = usePredictMarketList(activeFilter?.params ?? {}, { enabled: isReady });
// Keep the latest tab/filter selection in a ref so the focus effect can read
// it without re-firing "feed viewed" every time the tab/filter changes (those
// have their own dedicated events).
const feedSelectionRef = useRef({ activeTabId, activeFilterId });
useEffect(() => {
feedSelectionRef.current = { activeTabId, activeFilterId };
}, [activeTabId, activeFilterId]);
// Tracks whether "feed viewed" has already fired in the current focus session.
// Prevents double-fires if isReady oscillates (e.g. config re-resolves) while
// the screen is focused, since useFocusEffect re-runs on each dep change.
const feedViewedFiredRef = useRef(false);
// Reset the guard on each new screen focus so return visits can re-fire.
useFocusEffect(
useCallback(() => {
feedViewedFiredRef.current = false;
}, []),
);
// Fire once per focus when the feed config is ready and the filter selection
// has settled. `isFilterSettled` delays the fire when `initialFilterId`
// targets a dynamic chip that hasn't resolved yet; `feedSelectionRef` carries
// the latest tab/filter at fire-time so they don't need to be effect deps.
useFocusEffect(
useCallback(() => {
if (
!isReady ||
!feedId ||
!isFilterSettled ||
feedViewedFiredRef.current
) {
return;
}
feedViewedFiredRef.current = true;
Engine.context.PredictController.trackFeedViewed({
feedId,
tabId: feedSelectionRef.current.activeTabId,
filterId: feedSelectionRef.current.activeFilterId,
trackingMode: 'focus',
entryPoint,
});
}, [isReady, feedId, isFilterSettled, entryPoint]),
);
const handleBack = useCallback(() => {
if (navigation.canGoBack()) {
navigation.goBack();
return;
}
navigation.navigate(Routes.PREDICT.ROOT);
}, [navigation]);
const handleShowSearch = useCallback(() => {
Engine.context.PredictController.trackSearchInteracted({
interactionType: PredictEventValues.SEARCH_INTERACTION.OPENED,
predictFeedTab: activeTabId,
entryPoint,
});
showSearch();
}, [activeTabId, entryPoint, showSearch]);
// Unknown feed -> bounce back so the user never lands on an empty shell.
useEffect(() => {
if (status === 'not-found') {
handleBack();
}
}, [status, handleBack]);
const tabItems = useMemo<TabItem[]>(
() =>
tabs.map((tab) => ({
key: tab.id,
label: strings(tab.titleKey),
content: null,
})),
[tabs],
);
const activeIndex = useMemo(() => {
const index = tabs.findIndex((tab) => tab.id === activeTabId);
return index === -1 ? 0 : index;
}, [tabs, activeTabId]);
const handleTabPress = useCallback(
(index: number) => {
const tab = tabs[index];
if (tab && tab.id !== activeTabId) {
setActiveTabId(tab.id);
if (feedId) {
Engine.context.PredictController.trackFeedTabChanged({
feedId,
tabId: tab.id,
entryPoint,
});
}
}
},
[tabs, setActiveTabId, feedId, activeTabId, entryPoint],
);
const handleFilterSelect = useCallback(
(filterId: string) => {
if (filterId === activeFilterId) {
return;
}
setActiveFilterId(filterId);
if (feedId) {
const isDynamicFilter =
filters.find((filter) => filter.id === filterId)?.isDynamic ?? false;
Engine.context.PredictController.trackFeedFilterChanged({
feedId,
tabId: activeTabId,
filterId,
isDynamicFilter,
entryPoint,
});
}
},
[
setActiveFilterId,
filters,
feedId,
activeTabId,
activeFilterId,
entryPoint,
],
);
const chips = useMemo(
() =>
filters.map((filter) => ({
key: filter.id,
label: filter.titleKey
? strings(filter.titleKey)
: (filter.label ?? ''),
})),
[filters],
);
const handleEndReached = useCallback(() => {
if (hasNextPage && !isFetchingNextPage) {
fetchNextPage();
}
}, [hasNextPage, isFetchingNextPage, fetchNextPage]);
const renderItem = useCallback(
({ item, index }: { item: PredictMarketType; index: number }) => (
<PredictMarket
market={item}
entryPoint={entryPoint}
testID={getPredictFeedViewSelector.marketCard(index + 1)}
predictFeedTab={activeTabId}
transactionActiveAbTests={transactionActiveAbTests}
/>
),
[entryPoint, activeTabId, transactionActiveAbTests],
);
const keyExtractor = useCallback((item: PredictMarketType) => item.id, []);
const renderFooter = useCallback(() => {
if (!isFetchingNextPage) {
return null;
}
return (
<Box twClassName="py-2">
<PredictMarketSkeleton
testID={getPredictFeedViewSelector.skeletonFooter(1)}
/>
</Box>
);
}, [isFetchingNextPage]);
const renderContent = () => {
if (isLoading) {
return (
<Box twClassName="flex-1 px-4">
{Array.from({ length: INITIAL_SKELETON_COUNT }).map((_, index) => (
<PredictMarketSkeleton
key={`skeleton-${index}`}
testID={getPredictFeedViewSelector.skeleton(index + 1)}
/>
))}
</Box>
);
}
// Only take over the whole screen with the error/retry state when nothing
// has loaded yet. A failed *next-page* fetch must not discard the markets
// (and scroll position) already on screen, so when markets exist we fall
// through to the list and let pagination retry on the next scroll.
if (error && markets.length === 0) {
return (
<Box
twClassName="flex-1"
testID={PredictFeedViewSelectorsIDs.ERROR_STATE}
>
<PredictOffline onRetry={refetch} />
</Box>
);
}
if (markets.length === 0) {
return (
<Box
twClassName="flex-1 justify-center items-center p-8"
testID={PredictFeedViewSelectorsIDs.EMPTY_STATE}
>
<Text
variant={TextVariant.BodyMd}
color={TextColor.PrimaryAlternative}
>
{strings('predict.search_empty_state', {
category: titleKey ? strings(titleKey) : '',
})}
</Text>
</Box>
);
}
return (
// flex-1 wrapper so FlashList gets a bounded height in this column layout;
// without it the list can collapse to zero height and break scroll/pagination.
<Box twClassName="flex-1">
<FlashList
testID={PredictFeedViewSelectorsIDs.MARKET_LIST}
data={markets}
renderItem={renderItem}
keyExtractor={keyExtractor}
onEndReached={handleEndReached}
onEndReachedThreshold={0.7}
ListFooterComponent={renderFooter}
contentContainerStyle={tw.style('px-4 pb-4')}
showsVerticalScrollIndicator={false}
/>
</Box>
);
};
// Unknown feed: render nothing while the effect navigates away.
if (!isReady) {
return null;
}
return (
<SafeAreaView
edges={['bottom', 'left', 'right']}
style={tw.style('flex-1 bg-default')}
testID={PredictFeedViewSelectorsIDs.CONTAINER}
>
<HeaderStandard
includesTopInset
title={titleKey ? strings(titleKey) : undefined}
onBack={header?.showBackButton ? handleBack : undefined}
backButtonProps={{ testID: PredictMarketListSelectorsIDs.BACK_BUTTON }}
endButtonIconProps={
header?.showSearchButton
? [
{
iconName: IconName.Search,
onPress: handleShowSearch,
testID: PredictSearchSelectorsIDs.SEARCH_BUTTON,
},
]
: undefined
}
testID={PredictFeedViewSelectorsIDs.HEADER}
/>
<Box twClassName="flex-1">
{showTabBar && (
<TabsBar
tabs={tabItems}
activeIndex={activeIndex}
onTabPress={handleTabPress}
testID={PredictFeedViewSelectorsIDs.TABS}
/>
)}
{showFilterBar && (
<PredictChipList
chips={chips}
activeChipKey={activeFilterId ?? ''}
onChipSelect={handleFilterSelect}
testID={PredictFeedViewSelectorsIDs.FILTERS}
/>
)}
{renderContent()}
</Box>
<PredictSearchOverlay
isVisible={isSearchVisible}
searchQuery={searchQuery}
onSearchChange={setSearchQuery}
onClose={clearSearchAndClose}
transactionActiveAbTests={transactionActiveAbTests}
/>
</SafeAreaView>
);
};
export default PredictFeedView;