-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
PopoverMenu.tsx
345 lines (307 loc) · 14.7 KB
/
PopoverMenu.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
import lodashIsEqual from 'lodash/isEqual';
import type {RefObject} from 'react';
import React, {useLayoutEffect, useState} from 'react';
import {StyleSheet} from 'react-native';
import type {View} from 'react-native';
import type {ModalProps} from 'react-native-modal';
import useArrowKeyFocusManager from '@hooks/useArrowKeyFocusManager';
import useKeyboardShortcut from '@hooks/useKeyboardShortcut';
import useResponsiveLayout from '@hooks/useResponsiveLayout';
import useTheme from '@hooks/useTheme';
import useThemeStyles from '@hooks/useThemeStyles';
import useWindowDimensions from '@hooks/useWindowDimensions';
import * as Browser from '@libs/Browser';
import * as Modal from '@userActions/Modal';
import CONST from '@src/CONST';
import type {AnchorPosition} from '@src/styles';
import type {PendingAction} from '@src/types/onyx/OnyxCommon';
import type AnchorAlignment from '@src/types/utils/AnchorAlignment';
import FocusableMenuItem from './FocusableMenuItem';
import FocusTrapForModal from './FocusTrap/FocusTrapForModal';
import * as Expensicons from './Icon/Expensicons';
import type {MenuItemProps} from './MenuItem';
import MenuItem from './MenuItem';
import type BaseModalProps from './Modal/types';
import OfflineWithFeedback from './OfflineWithFeedback';
import PopoverWithMeasuredContent from './PopoverWithMeasuredContent';
import ScrollView from './ScrollView';
import Text from './Text';
type PopoverMenuItem = MenuItemProps & {
/** Text label */
text: string;
/** A callback triggered when this item is selected */
onSelected?: () => void;
/** Sub menu items to be rendered after a menu item is selected */
subMenuItems?: PopoverMenuItem[];
/** Back button text to be shown if sub menu items are opened */
backButtonText?: string;
/** Determines whether the menu item is disabled or not */
disabled?: boolean;
/** Determines whether the menu item's onSelected() function is called after the modal is hidden
* It is meant to be used in situations where, after clicking on the modal, another one is opened.
*/
shouldCallAfterModalHide?: boolean;
/** Whether to close all modals */
shouldCloseAllModals?: boolean;
pendingAction?: PendingAction;
};
type PopoverModalProps = Pick<ModalProps, 'animationIn' | 'animationOut' | 'animationInTiming'>;
type PopoverMenuProps = Partial<PopoverModalProps> & {
/** Callback method fired when the user requests to close the modal */
onClose: () => void;
/** Callback method fired when the modal is shown */
onModalShow?: () => void;
/** State that determines whether to display the modal or not */
isVisible: boolean;
/** Callback to fire when a CreateMenu item is selected */
onItemSelected: (selectedItem: PopoverMenuItem, index: number) => void;
/** Menu items to be rendered on the list */
menuItems: PopoverMenuItem[];
/** Optional non-interactive text to display as a header for any create menu */
headerText?: string;
/** Whether disable the animations */
disableAnimation?: boolean;
/** The horizontal and vertical anchors points for the popover */
anchorPosition: AnchorPosition;
/** Ref of the anchor */
anchorRef: RefObject<View | HTMLDivElement>;
/** Where the popover should be positioned relative to the anchor points. */
anchorAlignment?: AnchorAlignment;
/** Whether we don't want to show overlay */
withoutOverlay?: boolean;
/** Should we announce the Modal visibility changes? */
shouldSetModalVisibility?: boolean;
/** Whether we want to show the popover on the right side of the screen */
fromSidebarMediumScreen?: boolean;
/**
* Whether the modal should enable the new focus manager.
* We are attempting to migrate to a new refocus manager, adding this property for gradual migration.
* */
shouldEnableNewFocusManagement?: boolean;
/** How to re-focus after the modal is dismissed */
restoreFocusType?: BaseModalProps['restoreFocusType'];
/** Whether to show the selected option checkmark */
shouldShowSelectedItemCheck?: boolean;
};
function PopoverMenu({
menuItems,
onItemSelected,
isVisible,
anchorPosition,
anchorRef,
onClose,
onModalShow,
headerText,
fromSidebarMediumScreen,
anchorAlignment = {
horizontal: CONST.MODAL.ANCHOR_ORIGIN_HORIZONTAL.LEFT,
vertical: CONST.MODAL.ANCHOR_ORIGIN_VERTICAL.BOTTOM,
},
animationIn = 'fadeIn',
animationOut = 'fadeOut',
animationInTiming = CONST.ANIMATED_TRANSITION,
disableAnimation = true,
withoutOverlay = false,
shouldSetModalVisibility = true,
shouldEnableNewFocusManagement,
restoreFocusType,
shouldShowSelectedItemCheck = false,
}: PopoverMenuProps) {
const styles = useThemeStyles();
const theme = useTheme();
// We need to use isSmallScreenWidth instead of shouldUseNarrowLayout to apply correct popover styles
const {isSmallScreenWidth} = useResponsiveLayout();
const [currentMenuItems, setCurrentMenuItems] = useState(menuItems);
const currentMenuItemsFocusedIndex = currentMenuItems?.findIndex((option) => option.isSelected);
const [enteredSubMenuIndexes, setEnteredSubMenuIndexes] = useState<readonly number[]>(CONST.EMPTY_ARRAY);
const {windowHeight} = useWindowDimensions();
const [focusedIndex, setFocusedIndex] = useArrowKeyFocusManager({initialFocusedIndex: currentMenuItemsFocusedIndex, maxIndex: currentMenuItems.length - 1, isActive: isVisible});
const selectItem = (index: number) => {
const selectedItem = currentMenuItems.at(index);
if (!selectedItem) {
return;
}
if (selectedItem?.subMenuItems) {
setCurrentMenuItems([...selectedItem.subMenuItems]);
setEnteredSubMenuIndexes([...enteredSubMenuIndexes, index]);
const selectedSubMenuItemIndex = selectedItem?.subMenuItems.findIndex((option) => option.isSelected);
setFocusedIndex(selectedSubMenuItemIndex);
} else if (selectedItem.shouldCallAfterModalHide && !Browser.isSafari()) {
onItemSelected(selectedItem, index);
Modal.close(
() => {
selectedItem.onSelected?.();
},
undefined,
selectedItem.shouldCloseAllModals,
);
} else {
onItemSelected(selectedItem, index);
selectedItem.onSelected?.();
}
};
const getPreviousSubMenu = () => {
let currentItems = menuItems;
for (let i = 0; i < enteredSubMenuIndexes.length - 1; i++) {
const nextItems = currentItems[enteredSubMenuIndexes[i]].subMenuItems;
if (!nextItems) {
return currentItems;
}
currentItems = nextItems;
}
return currentItems;
};
const renderBackButtonItem = () => {
const previousMenuItems = getPreviousSubMenu();
const previouslySelectedItem = previousMenuItems[enteredSubMenuIndexes[enteredSubMenuIndexes.length - 1]];
const hasBackButtonText = !!previouslySelectedItem.backButtonText;
return (
<MenuItem
key={previouslySelectedItem.text}
icon={Expensicons.BackArrow}
iconFill={theme.icon}
style={hasBackButtonText ? styles.pv0 : undefined}
title={hasBackButtonText ? previouslySelectedItem.backButtonText : previouslySelectedItem.text}
titleStyle={hasBackButtonText ? styles.createMenuHeaderText : undefined}
shouldShowBasicTitle={hasBackButtonText}
shouldCheckActionAllowedOnPress={false}
description={previouslySelectedItem.description}
onPress={() => {
setCurrentMenuItems(previousMenuItems);
setFocusedIndex(-1);
setEnteredSubMenuIndexes((prevState) => prevState.slice(0, -1));
}}
/>
);
};
const renderHeaderText = () => {
if (!headerText || enteredSubMenuIndexes.length !== 0) {
return;
}
return <Text style={[styles.createMenuHeaderText, styles.ph5, styles.pv3]}>{headerText}</Text>;
};
useKeyboardShortcut(
CONST.KEYBOARD_SHORTCUTS.ENTER,
() => {
if (focusedIndex === -1) {
return;
}
selectItem(focusedIndex);
setFocusedIndex(-1); // Reset the focusedIndex on selecting any menu
},
{isActive: isVisible},
);
const onModalHide = () => {
setFocusedIndex(-1);
};
// When the menu items are changed, we want to reset the sub-menu to make sure
// we are not accessing the wrong sub-menu parent or possibly undefined when rendering the back button.
// We use useLayoutEffect so the reset happens before the repaint
useLayoutEffect(() => {
if (menuItems.length === 0) {
return;
}
setEnteredSubMenuIndexes(CONST.EMPTY_ARRAY);
setCurrentMenuItems(menuItems);
}, [menuItems]);
return (
<PopoverWithMeasuredContent
anchorPosition={anchorPosition}
anchorRef={anchorRef}
anchorAlignment={anchorAlignment}
onClose={() => {
setCurrentMenuItems(menuItems);
setEnteredSubMenuIndexes(CONST.EMPTY_ARRAY);
onClose();
}}
isVisible={isVisible}
onModalHide={onModalHide}
onModalShow={onModalShow}
animationIn={animationIn}
animationOut={animationOut}
animationInTiming={animationInTiming}
disableAnimation={disableAnimation}
fromSidebarMediumScreen={fromSidebarMediumScreen}
withoutOverlay={withoutOverlay}
shouldSetModalVisibility={shouldSetModalVisibility}
shouldEnableNewFocusManagement={shouldEnableNewFocusManagement}
useNativeDriver
restoreFocusType={restoreFocusType}
>
<FocusTrapForModal active={isVisible}>
<ScrollView style={isSmallScreenWidth ? {maxHeight: windowHeight - 250} : styles.createMenuContainer}>
{renderHeaderText()}
{enteredSubMenuIndexes.length > 0 && renderBackButtonItem()}
{currentMenuItems.map((item, menuIndex) => (
<OfflineWithFeedback
// eslint-disable-next-line react/no-array-index-key
key={`${item.text}_${menuIndex}`}
pendingAction={item.pendingAction}
>
<FocusableMenuItem
icon={item.icon}
iconWidth={item.iconWidth}
iconHeight={item.iconHeight}
iconFill={item.iconFill}
contentFit={item.contentFit}
title={item.text}
shouldShowSelectedItemCheck={shouldShowSelectedItemCheck}
titleStyle={StyleSheet.flatten([styles.flex1, item.titleStyle])}
shouldCheckActionAllowedOnPress={false}
description={item.description}
numberOfLinesDescription={item.numberOfLinesDescription}
onPress={() => selectItem(menuIndex)}
focused={focusedIndex === menuIndex}
displayInDefaultIconColor={item.displayInDefaultIconColor}
shouldShowRightIcon={item.shouldShowRightIcon}
shouldShowRightComponent={item.shouldShowRightComponent}
iconRight={item.iconRight}
rightComponent={item.rightComponent}
shouldPutLeftPaddingWhenNoIcon={item.shouldPutLeftPaddingWhenNoIcon}
label={item.label}
style={{backgroundColor: item.isSelected ? theme.activeComponentBG : undefined}}
isLabelHoverable={item.isLabelHoverable}
floatRightAvatars={item.floatRightAvatars}
floatRightAvatarSize={item.floatRightAvatarSize}
shouldShowSubscriptRightAvatar={item.shouldShowSubscriptRightAvatar}
disabled={item.disabled}
onFocus={() => setFocusedIndex(menuIndex)}
success={item.success}
containerStyle={item.containerStyle}
shouldRenderTooltip={item.shouldRenderTooltip}
tooltipAnchorAlignment={item.tooltipAnchorAlignment}
tooltipShiftHorizontal={item.tooltipShiftHorizontal}
tooltipShiftVertical={item.tooltipShiftVertical}
tooltipWrapperStyle={item.tooltipWrapperStyle}
renderTooltipContent={item.renderTooltipContent}
numberOfLinesTitle={item.numberOfLinesTitle}
interactive={item.interactive}
isSelected={item.isSelected}
badgeText={item.badgeText}
/>
</OfflineWithFeedback>
))}
</ScrollView>
</FocusTrapForModal>
</PopoverWithMeasuredContent>
);
}
PopoverMenu.displayName = 'PopoverMenu';
export default React.memo(
PopoverMenu,
(prevProps, nextProps) =>
prevProps.menuItems.length === nextProps.menuItems.length &&
prevProps.isVisible === nextProps.isVisible &&
lodashIsEqual(prevProps.anchorPosition, nextProps.anchorPosition) &&
prevProps.anchorRef === nextProps.anchorRef &&
prevProps.headerText === nextProps.headerText &&
prevProps.fromSidebarMediumScreen === nextProps.fromSidebarMediumScreen &&
lodashIsEqual(prevProps.anchorAlignment, nextProps.anchorAlignment) &&
prevProps.animationIn === nextProps.animationIn &&
prevProps.animationOut === nextProps.animationOut &&
prevProps.animationInTiming === nextProps.animationInTiming &&
prevProps.disableAnimation === nextProps.disableAnimation &&
prevProps.withoutOverlay === nextProps.withoutOverlay &&
prevProps.shouldSetModalVisibility === nextProps.shouldSetModalVisibility,
);
export type {PopoverMenuItem, PopoverMenuProps};