From 9115aa8c56ce200f52803e91c48e6a252da140fb Mon Sep 17 00:00:00 2001 From: Jose Luis Leon Date: Tue, 16 Jul 2024 10:41:30 -0500 Subject: [PATCH] fix(core): Update spot on layout changes (#153) --- .../attach-step/AttachStep.component.tsx | 39 +++++++++++++++---- 1 file changed, 32 insertions(+), 7 deletions(-) diff --git a/package/src/lib/components/attach-step/AttachStep.component.tsx b/package/src/lib/components/attach-step/AttachStep.component.tsx index 71806f6..23fba6c 100644 --- a/package/src/lib/components/attach-step/AttachStep.component.tsx +++ b/package/src/lib/components/attach-step/AttachStep.component.tsx @@ -1,5 +1,14 @@ -import React, { ReactElement, ReactNode, RefObject, cloneElement, useContext, useEffect, useRef } from "react"; -import { StyleProp, View } from "react-native"; +import React, { + ReactElement, + ReactNode, + RefObject, + cloneElement, + useCallback, + useContext, + useEffect, + useRef, +} from "react"; +import { LayoutChangeEvent, StyleProp, View } from "react-native"; import { SpotlightTourContext } from "../../SpotlightTour.context"; @@ -8,6 +17,12 @@ export interface ChildProps { * A React children, if any. */ children?: ReactNode; + /** + * Native components layout change event. + * + * @param event The layout event. + */ + onLayout?: (event: LayoutChangeEvent) => void; /** * A React reference. */ @@ -54,16 +69,25 @@ export interface AttachStepProps { export function AttachStep({ children, fill = false, index }: AttachStepProps): ReactElement { const { current, changeSpot } = useContext(SpotlightTourContext); - const childRef = useRef(null); + const ref = useRef(null); - useEffect(() => { + const updateSpot = useCallback((): void => { if (current === index) { - childRef.current?.measureInWindow((x, y, width, height) => { + ref.current?.measureInWindow((x, y, width, height) => { changeSpot({ height, width, x, y }); }); } }, [changeSpot, current, index]); + const onLayout = useCallback((event: LayoutChangeEvent): void => { + updateSpot(); + children.props.onLayout?.(event); + }, [updateSpot, children.props.onLayout]); + + useEffect(() => { + updateSpot(); + }, [updateSpot]); + if (typeof children.type === "function") { const { style, ...rest } = children.props; const childStyle = style ?? { }; @@ -71,10 +95,11 @@ export function AttachStep({ children, fill = false, index }: AttachStepProps return ( {cloneElement( children, @@ -87,7 +112,7 @@ export function AttachStep({ children, fill = false, index }: AttachStepProps return cloneElement( children, - { ...children.props, ref: childRef }, + { ...children.props, onLayout, ref }, children.props?.children, ); }