UNPKG

@awsui/components-react

Version:

On July 19th, 2022, we launched [Cloudscape Design System](https://cloudscape.design). Cloudscape is an evolution of AWS-UI. It consists of user interface guidelines, front-end components, design resources, and development tools for building intuitive, en

48 lines 2.13 kB
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import { useCallback, useRef, useState } from 'react'; /** * A hook that uses an Intersection Observer on the target element ref * and detects if the element is intersecting with its parent. */ export function useIntersectionObserver({ initialState = false, } = {}) { const observerRef = useRef(null); const [isIntersecting, setIsIntersecting] = useState(initialState); const ref = useCallback(targetElement => { if (typeof IntersectionObserver === 'undefined') { // Do nothing in environments like JSDOM return; } if (observerRef.current) { // Dismiss previous observer because the target changed observerRef.current.disconnect(); } // Create a new observer with the target element if (targetElement) { // Fix for AWSUI-60898: In Firefox, IntersectionObserver instances inside an // iframe context can't detect visibility changes caused by changes to elements // outside the iframe (e.g. if an element wrapping the iframe is set to `display: none`). let TopLevelIntersectionObserver = IntersectionObserver; try { if (window.top) { TopLevelIntersectionObserver = window.top.IntersectionObserver; } } catch { // Tried to access a cross-origin iframe. Fall back to current IntersectionObserver. } observerRef.current = new TopLevelIntersectionObserver(entries => { let latestEntry = entries[0]; for (const entry of entries) { if (entry.time > latestEntry.time) { latestEntry = entry; } } setIsIntersecting(latestEntry.isIntersecting); }); observerRef.current.observe(targetElement); } }, []); return { ref, isIntersecting }; } //# sourceMappingURL=index.js.map