From 46090f5d4968b16e5c46a83e26e40dca05d0ad2d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Muzyk?= Date: Mon, 28 Jul 2025 13:03:38 +0200 Subject: [PATCH 1/3] feat: 65634 Reduce initial amount of items per page of selection list --- src/CONST/index.ts | 2 +- .../SelectionList/BaseSelectionList.tsx | 81 +++++++++-- tests/unit/BaseSelectionListTest.tsx | 127 +++++++++++++++++- 3 files changed, 198 insertions(+), 12 deletions(-) diff --git a/src/CONST/index.ts b/src/CONST/index.ts index a2029dd35303..24d7bd6d5602 100755 --- a/src/CONST/index.ts +++ b/src/CONST/index.ts @@ -5205,7 +5205,7 @@ const CONST = { * The maximum count of items per page for SelectionList. * When paginate, it multiplies by page number. */ - MAX_SELECTION_LIST_PAGE_LENGTH: 500, + MAX_SELECTION_LIST_PAGE_LENGTH: 50, /** * Bank account names diff --git a/src/components/SelectionList/BaseSelectionList.tsx b/src/components/SelectionList/BaseSelectionList.tsx index 1ea9636fec34..46fd6695706d 100644 --- a/src/components/SelectionList/BaseSelectionList.tsx +++ b/src/components/SelectionList/BaseSelectionList.tsx @@ -167,10 +167,34 @@ function BaseSelectionList( const {isKeyboardShown} = useKeyboardState(); const [itemsToHighlight, setItemsToHighlight] = useState | null>(null); const itemFocusTimeoutRef = useRef(null); - const [currentPage, setCurrentPage] = useState(1); + const isItemSelected = useCallback( + (item: TItem) => item.isSelected ?? ((isSelected?.(item) ?? selectedItems.includes(item.keyForList ?? '')) && canSelectMultiple), + [isSelected, selectedItems, canSelectMultiple], + ); + /** Calculates on which page is selected item so we can scroll to it on first render */ + const calculateInitialCurrentPage = useCallback(() => { + if (canSelectMultiple || sections.length === 0) { + return 1; + } + + let currentIndex = 0; + for (const section of sections) { + if (section.data) { + for (const item of section.data) { + if (isItemSelected(item)) { + return Math.floor(currentIndex / CONST.MAX_SELECTION_LIST_PAGE_LENGTH) + 1; + } + currentIndex++; + } + } + } + return 1; + }, [canSelectMultiple, isItemSelected, sections]); + const [currentPage, setCurrentPage] = useState(() => calculateInitialCurrentPage()); const isTextInputFocusedRef = useRef(false); const {singleExecution} = useSingleExecution(); const [itemHeights, setItemHeights] = useState>({}); + const pendingScrollIndexRef = useRef(null); const onItemLayout = (event: LayoutChangeEvent, itemKey: string | null | undefined) => { if (!itemKey) { @@ -187,11 +211,6 @@ function BaseSelectionList( const incrementPage = () => setCurrentPage((prev) => prev + 1); - const isItemSelected = useCallback( - (item: TItem) => item.isSelected ?? ((isSelected?.(item) ?? selectedItems.includes(item.keyForList ?? '')) && canSelectMultiple), - [isSelected, selectedItems, canSelectMultiple], - ); - const canShowProductTrainingTooltipMemo = useMemo(() => { return canShowProductTrainingTooltip && isFocused; }, [canShowProductTrainingTooltip, isFocused]); @@ -324,6 +343,17 @@ function BaseSelectionList( return; } + // Calculate which page is needed to show this index + const requiredPage = Math.ceil((index + 1) / CONST.MAX_SELECTION_LIST_PAGE_LENGTH); + + // If the required page is beyond the current page, load all pages up to it, + // then return early and let the scroll happen after the page update + if (requiredPage > currentPage) { + pendingScrollIndexRef.current = index; + setCurrentPage(requiredPage); + return; + } + const itemIndex = item.index ?? -1; const sectionIndex = item.sectionIndex ?? -1; let viewOffsetToKeepFocusedItemAtTopOfViewableArea = 0; @@ -340,10 +370,11 @@ function BaseSelectionList( } listRef.current.scrollToLocation({sectionIndex, itemIndex, animated, viewOffset: variables.contentHeaderHeight - viewOffsetToKeepFocusedItemAtTopOfViewableArea}); + pendingScrollIndexRef.current = null; }, // eslint-disable-next-line react-compiler/react-compiler, react-hooks/exhaustive-deps - [flattenedSections.allOptions], + [flattenedSections.allOptions, currentPage], ); const [disabledArrowKeyIndexes, setDisabledArrowKeyIndexes] = useState(flattenedSections.disabledArrowKeyOptionsIndexes); @@ -356,6 +387,21 @@ function BaseSelectionList( // eslint-disable-next-line react-compiler/react-compiler, react-hooks/exhaustive-deps }, [flattenedSections.disabledArrowKeyOptionsIndexes]); + /** Check whether there is a need to scroll to an item and if all items are loaded */ + useEffect(() => { + if (pendingScrollIndexRef.current === null) { + return; + } + + const indexToScroll = pendingScrollIndexRef.current; + const targetItem = flattenedSections.allOptions.at(indexToScroll); + + if (targetItem && indexToScroll < CONST.MAX_SELECTION_LIST_PAGE_LENGTH * currentPage) { + pendingScrollIndexRef.current = null; + scrollToIndex(indexToScroll, true); + } + }, [currentPage, scrollToIndex, flattenedSections.allOptions]); + const debouncedScrollToIndex = useMemo(() => lodashDebounce(scrollToIndex, CONST.TIMING.LIST_SCROLLING_DEBOUNCE_TIME, {leading: true, trailing: true}), [scrollToIndex]); const setHasKeyBeenPressed = useCallback(() => { @@ -770,6 +816,21 @@ function BaseSelectionList( ) { return; } + // Reset the current page to 1 when the user types something + if (prevTextInputValue !== textInputValue) { + setCurrentPage(1); + } + + // When clearing the search, scroll to the selected item if one exists and is different from last one + if (prevTextInputValue !== '' && textInputValue === '') { + const foundSelectedItemIndex = flattenedSections.allOptions.findIndex(isItemSelected); + const singleSectionList = slicedSections.length < 2; + if (foundSelectedItemIndex !== -1 && singleSectionList) { + updateAndScrollToFocusedIndex(foundSelectedItemIndex); + return; + } + } + // Remove the focus if the search input is empty and prev search input not empty or selected options length is changed (and allOptions length remains the same) // else focus on the first non disabled item const newSelectedIndex = @@ -778,9 +839,6 @@ function BaseSelectionList( ? -1 : 0; - // Reset the current page to 1 when the user types something - setCurrentPage(1); - updateAndScrollToFocusedIndex(newSelectedIndex); }, [ canSelectMultiple, @@ -792,6 +850,9 @@ function BaseSelectionList( prevSelectedOptionsLength, prevAllOptionsLength, shouldUpdateFocusedIndex, + flattenedSections.allOptions, + isItemSelected, + slicedSections.length, ]); useEffect( diff --git a/tests/unit/BaseSelectionListTest.tsx b/tests/unit/BaseSelectionListTest.tsx index 575476b354c7..faf5c7395dd1 100644 --- a/tests/unit/BaseSelectionListTest.tsx +++ b/tests/unit/BaseSelectionListTest.tsx @@ -1,5 +1,6 @@ import * as NativeNavigation from '@react-navigation/native'; import {fireEvent, render, screen} from '@testing-library/react-native'; +import {useState} from 'react'; import {SectionList} from 'react-native'; import BaseSelectionList from '@components/SelectionList/BaseSelectionList'; import RadioListItem from '@components/SelectionList/RadioListItem'; @@ -10,6 +11,9 @@ import CONST from '@src/CONST'; type BaseSelectionListSections = { sections: SelectionListProps['sections']; canSelectMultiple?: boolean; + initialNumToRender?: number; + searchText?: string; + setSearchText?: (searchText: string) => void; }; const mockSections = Array.from({length: 10}, (_, index) => ({ @@ -18,6 +22,18 @@ const mockSections = Array.from({length: 10}, (_, index) => ({ isSelected: index === 1, })); +const largeMockSections = Array.from({length: 100}, (_, index) => ({ + text: `Item ${index}`, + keyForList: `${index}`, + isSelected: index === 1, +})); + +const largeMockSectionsWithSelectedItemFromSecondPage = Array.from({length: 100}, (_, index) => ({ + text: `Item ${index}`, + keyForList: `${index}`, + isSelected: index === 70, +})); + jest.mock('@src/components/ConfirmedRoute.tsx'); jest.mock('@react-navigation/native', () => { const actualNav = jest.requireActual('@react-navigation/native'); @@ -28,20 +44,31 @@ jest.mock('@react-navigation/native', () => { }; }); +jest.mock('@hooks/useLocalize', () => + jest.fn(() => ({ + translate: jest.fn((key: string) => key), + numberFormat: jest.fn((num: number) => num.toString()), + })), +); + describe('BaseSelectionList', () => { const onSelectRowMock = jest.fn(); function BaseListItemRenderer(props: BaseSelectionListSections) { - const {sections, canSelectMultiple} = props; + const {sections, canSelectMultiple, initialNumToRender, setSearchText, searchText} = props; const focusedKey = sections[0].data.find((item) => item.isSelected)?.keyForList; return ( ); } @@ -87,4 +114,102 @@ describe('BaseSelectionList', () => { fireEvent.press(screen.getByTestId(`${CONST.BASE_LIST_ITEM_TEST_ID}0`)); expect(spy).toHaveBeenCalledWith(expect.objectContaining({itemIndex: 0})); }); + + it('should show only elements from first page and Show More button when items exceed page limit', () => { + render( + , + ); + + // Should render exactly first page (50 items) + expect(screen.getByTestId(`${CONST.BASE_LIST_ITEM_TEST_ID}0`)).toBeTruthy(); + expect(screen.getByTestId(`${CONST.BASE_LIST_ITEM_TEST_ID}49`)).toBeTruthy(); + + // Should NOT render items from second page + expect(screen.queryByTestId(`${CONST.BASE_LIST_ITEM_TEST_ID}50`)).toBeFalsy(); + expect(screen.queryByTestId(`${CONST.BASE_LIST_ITEM_TEST_ID}99`)).toBeFalsy(); + + expect(screen.getByText('common.showMore')).toBeTruthy(); + expect(screen.getByText('50')).toBeTruthy(); + expect(screen.getByText('100')).toBeTruthy(); + }); + + it('should hide Show More button when items fit on one page', () => { + render( + , + ); + + expect(screen.queryByText('common.showMore')).toBeFalsy(); + expect(screen.getByTestId(`${CONST.BASE_LIST_ITEM_TEST_ID}0`)).toBeTruthy(); + expect(screen.getByTestId(`${CONST.BASE_LIST_ITEM_TEST_ID}9`)).toBeTruthy(); + }); + + it('should load more items when Show More button is clicked', () => { + render( + , + ); + + // Click Show More button + fireEvent.press(screen.getByText('common.showMore')); + + // Should now show items from second page + expect(screen.getByTestId(`${CONST.BASE_LIST_ITEM_TEST_ID}50`)).toBeTruthy(); + expect(screen.getByTestId(`${CONST.BASE_LIST_ITEM_TEST_ID}99`)).toBeTruthy(); + + // Should not show, Show more button as we rendered whole list + expect(screen.queryByText('common.showMore')).toBeFalsy(); + }); + + it('should search for first item then scroll back to preselected item when search is cleared', () => { + function SearchableListWrapper() { + const [searchText, setSearchText] = useState(''); + + // Filter sections based on search text + const filteredSections = searchText + ? largeMockSectionsWithSelectedItemFromSecondPage.filter((item) => item.text.toLowerCase().includes(searchText.toLowerCase())) + : largeMockSectionsWithSelectedItemFromSecondPage; + + return ( + + ); + } + + render(); + + // Initially should show item 70 as selected and visible + expect(screen.getByTestId(`${CONST.BASE_LIST_ITEM_TEST_ID}70`)).toBeTruthy(); + expect(screen.getByTestId(`${CONST.BASE_LIST_ITEM_TEST_ID}70`)).toBeSelected(); + + // Search for "Item 0" + fireEvent.changeText(screen.getByTestId('selection-list-text-input'), 'Item 0'); + + // Should show only the first item (Item 0) in search results + expect(screen.getByTestId(`${CONST.BASE_LIST_ITEM_TEST_ID}0`)).toBeTruthy(); + expect(screen.queryByTestId(`${CONST.BASE_LIST_ITEM_TEST_ID}70`)).toBeFalsy(); + expect(screen.queryByTestId(`${CONST.BASE_LIST_ITEM_TEST_ID}1`)).toBeFalsy(); + + // Clear the search text + fireEvent.changeText(screen.getByTestId('selection-list-text-input'), ''); + + // Should show the preselected item 70 + expect(screen.getByTestId(`${CONST.BASE_LIST_ITEM_TEST_ID}70`)).toBeTruthy(); + expect(screen.getByTestId(`${CONST.BASE_LIST_ITEM_TEST_ID}70`)).toBeSelected(); + }); }); From 46f73183750fdcb4c866a00df79b2227909dc94b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Muzyk?= Date: Wed, 30 Jul 2025 14:49:40 +0200 Subject: [PATCH 2/3] fix: remove multiple select list from condition causing scroll on search clear --- src/components/SelectionList/BaseSelectionList.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/components/SelectionList/BaseSelectionList.tsx b/src/components/SelectionList/BaseSelectionList.tsx index 46fd6695706d..bec06076b099 100644 --- a/src/components/SelectionList/BaseSelectionList.tsx +++ b/src/components/SelectionList/BaseSelectionList.tsx @@ -825,7 +825,7 @@ function BaseSelectionList( if (prevTextInputValue !== '' && textInputValue === '') { const foundSelectedItemIndex = flattenedSections.allOptions.findIndex(isItemSelected); const singleSectionList = slicedSections.length < 2; - if (foundSelectedItemIndex !== -1 && singleSectionList) { + if (foundSelectedItemIndex !== -1 && singleSectionList && !canSelectMultiple) { updateAndScrollToFocusedIndex(foundSelectedItemIndex); return; } From f6701077278063356ed281e61cb79d950ccbe6bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Muzyk?= Date: Mon, 4 Aug 2025 09:53:04 +0200 Subject: [PATCH 3/3] fix: handle no results edge case --- src/components/SelectionList/BaseSelectionList.tsx | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/components/SelectionList/BaseSelectionList.tsx b/src/components/SelectionList/BaseSelectionList.tsx index bec06076b099..fd99b2eca6c8 100644 --- a/src/components/SelectionList/BaseSelectionList.tsx +++ b/src/components/SelectionList/BaseSelectionList.tsx @@ -816,21 +816,24 @@ function BaseSelectionList( ) { return; } - // Reset the current page to 1 when the user types something - if (prevTextInputValue !== textInputValue) { - setCurrentPage(1); - } - // When clearing the search, scroll to the selected item if one exists and is different from last one + // Handle clearing search if (prevTextInputValue !== '' && textInputValue === '') { const foundSelectedItemIndex = flattenedSections.allOptions.findIndex(isItemSelected); const singleSectionList = slicedSections.length < 2; if (foundSelectedItemIndex !== -1 && singleSectionList && !canSelectMultiple) { + const requiredPage = Math.ceil((foundSelectedItemIndex + 1) / CONST.MAX_SELECTION_LIST_PAGE_LENGTH); + setCurrentPage(requiredPage); updateAndScrollToFocusedIndex(foundSelectedItemIndex); return; } } + // Reset the current page to 1 when the user types something + if (prevTextInputValue !== textInputValue) { + setCurrentPage(1); + } + // Remove the focus if the search input is empty and prev search input not empty or selected options length is changed (and allOptions length remains the same) // else focus on the first non disabled item const newSelectedIndex =