react-native-reanimated
Version:
More powerful alternative to Animated library for React Native.
92 lines (90 loc) • 2.96 kB
JavaScript
'use strict';
import { useRef } from 'react';
import { findNodeHandle } from '../platformFunctions/findNodeHandle';
export function useAnimatedRefBase(getWrapper, onDetach) {
const observers = useRef(new Map()).current;
const wrapperRef = useRef(null);
const resultRef = useRef(null);
if (!resultRef.current) {
const fun = ref => {
if (ref) {
wrapperRef.current = getWrapper(ref);
// We have to unwrap the tag from the shadow node wrapper.
// @ts-expect-error this can't be typed well.
fun.getTag = () => ref.getScrollableNode?.() || findNodeHandle(ref);
fun.current = ref;
if (observers.size) {
const currentTag = fun?.getTag?.() ?? null;
observers.forEach(({
tag,
cleanup
}, observer) => {
// React calls the ref again for the same view whenever the ref passed to it changes.
if (tag === currentTag) {
return;
}
// Perform the cleanup before calling the observer again.
// This ensures that all events that were set up in the observer
// are cleaned up before the observer sets up new events during
// the next call.
cleanup?.();
observers.set(observer, {
tag: currentTag,
cleanup: observer(currentTag)
});
});
}
} else if (ref === null) {
// React calls a callback ref with null when the element unmounts.
// Calling the ref with no argument only reads the wrapper, so it must
// not detach.
// Drop the instance so that this ref, which the owner's closures often
// keep reachable, does not retain the unmounted component and
// everything its props reach.
wrapperRef.current = null;
fun.getTag = () => null;
fun.current = null;
if (observers.size) {
queueMicrotask(cleanUpObserversIfDetached);
}
onDetach?.();
}
return wrapperRef.current;
};
const cleanUpObserversIfDetached = () => {
if (fun.current !== null) {
return;
}
observers.forEach(({
tag,
cleanup
}, observer) => {
if (tag === null) {
return;
}
cleanup?.();
observers.set(observer, {
tag: null,
cleanup: undefined
});
});
};
fun.observe = observer => {
// Call observer immediately to get the initial value
const tag = fun?.getTag?.() ?? null;
observers.set(observer, {
tag,
cleanup: observer(tag)
});
return () => {
observers.get(observer)?.cleanup?.();
observers.delete(observer);
};
};
fun.current = null;
fun.getTag = () => null;
resultRef.current = fun;
}
return resultRef.current;
}
//# sourceMappingURL=useAnimatedRefCommon.js.map