-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
WorkspacesListPage.tsx
executable file
·463 lines (423 loc) · 20.3 KB
/
WorkspacesListPage.tsx
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
import React, {useCallback, useMemo, useState} from 'react';
import {FlatList, View} from 'react-native';
import {withOnyx} from 'react-native-onyx';
import type {OnyxCollection, OnyxEntry} from 'react-native-onyx';
import type {ValueOf} from 'type-fest';
import Button from '@components/Button';
import ConfirmModal from '@components/ConfirmModal';
import FeatureList from '@components/FeatureList';
import type {FeatureListItem} from '@components/FeatureList';
import HeaderWithBackButton from '@components/HeaderWithBackButton';
import * as Expensicons from '@components/Icon/Expensicons';
import * as Illustrations from '@components/Icon/Illustrations';
import LottieAnimations from '@components/LottieAnimations';
import type {MenuItemProps} from '@components/MenuItem';
import OfflineWithFeedback from '@components/OfflineWithFeedback';
import type {OfflineWithFeedbackProps} from '@components/OfflineWithFeedback';
import type {PopoverMenuItem} from '@components/PopoverMenu';
import {PressableWithoutFeedback} from '@components/Pressable';
import ScreenWrapper from '@components/ScreenWrapper';
import ScrollView from '@components/ScrollView';
import Text from '@components/Text';
import useActiveWorkspace from '@hooks/useActiveWorkspace';
import useLocalize from '@hooks/useLocalize';
import useNetwork from '@hooks/useNetwork';
import useResponsiveLayout from '@hooks/useResponsiveLayout';
import useTheme from '@hooks/useTheme';
import useThemeStyles from '@hooks/useThemeStyles';
import interceptAnonymousUser from '@libs/interceptAnonymousUser';
import localeCompare from '@libs/LocaleCompare';
import Navigation from '@libs/Navigation/Navigation';
import * as PolicyUtils from '@libs/PolicyUtils';
import * as ReportUtils from '@libs/ReportUtils';
import type {AvatarSource} from '@libs/UserUtils';
import * as App from '@userActions/App';
import * as Modal from '@userActions/Modal';
import * as Policy from '@userActions/Policy/Policy';
import * as Session from '@userActions/Session';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES from '@src/ROUTES';
import type {Policy as PolicyType, ReimbursementAccount, Report, Session as SessionType} from '@src/types/onyx';
import type * as OnyxCommon from '@src/types/onyx/OnyxCommon';
import {isEmptyObject} from '@src/types/utils/EmptyObject';
import WorkspacesListRow from './WorkspacesListRow';
type WorkspaceItem = Required<Pick<MenuItemProps, 'title' | 'disabled'>> &
Pick<MenuItemProps, 'brickRoadIndicator' | 'iconFill' | 'fallbackIcon'> &
Pick<OfflineWithFeedbackProps, 'errors' | 'pendingAction'> &
Pick<PolicyType, 'role' | 'type' | 'ownerAccountID'> & {
icon: AvatarSource;
action: () => void;
dismissError: () => void;
iconType?: ValueOf<typeof CONST.ICON_TYPE_AVATAR | typeof CONST.ICON_TYPE_ICON>;
policyID?: string;
adminRoom?: string | null;
announceRoom?: string | null;
isJoinRequestPending?: boolean;
};
// eslint-disable-next-line react/no-unused-prop-types
type GetMenuItem = {item: WorkspaceItem; index: number};
type ChatType = {
adminRoom?: string | null;
announceRoom?: string | null;
};
type ChatPolicyType = Record<string, ChatType>;
type WorkspaceListPageOnyxProps = {
/** The list of this user's policies */
policies: OnyxCollection<PolicyType>;
/** Bank account attached to free plan */
reimbursementAccount: OnyxEntry<ReimbursementAccount>;
/** All reports shared with the user (coming from Onyx) */
reports: OnyxCollection<Report>;
/** Session info for the currently logged in user. */
session: OnyxEntry<SessionType>;
};
type WorkspaceListPageProps = WorkspaceListPageOnyxProps;
const workspaceFeatures: FeatureListItem[] = [
{
icon: Illustrations.MoneyReceipts,
translationKey: 'workspace.emptyWorkspace.features.trackAndCollect',
},
{
icon: Illustrations.CreditCardsNew,
translationKey: 'workspace.emptyWorkspace.features.companyCards',
},
{
icon: Illustrations.MoneyWings,
translationKey: 'workspace.emptyWorkspace.features.reimbursements',
},
];
/**
* Dismisses the errors on one item
*/
function dismissWorkspaceError(policyID: string, pendingAction: OnyxCommon.PendingAction | undefined) {
if (pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE) {
Policy.clearDeleteWorkspaceError(policyID);
return;
}
if (pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD) {
Policy.removeWorkspace(policyID);
return;
}
Policy.clearErrors(policyID);
}
const stickyHeaderIndices = [0];
function WorkspacesListPage({policies, reimbursementAccount, reports, session}: WorkspaceListPageProps) {
const theme = useTheme();
const styles = useThemeStyles();
const {translate} = useLocalize();
const {isOffline} = useNetwork();
const {shouldUseNarrowLayout, isMediumScreenWidth} = useResponsiveLayout();
const {activeWorkspaceID, setActiveWorkspaceID} = useActiveWorkspace();
const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
const [policyIDToDelete, setPolicyIDToDelete] = useState<string>();
const [policyNameToDelete, setPolicyNameToDelete] = useState<string>();
const isLessThanMediumScreen = isMediumScreenWidth || shouldUseNarrowLayout;
const confirmDeleteAndHideModal = () => {
if (!policyIDToDelete || !policyNameToDelete) {
return;
}
Policy.deleteWorkspace(policyIDToDelete, policyNameToDelete);
setIsDeleteModalOpen(false);
// If the workspace being deleted is the active workspace, switch to the "All Workspaces" view
if (activeWorkspaceID === policyIDToDelete) {
setActiveWorkspaceID(undefined);
Navigation.navigateWithSwitchPolicyID({policyID: undefined});
}
};
/**
* Gets the menu item for each workspace
*/
const getMenuItem = useCallback(
({item, index}: GetMenuItem) => {
const isAdmin = item.role === CONST.POLICY.ROLE.ADMIN;
const isOwner = item.ownerAccountID === session?.accountID;
// Menu options to navigate to the chat report of #admins and #announce room.
// For navigation, the chat report ids may be unavailable due to the missing chat reports in Onyx.
// In such cases, let us use the available chat report ids from the policy.
const threeDotsMenuItems: PopoverMenuItem[] = [];
if (isOwner) {
threeDotsMenuItems.push({
icon: Expensicons.Trashcan,
text: translate('workspace.common.delete'),
onSelected: () =>
Modal.close(() => {
setPolicyIDToDelete(item.policyID ?? '-1');
setPolicyNameToDelete(item.title);
setIsDeleteModalOpen(true);
}),
});
}
if (!(isAdmin || isOwner)) {
threeDotsMenuItems.push({
icon: Expensicons.Exit,
text: translate('common.leave'),
onSelected: Session.checkIfActionIsAllowed(() => Policy.leaveWorkspace(item.policyID ?? '-1')),
});
}
if (isAdmin && item.adminRoom) {
threeDotsMenuItems.push({
icon: Expensicons.Hashtag,
text: translate('workspace.common.goToRoom', {roomName: CONST.REPORT.WORKSPACE_CHAT_ROOMS.ADMINS}),
onSelected: () => Navigation.navigate(ROUTES.REPORT_WITH_ID.getRoute(item.adminRoom ?? '')),
});
}
if (item.announceRoom) {
threeDotsMenuItems.push({
icon: Expensicons.Hashtag,
text: translate('workspace.common.goToRoom', {roomName: CONST.REPORT.WORKSPACE_CHAT_ROOMS.ANNOUNCE}),
onSelected: () => Navigation.navigate(ROUTES.REPORT_WITH_ID.getRoute(item.announceRoom ?? '')),
});
}
return (
<OfflineWithFeedback
key={`${item.title}_${index}`}
pendingAction={item.pendingAction}
errorRowStyles={styles.ph5}
onClose={item.dismissError}
errors={item.errors}
style={styles.mb3}
>
<PressableWithoutFeedback
role={CONST.ROLE.BUTTON}
accessibilityLabel="row"
style={[styles.mh5]}
disabled={item.disabled}
onPress={item.action}
>
{({hovered}) => (
<WorkspacesListRow
title={item.title}
policyID={item.policyID}
menuItems={threeDotsMenuItems}
workspaceIcon={item.icon}
ownerAccountID={item.ownerAccountID}
workspaceType={item.type}
isJoinRequestPending={item?.isJoinRequestPending}
rowStyles={hovered && styles.hoveredComponentBG}
layoutWidth={isLessThanMediumScreen ? CONST.LAYOUT_WIDTH.NARROW : CONST.LAYOUT_WIDTH.WIDE}
brickRoadIndicator={item.brickRoadIndicator}
shouldDisableThreeDotsMenu={item.disabled}
style={[item.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE ? styles.offlineFeedback.deleted : {}]}
/>
)}
</PressableWithoutFeedback>
</OfflineWithFeedback>
);
},
[isLessThanMediumScreen, styles.mb3, styles.mh5, styles.ph5, styles.hoveredComponentBG, translate, styles.offlineFeedback.deleted, session?.accountID],
);
const listHeaderComponent = useCallback(() => {
if (isLessThanMediumScreen) {
return <View style={styles.mt5} />;
}
return (
<View style={[styles.flexRow, styles.gap5, styles.p5, styles.pl10, styles.appBG]}>
<View style={[styles.flexRow, styles.flex1]}>
<Text
numberOfLines={1}
style={[styles.flexGrow1, styles.textLabelSupporting]}
>
{translate('workspace.common.workspaceName')}
</Text>
</View>
<View style={[styles.flexRow, styles.flex1, styles.workspaceOwnerSectionTitle]}>
<Text
numberOfLines={1}
style={[styles.flexGrow1, styles.textLabelSupporting]}
>
{translate('workspace.common.workspaceOwner')}
</Text>
</View>
<View style={[styles.flexRow, styles.flex1, styles.workspaceTypeSectionTitle]}>
<Text
numberOfLines={1}
style={[styles.flexGrow1, styles.textLabelSupporting]}
>
{translate('workspace.common.workspaceType')}
</Text>
</View>
<View style={[styles.workspaceRightColumn, styles.mr2]} />
</View>
);
}, [isLessThanMediumScreen, styles, translate]);
const policyRooms = useMemo(() => {
if (!reports || isEmptyObject(reports)) {
return;
}
return Object.values(reports).reduce<ChatPolicyType>((result, report) => {
if (!report?.reportID || !report.policyID) {
return result;
}
if (!result[report.policyID]) {
// eslint-disable-next-line no-param-reassign
result[report.policyID] = {};
}
switch (report.chatType) {
case CONST.REPORT.CHAT_TYPE.POLICY_ADMINS:
// eslint-disable-next-line no-param-reassign
result[report.policyID].adminRoom = report.reportID;
break;
case CONST.REPORT.CHAT_TYPE.POLICY_ANNOUNCE:
// eslint-disable-next-line no-param-reassign
result[report.policyID].announceRoom = report.reportID;
break;
default:
break;
}
return result;
}, {});
}, [reports]);
/**
* Add free policies (workspaces) to the list of menu items and returns the list of menu items
*/
const workspaces = useMemo(() => {
const reimbursementAccountBrickRoadIndicator = reimbursementAccount?.errors ? CONST.BRICK_ROAD_INDICATOR_STATUS.ERROR : undefined;
if (isEmptyObject(policies)) {
return [];
}
return Object.values(policies)
.filter((policy): policy is PolicyType => PolicyUtils.shouldShowPolicy(policy, !!isOffline))
.map((policy): WorkspaceItem => {
if (policy?.isJoinRequestPending && policy?.policyDetailsForNonMembers) {
const policyInfo = Object.values(policy.policyDetailsForNonMembers)[0];
const id = Object.keys(policy.policyDetailsForNonMembers)[0];
return {
title: policyInfo.name,
icon: policyInfo.avatar ? policyInfo.avatar : ReportUtils.getDefaultWorkspaceAvatar(policy.name),
disabled: true,
ownerAccountID: policyInfo.ownerAccountID,
type: policyInfo.type,
iconType: policyInfo.avatar ? CONST.ICON_TYPE_AVATAR : CONST.ICON_TYPE_ICON,
iconFill: theme.textLight,
fallbackIcon: Expensicons.FallbackWorkspaceAvatar,
policyID: id,
role: CONST.POLICY.ROLE.USER,
errors: null,
action: () => null,
dismissError: () => null,
isJoinRequestPending: true,
};
}
return {
title: policy.name,
icon: policy.avatarURL ? policy.avatarURL : ReportUtils.getDefaultWorkspaceAvatar(policy.name),
action: () => Navigation.navigate(ROUTES.WORKSPACE_INITIAL.getRoute(policy.id)),
brickRoadIndicator: reimbursementAccountBrickRoadIndicator ?? PolicyUtils.getPolicyBrickRoadIndicatorStatus(policy),
pendingAction: policy.pendingAction,
errors: policy.errors,
dismissError: () => dismissWorkspaceError(policy.id, policy.pendingAction),
disabled: policy.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE,
iconType: policy.avatarURL ? CONST.ICON_TYPE_AVATAR : CONST.ICON_TYPE_ICON,
iconFill: theme.textLight,
fallbackIcon: Expensicons.FallbackWorkspaceAvatar,
policyID: policy.id,
adminRoom: policyRooms?.[policy.id]?.adminRoom ?? policy.chatReportIDAdmins?.toString(),
announceRoom: policyRooms?.[policy.id]?.announceRoom ?? policy.chatReportIDAnnounce?.toString(),
ownerAccountID: policy.ownerAccountID,
role: policy.role,
type: policy.type,
};
})
.sort((a, b) => localeCompare(a.title, b.title));
}, [reimbursementAccount?.errors, policies, isOffline, theme.textLight, policyRooms]);
const getHeaderButton = () => (
<Button
accessibilityLabel={translate('workspace.new.newWorkspace')}
success
medium
text={translate('workspace.new.newWorkspace')}
onPress={() => interceptAnonymousUser(() => App.createWorkspaceWithPolicyDraftAndNavigateToIt())}
icon={Expensicons.Plus}
style={[shouldUseNarrowLayout && styles.flexGrow1, shouldUseNarrowLayout && styles.mb3]}
/>
);
if (isEmptyObject(workspaces)) {
return (
<ScreenWrapper
includeSafeAreaPaddingBottom={false}
shouldEnablePickerAvoiding={false}
shouldEnableMaxHeight
testID={WorkspacesListPage.displayName}
shouldShowOfflineIndicatorInWideScreen
>
<HeaderWithBackButton
title={translate('common.workspaces')}
shouldShowBackButton={shouldUseNarrowLayout}
onBackButtonPress={() => Navigation.goBack()}
icon={Illustrations.BigRocket}
>
{!shouldUseNarrowLayout && getHeaderButton()}
</HeaderWithBackButton>
{shouldUseNarrowLayout && <View style={[styles.pl5, styles.pr5]}>{getHeaderButton()}</View>}
<ScrollView contentContainerStyle={styles.pt3}>
<View style={[styles.flex1, isLessThanMediumScreen ? styles.workspaceSectionMobile : styles.workspaceSection]}>
<FeatureList
menuItems={workspaceFeatures}
title={translate('workspace.emptyWorkspace.title')}
subtitle={translate('workspace.emptyWorkspace.subtitle')}
ctaText={translate('workspace.new.newWorkspace')}
ctaAccessibilityLabel={translate('workspace.new.newWorkspace')}
onCtaPress={() => interceptAnonymousUser(() => App.createWorkspaceWithPolicyDraftAndNavigateToIt())}
illustration={LottieAnimations.WorkspacePlanet}
// We use this style to vertically center the illustration, as the original illustration is not centered
illustrationStyle={styles.emptyWorkspaceIllustrationStyle}
titleStyles={styles.textHeadlineH1}
/>
</View>
</ScrollView>
</ScreenWrapper>
);
}
return (
<ScreenWrapper
shouldEnablePickerAvoiding={false}
shouldShowOfflineIndicatorInWideScreen
testID={WorkspacesListPage.displayName}
>
<View style={styles.flex1}>
<HeaderWithBackButton
title={translate('common.workspaces')}
shouldShowBackButton={shouldUseNarrowLayout}
onBackButtonPress={() => Navigation.goBack()}
icon={Illustrations.BigRocket}
>
{!shouldUseNarrowLayout && getHeaderButton()}
</HeaderWithBackButton>
{shouldUseNarrowLayout && <View style={[styles.pl5, styles.pr5]}>{getHeaderButton()}</View>}
<FlatList
data={workspaces}
renderItem={getMenuItem}
ListHeaderComponent={listHeaderComponent}
stickyHeaderIndices={stickyHeaderIndices}
/>
</View>
<ConfirmModal
title={translate('workspace.common.delete')}
isVisible={isDeleteModalOpen}
onConfirm={confirmDeleteAndHideModal}
onCancel={() => setIsDeleteModalOpen(false)}
prompt={translate('workspace.common.deleteConfirmation')}
confirmText={translate('common.delete')}
cancelText={translate('common.cancel')}
danger
/>
</ScreenWrapper>
);
}
WorkspacesListPage.displayName = 'WorkspacesListPage';
export default withOnyx<WorkspaceListPageProps, WorkspaceListPageOnyxProps>({
policies: {
key: ONYXKEYS.COLLECTION.POLICY,
},
// @ts-expect-error: ONYXKEYS.REIMBURSEMENT_ACCOUNT is conflicting with ONYXKEYS.FORMS.REIMBURSEMENT_ACCOUNT_FORM
reimbursementAccount: {
key: ONYXKEYS.REIMBURSEMENT_ACCOUNT,
},
reports: {
key: ONYXKEYS.COLLECTION.REPORT,
},
session: {
key: ONYXKEYS.SESSION,
},
})(WorkspacesListPage);