GoScrobble/web/node_modules/@restart/hooks/cjs/useResizeObserver.js

61 lines
1.5 KiB
JavaScript

"use strict";
exports.__esModule = true;
exports.default = useResizeObserver;
var _react = require("react");
var _useIsomorphicEffect = _interopRequireDefault(require("./useIsomorphicEffect"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var targetMap = new WeakMap();
var resizeObserver;
function getResizeObserver() {
// eslint-disable-next-line no-return-assign
return resizeObserver = resizeObserver || new window.ResizeObserver(function (entries) {
entries.forEach(function (entry) {
var handler = targetMap.get(entry.target);
if (handler) handler(entry.contentRect);
});
});
}
/**
* Efficiently observe size changes on an element. Depends on the `ResizeObserver` api,
* and polyfills are needed in older browsers.
*
* ```ts
* const [ref, attachRef] = useCallbackRef(null);
*
* const rect = useResizeObserver(ref);
*
* return (
* <div ref={attachRef}>
* {JSON.stringify(rect)}
* </div>
* )
* ```
*
* @param element The DOM element to observe
*/
function useResizeObserver(element) {
var _useState = (0, _react.useState)(null),
rect = _useState[0],
setRect = _useState[1];
(0, _useIsomorphicEffect.default)(function () {
if (!element) return;
getResizeObserver().observe(element);
setRect(element.getBoundingClientRect());
targetMap.set(element, function (rect) {
setRect(rect);
});
return function () {
targetMap.delete(element);
};
}, [element]);
return rect;
}