UNPKG

@tanstack/solid-router

Version:

Modern and scalable routing for Solid applications

55 lines (54 loc) • 1.77 kB
const require_runtime = require("./_virtual/_rolldown/runtime.cjs"); let solid_js = require("solid-js"); solid_js = require_runtime.__toESM(solid_js, 1); //#region src/utils.ts /** * React hook to wrap `IntersectionObserver`. * * This hook will create an `IntersectionObserver` and observe the ref passed to it. * * When the intersection changes, the callback will be called with the `IntersectionObserverEntry`. * * @param ref - The ref to observe * @param callback - The callback to call when the intersection changes * @param disabled - Whether observation is disabled * @param cleanupWhenDisabled - Whether cleanup is needed without an observer (defaults to true) * @returns The IntersectionObserver instance * @example * ```tsx * const MyComponent = () => { * const ref = React.useRef<HTMLDivElement>(null) * useIntersectionObserver( * ref, * (entry) => { doSomething(entry) }, * false * ) * return <div ref={ref} /> * ``` */ function useIntersectionObserver(ref, callback, disabled, cleanupWhenDisabled) { const isIntersectionObserverAvailable = typeof IntersectionObserver === "function"; let observerRef = null; solid_js.createEffect(() => { const r = ref(); if (disabled() || !r || !isIntersectionObserverAvailable) { if (cleanupWhenDisabled?.() ?? true) solid_js.onCleanup(() => callback()); return; } let active = true; const observer = new IntersectionObserver((entries) => { if (active) callback(entries.pop()); }, { rootMargin: "100px" }); observerRef = observer; observer.observe(r); solid_js.onCleanup(() => { active = false; observer.disconnect(); callback(); }); }); return () => observerRef; } //#endregion exports.useIntersectionObserver = useIntersectionObserver; //# sourceMappingURL=utils.cjs.map