| 1 | "use strict";
|
|---|
| 2 |
|
|---|
| 3 | Object.defineProperty(exports, "__esModule", {
|
|---|
| 4 | value: true
|
|---|
| 5 | });
|
|---|
| 6 | exports.useElementOffset = useElementOffset;
|
|---|
| 7 | var _react = require("react");
|
|---|
| 8 | var EPS = 1;
|
|---|
| 9 |
|
|---|
| 10 | /**
|
|---|
| 11 | * TODO this documentation does not reflect what this hook is doing, update it.
|
|---|
| 12 | * Stores the `offsetHeight`, `offsetLeft`, `offsetTop`, and `offsetWidth` of a DOM element.
|
|---|
| 13 | */
|
|---|
| 14 |
|
|---|
| 15 | /**
|
|---|
| 16 | * Use this to listen to element layout changes.
|
|---|
| 17 | *
|
|---|
| 18 | * Very useful for reading actual sizes of DOM elements relative to the viewport.
|
|---|
| 19 | *
|
|---|
| 20 | * @param extraDependencies use this to trigger new DOM dimensions read when any of these change. Good for things like payload and label, that will re-render something down in the children array, but you want to read the layout box of a parent.
|
|---|
| 21 | * @returns [lastElementOffset, updateElementOffset] most recent value, and setter. Pass the setter to a DOM element ref like this: `<div ref={updateElementOffset}>`
|
|---|
| 22 | */
|
|---|
| 23 | function useElementOffset() {
|
|---|
| 24 | var extraDependencies = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
|
|---|
| 25 | var [lastBoundingBox, setLastBoundingBox] = (0, _react.useState)({
|
|---|
| 26 | height: 0,
|
|---|
| 27 | left: 0,
|
|---|
| 28 | top: 0,
|
|---|
| 29 | width: 0
|
|---|
| 30 | });
|
|---|
| 31 | var updateBoundingBox = (0, _react.useCallback)(node => {
|
|---|
| 32 | if (node != null) {
|
|---|
| 33 | var rect = node.getBoundingClientRect();
|
|---|
| 34 | var box = {
|
|---|
| 35 | height: rect.height,
|
|---|
| 36 | left: rect.left,
|
|---|
| 37 | top: rect.top,
|
|---|
| 38 | width: rect.width
|
|---|
| 39 | };
|
|---|
| 40 | if (Math.abs(box.height - lastBoundingBox.height) > EPS || Math.abs(box.left - lastBoundingBox.left) > EPS || Math.abs(box.top - lastBoundingBox.top) > EPS || Math.abs(box.width - lastBoundingBox.width) > EPS) {
|
|---|
| 41 | setLastBoundingBox({
|
|---|
| 42 | height: box.height,
|
|---|
| 43 | left: box.left,
|
|---|
| 44 | top: box.top,
|
|---|
| 45 | width: box.width
|
|---|
| 46 | });
|
|---|
| 47 | }
|
|---|
| 48 | }
|
|---|
| 49 | },
|
|---|
| 50 | // eslint-disable-next-line react-hooks/exhaustive-deps
|
|---|
| 51 | [lastBoundingBox.width, lastBoundingBox.height, lastBoundingBox.top, lastBoundingBox.left, ...extraDependencies]);
|
|---|
| 52 | return [lastBoundingBox, updateBoundingBox];
|
|---|
| 53 | } |
|---|