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

Hoverable Component refactor #31518

Merged
Merged
Show file tree
Hide file tree
Changes from 22 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
5504cc0
split the Hoverable into Active and Disabled parts
kacper-mikolajczak Nov 18, 2023
cb8a310
unset Hovered when document visibility has changed
kacper-mikolajczak Nov 20, 2023
8669939
Add missing clarifying comment
kacper-mikolajczak Nov 20, 2023
87d8979
remove onMouse* props from Hoverable
kacper-mikolajczak Nov 21, 2023
a78b9f8
remove unused props
kacper-mikolajczak Nov 21, 2023
772fae1
add has hover support in condition
kacper-mikolajczak Nov 22, 2023
8276438
add unsetHoveredIfOutside functionality
kacper-mikolajczak Nov 22, 2023
1f910d2
add onBlur handler
kacper-mikolajczak Nov 22, 2023
0129ddb
change generic type to HTMLElement
kacper-mikolajczak Nov 24, 2023
a2bf1a5
simplify unsetHoveredIfOutside listener
kacper-mikolajczak Nov 26, 2023
cb964d5
Merge branch 'main' into refactor/hoverable-component
kacper-mikolajczak Nov 26, 2023
dfa7be4
replace ternary with if statement
kacper-mikolajczak Nov 28, 2023
88bb94c
use RefCallback instead of annonymous function type
kacper-mikolajczak Nov 28, 2023
e0fe2e5
make deps with child props more precise
kacper-mikolajczak Nov 28, 2023
4b49dc2
rename events callbacks names
kacper-mikolajczak Nov 28, 2023
182fd8d
rename events callbacks
kacper-mikolajczak Nov 28, 2023
60bc902
rename isScrolling to isScrollingRef
kacper-mikolajczak Nov 28, 2023
c63786a
change ref to elementRef
kacper-mikolajczak Nov 28, 2023
5464c33
add a new line between description and params in jsdoc
kacper-mikolajczak Nov 28, 2023
963c6d0
extract assignRef
kacper-mikolajczak Nov 28, 2023
81c8e42
change assignRef description
kacper-mikolajczak Nov 29, 2023
2dd8968
Update src/components/Hoverable/ActiveHoverable.tsx
kacper-mikolajczak Nov 29, 2023
783c64a
rename disabled to isDisabled
kacper-mikolajczak Nov 30, 2023
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
137 changes: 137 additions & 0 deletions src/components/Hoverable/ActiveHoverable.tsx
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, []);
Copy link
Contributor

Choose a reason for hiding this comment

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

Why useImperativeHandle instead of forwardRef?

Copy link
Contributor Author

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 the Hoverable level. As you can see, it basically passes elementRef (local useRef for holding the HTML element ref) to the outerRef (parent's scope).

Without using useImperativeHandle we could not forward the ref and at the same time have it accessible in the Hoverable (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):

            {/* Requires an HTML element ref from the direct children  */}
            <BoundsObserver>
                {/* Thus we need to forward the ref through Hoverable to the button, 
                    while still being able to access it inside Hoverable for the onBlur handler */}
                <Hoverable>
                    <button>Click me</button>
                </Hoverable>
            </BoundsObserver>

Hope that helps!

Copy link
Contributor

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 the BoundsObserver implementation. But I don't have any specific idea.

The relevant line in BoundsObserver is probably this one.

Copy link
Contributor

Choose a reason for hiding this comment

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

Requires an HTML element ref from the direct children

Yes, it requires its direct child to be "compatible" with this method of retrieving the HTML element.

Copy link
Contributor Author

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.


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);
Copy link
Contributor

Choose a reason for hiding this comment

The 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)

Copy link
Contributor Author

Choose a reason for hiding this comment

The 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 addEventListener and removeEventListener is accessible from outside (e.g. listener's options argument). I will give it a moment after all the minor changes to the PR are resolved 👍

Copy link
Contributor

Choose a reason for hiding this comment

The 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.

Copy link
Contributor Author

Choose a reason for hiding this comment

The 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:

  • every listener (callback) needs to be memoized now, and we cannot simply inline it as there is no access to useEffect (see effect in line 77 of ActiveHoverable)
  • cannot opt out of listening if not needed (see effect in line 53 of ActiveHoverable)

Let me know what you think about it 👍

Copy link
Contributor

Choose a reason for hiding this comment

The 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);
215 changes: 15 additions & 200 deletions src/components/Hoverable/index.tsx
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.
Copy link
Contributor

Choose a reason for hiding this comment

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

NABish but this prop should be isDisabled:

Suggested change
function Hoverable({disabled, ...props}: HoverableProps, ref: Ref<HTMLElement>) {
function Hoverable({isDisabled, ...props}: HoverableProps, ref: Ref<HTMLElement>) {

Copy link
Contributor Author

Choose a reason for hiding this comment

The 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);
10 changes: 2 additions & 8 deletions src/components/Hoverable/types.ts
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;
Expand All @@ -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
Copy link
Contributor

Choose a reason for hiding this comment

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

Callbacks removed ✅

Copy link
Contributor Author

Choose a reason for hiding this comment

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

That's correct 👍

Copy link
Contributor

Choose a reason for hiding this comment

The 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.

Copy link
Contributor Author

Choose a reason for hiding this comment

The 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 👍

Copy link
Contributor

Choose a reason for hiding this comment

The 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;
};
Expand Down
Loading
Loading