@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 (47 loc) • 1.76 kB
JavaScript
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
const map = new WeakMap();
const MANUAL_TRIGGER_DELAY = 150;
/**
* This function determines whether an element is in the viewport. The callback
* is batched with other elements that also use this function, in order to improve
* performance.
*/
export function isInViewport(element, callback) {
let resolve = (value) => {
resolve = () => { }; // Prevent multiple execution
callback(value);
};
map.set(element, inViewport => resolve(inViewport));
observer.observe(element);
/*
If the IntersectionObserver does not fire in reasonable time (for example
in a background page in Chrome), we need to call the callback manually.
See https://issues.chromium.org/issues/41383759
*/
const timeoutHandle = setTimeout(() => resolve(false), MANUAL_TRIGGER_DELAY);
// Cleanup
return () => {
clearTimeout(timeoutHandle);
map.delete(element);
observer.unobserve(element);
};
}
function createIntersectionObserver(callback) {
if (typeof IntersectionObserver === 'undefined') {
return {
observe: () => { },
unobserve: () => { },
};
}
return new IntersectionObserver(callback);
}
const observer = createIntersectionObserver(function isInViewportObserver(entries) {
var _a;
for (const entry of entries) {
observer.unobserve(entry.target); // We only want the first run of the observer for each element.
(_a = map.get(entry.target)) === null || _a === void 0 ? void 0 : _a(entry.isIntersecting);
map.delete(entry.target);
}
});
//# sourceMappingURL=is-in-viewport.js.map