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

reset tooltip position on scroll #56209

Merged
merged 17 commits into from
Mar 7, 2025
8 changes: 7 additions & 1 deletion src/components/LHNOptionsList/LHNOptionsList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import useLHNEstimatedListSize from '@hooks/useLHNEstimatedListSize';
import useLocalize from '@hooks/useLocalize';
import useNetwork from '@hooks/useNetwork';
import usePrevious from '@hooks/usePrevious';
import useScrollEventEmitter from '@hooks/useScrollEventEmitter';
import useTheme from '@hooks/useTheme';
import useThemeStyles from '@hooks/useThemeStyles';
import {isValidDraftComment} from '@libs/DraftCommentUtils';
Expand Down Expand Up @@ -68,6 +69,10 @@ function LHNOptionsList({style, contentContainerStyles, data, onSelectRow, optio
onFirstItemRendered();
}, [onFirstItemRendered]);

// 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 emptyLHNSubtitle = useMemo(
() => (
<View style={[styles.alignItemsCenter, styles.flexRow, styles.justifyContentCenter, styles.flexWrap, styles.textAlignCenter]}>
Expand Down Expand Up @@ -262,8 +267,9 @@ function LHNOptionsList({style, contentContainerStyles, data, onSelectRow, optio
if (isWebOrDesktop) {
saveScrollIndex(route, Math.floor(e.nativeEvent.contentOffset.y / estimatedItemSize));
}
triggerScrollEvent();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In theory, we only display 1 educational tooltip at a time. Is it easier if we can reuse the existing scrolling event here

const onScroll = (event: NativeSyntheticEvent<NativeScrollEvent>) => {
onScrollProp(event);
if (!updateInProgress.current) {
updateInProgress.current = true;
DeviceEventEmitter.emit(CONST.EVENTS.SCROLLING, true);
}
};
/**
* Emits when the scrolling has ended.
*/
const onScrollEnd = () => {
DeviceEventEmitter.emit(CONST.EVENTS.SCROLLING, false);
updateInProgress.current = false;
};

And we also introduce additional prop to EducationalTooltip (i.e shouldHideOnScroll). Then we check if it's displayed and shouldHideOnScroll, we will hide/display tooltip. Wdyt?

Copy link
Contributor Author

@mohit6789 mohit6789 Feb 27, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We need show/hide tooltip in scrolling for SearchPage as well so I have created new hook. And in future we need to add more we can reuse same hook. So as per me current implementation can be reused in other places as well. Let me know if you have any other opinion.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The problem with this approach:

  • We're gonna add more places, like InviteMemberListItem, it also use SelectionList.
  • If later, we remove EducationTooltip in those places, let's say this component LHNOptionsList, we probably forgot to remove this scroll event emitter as well.

The new hook is a good idea, I like it. It helps reuse. But if we can also have a way to avoid above concerns, that should be great. Any thoughts? Something like put this new hook into SelectionList

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@hoangzinh I did not understand what you are trying to say. Can you please provide code snippet about your thoughts?

What I understand is, we need to call triggerScrollEvent() whenever scrolling happened, and also this is not limited to SelectionList right? We can have different types of wrapper which can scroll, so I am not sure if we can make changes in one places and it will be applied to all the places.

Copy link
Contributor Author

@mohit6789 mohit6789 Mar 3, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In LHNOptionsList we used FlashList component while in Search we use SelectionListWithModal which internally use SelectionList so I think it is better idea to use the new hook and trigger the event whenever necessary.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm I see the problem. Basically, what I meant is putting useScrollEventEmitter in SelectionList, so other components using SelectionList, we don't need to initialize useScrollEventEmitter anymore. Anyways, I'm good with current, but 2 things:

  • Can you add a comment above this line, to explain why do we need this line? It will help to remove/improve later.

    const triggerScrollEvent = useScrollEventEmitter({tooltipName: CONST.PRODUCT_TRAINING_TOOLTIP_NAMES.SEARCH_FILTER_BUTTON_TOOLTIP});

  • I'm still thinking that we don't need to inject tooltipName into useScrollEventEmitter and simply call useScrollEventEmitter(). Reason: In some components, we have 2-3 kinds of EducationalTooltip. For example, in OptionRowLHN, it has 2 kinds of tooltip

    const tooltip = shouldShowGetStartedTooltip ? CONST.PRODUCT_TRAINING_TOOLTIP_NAMES.CONCEIRGE_LHN_GBR : CONST.PRODUCT_TRAINING_TOOLTIP_NAMES.LHN_WORKSPACE_CHAT_TOOLTIP;

    If we go with current approach, do we need to setup 2 useScrollEventEmitter?

const triggerScrollEvent1 = useScrollEventEmitter({tooltipName: CONST.PRODUCT_TRAINING_TOOLTIP_NAMES. 
});
const triggerScrollEvent2 = useScrollEventEmitter({tooltipName: CONST.PRODUCT_TRAINING_TOOLTIP_NAMES.CONCEIRGE_LHN_GBR});
...

triggerScrollEvent1();
triggerScrollEvent2();

My thoughts here is we can introduce an additional prop shouldHideOnScroll in BaseEducationalTooltip, then only setup 1 useScrollEventEmitter() in OptionRowLHN and pass shouldHideOnScroll={true} here

<EducationalTooltip
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
shouldRender={shouldShowProductTrainingTooltip}
renderTooltipContent={renderProductTrainingTooltip}
anchorAlignment={{
horizontal: shouldShowWokspaceChatTooltip ? CONST.MODAL.ANCHOR_ORIGIN_HORIZONTAL.LEFT : CONST.MODAL.ANCHOR_ORIGIN_HORIZONTAL.RIGHT,
vertical: CONST.MODAL.ANCHOR_ORIGIN_VERTICAL.TOP,
}}
shiftHorizontal={shouldShowWokspaceChatTooltip ? variables.workspaceLHNtooltipShiftHorizontal : variables.gbrTooltipShiftHorizontal}
shiftVertical={shouldShowWokspaceChatTooltip ? 0 : variables.composerTooltipShiftVertical}
wrapperStyle={styles.productTrainingTooltipWrapper}
onTooltipPress={onOptionPress}
>

wdyt? @mohit6789

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let me try to implement it, and see if this will work or not

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changes pushed

},
[estimatedItemSize, isWebOrDesktop, route, saveScrollIndex, saveScrollOffset],
[estimatedItemSize, isWebOrDesktop, route, saveScrollIndex, saveScrollOffset, triggerScrollEvent],
);

const onLayout = useCallback(() => {
Expand Down
1 change: 1 addition & 0 deletions src/components/LHNOptionsList/OptionRowLHN.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,7 @@ function OptionRowLHN({reportID, isFocused = false, onSelectRow = () => {}, opti
shiftVertical={shouldShowWokspaceChatTooltip ? 0 : variables.composerTooltipShiftVertical}
wrapperStyle={styles.productTrainingTooltipWrapper}
onTooltipPress={onOptionPress}
shouldHideOnScroll
>
<View>
<Hoverable>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -359,6 +359,7 @@ function SearchPageHeader({queryJSON, searchName, searchRouterListVisible, hideS
wrapperStyle={styles.productTrainingTooltipWrapper}
renderTooltipContent={renderProductTrainingTooltip}
onTooltipPress={onFiltersButtonPress}
shouldHideOnScroll
>
<Button
innerStyles={[styles.searchAutocompleteInputResults, styles.borderNone, styles.bgTransparent]}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,27 +1,84 @@
import {NavigationContext} from '@react-navigation/native';
import React, {memo, useContext, useEffect, useRef, useState} from 'react';
import type {LayoutRectangle, NativeSyntheticEvent} from 'react-native';
import React, {memo, useCallback, useContext, useEffect, useLayoutEffect, useRef, useState} from 'react';
import type {LayoutRectangle, NativeMethods, NativeSyntheticEvent} from 'react-native';
import {DeviceEventEmitter, Dimensions} from 'react-native';
import GenericTooltip from '@components/Tooltip/GenericTooltip';
import type {EducationalTooltipProps} from '@components/Tooltip/types';
import measureTooltipCoordinate from './measureTooltipCoordinate';
import type {EducationalTooltipProps, GenericTooltipState} from '@components/Tooltip/types';
import useSafeAreaInsets from '@hooks/useSafeAreaInsets';
import variables from '@styles/variables';
import CONST from '@src/CONST';
import measureTooltipCoordinate, {getTooltipCoordinates} from './measureTooltipCoordinate';

type LayoutChangeEventWithTarget = NativeSyntheticEvent<{layout: LayoutRectangle; target: HTMLElement}>;

type ScrollingEventData = {
isScrolling: boolean;
};
/**
* A component used to wrap an element intended for displaying a tooltip.
* This tooltip would show immediately without user's interaction and hide after 5 seconds.
*/
function BaseEducationalTooltip({children, shouldRender = false, shouldHideOnNavigate = true, ...props}: EducationalTooltipProps) {
const hideTooltipRef = useRef<() => void>();
function BaseEducationalTooltip({children, shouldRender = false, shouldHideOnNavigate = true, shouldHideOnScroll = false, ...props}: EducationalTooltipProps) {
const genericTooltipStateRef = useRef<GenericTooltipState>();
const tooltipElementRef = useRef<React.Component & Readonly<NativeMethods>>();

const [shouldMeasure, setShouldMeasure] = useState(false);
const show = useRef<() => void>();

const navigator = useContext(NavigationContext);
const insets = useSafeAreaInsets();

const setTooltipPosition = useCallback(
(isScrolling: boolean) => {
if (!shouldHideOnScroll || !genericTooltipStateRef.current || !tooltipElementRef.current) {
return;
}

const {hideTooltip, showTooltip, updateTargetBounds} = genericTooltipStateRef.current;
if (isScrolling) {
hideTooltip();
} else {
getTooltipCoordinates(tooltipElementRef.current, (bounds) => {
updateTargetBounds(bounds);
const {y, height} = bounds;

const offset = 10; // Tooltip hides when content moves 10px past header/footer.
const dimensions = Dimensions.get('screen');
const top = y - (insets.top || 0);
const bottom = y + height + insets.bottom || 0;

// Calculate the available space at the top, considering the header height and offset
const availableHeightForTop = top - (variables.contentHeaderHeight - offset);

// Calculate the total height available after accounting for the bottom tab and offset
const availableHeightForBottom = dimensions.height - (bottom + variables.bottomTabHeight - offset);

if (availableHeightForTop < 0 || availableHeightForBottom < 0) {
hideTooltip();
} else {
showTooltip();
}
});
}
},
[insets, shouldHideOnScroll],
);

useLayoutEffect(() => {
if (!shouldRender || !shouldHideOnScroll) {
return;
}
setTooltipPosition(false);
const scrollingListener = DeviceEventEmitter.addListener(CONST.EVENTS.SCROLLING, ({isScrolling}: ScrollingEventData = {isScrolling: false}) => {
setTooltipPosition(isScrolling);
});

return () => scrollingListener.remove();
}, [shouldRender, shouldHideOnScroll, setTooltipPosition]);

useEffect(() => {
return () => {
hideTooltipRef.current?.();
genericTooltipStateRef.current?.hideTooltip();
};
}, []);

Expand All @@ -30,7 +87,7 @@ function BaseEducationalTooltip({children, shouldRender = false, shouldHideOnNav
return;
}
if (!shouldRender) {
hideTooltipRef.current?.();
genericTooltipStateRef.current?.hideTooltip();
return;
}
// When tooltip is used inside an animated view (e.g. popover), we need to wait for the animation to finish before measuring content.
Expand All @@ -50,7 +107,7 @@ function BaseEducationalTooltip({children, shouldRender = false, shouldHideOnNav
if (!shouldHideOnNavigate) {
return;
}
hideTooltipRef.current?.();
genericTooltipStateRef.current?.hideTooltip();
});
return unsubscribe;
}, [navigator, shouldHideOnNavigate]);
Expand All @@ -63,16 +120,18 @@ function BaseEducationalTooltip({children, shouldRender = false, shouldHideOnNav
// eslint-disable-next-line react/jsx-props-no-spreading
{...props}
>
{({showTooltip, hideTooltip, updateTargetBounds}) => {
{(genericTooltipState) => {
const {updateTargetBounds, showTooltip} = genericTooltipState;
// eslint-disable-next-line react-compiler/react-compiler
hideTooltipRef.current = hideTooltip;
genericTooltipStateRef.current = genericTooltipState;
return React.cloneElement(children as React.ReactElement, {
onLayout: (e: LayoutChangeEventWithTarget) => {
if (!shouldMeasure) {
setShouldMeasure(true);
}
// e.target is specific to native, use e.nativeEvent.target on web instead
const target = e.target || e.nativeEvent.target;
tooltipElementRef.current = target;
show.current = () => measureTooltipCoordinate(target, updateTargetBounds, showTooltip);
},
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,11 @@ export default function measureTooltipCoordinate(target: React.Component & Reado
showTooltip();
});
}

function getTooltipCoordinates(target: React.Component & Readonly<NativeMethods>, callback: (rect: LayoutRectangle) => void) {
return target?.measure((x, y, width, height, px, py) => {
callback({height, width, x: px, y: py});
});
}

export {getTooltipCoordinates};
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,11 @@ export default function measureTooltipCoordinate(target: React.Component & Reado
showTooltip();
});
}

function getTooltipCoordinates(target: React.Component & Readonly<NativeMethods>, callback: (rect: LayoutRectangle) => void) {
return target?.measureInWindow((x, y, width, height) => {
callback({height, width, x, y});
});
}

export {getTooltipCoordinates};
5 changes: 4 additions & 1 deletion src/components/Tooltip/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,9 @@ type EducationalTooltipProps = ChildrenProps &

/** Whether the tooltip should hide when navigating */
shouldHideOnNavigate?: boolean;

/** Whether the tooltip should hide during scrolling */
shouldHideOnScroll?: boolean;
};

type TooltipExtendedProps = (EducationalTooltipProps | TooltipProps) & {
Expand All @@ -95,4 +98,4 @@ type TooltipExtendedProps = (EducationalTooltipProps | TooltipProps) & {
};

export default TooltipProps;
export type {EducationalTooltipProps, GenericTooltipProps, SharedTooltipProps, TooltipExtendedProps};
export type {EducationalTooltipProps, GenericTooltipProps, SharedTooltipProps, TooltipExtendedProps, GenericTooltipState};
49 changes: 49 additions & 0 deletions src/hooks/useScrollEventEmitter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import {useCallback, useEffect, useRef} from 'react';
import {DeviceEventEmitter} from 'react-native';
import CONST from '@src/CONST';

/**
* This hook tracks scroll events and emits a "scrolling" event when scrolling starts and ends.
*/
const useScrollEventEmitter = () => {
const isScrollingRef = useRef<boolean>(false);
const timeoutRef = useRef<NodeJS.Timeout | null>(null);

const triggerScrollEvent = useCallback(() => {
const emitScrolling = (isScrolling: boolean) => {
DeviceEventEmitter.emit(CONST.EVENTS.SCROLLING, {
isScrolling,
});
};

// Start emitting the scrolling event when the scroll begins
if (!isScrollingRef.current) {
emitScrolling(true);
isScrollingRef.current = true;
}

// End the scroll and emit after a brief timeout to detect the end of scrolling
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}

timeoutRef.current = setTimeout(() => {
emitScrolling(false);
isScrollingRef.current = false;
}, 250);
}, []);

// Cleanup timeout on unmount
useEffect(() => {
return () => {
if (!timeoutRef.current) {
return;
}
clearTimeout(timeoutRef.current);
};
}, []);

return triggerScrollEvent;
};

export default useScrollEventEmitter;
8 changes: 7 additions & 1 deletion src/pages/Search/SearchPageNarrow.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React, {useCallback, useState} from 'react';
import {View} from 'react-native';
import {useOnyx} from 'react-native-onyx';
import Animated, {clamp, useAnimatedScrollHandler, useAnimatedStyle, useSharedValue, withTiming} from 'react-native-reanimated';
import Animated, {clamp, runOnJS, useAnimatedScrollHandler, useAnimatedStyle, useSharedValue, withTiming} from 'react-native-reanimated';
import FullPageNotFoundView from '@components/BlockingViews/FullPageNotFoundView';
import HeaderWithBackButton from '@components/HeaderWithBackButton';
import BottomTabBar from '@components/Navigation/BottomTabBar';
Expand All @@ -15,6 +15,7 @@ import SearchStatusBar from '@components/Search/SearchPageHeader/SearchStatusBar
import type {SearchQueryJSON} from '@components/Search/types';
import useLocalize from '@hooks/useLocalize';
import useResponsiveLayout from '@hooks/useResponsiveLayout';
import useScrollEventEmitter from '@hooks/useScrollEventEmitter';
import useStyleUtils from '@hooks/useStyleUtils';
import useThemeStyles from '@hooks/useThemeStyles';
import useWindowDimensions from '@hooks/useWindowDimensions';
Expand Down Expand Up @@ -47,6 +48,10 @@ function SearchPageNarrow({queryJSON, policyID, searchName, shouldGroupByReports
const {clearSelectedTransactions} = useSearchContext();
const [searchRouterListVisible, setSearchRouterListVisible] = useState(false);

// 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 handleBackButtonPress = useCallback(() => {
if (!selectionMode?.isEnabled) {
return false;
Expand All @@ -65,6 +70,7 @@ function SearchPageNarrow({queryJSON, policyID, searchName, shouldGroupByReports

const scrollHandler = useAnimatedScrollHandler({
onScroll: (event) => {
runOnJS(triggerScrollEvent)();
const {contentOffset, layoutMeasurement, contentSize} = event;
if (windowHeight > contentSize.height) {
return;
Expand Down