@liveblocks/react-ui
Version:
A set of React pre-built components for the Liveblocks products. Liveblocks is the all-in-one toolkit to build collaborative products like Figma, Notion, and more.
68 lines (65 loc) • 1.73 kB
JavaScript
import { useState, useEffect } from 'react';
import { useLatest } from './use-latest.js';
let intersectionObserver;
const intersectionCallbacks = /* @__PURE__ */ new WeakMap();
function observe(element, callback) {
if (!intersectionObserver) {
intersectionObserver = new IntersectionObserver((entries) => {
for (const entry of entries) {
const callback2 = intersectionCallbacks.get(entry.target);
callback2?.(entry);
}
});
}
intersectionCallbacks.set(element, callback);
intersectionObserver.observe(element);
}
function unobserve(element) {
intersectionCallbacks.delete(element);
intersectionObserver?.unobserve(element);
}
function useVisible(ref, options) {
const [isVisible, setVisible] = useState(false);
const enabled = options?.enabled ?? true;
useEffect(() => {
const element = ref.current;
if (!element) {
return;
}
if (enabled) {
observe(element, (entry) => {
setVisible(entry.isIntersecting);
});
} else {
unobserve(element);
}
return () => {
unobserve(element);
};
}, [enabled]);
return isVisible;
}
function useVisibleCallback(ref, callback, options) {
const enabled = options?.enabled ?? true;
const latestCallback = useLatest(callback);
useEffect(() => {
const element = ref.current;
if (!element) {
return;
}
if (enabled) {
observe(element, (entry) => {
if (entry.isIntersecting) {
latestCallback.current();
}
});
} else {
unobserve(element);
}
return () => {
unobserve(element);
};
}, [enabled]);
}
export { useVisible, useVisibleCallback };
//# sourceMappingURL=use-visible.js.map