-
Notifications
You must be signed in to change notification settings - Fork 2.9k
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
Hoverable Component refactor #31518
Hoverable Component refactor #31518
Changes from 22 commits
5504cc0
cb8a310
8669939
87d8979
a78b9f8
772fae1
8276438
1f910d2
0129ddb
a2bf1a5
cb964d5
dfa7be4
88bb94c
e0fe2e5
4b49dc2
182fd8d
60bc902
c63786a
5464c33
963c6d0
81c8e42
2dd8968
783c64a
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,137 @@ | ||
import {cloneElement, forwardRef, Ref, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState} from 'react'; | ||
import {DeviceEventEmitter} from 'react-native'; | ||
import assignRef from '@libs/assignRef'; | ||
import CONST from '@src/CONST'; | ||
import HoverableProps from './types'; | ||
|
||
type ActiveHoverableProps = Omit<HoverableProps, 'disabled'>; | ||
|
||
function ActiveHoverable({onHoverIn, onHoverOut, shouldHandleScroll, children}: ActiveHoverableProps, outerRef: Ref<HTMLElement>) { | ||
const [isHovered, setIsHovered] = useState(false); | ||
|
||
const elementRef = useRef<HTMLElement | null>(null); | ||
const isScrollingRef = useRef(false); | ||
const isHoveredRef = useRef(false); | ||
|
||
const updateIsHovered = useCallback( | ||
(hovered: boolean) => { | ||
isHoveredRef.current = hovered; | ||
if (shouldHandleScroll && isScrollingRef.current) { | ||
return; | ||
} | ||
setIsHovered(hovered); | ||
}, | ||
[shouldHandleScroll], | ||
); | ||
|
||
// Expose inner ref to parent through outerRef. This enable us to use ref both in parent and child. | ||
useImperativeHandle<HTMLElement | null, HTMLElement | null>(outerRef, () => elementRef.current, []); | ||
|
||
useEffect(() => { | ||
if (isHovered) { | ||
onHoverIn?.(); | ||
} else { | ||
onHoverOut?.(); | ||
} | ||
}, [isHovered, onHoverIn, onHoverOut]); | ||
|
||
useEffect(() => { | ||
kacper-mikolajczak marked this conversation as resolved.
Show resolved
Hide resolved
|
||
if (!shouldHandleScroll) { | ||
return; | ||
} | ||
|
||
const scrollingListener = DeviceEventEmitter.addListener(CONST.EVENTS.SCROLLING, (scrolling) => { | ||
isScrollingRef.current = scrolling; | ||
if (!isScrollingRef.current) { | ||
setIsHovered(isHoveredRef.current); | ||
} | ||
}); | ||
|
||
return () => scrollingListener.remove(); | ||
}, [shouldHandleScroll]); | ||
|
||
useEffect(() => { | ||
// Do not mount a listener if the component is not hovered | ||
if (!isHovered) { | ||
return; | ||
} | ||
kacper-mikolajczak marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
/** | ||
* Checks the hover state of a component and updates it based on the event target. | ||
* This is necessary to handle cases where the hover state might get stuck due to an unreliable mouseleave trigger, | ||
* such as when an element is removed before the mouseleave event is triggered. | ||
* @param event The hover event object. | ||
*/ | ||
const unsetHoveredIfOutside = (event: MouseEvent) => { | ||
if (!elementRef.current || elementRef.current.contains(event.target as Node)) { | ||
return; | ||
} | ||
|
||
setIsHovered(false); | ||
}; | ||
|
||
document.addEventListener('mouseover', unsetHoveredIfOutside); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. While it's definitely not the first time we subscribed to an HTML event, I believe it would also be beneficial to extract an utility like: function useEventListenerEffect(enabled: boolean, target, callback) There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We could extract the utility, but we need to mkae sure the entire functionality of There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yes, you're right. Also, it would be great to hook into TypeScript's type mapping for HTML event types. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. After careful consideration, I found a few reasons not to implement such solution or at least to not do it here when the scope is quite different. Here is a implementation that I made in order to test the suggestion: const useEventListener = (element: HTMLElement, ...listenerParams: Parameters<typeof addEventListener>) => {
useEffect(() => {
element.addEventListener(...listenerParams);
return () => element.removeEventListener(...listenerParams);
}, [element, listenerParams]);
}; Here are my concerns:
Let me know what you think about it 👍 There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think something like this would work: function useTargetEventEffect<Ev>(
enabled: boolean,
target: EventTarget,
type: string,
listener: (ev: Ev) => void,
options?: boolean | AddEventListenerOptions,
): void {
useEffect(() => {
if (!enabled) {
return;
}
target.addEventListener(type, listener as EventListener, options);
return () => target.removeEventListener(type, listener as EventListener, options);
}, [enabled, target, type, listener, options]);
}
function useDocumentEventEffect<K extends keyof DocumentEventMap>(
enabled: boolean,
type: K,
listener: (ev: DocumentEventMap[K]) => void,
options?: boolean | AddEventListenerOptions,
): void {
useTargetEventEffect(
enabled,
document,
type,
listener,
options,
);
}
function useElementEventEffect<K extends keyof HTMLElementEventMap>(
enabled: boolean,
element: HTMLElement,
type: K,
listener: (ev: HTMLElementEventMap[K]) => void,
options?: boolean | AddEventListenerOptions,
): void {
useTargetEventEffect(
enabled,
element,
type,
listener,
options,
);
} But I'm not 100% sure, this would need to be carefully tested. We can consider this out of scope for now. |
||
|
||
return () => document.removeEventListener('mouseover', unsetHoveredIfOutside); | ||
}, [isHovered, elementRef]); | ||
|
||
useEffect(() => { | ||
const unsetHoveredWhenDocumentIsHidden = () => document.visibilityState === 'hidden' && setIsHovered(false); | ||
|
||
document.addEventListener('visibilitychange', unsetHoveredWhenDocumentIsHidden); | ||
|
||
return () => document.removeEventListener('visibilitychange', unsetHoveredWhenDocumentIsHidden); | ||
}, []); | ||
|
||
const child = useMemo(() => (typeof children === 'function' ? children(!isScrollingRef.current && isHovered) : children), [children, isHovered]); | ||
|
||
const childOnMouseEnter = child.props.onMouseEnter; | ||
const childOnMouseLeave = child.props.onMouseLeave; | ||
|
||
const hoverAndForwardOnMouseEnter = useCallback( | ||
(e: MouseEvent) => { | ||
updateIsHovered(true); | ||
childOnMouseEnter?.(e); | ||
}, | ||
[updateIsHovered, childOnMouseEnter], | ||
); | ||
|
||
const unhoverAndForwardOnMouseLeave = useCallback( | ||
(e: MouseEvent) => { | ||
updateIsHovered(false); | ||
childOnMouseLeave?.(e); | ||
}, | ||
[updateIsHovered, childOnMouseLeave], | ||
); | ||
|
||
const unhoverAndForwardOnBlur = useCallback( | ||
(event: MouseEvent) => { | ||
// Check if the blur event occurred due to clicking outside the element | ||
// and the wrapperView contains the element that caused the blur and reset isHovered | ||
if (!elementRef.current?.contains(event.target as Node) && !elementRef.current?.contains(event.relatedTarget as Node)) { | ||
setIsHovered(false); | ||
} | ||
|
||
child.props.onBlur?.(event); | ||
}, | ||
[child.props], | ||
); | ||
|
||
// We need to access the ref of a children from both parent and current component | ||
// So we pass it to current ref and assign it once again to the child ref prop | ||
const hijackRef = (el: HTMLElement) => { | ||
kacper-mikolajczak marked this conversation as resolved.
Show resolved
Hide resolved
|
||
elementRef.current = el; | ||
if (child.ref) { | ||
assignRef(child.ref, el); | ||
} | ||
}; | ||
|
||
return cloneElement(child, { | ||
ref: hijackRef, | ||
onMouseEnter: hoverAndForwardOnMouseEnter, | ||
onMouseLeave: unhoverAndForwardOnMouseLeave, | ||
onBlur: unhoverAndForwardOnBlur, | ||
}); | ||
} | ||
|
||
export default forwardRef(ActiveHoverable); |
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
@@ -1,212 +1,27 @@ | ||||||
import React, {ForwardedRef, forwardRef, MutableRefObject, ReactElement, RefAttributes, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState} from 'react'; | ||||||
import {DeviceEventEmitter} from 'react-native'; | ||||||
import * as DeviceCapabilities from '@libs/DeviceCapabilities'; | ||||||
import CONST from '@src/CONST'; | ||||||
import React, {cloneElement, forwardRef, Ref} from 'react'; | ||||||
import {hasHoverSupport} from '@libs/DeviceCapabilities'; | ||||||
import ActiveHoverable from './ActiveHoverable'; | ||||||
import HoverableProps from './types'; | ||||||
|
||||||
/** | ||||||
* Maps the children of a Hoverable component to | ||||||
* - a function that is called with the parameter | ||||||
* - the child itself if it is the only child | ||||||
* @param children The children to map. | ||||||
* @param callbackParam The parameter to pass to the children function. | ||||||
* @returns The mapped children. | ||||||
*/ | ||||||
function mapChildren(children: ((isHovered: boolean) => ReactElement) | ReactElement | ReactElement[], callbackParam: boolean): ReactElement & RefAttributes<HTMLElement> { | ||||||
if (Array.isArray(children)) { | ||||||
return children[0]; | ||||||
} | ||||||
|
||||||
if (typeof children === 'function') { | ||||||
return children(callbackParam); | ||||||
} | ||||||
|
||||||
return children; | ||||||
} | ||||||
|
||||||
/** | ||||||
* Assigns a ref to an element, either by setting the current property of the ref object or by calling the ref function | ||||||
* @param ref The ref object or function. | ||||||
* @param element The element to assign the ref to. | ||||||
*/ | ||||||
function assignRef(ref: ((instance: HTMLElement | null) => void) | MutableRefObject<HTMLElement | null>, element: HTMLElement) { | ||||||
if (!ref) { | ||||||
return; | ||||||
} | ||||||
if (typeof ref === 'function') { | ||||||
ref(element); | ||||||
} else if ('current' in ref) { | ||||||
// eslint-disable-next-line no-param-reassign | ||||||
ref.current = element; | ||||||
} | ||||||
} | ||||||
|
||||||
/** | ||||||
* It is necessary to create a Hoverable component instead of relying solely on Pressable support for hover state, | ||||||
* because nesting Pressables causes issues where the hovered state of the child cannot be easily propagated to the | ||||||
* parent. https://github.com/necolas/react-native-web/issues/1875 | ||||||
*/ | ||||||
function Hoverable( | ||||||
{disabled = false, onHoverIn = () => {}, onHoverOut = () => {}, onMouseEnter = () => {}, onMouseLeave = () => {}, children, shouldHandleScroll = false}: HoverableProps, | ||||||
outerRef: ForwardedRef<HTMLElement>, | ||||||
) { | ||||||
const [isHovered, setIsHovered] = useState(false); | ||||||
|
||||||
const isScrolling = useRef(false); | ||||||
const isHoveredRef = useRef(false); | ||||||
const ref = useRef<HTMLElement | null>(null); | ||||||
|
||||||
const updateIsHoveredOnScrolling = useCallback( | ||||||
(hovered: boolean) => { | ||||||
if (disabled) { | ||||||
return; | ||||||
} | ||||||
|
||||||
isHoveredRef.current = hovered; | ||||||
|
||||||
if (shouldHandleScroll && isScrolling.current) { | ||||||
return; | ||||||
} | ||||||
setIsHovered(hovered); | ||||||
}, | ||||||
[disabled, shouldHandleScroll], | ||||||
); | ||||||
|
||||||
useEffect(() => { | ||||||
const unsetHoveredWhenDocumentIsHidden = () => document.visibilityState === 'hidden' && setIsHovered(false); | ||||||
|
||||||
document.addEventListener('visibilitychange', unsetHoveredWhenDocumentIsHidden); | ||||||
|
||||||
return () => document.removeEventListener('visibilitychange', unsetHoveredWhenDocumentIsHidden); | ||||||
}, []); | ||||||
|
||||||
useEffect(() => { | ||||||
if (!shouldHandleScroll) { | ||||||
return; | ||||||
} | ||||||
|
||||||
const scrollingListener = DeviceEventEmitter.addListener(CONST.EVENTS.SCROLLING, (scrolling) => { | ||||||
isScrolling.current = scrolling; | ||||||
if (!scrolling) { | ||||||
setIsHovered(isHoveredRef.current); | ||||||
} | ||||||
}); | ||||||
|
||||||
return () => scrollingListener.remove(); | ||||||
}, [shouldHandleScroll]); | ||||||
|
||||||
useEffect(() => { | ||||||
if (!DeviceCapabilities.hasHoverSupport()) { | ||||||
return; | ||||||
} | ||||||
|
||||||
/** | ||||||
* Checks the hover state of a component and updates it based on the event target. | ||||||
* This is necessary to handle cases where the hover state might get stuck due to an unreliable mouseleave trigger, | ||||||
* such as when an element is removed before the mouseleave event is triggered. | ||||||
* @param event The hover event object. | ||||||
*/ | ||||||
const unsetHoveredIfOutside = (event: MouseEvent) => { | ||||||
if (!ref.current || !isHovered) { | ||||||
return; | ||||||
} | ||||||
|
||||||
if (ref.current.contains(event.target as Node)) { | ||||||
return; | ||||||
} | ||||||
|
||||||
setIsHovered(false); | ||||||
}; | ||||||
|
||||||
document.addEventListener('mouseover', unsetHoveredIfOutside); | ||||||
|
||||||
return () => document.removeEventListener('mouseover', unsetHoveredIfOutside); | ||||||
}, [isHovered]); | ||||||
|
||||||
useEffect(() => { | ||||||
if (!disabled || !isHovered) { | ||||||
return; | ||||||
} | ||||||
setIsHovered(false); | ||||||
}, [disabled, isHovered]); | ||||||
|
||||||
useEffect(() => { | ||||||
if (disabled) { | ||||||
return; | ||||||
} | ||||||
if (onHoverIn && isHovered) { | ||||||
return onHoverIn(); | ||||||
} | ||||||
if (onHoverOut && !isHovered) { | ||||||
return onHoverOut(); | ||||||
} | ||||||
}, [disabled, isHovered, onHoverIn, onHoverOut]); | ||||||
|
||||||
// Expose inner ref to parent through outerRef. This enable us to use ref both in parent and child. | ||||||
useImperativeHandle<HTMLElement | null, HTMLElement | null>(outerRef, () => ref.current, []); | ||||||
|
||||||
const child = useMemo(() => React.Children.only(mapChildren(children, isHovered)), [children, isHovered]); | ||||||
|
||||||
const enableHoveredOnMouseEnter = useCallback( | ||||||
(event: MouseEvent) => { | ||||||
updateIsHoveredOnScrolling(true); | ||||||
onMouseEnter(event); | ||||||
|
||||||
if (typeof child.props.onMouseEnter === 'function') { | ||||||
child.props.onMouseEnter(event); | ||||||
} | ||||||
}, | ||||||
[child.props, onMouseEnter, updateIsHoveredOnScrolling], | ||||||
); | ||||||
|
||||||
const disableHoveredOnMouseLeave = useCallback( | ||||||
(event: MouseEvent) => { | ||||||
updateIsHoveredOnScrolling(false); | ||||||
onMouseLeave(event); | ||||||
|
||||||
if (typeof child.props.onMouseLeave === 'function') { | ||||||
child.props.onMouseLeave(event); | ||||||
} | ||||||
}, | ||||||
[child.props, onMouseLeave, updateIsHoveredOnScrolling], | ||||||
); | ||||||
|
||||||
const disableHoveredOnBlur = useCallback( | ||||||
(event: MouseEvent) => { | ||||||
// Check if the blur event occurred due to clicking outside the element | ||||||
// and the wrapperView contains the element that caused the blur and reset isHovered | ||||||
if (!ref.current?.contains(event.target as Node) && !ref.current?.contains(event.relatedTarget as Node)) { | ||||||
setIsHovered(false); | ||||||
} | ||||||
|
||||||
if (typeof child.props.onBlur === 'function') { | ||||||
child.props.onBlur(event); | ||||||
} | ||||||
}, | ||||||
[child.props], | ||||||
); | ||||||
|
||||||
// We need to access the ref of a children from both parent and current component | ||||||
// So we pass it to current ref and assign it once again to the child ref prop | ||||||
const hijackRef = (el: HTMLElement) => { | ||||||
ref.current = el; | ||||||
if (child.ref) { | ||||||
assignRef(child.ref, el); | ||||||
} | ||||||
}; | ||||||
|
||||||
if (!DeviceCapabilities.hasHoverSupport()) { | ||||||
return React.cloneElement(child, { | ||||||
ref: hijackRef, | ||||||
}); | ||||||
function Hoverable({disabled, ...props}: HoverableProps, ref: Ref<HTMLElement>) { | ||||||
// If Hoverable is disabled, just render the child without additional logic or event listeners. | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. NABish but this prop should be
Suggested change
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Done ✅ |
||||||
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing | ||||||
if (disabled || !hasHoverSupport()) { | ||||||
kacper-mikolajczak marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||
return cloneElement(typeof props.children === 'function' ? props.children(false) : props.children, {ref}); | ||||||
} | ||||||
|
||||||
return React.cloneElement(child, { | ||||||
ref: hijackRef, | ||||||
onMouseEnter: enableHoveredOnMouseEnter, | ||||||
onMouseLeave: disableHoveredOnMouseLeave, | ||||||
onBlur: disableHoveredOnBlur, | ||||||
}); | ||||||
return ( | ||||||
<ActiveHoverable | ||||||
// eslint-disable-next-line react/jsx-props-no-spreading | ||||||
{...props} | ||||||
ref={ref} | ||||||
/> | ||||||
); | ||||||
} | ||||||
|
||||||
export default forwardRef(Hoverable); |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,8 +1,8 @@ | ||
import {ReactElement} from 'react'; | ||
import {ReactElement, RefAttributes} from 'react'; | ||
|
||
type HoverableProps = { | ||
/** Children to wrap with Hoverable. */ | ||
children: ((isHovered: boolean) => ReactElement) | ReactElement; | ||
children: ((isHovered: boolean) => ReactElement & RefAttributes<HTMLElement>) | (ReactElement & RefAttributes<HTMLElement>); | ||
|
||
/** Whether to disable the hover action */ | ||
disabled?: boolean; | ||
|
@@ -13,12 +13,6 @@ type HoverableProps = { | |
/** Function that executes when the mouse leaves the children. */ | ||
onHoverOut?: () => void; | ||
|
||
/** Direct pass-through of React's onMouseEnter event. */ | ||
onMouseEnter?: (event: MouseEvent) => void; | ||
|
||
/** Direct pass-through of React's onMouseLeave event. */ | ||
onMouseLeave?: (event: MouseEvent) => void; | ||
|
||
/** Decides whether to handle the scroll behaviour to show hover once the scroll ends */ | ||
Comment on lines
-16
to
-21
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Callbacks removed ✅ There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. That's correct 👍 There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This comment is in the context of the "checklist" prepared by Vit. It would be good to ensure all of its parts are handled as required. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Ah right, that's actually a checklist written by me in order to track all potential changes :D I anwered your questions there 👍 There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Oh, fine. I thought this was from Expensify's side. Thank you |
||
shouldHandleScroll?: boolean; | ||
}; | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why
useImperativeHandle
instead offorwardRef
?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hi @roryabraham, in this case we use both.
useImperativeHandle
is there to let us access forwarded ref at theHoverable
level. As you can see, it basically passeselementRef
(localuseRef
for holding theHTML element
ref) to theouterRef
(parent's scope).Without using
useImperativeHandle
we could not forward the ref and at the same time have it accessible in theHoverable
(techincally we could, but that would mean hacking around with refs, while this hook hides it behind the abstraction).Here is an example of
BaseTooltip
component (noise removed for brevity):Hope that helps!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If
BoundsObserver
is the single reason we have to do the "tricky stuff", we can consider changing theBoundsObserver
implementation. But I don't have any specific idea.The relevant line in
BoundsObserver
is probably this one.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes, it requires its direct child to be "compatible" with this method of retrieving the HTML element.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thank you for additional insight @cubuspl42! In my opinion, the current flow, even if not clear at the first sight, is well suited for such task.