recharts
Version:
React charts
188 lines (181 loc) • 9.09 kB
JavaScript
function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
import throttle from 'es-toolkit/compat/throttle';
/**
* Which box of an element to measure.
*
* - `content-box`: without padding, border, and scrollbar. A chart renders inside this box.
* - `border-box`: including padding and border. This is how much space an element takes up, for example a Legend.
*
* @see {@link https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing}
*/
function parsePixels(value) {
var parsed = parseFloat(value);
return Number.isNaN(parsed) ? 0 : parsed;
}
function isPixels(value) {
return value.endsWith('px');
}
/**
* Measures the border box from the computed style, keeping fractional pixels.
* `offsetWidth` and `offsetHeight` would round to whole pixels, which moves whatever is positioned around the element.
*
* @param element the element to measure
* @param computedStyle the computed style of the element
* @returns the width and height of the border box
*/
function getBorderBoxSize(element, computedStyle) {
if (element.getClientRects().length === 0 || !isPixels(computedStyle.width) || !isPixels(computedStyle.height)) {
/*
* The computed size is not a used layout size. This happens when the element has no layout box
* (`display: none` on it or on an ancestor), where the computed style still has any width and height
* set in CSS, but offsetWidth and offsetHeight are 0. It also happens for `auto` on an inline element,
* and in jsdom, which does no layout.
*/
return {
width: element.offsetWidth,
height: element.offsetHeight
};
}
var width = parsePixels(computedStyle.width);
var height = parsePixels(computedStyle.height);
if (computedStyle.boxSizing === 'border-box') {
return {
width,
height
};
}
return {
width: width + parsePixels(computedStyle.paddingLeft) + parsePixels(computedStyle.paddingRight) + parsePixels(computedStyle.borderLeftWidth) + parsePixels(computedStyle.borderRightWidth),
height: height + parsePixels(computedStyle.paddingTop) + parsePixels(computedStyle.paddingBottom) + parsePixels(computedStyle.borderTopWidth) + parsePixels(computedStyle.borderBottomWidth)
};
}
/**
* Measures the layout size of an element.
*
* Unlike `getBoundingClientRect()`, this reads the layout size, which CSS transforms do not affect.
* An element that mounts inside a scaled parent (for example during an animation) gets its real size,
* and the size stays right after the transform goes away, even though ResizeObserver does not fire then.
*
* The content box is in whole pixels, because charts render at whole pixel sizes.
* The border box keeps fractional pixels, because other elements are positioned around it.
*
* @param element the element to measure
* @param box which box to measure
* @returns the width and height of the box
*/
export function getElementSize(element, box) {
var computedStyle = window.getComputedStyle(element);
if (box === 'border-box') {
return getBorderBoxSize(element, computedStyle);
}
// clientWidth and clientHeight include padding, but not border or scrollbar
var horizontalPadding = parsePixels(computedStyle.paddingLeft) + parsePixels(computedStyle.paddingRight);
var verticalPadding = parsePixels(computedStyle.paddingTop) + parsePixels(computedStyle.paddingBottom);
return {
width: Math.max(0, Math.round(element.clientWidth - horizontalPadding)),
height: Math.max(0, Math.round(element.clientHeight - verticalPadding))
};
}
/**
* Callback ref setter returned by {@link useElementSize}.
*
* Pass this to a DOM element's `ref` prop to start measuring it.
*
* @param node - the DOM element to measure, or `null` when the element unmounts
*/
function hasSignificantChange(previous, next, threshold) {
return Math.abs(previous.width - next.width) > threshold || Math.abs(previous.height - next.height) > threshold;
}
/**
* Measures the layout size of a DOM element, and optionally keeps measuring it as it resizes.
*
* Every measurement reads the layout size from the element itself, see {@link getElementSize}.
* ResizeObserver only tells this hook when to measure again.
*
* @param options see {@link UseElementSizeOptions}
* @returns [size, setMeasuredElement]. Pass the setter to a DOM element ref like this: `<div ref={setMeasuredElement}>`
*/
export function useElementSize(options) {
var box = options.box,
initialSize = options.initialSize,
observe = options.observe,
_options$measureWitho = options.measureWithoutResizeObserver,
measureWithoutResizeObserver = _options$measureWitho === void 0 ? true : _options$measureWitho,
_options$throttleMs = options.throttleMs,
throttleMs = _options$throttleMs === void 0 ? 0 : _options$throttleMs,
_options$threshold = options.threshold,
threshold = _options$threshold === void 0 ? 0 : _options$threshold,
_options$extraDepende = options.extraDependencies,
extraDependencies = _options$extraDepende === void 0 ? [] : _options$extraDepende,
onResize = options.onResize;
var _useState = useState(initialSize),
_useState2 = _slicedToArray(_useState, 2),
size = _useState2[0],
setSize = _useState2[1];
var elementRef = useRef(null);
var stopObservingRef = useRef(null);
/*
* A ref keeps the ResizeObserver from being re-created when the onResize function changes.
* The ref is updated on every commit, so the latest committed onResize function is always called.
*/
var onResizeRef = useRef(onResize);
useLayoutEffect(() => {
onResizeRef.current = onResize;
});
var shouldMeasure = !observe || measureWithoutResizeObserver || typeof ResizeObserver !== 'undefined';
var measure = useCallback(() => {
var node = elementRef.current;
if (node == null) {
return null;
}
var measured = getElementSize(node, box);
setSize(previous => hasSignificantChange(previous, measured, threshold) ? measured : previous);
return measured;
}, [box, threshold]);
var setMeasuredElement = useCallback(node => {
var _stopObservingRef$cur;
elementRef.current = node;
(_stopObservingRef$cur = stopObservingRef.current) === null || _stopObservingRef$cur === void 0 || _stopObservingRef$cur.call(stopObservingRef);
stopObservingRef.current = null;
if (node == null || !shouldMeasure) {
return;
}
measure();
if (!observe || typeof ResizeObserver === 'undefined') {
return;
}
var onObserved = () => {
var measured = measure();
if (measured != null) {
var _onResizeRef$current;
(_onResizeRef$current = onResizeRef.current) === null || _onResizeRef$current === void 0 || _onResizeRef$current.call(onResizeRef, measured);
}
};
var callback = throttleMs > 0 ? throttle(onObserved, throttleMs, {
leading: false,
trailing: true
}) : null;
var observer = new ResizeObserver(callback !== null && callback !== void 0 ? callback : onObserved);
// Observe the same box that this hook measures, so that a padding or border change notifies too
observer.observe(node, {
box
});
stopObservingRef.current = () => {
observer.disconnect();
callback === null || callback === void 0 || callback.cancel();
};
}, [box, measure, observe, shouldMeasure, throttleMs]);
useEffect(() => {
if (observe && shouldMeasure) {
measure();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [measure, observe, shouldMeasure, ...extraDependencies]);
return [size, setMeasuredElement];
}