-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathPerpsHomeView.tsx
More file actions
502 lines (452 loc) · 17.1 KB
/
PerpsHomeView.tsx
File metadata and controls
502 lines (452 loc) · 17.1 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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
import React, {
useCallback,
useState,
useRef,
useEffect,
useMemo,
} from 'react';
import { View, ScrollView, Modal } from 'react-native';
import {
SafeAreaView,
useSafeAreaInsets,
} from 'react-native-safe-area-context';
import {
useNavigation,
useRoute,
type NavigationProp,
type RouteProp,
} from '@react-navigation/native';
import {
Button,
ButtonVariant,
ButtonSize,
} from '@metamask/design-system-react-native';
import { useStyles } from '../../../../../component-library/hooks';
import { TextColor } from '../../../../../component-library/components/Texts/Text';
import { strings } from '../../../../../../locales/i18n';
import { formatPnl, formatPercentage } from '../../utils/formatUtils';
import Routes from '../../../../../constants/navigation/Routes';
import {
usePerpsHomeData,
usePerpsNavigation,
usePerpsMeasurement,
} from '../../hooks';
import { usePerpsHomeActions } from '../../hooks/usePerpsHomeActions';
import PerpsBottomSheetTooltip from '../../components/PerpsBottomSheetTooltip';
import { BigNumber } from 'bignumber.js';
import { usePerpsLivePositions, usePerpsLiveAccount } from '../../hooks/stream';
import {
HOME_SCREEN_CONFIG,
LEARN_MORE_CONFIG,
SUPPORT_CONFIG,
} from '../../constants/perpsConfig';
import PerpsMarketBalanceActions from '../../components/PerpsMarketBalanceActions';
import PerpsCard from '../../components/PerpsCard';
import PerpsWatchlistMarkets from '../../components/PerpsWatchlistMarkets/PerpsWatchlistMarkets';
import PerpsMarketTypeSection from '../../components/PerpsMarketTypeSection';
import PerpsRecentActivityList from '../../components/PerpsRecentActivityList/PerpsRecentActivityList';
import PerpsHomeSection from '../../components/PerpsHomeSection';
import PerpsRowSkeleton from '../../components/PerpsRowSkeleton';
import PerpsHomeHeader from '../../components/PerpsHomeHeader';
import type { PerpsNavigationParamList } from '../../types/navigation';
import { useMetrics, MetaMetricsEvents } from '../../../../hooks/useMetrics';
import styleSheet from './PerpsHomeView.styles';
import { TraceName } from '../../../../../util/trace';
import {
PerpsEventProperties,
PerpsEventValues,
} from '../../constants/eventNames';
import { usePerpsEventTracking } from '../../hooks/usePerpsEventTracking';
import { PerpsHomeViewSelectorsIDs } from '../../../../../../e2e/selectors/Perps/Perps.selectors';
import PerpsCloseAllPositionsView from '../PerpsCloseAllPositionsView/PerpsCloseAllPositionsView';
import PerpsCancelAllOrdersView from '../PerpsCancelAllOrdersView/PerpsCancelAllOrdersView';
import { BottomSheetRef } from '../../../../../component-library/components/BottomSheets/BottomSheet';
import PerpsNavigationCard, {
NavigationItem,
} from '../../components/PerpsNavigationCard/PerpsNavigationCard';
const PerpsHomeView = () => {
const { styles } = useStyles(styleSheet, {});
const insets = useSafeAreaInsets();
const navigation = useNavigation<NavigationProp<PerpsNavigationParamList>>();
const route =
useRoute<RouteProp<PerpsNavigationParamList, 'PerpsMarketListView'>>();
const { trackEvent, createEventBuilder } = useMetrics();
// Use centralized navigation hook
const perpsNavigation = usePerpsNavigation();
// Bottom sheet state and refs
const [showCloseAllSheet, setShowCloseAllSheet] = useState(false);
const [showCancelAllSheet, setShowCancelAllSheet] = useState(false);
const closeAllSheetRef = useRef<BottomSheetRef>(null);
const cancelAllSheetRef = useRef<BottomSheetRef>(null);
// Use hook for eligibility checks and action handlers
// Pass button location for tracking deposit entry point
const {
handleAddFunds,
handleWithdraw,
isEligibilityModalVisible,
closeEligibilityModal,
} = usePerpsHomeActions({
buttonLocation: PerpsEventValues.BUTTON_LOCATION.PERPS_HOME,
});
// Get balance state directly from Redux
const { account: perpsAccount } = usePerpsLiveAccount({ throttleMs: 1000 });
const totalBalance = perpsAccount?.totalBalance || '0';
const isBalanceEmpty = BigNumber(totalBalance).isZero();
// Calculate P&L for positions subtitle
const unrealizedPnl = perpsAccount?.unrealizedPnl || '0';
const roe = parseFloat(perpsAccount?.returnOnEquity || '0');
// Fetch all home screen data
const {
positions,
orders,
watchlistMarkets,
perpsMarkets, // Crypto markets (renamed from trendingMarkets)
stocksAndCommoditiesMarkets,
forexMarkets,
recentActivity,
sortBy,
isLoading,
} = usePerpsHomeData({});
// Calculate positions subtitle with P&L
const hasPositions = positions.length > 0;
const { positionsSubtitle, positionsSubtitleColor, positionsSubtitleSuffix } =
useMemo(() => {
const pnlNum = parseFloat(unrealizedPnl);
const isPnlZero = BigNumber(unrealizedPnl).isZero();
// Only show subtitle when there are positions and P&L is non-zero
if (!hasPositions || isPnlZero) {
return {
positionsSubtitle: undefined,
positionsSubtitleColor: undefined,
positionsSubtitleSuffix: undefined,
};
}
const color =
pnlNum > 0
? TextColor.Success
: pnlNum < 0
? TextColor.Error
: TextColor.Alternative;
// Format: "-$18.47 (2.1%)" colored + "Unrealized PnL" in default color
const subtitle = `${formatPnl(pnlNum)} (${formatPercentage(roe, 1)})`;
const suffix = strings('perps.unrealized_pnl');
return {
positionsSubtitle: subtitle,
positionsSubtitleColor: color,
positionsSubtitleSuffix: suffix,
};
}, [hasPositions, unrealizedPnl, roe]);
// Determine if any data is loading for initial load tracking
// Orders and activity load via WebSocket instantly, only track positions and markets
const isAnyLoading = isLoading.positions || isLoading.markets;
// Performance tracking: Measure screen load time until data is displayed
usePerpsMeasurement({
traceName: TraceName.PerpsMarketListView, // Keep same trace name for consistency
conditions: [!isAnyLoading],
});
// Track home screen viewed event
const source =
route.params?.source || PerpsEventValues.SOURCE.MAIN_ACTION_BUTTON;
// Get perp balance status for tracking
const livePositions = usePerpsLivePositions({ throttleMs: 5000 });
const hasPerpBalance =
livePositions.positions.length > 0 ||
(!!perpsAccount?.totalBalance && parseFloat(perpsAccount.totalBalance) > 0);
// Extract button_clicked and button_location from route params
const buttonClicked = route.params?.button_clicked;
const buttonLocation = route.params?.button_location;
usePerpsEventTracking({
eventName: MetaMetricsEvents.PERPS_SCREEN_VIEWED,
conditions: [!isAnyLoading],
properties: {
[PerpsEventProperties.SCREEN_TYPE]:
PerpsEventValues.SCREEN_TYPE.PERPS_HOME,
[PerpsEventProperties.SOURCE]: source,
[PerpsEventProperties.HAS_PERP_BALANCE]: hasPerpBalance,
...(buttonClicked && {
[PerpsEventProperties.BUTTON_CLICKED]: buttonClicked,
}),
...(buttonLocation && {
[PerpsEventProperties.BUTTON_LOCATION]: buttonLocation,
}),
},
});
const handleSearchToggle = useCallback(() => {
// Track button click
trackEvent(
createEventBuilder(MetaMetricsEvents.PERPS_UI_INTERACTION)
.addProperties({
[PerpsEventProperties.INTERACTION_TYPE]:
PerpsEventValues.INTERACTION_TYPE.BUTTON_CLICKED,
[PerpsEventProperties.BUTTON_CLICKED]:
PerpsEventValues.BUTTON_CLICKED.MAGNIFYING_GLASS,
[PerpsEventProperties.BUTTON_LOCATION]:
PerpsEventValues.BUTTON_LOCATION.PERPS_HOME,
})
.build(),
);
// Navigate to MarketListView with search enabled
perpsNavigation.navigateToMarketList({
defaultSearchVisible: true,
source: PerpsEventValues.SOURCE.HOMESCREEN_TAB,
fromHome: true,
button_clicked: PerpsEventValues.BUTTON_CLICKED.MAGNIFYING_GLASS,
button_location: PerpsEventValues.BUTTON_LOCATION.PERPS_HOME,
});
}, [perpsNavigation, trackEvent, createEventBuilder]);
const navigtateToTutorial = useCallback(() => {
// Track tutorial button click
trackEvent(
createEventBuilder(MetaMetricsEvents.PERPS_UI_INTERACTION)
.addProperties({
[PerpsEventProperties.INTERACTION_TYPE]:
PerpsEventValues.INTERACTION_TYPE.BUTTON_CLICKED,
[PerpsEventProperties.BUTTON_CLICKED]:
PerpsEventValues.BUTTON_CLICKED.TUTORIAL,
[PerpsEventProperties.BUTTON_LOCATION]:
PerpsEventValues.BUTTON_LOCATION.PERPS_HOME,
})
.build(),
);
navigation.navigate(Routes.PERPS.TUTORIAL, {
source: PerpsEventValues.SOURCE.HOMESCREEN_TAB,
});
}, [navigation, trackEvent, createEventBuilder]);
const navigateToContactSupport = useCallback(() => {
navigation.navigate(Routes.WEBVIEW.MAIN, {
screen: Routes.WEBVIEW.SIMPLE,
params: {
url: SUPPORT_CONFIG.URL,
title: strings(SUPPORT_CONFIG.TITLE_KEY),
},
});
trackEvent(
createEventBuilder(MetaMetricsEvents.NAVIGATION_TAPS_GET_HELP).build(),
);
}, [createEventBuilder, navigation, trackEvent]);
const navigationItems: NavigationItem[] = useMemo(() => {
const items: NavigationItem[] = [
{
label: strings(SUPPORT_CONFIG.TITLE_KEY),
onPress: () => navigateToContactSupport(),
testID: PerpsHomeViewSelectorsIDs.SUPPORT_BUTTON,
},
];
// Avoid duplicate "Learn more" button (shown in empty state card)
if (!isBalanceEmpty) {
items.push({
label: strings(LEARN_MORE_CONFIG.TITLE_KEY),
onPress: () => navigtateToTutorial(),
testID: PerpsHomeViewSelectorsIDs.LEARN_MORE_BUTTON,
});
}
return items;
}, [navigateToContactSupport, navigtateToTutorial, isBalanceEmpty]);
// Bottom sheet handlers - open sheets directly
const handleCloseAllPress = useCallback(() => {
setShowCloseAllSheet(true);
}, []);
const handleCancelAllPress = useCallback(() => {
setShowCancelAllSheet(true);
}, []);
// Open bottom sheets when state changes
useEffect(() => {
if (showCloseAllSheet) {
closeAllSheetRef.current?.onOpenBottomSheet();
}
}, [showCloseAllSheet]);
useEffect(() => {
if (showCancelAllSheet) {
cancelAllSheetRef.current?.onOpenBottomSheet();
}
}, [showCancelAllSheet]);
// Handle sheet close callbacks
const handleCloseAllSheetClose = useCallback(() => {
setShowCloseAllSheet(false);
}, []);
const handleCancelAllSheetClose = useCallback(() => {
setShowCancelAllSheet(false);
}, []);
// Calculate actual footer dimensions
// Footer: paddingTop(16) + button(48) + paddingBottom(16 + insets.bottom)
const footerHeight = 80 + insets.bottom;
const bottomSpacerStyle = useMemo(
() => ({
// When footer is visible, add space for it. Otherwise minimal spacing for tab bar.
height: isBalanceEmpty ? 16 : footerHeight + 16,
}),
[isBalanceEmpty, footerHeight],
);
// Add safe area inset to footer for Android navigation bar
const fixedFooterStyle = useMemo(
() => [styles.fixedFooter, { paddingBottom: 16 + insets.bottom }],
[styles.fixedFooter, insets.bottom],
);
// Always navigate to wallet home to avoid navigation loops (tutorial/onboarding flow)
const handleBackPress = perpsNavigation.navigateToWallet;
return (
<SafeAreaView style={styles.container}>
{/* Header - Using extracted component */}
<PerpsHomeHeader
isSearchVisible={false}
onBack={handleBackPress}
onSearchToggle={handleSearchToggle}
testID="perps-home"
/>
{/* Main Content - ScrollView with all carousels */}
<ScrollView
style={styles.scrollView}
contentContainerStyle={styles.scrollViewContent}
showsVerticalScrollIndicator={false}
>
{/* Balance Actions Component */}
<PerpsMarketBalanceActions
showActionButtons={HOME_SCREEN_CONFIG.SHOW_HEADER_ACTION_BUTTONS}
/>
{/* Positions Section */}
<PerpsHomeSection
title={strings('perps.home.positions')}
subtitle={positionsSubtitle}
subtitleColor={positionsSubtitleColor}
subtitleSuffix={positionsSubtitleSuffix}
subtitleTestID={PerpsHomeViewSelectorsIDs.POSITIONS_PNL_VALUE}
isLoading={isLoading.positions}
isEmpty={positions.length === 0}
showWhenEmpty={false}
onActionPress={handleCloseAllPress}
renderSkeleton={() => <PerpsRowSkeleton count={2} />}
>
<View style={styles.positionsOrdersContainer}>
{positions.map((position, index) => (
<PerpsCard
key={`${position.coin}-${index}`}
position={position}
source={PerpsEventValues.SOURCE.HOMESCREEN_TAB}
/>
))}
</View>
</PerpsHomeSection>
{/* Orders Section */}
<PerpsHomeSection
title={strings('perps.home.orders')}
isLoading={isLoading.orders}
isEmpty={orders.length === 0}
showWhenEmpty={false}
onActionPress={handleCancelAllPress}
renderSkeleton={() => <PerpsRowSkeleton count={2} />}
>
<View style={styles.positionsOrdersContainer}>
{orders.map((order) => (
<PerpsCard
key={order.orderId}
order={order}
source={PerpsEventValues.SOURCE.HOMESCREEN_TAB}
/>
))}
</View>
</PerpsHomeSection>
{/* Watchlist Section */}
<PerpsWatchlistMarkets
markets={watchlistMarkets}
isLoading={isLoading.markets}
positions={positions}
orders={orders}
/>
{/* Crypto Markets List */}
<PerpsMarketTypeSection
title={strings('perps.home.crypto')}
markets={perpsMarkets}
marketType="crypto"
sortBy={sortBy}
isLoading={isLoading.markets}
/>
{/* Stocks & Commodities Markets List */}
<PerpsMarketTypeSection
title={strings('perps.home.stocks_and_commodities')}
markets={stocksAndCommoditiesMarkets}
marketType="stocks_and_commodities"
sortBy={sortBy}
isLoading={isLoading.markets}
/>
{/* Forex Markets List */}
<PerpsMarketTypeSection
title={strings('perps.home.forex')}
markets={forexMarkets}
marketType="forex"
isLoading={isLoading.markets}
/>
{/* Recent Activity List */}
<PerpsRecentActivityList
transactions={recentActivity}
isLoading={isLoading.activity}
/>
<View style={styles.sectionContent}>
<PerpsNavigationCard items={navigationItems} />
</View>
{/* Bottom spacing for tab bar */}
<View style={bottomSpacerStyle} />
</ScrollView>
{/* Close All Positions Bottom Sheet */}
{showCloseAllSheet && (
<PerpsCloseAllPositionsView
sheetRef={closeAllSheetRef}
onClose={handleCloseAllSheetClose}
/>
)}
{/* Cancel All Orders Bottom Sheet */}
{showCancelAllSheet && (
<PerpsCancelAllOrdersView
sheetRef={cancelAllSheetRef}
onClose={handleCancelAllSheetClose}
/>
)}
{/* Fixed Footer with Action Buttons - Only show when balance is not empty and no sheets are open */}
{!isBalanceEmpty &&
!showCloseAllSheet &&
!showCancelAllSheet &&
!HOME_SCREEN_CONFIG.SHOW_HEADER_ACTION_BUTTONS && (
<View style={fixedFooterStyle}>
<View style={styles.footerButtonsContainer}>
<View style={styles.footerButton}>
<Button
variant={ButtonVariant.Secondary}
size={ButtonSize.Lg}
onPress={handleWithdraw}
isFullWidth
testID={PerpsHomeViewSelectorsIDs.WITHDRAW_BUTTON}
>
{strings('perps.withdraw')}
</Button>
</View>
<View style={styles.footerButton}>
<Button
variant={ButtonVariant.Primary}
size={ButtonSize.Lg}
onPress={handleAddFunds}
isFullWidth
testID={PerpsHomeViewSelectorsIDs.ADD_FUNDS_BUTTON}
>
{strings('perps.add_funds')}
</Button>
</View>
</View>
</View>
)}
{/* Eligibility Modal */}
{isEligibilityModalVisible && (
// Android Compatibility: Wrap the <Modal> in a plain <View> component to prevent rendering issues and freezing.
<View>
<Modal visible transparent animationType="none" statusBarTranslucent>
<PerpsBottomSheetTooltip
isVisible
onClose={closeEligibilityModal}
contentKey={'geo_block'}
testID={'perps-home-geo-block-tooltip'}
/>
</Modal>
</View>
)}
</SafeAreaView>
);
};
export default PerpsHomeView;