Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
54 changes: 44 additions & 10 deletions src/components/ScrollOffsetContextProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import {findFocusedRoute} from '@react-navigation/native';
import type {ParamListBase} from '@react-navigation/native';
import React, {createContext, useCallback, useEffect, useMemo, useRef} from 'react';
import useOnyx from '@hooks/useOnyx';
Expand Down Expand Up @@ -40,11 +41,21 @@ const defaultValue: ScrollOffsetContextValue = {

const ScrollOffsetContext = createContext<ScrollOffsetContextValue>(defaultValue);

/** This function is prepared to work with HOME screens. May need modification if we want to handle other types of screens. */
/** This function is prepared to work with HOME and SEARCH screens. */
function getKey(route: PlatformStackRouteProp<ParamListBase> | NavigationPartialRoute): string {
// Handle routes with direct policyID parameter (HOME screens)
if (route.params && 'policyID' in route.params && typeof route.params.policyID === 'string') {
return `${route.name}-${route.params.policyID}`;
}

// Handle SEARCH screens with query parameters
if (route.name === SCREENS.SEARCH.ROOT && route.params && 'q' in route.params && typeof route.params.q === 'string') {
// Encode the query to handle spaces and special characters
const encodedQuery = encodeURIComponent(route.params.q);
return `${route.name}-${encodedQuery}`;
}

// For other routes, just use route name
return `${route.name}-global`;
}

Expand All @@ -58,9 +69,9 @@ function ScrollOffsetContextProvider({children}: ScrollOffsetContextProviderProp
return;
}

// If the priority mode changes, we need to clear the scroll offsets for the home screens because it affects the size of the elements and scroll positions wouldn't be correct.
// If the priority mode changes, we need to clear the scroll offsets for the home and search screens because it affects the size of the elements and scroll positions wouldn't be correct.
for (const key of Object.keys(scrollOffsetsRef.current)) {
if (key.includes(SCREENS.HOME)) {
if (key.includes(SCREENS.HOME) || key.includes(SCREENS.SEARCH.ROOT)) {
delete scrollOffsetsRef.current[key];
}
}
Expand All @@ -77,16 +88,39 @@ function ScrollOffsetContextProvider({children}: ScrollOffsetContextProviderProp
return scrollOffsetsRef.current[getKey(route)];
}, []);

const cleanStaleScrollOffsets: ScrollOffsetContextValue['cleanStaleScrollOffsets'] = useCallback((state) => {
const sidebarRoutes = state.routes.filter((route) => isSidebarScreenName(route.name));
const scrollOffsetKeysOfExistingScreens = sidebarRoutes.map((route) => getKey(route));
for (const key of Object.keys(scrollOffsetsRef.current)) {
if (!scrollOffsetKeysOfExistingScreens.includes(key)) {
delete scrollOffsetsRef.current[key];
const cleanScrollOffsets = useCallback((keys: string[], shouldDelete: (key: string) => boolean) => {
keys.forEach((key) => {
if (!shouldDelete(key)) {
return;
}
}

delete scrollOffsetsRef.current[key];
});
}, []);

const cleanStaleScrollOffsets: ScrollOffsetContextValue['cleanStaleScrollOffsets'] = useCallback(
(state) => {
const sidebarRoutes = state.routes.filter((route) => isSidebarScreenName(route.name));
const existingScreenKeys = sidebarRoutes.map(getKey);

const focusedRoute = findFocusedRoute(state);
const routeName = focusedRoute?.name;

const isSearchScreen = routeName === SCREENS.SEARCH.ROOT;
const isSearchMoneyRequestReport = routeName === SCREENS.SEARCH.MONEY_REQUEST_REPORT || routeName === SCREENS.SEARCH.REPORT_RHP;

const scrollOffsetKeys = Object.keys(scrollOffsetsRef.current);

if (isSearchScreen || isSearchMoneyRequestReport) {
const currentKey = focusedRoute ? getKey(focusedRoute) : null;
cleanScrollOffsets(scrollOffsetKeys, (key) => key.startsWith(SCREENS.SEARCH.ROOT) && key !== currentKey && !isSearchMoneyRequestReport);
return;
}
cleanScrollOffsets(scrollOffsetKeys, (key) => !existingScreenKeys.includes(key));
},
[cleanScrollOffsets],
);

const saveScrollIndex: ScrollOffsetContextValue['saveScrollIndex'] = useCallback((route, scrollIndex) => {
scrollOffsetsRef.current[getKey(route)] = scrollIndex;
}, []);
Expand Down
20 changes: 17 additions & 3 deletions src/components/Search/SearchList/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {useRoute} from '@react-navigation/native';
import {useFocusEffect, useRoute} from '@react-navigation/native';
import type {FlashListProps, FlashListRef, ViewToken} from '@shopify/flash-list';
import React, {forwardRef, useCallback, useImperativeHandle, useMemo, useRef, useState} from 'react';
import React, {forwardRef, useCallback, useContext, useImperativeHandle, useMemo, useRef, useState} from 'react';
import type {ForwardedRef} from 'react';
import {View} from 'react-native';
import type {NativeSyntheticEvent, StyleProp, ViewStyle} from 'react-native';
Expand All @@ -11,6 +11,7 @@ import MenuItem from '@components/MenuItem';
import Modal from '@components/Modal';
import {usePersonalDetails} from '@components/OnyxListItemProvider';
import {PressableWithFeedback} from '@components/Pressable';
import {ScrollOffsetContext} from '@components/ScrollOffsetContextProvider';
import type {SearchColumnType, SearchQueryJSON} from '@components/Search/types';
import type ChatListItem from '@components/SelectionList/ChatListItem';
import type TaskListItem from '@components/SelectionList/Search/TaskListItem';
Expand Down Expand Up @@ -184,6 +185,7 @@ function SearchList(
const [userBillingFundID] = useOnyx(ONYXKEYS.NVP_BILLING_FUND_ID, {canBeMissing: true});

const route = useRoute();
const {getScrollOffset} = useContext(ScrollOffsetContext);

const handleLongPressRow = useCallback(
(item: SearchListItem) => {
Expand Down Expand Up @@ -238,6 +240,19 @@ function SearchList(
[data],
);

useFocusEffect(
useCallback(() => {
const offset = getScrollOffset(route);
requestAnimationFrame(() => {
if (!offset || !listRef.current) {
Comment thread
huult marked this conversation as resolved.
return;
}

listRef.current.scrollToOffset({offset, animated: false});
});
}, [getScrollOffset, route]),
);

useImperativeHandle(ref, () => ({scrollToIndex}), [scrollToIndex]);

const renderItem = useCallback(
Expand Down Expand Up @@ -336,7 +351,6 @@ function SearchList(
)}
</View>
)}

<BaseSearchList
data={data}
renderItem={renderItem}
Expand Down
11 changes: 10 additions & 1 deletion src/pages/Search/SearchPage.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react';
import React, {useCallback, useContext, useEffect, useMemo, useRef, useState} from 'react';
import {InteractionManager, View} from 'react-native';
import FullPageNotFoundView from '@components/BlockingViews/FullPageNotFoundView';
import type {DropdownOption} from '@components/ButtonWithDropdownMenu/types';
Expand All @@ -10,6 +10,7 @@ import DropZoneUI from '@components/DropZone/DropZoneUI';
import * as Expensicons from '@components/Icon/Expensicons';
import type {PopoverMenuItem} from '@components/PopoverMenu';
import ScreenWrapper from '@components/ScreenWrapper';
import {ScrollOffsetContext} from '@components/ScrollOffsetContextProvider';
import Search from '@components/Search';
import {useSearchContext} from '@components/Search/SearchContext';
import SearchPageFooter from '@components/Search/SearchPageFooter';
Expand Down Expand Up @@ -89,6 +90,7 @@ function SearchPage({route}: SearchPageProps) {
const [isDownloadExportModalVisible, setIsDownloadExportModalVisible] = useState(false);
const [isExportWithTemplateModalVisible, setIsExportWithTemplateModalVisible] = useState(false);
const queryJSON = useMemo(() => buildSearchQueryJSON(route.params.q), [route.params.q]);
const {saveScrollOffset} = useContext(ScrollOffsetContext);

// eslint-disable-next-line rulesdir/no-default-id-values
const [currentSearchResults] = useOnyx(`${ONYXKEYS.COLLECTION.SNAPSHOT}${queryJSON?.hash ?? CONST.DEFAULT_NUMBER_ID}`, {canBeMissing: true});
Expand Down Expand Up @@ -779,6 +781,13 @@ function SearchPage({route}: SearchPageProps) {
searchResults={searchResults}
handleSearch={handleSearchAction}
isMobileSelectionModeEnabled={isMobileSelectionModeEnabled}
onSearchListScroll={(e) => {
if (!e.nativeEvent.contentOffset.y) {
return;
}

saveScrollOffset(route, e.nativeEvent.contentOffset.y);
}}
/>
{shouldShowFooter && <SearchPageFooter metadata={metadata} />}
<DragAndDropConsumer onDrop={initScanRequest}>
Expand Down
8 changes: 7 additions & 1 deletion src/pages/Search/SearchPageNarrow.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import React, {useCallback, useState} from 'react';
import {useRoute} from '@react-navigation/native';
import React, {useCallback, useContext, useState} from 'react';
import {View} from 'react-native';
import Animated, {clamp, runOnJS, useAnimatedScrollHandler, useAnimatedStyle, useSharedValue, withTiming} from 'react-native-reanimated';
import FullPageNotFoundView from '@components/BlockingViews/FullPageNotFoundView';
Expand All @@ -8,6 +9,7 @@ import NavigationTabBar from '@components/Navigation/NavigationTabBar';
import NAVIGATION_TABS from '@components/Navigation/NavigationTabBar/NAVIGATION_TABS';
import TopBar from '@components/Navigation/TopBar';
import ScreenWrapper from '@components/ScreenWrapper';
import {ScrollOffsetContext} from '@components/ScrollOffsetContextProvider';
import Search from '@components/Search';
import {useSearchContext} from '@components/Search/SearchContext';
import SearchPageFooter from '@components/Search/SearchPageFooter';
Expand Down Expand Up @@ -61,6 +63,8 @@ function SearchPageNarrow({queryJSON, headerButtonsOptions, searchResults, isMob
// Controls the visibility of the educational tooltip based on user scrolling.
// Hides the tooltip when the user is scrolling and displays it once scrolling stops.
const triggerScrollEvent = useScrollEventEmitter();
const route = useRoute();
const {saveScrollOffset} = useContext(ScrollOffsetContext);

const scrollOffset = useSharedValue(0);
const topBarOffset = useSharedValue<number>(StyleUtils.searchHeaderDefaultOffset);
Expand Down Expand Up @@ -93,6 +97,8 @@ function SearchPageNarrow({queryJSON, headerButtonsOptions, searchResults, isMob
const isScrollingDown = currentOffset > scrollOffset.get();
const distanceScrolled = currentOffset - scrollOffset.get();

runOnJS(saveScrollOffset)(route, currentOffset);

if (isScrollingDown && contentOffset.y > TOO_CLOSE_TO_TOP_DISTANCE) {
topBarOffset.set(clamp(topBarOffset.get() - distanceScrolled, variables.minimalTopBarOffset, StyleUtils.searchHeaderDefaultOffset));
} else if (!isScrollingDown && distanceScrolled < 0 && contentOffset.y + layoutMeasurement.height < contentSize.height - TOO_CLOSE_TO_BOTTOM_DISTANCE) {
Expand Down
Loading