Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace OptionsSelector with SelectionList part 1 #39711

Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions src/components/SelectionList/BaseListItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,15 @@ function BaseListItem<TItem extends ListItem>({
</View>
</View>
)}
{!item.isSelected && !!item.brickRoadIndicator && (
<View style={[styles.alignItemsCenter, styles.justifyContentCenter]}>
<Icon
src={Expensicons.DotIndicator}
fill={item.brickRoadIndicator === CONST.BRICK_ROAD_INDICATOR_STATUS.INFO ? theme.iconSuccessFill : theme.danger}
/>
</View>
)}

{rightHandSideComponentRender()}
</View>
{FooterComponent}
Expand Down
25 changes: 19 additions & 6 deletions src/components/SelectionList/BaseSelectionList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,9 @@ function BaseSelectionList<TItem extends ListItem>(
textInputRef,
headerMessageStyle,
shouldHideListOnInitialRender = true,
textInputIconLeft,
sectionTitleStyles,
textInputAutoFocus = true,
}: BaseSelectionListProps<TItem>,
ref: ForwardedRef<SelectionListHandle>,
) {
Expand All @@ -79,7 +82,7 @@ function BaseSelectionList<TItem extends ListItem>(
const listRef = useRef<RNSectionList<TItem, SectionWithIndexOffset<TItem>>>(null);
const innerTextInputRef = useRef<RNTextInput | null>(null);
const focusTimeoutRef = useRef<NodeJS.Timeout | null>(null);
const shouldShowTextInput = !!textInputLabel;
const shouldShowTextInput = !!textInputLabel || !!textInputIconLeft;
const shouldShowSelectAll = !!onSelectAll;
const activeElementRole = useActiveElementRole();
const isFocused = useIsFocused();
Expand Down Expand Up @@ -310,7 +313,7 @@ function BaseSelectionList<TItem extends ListItem>(
// We do this so that we can reference the height in `getItemLayout` –
// we need to know the heights of all list items up-front in order to synchronously compute the layout of any given list item.
// So be aware that if you adjust the content of the section header (for example, change the font size), you may need to adjust this explicit height as well.
<View style={[styles.optionsListSectionHeader, styles.justifyContentCenter]}>
<View style={[styles.optionsListSectionHeader, styles.justifyContentCenter, sectionTitleStyles]}>
<Text style={[styles.ph4, styles.textLabelSupporting]}>{section.title}</Text>
</View>
);
Expand Down Expand Up @@ -377,6 +380,9 @@ function BaseSelectionList<TItem extends ListItem>(
/** Focuses the text input when the component comes into focus and after any navigation animations finish. */
useFocusEffect(
useCallback(() => {
if (!textInputAutoFocus) {
return;
}
if (shouldShowTextInput) {
focusTimeoutRef.current = setTimeout(() => {
if (!innerTextInputRef.current) {
Expand All @@ -391,7 +397,7 @@ function BaseSelectionList<TItem extends ListItem>(
}
clearTimeout(focusTimeoutRef.current);
};
}, [shouldShowTextInput]),
}, [shouldShowTextInput, textInputAutoFocus]),
);

const prevTextInputValue = usePrevious(textInputValue);
Expand Down Expand Up @@ -494,8 +500,12 @@ function BaseSelectionList<TItem extends ListItem>(
return;
}

// eslint-disable-next-line no-param-reassign
textInputRef.current = element as RNTextInput;
if (typeof textInputRef === 'function') {
textInputRef(element as RNTextInput);
} else {
// eslint-disable-next-line no-param-reassign
textInputRef.current = element as RNTextInput;
}
}}
label={textInputLabel}
accessibilityLabel={textInputLabel}
Expand All @@ -508,14 +518,17 @@ function BaseSelectionList<TItem extends ListItem>(
inputMode={inputMode}
selectTextOnFocus
spellCheck={false}
iconLeft={textInputIconLeft}
onSubmitEditing={selectFocusedOption}
blurOnSubmit={!!flattenedSections.allOptions.length}
isLoading={isLoadingNewOptions}
testID="selection-list-text-input"
/>
</View>
)}
{!!headerMessage && (
{/* If we are loading new options we will avoid showing any header message. This is mostly because one of the header messages says there are no options. */}
{/* This is misleading because we might be in the process of loading fresh options from the server. */}
{!isLoadingNewOptions && !!headerMessage && (
<View style={headerMessageStyle ?? [styles.ph5, styles.pb5]}>
<Text style={[styles.textLabel, styles.colorMuted]}>{headerMessage}</Text>
</View>
Expand Down
19 changes: 16 additions & 3 deletions src/components/SelectionList/types.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import type {MutableRefObject, ReactElement, ReactNode} from 'react';
import type {GestureResponderEvent, InputModeOptions, LayoutChangeEvent, SectionListData, StyleProp, TextInput, TextStyle, ViewStyle} from 'react-native';
import type {MaybePhraseKey} from '@libs/Localize';
import type {BrickRoad} from '@libs/WorkspacesSettingsUtils';
import type CONST from '@src/CONST';
import type {Errors, Icon, PendingAction} from '@src/types/onyx/OnyxCommon';
import type {ReceiptErrors} from '@src/types/onyx/Transaction';
import type ChildrenProps from '@src/types/utils/ChildrenProps';
import type IconAsset from '@src/types/utils/IconAsset';
import type InviteMemberListItem from './InviteMemberListItem';
import type RadioListItem from './RadioListItem';
import type TableListItem from './TableListItem';
Expand Down Expand Up @@ -110,6 +112,8 @@ type ListItem = {

/** The search value from the selection list */
searchText?: string | null;

brickRoadIndicator?: BrickRoad | '' | null;
};

type ListItemProps = CommonListItemProps<ListItem> & {
Expand Down Expand Up @@ -214,14 +218,20 @@ type BaseSelectionListProps<TItem extends ListItem> = Partial<ChildrenProps> & {
/** Max length for the text input */
textInputMaxLength?: number;

/** Icon to display on the left side of TextInput */
textInputIconLeft?: IconAsset;

/** Whether text input should be focused */
textInputAutoFocus?: boolean;

/** Callback to fire when the text input changes */
onChangeText?: (text: string) => void;

/** Input mode for the text input */
inputMode?: InputModeOptions;

/** Item `keyForList` to focus initially */
initiallyFocusedOptionKey?: string;
initiallyFocusedOptionKey?: string | null;

/** Callback to fire when the list is scrolled */
onScroll?: () => void;
Expand Down Expand Up @@ -272,7 +282,7 @@ type BaseSelectionListProps<TItem extends ListItem> = Partial<ChildrenProps> & {
disableKeyboardShortcuts?: boolean;

/** Styles to apply to SelectionList container */
containerStyle?: ViewStyle;
containerStyle?: StyleProp<ViewStyle>;

/** Whether keyboard is visible on the screen */
isKeyboardShown?: boolean;
Expand All @@ -296,7 +306,10 @@ type BaseSelectionListProps<TItem extends ListItem> = Partial<ChildrenProps> & {
isRowMultilineSupported?: boolean;

/** Ref for textInput */
textInputRef?: MutableRefObject<TextInput | null>;
textInputRef?: MutableRefObject<TextInput | null> | ((ref: TextInput | null) => void);

/** Styles for the section title */
sectionTitleStyles?: StyleProp<ViewStyle>;

/**
* When true, the list won't be visible until the list layout is measured. This prevents the list from "blinking" as it's scrolled to the bottom which is recommended for large lists.
Expand Down
22 changes: 8 additions & 14 deletions src/components/TagPicker/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import React, {useMemo, useState} from 'react';
import type {OnyxEntry} from 'react-native-onyx';
import {withOnyx} from 'react-native-onyx';
import type {EdgeInsets} from 'react-native-safe-area-context';
import OptionsSelector from '@components/OptionsSelector';
import SelectionList from '@components/SelectionList';
import RadioListItem from '@components/SelectionList/RadioListItem';
import useLocalize from '@hooks/useLocalize';
import useStyleUtils from '@hooks/useStyleUtils';
import useThemeStyles from '@hooks/useThemeStyles';
Expand Down Expand Up @@ -100,22 +101,15 @@ function TagPicker({selectedTag, tagListName, policyTags, tagListIndex, policyRe
const selectedOptionKey = sections[0]?.data?.filter((policyTag) => policyTag.searchText === selectedTag)?.[0]?.keyForList;

return (
<OptionsSelector
// @ts-expect-error TODO: Remove this once OptionsSelector (https://github.com/Expensify/App/issues/25125) is migrated to TypeScript.
contentContainerStyles={[{paddingBottom: StyleUtils.getSafeAreaMargins(insets).marginBottom}]}
optionHoveredStyle={styles.hoveredComponentBG}
sectionHeaderStyle={styles.mt5}
<SelectionList
ListItem={RadioListItem}
containerStyle={{paddingBottom: StyleUtils.getSafeAreaMargins(insets).marginBottom}}
filip-solecki marked this conversation as resolved.
Show resolved Hide resolved
sectionTitleStyles={styles.mt5}
sections={sections}
selectedOptions={selectedOptions}
textInputValue={searchValue}
headerMessage={headerMessage}
textInputLabel={translate('common.search')}
boldStyle
highlightSelectedOptions
textInputLabel={shouldShowTextInput ? translate('common.search') : undefined}
isRowMultilineSupported
shouldShowTextInput={shouldShowTextInput}
// Focus the first option when searching
focusedIndex={0}
// Focus the selected option on first load
initiallyFocusedOptionKey={selectedOptionKey}
onChangeText={setSearchValue}
onSelectRow={onSubmit}
Expand Down
15 changes: 8 additions & 7 deletions src/libs/OptionsListUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1105,7 +1105,7 @@ function getCategoryListSections(
*
* @param tags - an initial tag array
*/
function getTagsOptions(tags: Array<Pick<PolicyTag, 'name' | 'enabled'>>): Option[] {
function getTagsOptions(tags: Array<Pick<PolicyTag, 'name' | 'enabled'>>, selectedOptions?: SelectedTagOption[]): Option[] {
return tags.map((tag) => {
// This is to remove unnecessary escaping backslash in tag name sent from backend.
const cleanedName = PolicyUtils.getCleanedTagName(tag.name);
Expand All @@ -1115,6 +1115,7 @@ function getTagsOptions(tags: Array<Pick<PolicyTag, 'name' | 'enabled'>>): Optio
searchText: tag.name,
tooltipText: cleanedName,
isDisabled: !tag.enabled,
isSelected: selectedOptions?.some((selectedTag) => selectedTag.name === tag.name),
};
});
}
Expand Down Expand Up @@ -1146,7 +1147,7 @@ function getTagListSections(
// "Selected" section
title: '',
shouldShow: false,
data: getTagsOptions(selectedTagOptions),
data: getTagsOptions(selectedTagOptions, selectedOptions),
});

return tagSections;
Expand All @@ -1159,7 +1160,7 @@ function getTagListSections(
// "Search" section
title: '',
shouldShow: true,
data: getTagsOptions(searchTags),
data: getTagsOptions(searchTags, selectedOptions),
});

return tagSections;
Expand All @@ -1170,7 +1171,7 @@ function getTagListSections(
// "All" section when items amount less than the threshold
title: '',
shouldShow: false,
data: getTagsOptions(enabledTags),
data: getTagsOptions(enabledTags, selectedOptions),
});

return tagSections;
Expand All @@ -1195,7 +1196,7 @@ function getTagListSections(
// "Selected" section
title: '',
shouldShow: true,
data: getTagsOptions(selectedTagOptions),
data: getTagsOptions(selectedTagOptions, selectedOptions),
});
}

Expand All @@ -1206,15 +1207,15 @@ function getTagListSections(
// "Recent" section
title: Localize.translateLocal('common.recent'),
shouldShow: true,
data: getTagsOptions(cutRecentlyUsedTags),
data: getTagsOptions(cutRecentlyUsedTags, selectedOptions),
});
}

tagSections.push({
// "All" section when items amount more than the threshold
title: Localize.translateLocal('common.all'),
shouldShow: true,
data: getTagsOptions(filteredTags),
data: getTagsOptions(filteredTags, selectedOptions),
});

return tagSections;
Expand Down
49 changes: 14 additions & 35 deletions src/pages/WorkspaceSwitcherPage.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, {useCallback, useEffect, useMemo, useState} from 'react';
import React, {useCallback, useMemo, useState} from 'react';
import {View} from 'react-native';
import type {OnyxCollection} from 'react-native-onyx';
import {withOnyx} from 'react-native-onyx';
Expand All @@ -7,9 +7,10 @@ import Icon from '@components/Icon';
import * as Expensicons from '@components/Icon/Expensicons';
import {MagnifyingGlass} from '@components/Icon/Expensicons';
import OptionRow from '@components/OptionRow';
import OptionsSelector from '@components/OptionsSelector';
import PressableWithFeedback from '@components/Pressable/PressableWithFeedback';
import ScreenWrapper from '@components/ScreenWrapper';
import SelectionList from '@components/SelectionList';
import UserListItem from '@components/SelectionList/UserListItem';
import Text from '@components/Text';
import Tooltip from '@components/Tooltip';
import useActiveWorkspace from '@hooks/useActiveWorkspace';
Expand Down Expand Up @@ -57,7 +58,6 @@ function WorkspaceSwitcherPage({policies}: WorkspaceSwitcherPageProps) {
const theme = useTheme();
const styles = useThemeStyles();
const {isOffline} = useNetwork();
const [selectedOption, setSelectedOption] = useState<SimpleWorkspaceItem>();
const [searchTerm, setSearchTerm] = useState('');
const {inputCallbackRef} = useAutoFocusInput();
const {translate} = useLocalize();
Expand Down Expand Up @@ -105,11 +105,6 @@ function WorkspaceSwitcherPage({policies}: WorkspaceSwitcherPageProps) {

const {policyID} = option;

if (policyID) {
setSelectedOption(option);
} else {
setSelectedOption(undefined);
}
setActiveWorkspaceID(policyID);
Navigation.goBack();
if (policyID !== activeWorkspaceID) {
Expand Down Expand Up @@ -141,8 +136,9 @@ function WorkspaceSwitcherPage({policies}: WorkspaceSwitcherPageProps) {
boldStyle: hasUnreadData(policy?.id),
keyForList: policy?.id,
isPolicyAdmin: PolicyUtils.isPolicyAdmin(policy),
isSelected: policy?.id === activeWorkspaceID,
}));
}, [policies, getIndicatorTypeForPolicy, hasUnreadData, isOffline]);
}, [policies, getIndicatorTypeForPolicy, hasUnreadData, isOffline, activeWorkspaceID]);

const filteredAndSortedUserWorkspaces = useMemo(
() =>
Expand Down Expand Up @@ -236,28 +232,20 @@ function WorkspaceSwitcherPage({policies}: WorkspaceSwitcherPageProps) {
</View>

{usersWorkspaces.length > 0 ? (
<OptionsSelector
// @ts-expect-error TODO: remove this comment once OptionsSelector (https://github.com/Expensify/App/issues/25125) is migrated to TS
placeholder={translate('workspace.switcher.placeholder')}
ref={inputCallbackRef}
<SelectionList
ListItem={UserListItem}
textInputPlaceholder={translate('workspace.switcher.placeholder')}
textInputRef={inputCallbackRef}
sections={[usersWorkspacesSectionData]}
value={searchTerm}
shouldShowTextInput={usersWorkspaces.length >= CONST.WORKSPACE_SWITCHER.MINIMUM_WORKSPACES_TO_SHOW_SEARCH}
textInputValue={searchTerm}
onChangeText={setSearchTerm}
selectedOptions={selectedOption ? [selectedOption] : []}
onSelectRow={selectPolicy}
shouldPreventDefaultFocusOnSelectRow
headerMessage={headerMessage}
highlightSelectedOptions
shouldShowOptions
autoFocus={false}
canSelectMultipleOptions={false}
shouldShowSubscript={false}
showTitleTooltip={false}
contentContainerStyles={[styles.pt0, styles.mt0]}
textIconLeft={MagnifyingGlass}
// Null is to avoid selecting unfocused option when Global selected, undefined is to focus selected workspace
initiallyFocusedOptionKey={!activeWorkspaceID ? null : undefined}
containerStyle={[styles.pt0, styles.mt0]}
textInputIconLeft={usersWorkspaces.length >= CONST.WORKSPACE_SWITCHER.MINIMUM_WORKSPACES_TO_SHOW_SEARCH ? MagnifyingGlass : undefined}
initiallyFocusedOptionKey={activeWorkspaceID}
textInputAutoFocus={false}
/>
) : (
<WorkspaceCardCreateAWorkspace />
Expand All @@ -269,7 +257,6 @@ function WorkspaceSwitcherPage({policies}: WorkspaceSwitcherPageProps) {
setSearchTerm,
searchTerm,
selectPolicy,
selectedOption,
styles,
theme.textSupporting,
translate,
Expand All @@ -281,14 +268,6 @@ function WorkspaceSwitcherPage({policies}: WorkspaceSwitcherPageProps) {
],
);

useEffect(() => {
if (!activeWorkspaceID) {
return;
}
const optionToSet = usersWorkspaces.find((option) => option.policyID === activeWorkspaceID);
setSelectedOption(optionToSet);
}, [activeWorkspaceID, usersWorkspaces]);

return (
<ScreenWrapper testID={WorkspaceSwitcherPage.displayName}>
<HeaderWithBackButton
Expand Down
Loading
Loading