Skip to content

Commit

Permalink
fix(core): Update spot on layout changes (#153)
Browse files Browse the repository at this point in the history
  • Loading branch information
JoseLion authored Jul 16, 2024
1 parent d7bdd12 commit 9115aa8
Showing 1 changed file with 32 additions and 7 deletions.
39 changes: 32 additions & 7 deletions package/src/lib/components/attach-step/AttachStep.component.tsx
Original file line number Diff line number Diff line change
@@ -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";

Expand All @@ -8,6 +17,12 @@ export interface ChildProps<T> {
* A React children, if any.
*/
children?: ReactNode;
/**
* Native components layout change event.
*
* @param event The layout event.
*/
onLayout?: (event: LayoutChangeEvent) => void;
/**
* A React reference.
*/
Expand Down Expand Up @@ -54,27 +69,37 @@ export interface AttachStepProps<T> {
export function AttachStep<T>({ children, fill = false, index }: AttachStepProps<T>): ReactElement {
const { current, changeSpot } = useContext(SpotlightTourContext);

const childRef = useRef<View>(null);
const ref = useRef<View>(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 ?? { };

return (
<View
testID="attach-wrapper-view"
ref={childRef}
ref={ref}
style={{ alignSelf: fill ? "stretch" : "flex-start", ...childStyle }}
collapsable={false}
focusable={false}
onLayout={updateSpot}
>
{cloneElement(
children,
Expand All @@ -87,7 +112,7 @@ export function AttachStep<T>({ children, fill = false, index }: AttachStepProps

return cloneElement(
children,
{ ...children.props, ref: childRef },
{ ...children.props, onLayout, ref },
children.props?.children,
);
}

0 comments on commit 9115aa8

Please sign in to comment.