alinea
Version:
Headless git-based CMS
53 lines (51 loc) • 1.53 kB
JavaScript
import "../../chunks/chunk-NZLE2WMY.js";
// src/ui/hook/UseElementSize.ts
import { useLayoutEffect, useMemo, useRef, useState } from "react";
var subscribe = Object.assign(
(el, resizeCallback) => {
subscribe.callbacks.set(el, resizeCallback);
if (!subscribe.observerSingleton) {
subscribe.observerSingleton = new ResizeObserver((entries) => {
const callbacksEntries = [...subscribe.callbacks];
callbacksEntries.forEach(
([el2, cb]) => cb(entries.filter(({ target }) => target === el2))
);
});
}
subscribe.observerSingleton.observe(el);
return () => {
subscribe.observerSingleton?.unobserve(el);
subscribe.callbacks.delete(el);
};
},
{
callbacks: /* @__PURE__ */ new Map(),
observerSingleton: void 0
}
);
var useElementSize = (ref) => {
const elRef = useRef(null);
const [{ height, width }, setSize] = useState(() => ({
width: void 0,
// so they can set default values
height: void 0
// in the consuming component
}));
useLayoutEffect(() => {
const element = elRef.current || ref?.current;
if (element) {
const unsub = subscribe(element, (entries) => {
entries.forEach(
({ contentRect: { height: height2, width: width2 } }) => {
setSize({ height: height2, width: width2 });
}
);
});
return () => unsub();
}
}, [ref]);
return useMemo(() => ({ height, width, ref: elRef }), [height, width]);
};
export {
useElementSize
};