-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
BaseReportActionContextMenu.tsx
executable file
·336 lines (291 loc) · 14.5 KB
/
BaseReportActionContextMenu.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
import lodashIsEqual from 'lodash/isEqual';
import type {MutableRefObject, RefObject} from 'react';
import React, {memo, useMemo, useRef, useState} from 'react';
import {InteractionManager, View} from 'react-native';
// eslint-disable-next-line no-restricted-imports
import type {GestureResponderEvent, Text as RNText, View as ViewType} from 'react-native';
import type {OnyxEntry} from 'react-native-onyx';
import {useOnyx, withOnyx} from 'react-native-onyx';
import type {ContextMenuItemHandle} from '@components/ContextMenuItem';
import ContextMenuItem from '@components/ContextMenuItem';
import FocusTrapForModal from '@components/FocusTrap/FocusTrapForModal';
import useArrowKeyFocusManager from '@hooks/useArrowKeyFocusManager';
import useKeyboardShortcut from '@hooks/useKeyboardShortcut';
import useLocalize from '@hooks/useLocalize';
import useNetwork from '@hooks/useNetwork';
import useResponsiveLayout from '@hooks/useResponsiveLayout';
import useStyleUtils from '@hooks/useStyleUtils';
import * as ReportActionsUtils from '@libs/ReportActionsUtils';
import * as ReportUtils from '@libs/ReportUtils';
import * as Session from '@userActions/Session';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import type {Beta, ReportAction, ReportActions, Transaction} from '@src/types/onyx';
import {isEmptyObject} from '@src/types/utils/EmptyObject';
import type {ContextMenuAction, ContextMenuActionPayload} from './ContextMenuActions';
import ContextMenuActions from './ContextMenuActions';
import type {ContextMenuAnchor, ContextMenuType} from './ReportActionContextMenu';
import {hideContextMenu, showContextMenu} from './ReportActionContextMenu';
type BaseReportActionContextMenuOnyxProps = {
/** Beta features list */
betas: OnyxEntry<Beta[]>;
/** All of the actions of the report */
reportActions: OnyxEntry<ReportActions>;
/** The transaction linked to the report action this context menu is attached to. */
transaction: OnyxEntry<Transaction>;
};
type BaseReportActionContextMenuProps = BaseReportActionContextMenuOnyxProps & {
/** The ID of the report this report action is attached to. */
reportID: string;
/** The ID of the report action this context menu is attached to. */
reportActionID: string;
/** The ID of the original report from which the given reportAction is first created. */
// originalReportID is used in withOnyx to get the reportActions for the original report
// eslint-disable-next-line react/no-unused-prop-types
originalReportID: string;
/**
* If true, this component will be a small, row-oriented menu that displays icons but not text.
* If false, this component will be a larger, column-oriented menu that displays icons alongside text in each row.
*/
isMini?: boolean;
/** Controls the visibility of this component. */
isVisible?: boolean;
/** The copy selection. */
selection?: string;
/** Draft message - if this is set the comment is in 'edit' mode */
draftMessage?: string;
/** String representing the context menu type [LINK, REPORT_ACTION] which controls context menu choices */
type?: ContextMenuType;
/** Target node which is the target of ContentMenu */
anchor?: MutableRefObject<ContextMenuAnchor>;
/** Flag to check if the chat participant is Chronos */
isChronosReport?: boolean;
/** Whether the provided report is an archived room */
isArchivedRoom?: boolean;
/** Flag to check if the chat is pinned in the LHN. Used for the Pin/Unpin action */
isPinnedChat?: boolean;
/** Flag to check if the chat is unread in the LHN. Used for the Mark as Read/Unread action */
isUnreadChat?: boolean;
/** Content Ref */
contentRef?: RefObject<View>;
/** Function to check if context menu is active */
checkIfContextMenuActive?: () => void;
/** List of disabled actions */
disabledActions?: ContextMenuAction[];
/** Function to update emoji picker state */
setIsEmojiPickerActive?: (state: boolean) => void;
};
type MenuItemRefs = Record<string, ContextMenuItemHandle | null>;
function BaseReportActionContextMenu({
type = CONST.CONTEXT_MENU_TYPES.REPORT_ACTION,
anchor,
contentRef,
isChronosReport = false,
isArchivedRoom = false,
isMini = false,
isVisible = false,
isPinnedChat = false,
isUnreadChat = false,
selection = '',
draftMessage = '',
reportActionID,
transaction,
reportID,
betas,
reportActions,
checkIfContextMenuActive,
disabledActions = [],
setIsEmojiPickerActive,
}: BaseReportActionContextMenuProps) {
const StyleUtils = useStyleUtils();
const {translate} = useLocalize();
const {shouldUseNarrowLayout} = useResponsiveLayout();
const menuItemRefs = useRef<MenuItemRefs>({});
const [shouldKeepOpen, setShouldKeepOpen] = useState(false);
const wrapperStyle = StyleUtils.getReportActionContextMenuStyles(isMini, shouldUseNarrowLayout);
const {isOffline} = useNetwork();
const threedotRef = useRef<View>(null);
const reportAction: OnyxEntry<ReportAction> = useMemo(() => {
if (isEmptyObject(reportActions) || reportActionID === '0' || reportActionID === '-1') {
return;
}
return reportActions[reportActionID];
}, [reportActions, reportActionID]);
const sourceID = ReportUtils.getSourceIDFromReportAction(reportAction);
const [download] = useOnyx(`${ONYXKEYS.COLLECTION.DOWNLOAD}${sourceID}`);
const originalReportID = useMemo(() => ReportUtils.getOriginalReportID(reportID, reportAction), [reportID, reportAction]);
const shouldEnableArrowNavigation = !isMini && (isVisible || shouldKeepOpen);
let filteredContextMenuActions = ContextMenuActions.filter(
(contextAction) =>
!disabledActions.includes(contextAction) &&
contextAction.shouldShow(type, reportAction, isArchivedRoom, betas, anchor, isChronosReport, reportID, isPinnedChat, isUnreadChat, !!isOffline, isMini),
);
if (isMini) {
const menuAction = filteredContextMenuActions.at(-1);
const otherActions = filteredContextMenuActions.slice(0, -1);
if (otherActions.length > CONST.MINI_CONTEXT_MENU_MAX_ITEMS && menuAction) {
filteredContextMenuActions = otherActions.slice(0, CONST.MINI_CONTEXT_MENU_MAX_ITEMS - 1);
filteredContextMenuActions.push(menuAction);
} else {
filteredContextMenuActions = otherActions;
}
}
// Context menu actions that are not rendered as menu items are excluded from arrow navigation
const nonMenuItemActionIndexes = filteredContextMenuActions.map((contextAction, index) =>
'renderContent' in contextAction && typeof contextAction.renderContent === 'function' ? index : undefined,
);
const disabledIndexes = nonMenuItemActionIndexes.filter((index): index is number => index !== undefined);
const [focusedIndex, setFocusedIndex] = useArrowKeyFocusManager({
initialFocusedIndex: -1,
disabledIndexes,
maxIndex: filteredContextMenuActions.length - 1,
isActive: shouldEnableArrowNavigation,
});
/**
* Checks if user is anonymous. If true and the action doesn't accept for anonymous user, hides the context menu and
* shows the sign in modal. Else, executes the callback.
*/
const interceptAnonymousUser = (callback: () => void, isAnonymousAction = false) => {
if (Session.isAnonymousUser() && !isAnonymousAction) {
hideContextMenu(false);
InteractionManager.runAfterInteractions(() => {
Session.signOutAndRedirectToSignIn();
});
} else {
callback();
}
};
useKeyboardShortcut(
CONST.KEYBOARD_SHORTCUTS.ENTER,
(event) => {
if (!menuItemRefs.current[focusedIndex]) {
return;
}
// Ensures the event does not cause side-effects beyond the context menu, e.g. when an outside element is focused
if (event) {
event.stopPropagation();
}
menuItemRefs.current[focusedIndex]?.triggerPressAndUpdateSuccess?.();
setFocusedIndex(-1);
},
{isActive: shouldEnableArrowNavigation},
);
const openOverflowMenu = (event: GestureResponderEvent | MouseEvent, anchorRef: MutableRefObject<View | null>) => {
showContextMenu(
CONST.CONTEXT_MENU_TYPES.REPORT_ACTION,
event,
selection,
anchorRef?.current as ViewType | RNText | null,
reportID,
reportAction?.reportActionID,
originalReportID,
draftMessage,
checkIfContextMenuActive,
() => {
checkIfContextMenuActive?.();
setShouldKeepOpen(false);
},
ReportUtils.isArchivedRoomWithID(originalReportID),
ReportUtils.chatIncludesChronosWithID(originalReportID),
undefined,
undefined,
filteredContextMenuActions,
true,
() => {},
true,
);
};
return (
(isVisible || shouldKeepOpen) && (
<FocusTrapForModal active={!isMini}>
<View
ref={contentRef}
style={wrapperStyle}
>
{filteredContextMenuActions.map((contextAction, index) => {
const closePopup = !isMini;
const payload: ContextMenuActionPayload = {
// eslint-disable-next-line @typescript-eslint/non-nullable-type-assertion-style
reportAction: (reportAction ?? null) as ReportAction,
reportID,
draftMessage,
selection,
close: () => setShouldKeepOpen(false),
openContextMenu: () => setShouldKeepOpen(true),
interceptAnonymousUser,
openOverflowMenu,
setIsEmojiPickerActive,
};
if ('renderContent' in contextAction) {
return contextAction.renderContent(closePopup, payload);
}
const {textTranslateKey} = contextAction;
const isKeyInActionUpdateKeys =
textTranslateKey === 'reportActionContextMenu.editAction' ||
textTranslateKey === 'reportActionContextMenu.deleteAction' ||
textTranslateKey === 'reportActionContextMenu.deleteConfirmation';
const text = textTranslateKey && (isKeyInActionUpdateKeys ? translate(textTranslateKey, {action: reportAction}) : translate(textTranslateKey));
const transactionPayload = textTranslateKey === 'reportActionContextMenu.copyToClipboard' && transaction && {transaction};
const isMenuAction = textTranslateKey === 'reportActionContextMenu.menu';
return (
<ContextMenuItem
ref={(ref) => {
menuItemRefs.current[index] = ref;
}}
buttonRef={isMenuAction ? threedotRef : {current: null}}
icon={contextAction.icon}
text={text ?? ''}
successIcon={contextAction.successIcon}
successText={contextAction.successTextTranslateKey ? translate(contextAction.successTextTranslateKey) : undefined}
isMini={isMini}
key={contextAction.textTranslateKey}
onPress={(event) =>
interceptAnonymousUser(
() => contextAction.onPress?.(closePopup, {...payload, ...transactionPayload, event, ...(isMenuAction ? {anchorRef: threedotRef} : {})}),
contextAction.isAnonymousAction,
)
}
description={contextAction.getDescription?.(selection) ?? ''}
isAnonymousAction={contextAction.isAnonymousAction}
isFocused={focusedIndex === index}
shouldPreventDefaultFocusOnPress={contextAction.shouldPreventDefaultFocusOnPress}
onFocus={() => setFocusedIndex(index)}
onBlur={() => (index === filteredContextMenuActions.length - 1 || index === 1) && setFocusedIndex(-1)}
disabled={contextAction?.shouldDisable ? contextAction?.shouldDisable(download) : false}
shouldShowLoadingSpinnerIcon={contextAction?.shouldDisable ? contextAction?.shouldDisable(download) : false}
/>
);
})}
</View>
</FocusTrapForModal>
)
);
}
export default withOnyx<BaseReportActionContextMenuProps, BaseReportActionContextMenuOnyxProps>({
betas: {
key: ONYXKEYS.BETAS,
},
reportActions: {
key: ({originalReportID}) => `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${originalReportID}`,
canEvict: false,
},
transaction: {
key: ({reportActions, reportActionID}) => {
const reportAction = reportActions?.[reportActionID];
return `${ONYXKEYS.COLLECTION.TRANSACTION}${(reportAction && ReportActionsUtils.getLinkedTransactionID(reportAction)) ?? -1}`;
},
},
})(
memo(BaseReportActionContextMenu, (prevProps, nextProps) => {
const {reportActions: prevReportActions, ...prevPropsWithoutReportActions} = prevProps;
const {reportActions: nextReportActions, ...nextPropsWithoutReportActions} = nextProps;
const prevReportAction = prevReportActions?.[prevProps.reportActionID] ?? '';
const nextReportAction = nextReportActions?.[nextProps.reportActionID] ?? '';
// We only want to re-render when the report action that is attached to is changed
if (prevReportAction !== nextReportAction) {
return false;
}
return lodashIsEqual(prevPropsWithoutReportActions, nextPropsWithoutReportActions);
}),
);
export type {BaseReportActionContextMenuProps};