recharts
Version:
React charts
473 lines (452 loc) • 17.3 kB
JavaScript
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
import * as React from 'react';
import { useMemo } from 'react';
import { useUniqueId } from '../util/useUniqueId';
import { useRechartsTheme } from '../theme/RechartsThemeContext';
import { getEffectivePageBackground } from '../theme/pageBackground';
import { getThemeFillObject } from '../theme/themeFill';
var DEFAULT_PATTERN_OPACITY = 0.5;
/**
* How many pattern tiles at least fit across a small painted area.
* Fewer tiles would not read as a pattern.
*/
var MIN_TILES_ACROSS = 3;
/**
* Returns how much a pattern scales its tiles, so that at least {@link MIN_TILES_ACROSS} of them fit across the
* painted area. Tiles only get smaller: a large area keeps the tile size of the pattern.
* @param bounds the size of the painted area, if it is known
* @param tileSize the larger side of the tile
*/
function getTileScale(bounds, tileSize) {
if (bounds == null || tileSize <= 0) {
return 1;
}
return Math.min(1, Math.min(bounds.width, bounds.height) / MIN_TILES_ACROSS / tileSize);
}
/**
* Returns the `fill` attribute that references a fill definition.
* @param id the id given to the definition
*/
export function getFillUrl(id) {
return "url(#".concat(id, ")");
}
/**
* Turns a {@link RechartsPattern} into a fill definition: a repeating texture over the base color.
* The texture defaults to the `pageBackground` color from the theme, or white when no theme is set.
*
* Call it outside of components, so that the definition stays the same between renders.
*
* @example
* const stripes = pattern(patterns.diagonal);
* <Bar dataKey="uv" fill={{ definition: stripes }} />
*
* @param value the pattern to draw
* @returns a component to use as the `definition` of a {@link RechartsFill}
* @since 3.11
* @public
*/
export function pattern(value) {
function PatternDefinition(_ref) {
var _ref2, _value$color, _value$opacity;
var id = _ref.id,
color = _ref.color,
bounds = _ref.bounds;
var theme = useRechartsTheme();
var width = value.width,
height = value.height,
rotation = value.rotation;
var tileScale = getTileScale(bounds, Math.max(width, height));
var textureColor = (_ref2 = (_value$color = value.color) !== null && _value$color !== void 0 ? _value$color : getEffectivePageBackground(theme)) !== null && _ref2 !== void 0 ? _ref2 : '#fff';
var transforms = [];
if (rotation != null && rotation !== 0) {
transforms.push("rotate(".concat(rotation, ")"));
}
if (tileScale !== 1) {
transforms.push("scale(".concat(tileScale, ")"));
}
var paths = typeof value.path === 'string' ? [value.path] : value.path;
var isStroked = value.strokeWidth != null;
return /*#__PURE__*/React.createElement("pattern", {
id: id,
width: width,
height: height,
patternUnits: "userSpaceOnUse",
patternTransform: transforms.length > 0 ? transforms.join(' ') : undefined
}, /*#__PURE__*/React.createElement("rect", {
width: width,
height: height,
fill: color
}), /*#__PURE__*/React.createElement("g", {
opacity: (_value$opacity = value.opacity) !== null && _value$opacity !== void 0 ? _value$opacity : DEFAULT_PATTERN_OPACITY
}, paths.map(d => /*#__PURE__*/React.createElement("path", {
key: d,
d: d,
fill: isStroked ? 'none' : textureColor,
stroke: isStroked ? textureColor : 'none',
strokeWidth: value.strokeWidth
}))));
}
return PatternDefinition;
}
/**
* Turns a {@link RechartsLinearGradient} into a fill definition. Stops without a color use the base color.
*
* Call it outside of components, so that the definition stays the same between renders.
*
* @example
* const fade = linearGradient(gradients.fadeDown);
* <Bar dataKey="uv" fill={{ definition: fade }} />
*
* @param gradient the gradient to draw
* @returns a component to use as the `definition` of a {@link RechartsFill}
* @since 3.11
* @public
*/
export function linearGradient(gradient) {
function LinearGradientDefinition(_ref3) {
var id = _ref3.id,
color = _ref3.color;
var _gradient$x = gradient.x1,
x1 = _gradient$x === void 0 ? 0 : _gradient$x,
_gradient$y = gradient.y1,
y1 = _gradient$y === void 0 ? 0 : _gradient$y,
_gradient$x2 = gradient.x2,
x2 = _gradient$x2 === void 0 ? 0 : _gradient$x2,
_gradient$y2 = gradient.y2,
y2 = _gradient$y2 === void 0 ? 1 : _gradient$y2,
stops = gradient.stops;
return /*#__PURE__*/React.createElement("linearGradient", {
id: id,
x1: x1,
y1: y1,
x2: x2,
y2: y2
}, stops.map((stop, index) => {
var _stop$color;
return /*#__PURE__*/React.createElement("stop", {
// stops have no identity of their own, and their order is their meaning
key: index,
offset: stop.offset,
stopColor: (_stop$color = stop.color) !== null && _stop$color !== void 0 ? _stop$color : color,
stopOpacity: stop.opacity
});
}));
}
return LinearGradientDefinition;
}
/**
* Splits the `fill` prop of a graphical item into the base color, and the fill object if there is one.
* A fill object without `color` gives no color of its own, so the item keeps the theme colors.
* @param fill the `fill` prop
*/
export function splitFill(fill) {
if (fill == null || typeof fill === 'string') {
return {
color: fill,
fillObject: undefined
};
}
return {
color: fill.color,
fillObject: fill
};
}
/**
* DOM id of the fill definition of a graphical item.
* @param id id of the graphical item
*/
export function getSeriesFillId(id) {
return "".concat(id, "-fill");
}
/**
* Renders the definition of a fill object. Render it inside `<defs>`.
*/
export function FillObjectDefinition(_ref4) {
var id = _ref4.id,
fillObject = _ref4.fillObject,
color = _ref4.color,
bounds = _ref4.bounds;
var Definition = fillObject.definition;
return /*#__PURE__*/React.createElement(Definition, {
id: id,
color: color,
bounds: bounds
});
}
var entryFillCache = new WeakMap();
/**
* Returns true if the value can be rendered as a React component: a function, or a memo or forwardRef object.
* @param value the `definition` from a data entry
*/
function isDefinitionComponent(value) {
return typeof value === 'function' || value != null && typeof value === 'object' && '$$typeof' in value;
}
/**
* Reads the `fill` of a data entry, which can be a color string or a fill object.
* Data entries have no types, so this checks that an object has a `definition` before treating it as a fill object.
* Anything else counts as no fill.
* @param entry the data entry, possibly merged with the props of its Cell
*/
export function readEntryFill(entry) {
if (entry == null || typeof entry !== 'object' || !('fill' in entry)) {
return {
color: undefined,
fillObject: undefined
};
}
var fill = entry.fill;
if (typeof fill === 'string') {
return {
color: fill,
fillObject: undefined
};
}
if (fill == null || typeof fill !== 'object') {
return {
color: undefined,
fillObject: undefined
};
}
var cached = entryFillCache.get(fill);
if (cached != null) {
return {
color: cached.color,
fillObject: cached
};
}
var definition = 'definition' in fill ? fill.definition : undefined;
if (!isDefinitionComponent(definition)) {
return {
color: undefined,
fillObject: undefined
};
}
var color = 'color' in fill && typeof fill.color === 'string' ? fill.color : undefined;
// the same data entry gives the same fill object, so that it stays stable between renders
var fillObject = {
color,
definition
};
entryFillCache.set(fill, fillObject);
return {
color,
fillObject
};
}
/**
* DOM id of the fill definition of one data entry of a graphical item.
* @param id id of the graphical item
* @param index index of the data entry
*/
export function getEntryFillId(id, index) {
return "".concat(id, "-fill-").concat(index);
}
/**
* Returns the item without the fill object that its data entry may have spread into it.
* The item keeps the color of the fill object, or no `fill` at all, so that it takes the fill of the graphical item.
* Shapes never get a fill object, only colors and `url(#…)` references.
* @param item the item computed from the data entry, with the entry spread into it
* @param entry the data entry, possibly merged with the props of its Cell
*/
export function withEntryFillColor(item, entry) {
var _readEntryFill = readEntryFill(entry),
color = _readEntryFill.color,
fillObject = _readEntryFill.fillObject;
if (fillObject == null) {
return item;
}
if (color != null) {
return _objectSpread(_objectSpread({}, item), {}, {
fill: color
});
}
var itemWithoutFill = _objectSpread({}, item);
Reflect.deleteProperty(itemWithoutFill, 'fill');
return itemWithoutFill;
}
/**
* Renders the definitions of the data entries that have their own fill object. Render it inside `<defs>`.
*/
export function EntryFillDefinitions(_ref5) {
var id = _ref5.id,
entries = _ref5.entries;
return /*#__PURE__*/React.createElement(React.Fragment, null, entries.map(_ref6 => {
var index = _ref6.index,
payload = _ref6.payload,
color = _ref6.color;
var _readEntryFill2 = readEntryFill(payload),
fillObject = _readEntryFill2.fillObject;
return fillObject == null ? null : /*#__PURE__*/React.createElement(FillObjectDefinition, {
key: index,
id: getEntryFillId(id, index),
fillObject: fillObject,
color: color
});
}));
}
/**
* Returns true if any of the data entries has its own fill object.
* @param payloads the data entries
*/
export function hasEntryFillObjects(payloads) {
return payloads.some(payload => readEntryFill(payload).fillObject != null);
}
/**
* Returns the fill object a data entry paints with: its own, or none if it has its own color,
* or else the fill object of its graphical item.
* @param payload the data entry, possibly merged with the props of its Cell
* @param seriesFillObject the fill object of the graphical item
*/
export function getEntryFillObject(payload, seriesFillObject) {
var _readEntryFill3 = readEntryFill(payload),
color = _readEntryFill3.color,
fillObject = _readEntryFill3.fillObject;
if (fillObject != null) {
return fillObject;
}
return color == null ? seriesFillObject : undefined;
}
/**
* Returns the fill object of a data entry in a graphical item that takes one theme entry per data entry,
* like Pie and Funnel: the entry's own fill object, else the item's fill object, else the theme definition.
* An entry with its own color, or an item with its own colors, doesn't take the theme definition.
*
* @param payload the data entry, possibly merged with the props of its Cell
* @param index index of the data entry
* @param seriesFillObject the fill object of the graphical item
* @param themeFillObjects the fill object of each theme entry, from {@link useThemeFillObjects}
* @param seriesHasOwnColors true if the graphical item sets its own colors
*/
export function getIndexedEntryFillObject(payload, index, seriesFillObject, themeFillObjects, seriesHasOwnColors) {
var _readEntryFill4 = readEntryFill(payload),
color = _readEntryFill4.color,
fillObject = _readEntryFill4.fillObject;
if (fillObject != null) {
return fillObject;
}
if (color != null) {
return undefined;
}
if (seriesFillObject != null) {
return seriesFillObject;
}
if (themeFillObjects.length === 0 || seriesHasOwnColors) {
return undefined;
}
return themeFillObjects[index % themeFillObjects.length];
}
/**
* Returns the fill object of each theme entry, or undefined for an entry that fills with a color.
* The result is the same array as long as the theme stays the same.
*/
export function useThemeFillObjects() {
var _useRechartsTheme;
var graphicalItems = (_useRechartsTheme = useRechartsTheme()) === null || _useRechartsTheme === void 0 ? void 0 : _useRechartsTheme.graphicalItems;
return useMemo(() => (graphicalItems !== null && graphicalItems !== void 0 ? graphicalItems : []).map(style => getThemeFillObject(style.fill)), [graphicalItems]);
}
/**
* The paint of one fill in a component that isn't a graphical item, like a ReferenceArea or a grid.
* Makes a unique id for the definition.
*
* @param fill the `fill` prop: a color, or a fill object
* @param fallbackColor the color to use when the fill has no color of its own, for example from the theme
* @param idPrefix prefix of the unique id
* @param bounds the size of the painted area, if it is known when calling the hook
* @returns `paint` for the `fill` attribute, `color` for everything that needs a plain color,
* `definition` to render inside `<defs>`, and `renderDefinition` for when the size of the painted area
* is known only later
*/
export function useFillPaint(fill, fallbackColor, idPrefix, bounds) {
var id = useUniqueId(idPrefix);
var _splitFill = splitFill(fill),
color = _splitFill.color,
fillObject = _splitFill.fillObject;
var baseColor = color !== null && color !== void 0 ? color : fallbackColor;
if (fillObject == null) {
return {
paint: baseColor,
color: baseColor,
definition: null,
renderDefinition: () => null
};
}
var renderDefinition = paintedBounds => /*#__PURE__*/React.createElement(FillObjectDefinition, {
id: id,
fillObject: fillObject,
color: baseColor,
bounds: paintedBounds
});
return {
paint: getFillUrl(id),
color: baseColor,
definition: renderDefinition(bounds),
renderDefinition
};
}
/**
* The paints of a list of fills, like the stripes of a grid. Each fill object gets its own definition.
*
* @param fills the fills: colors or fill objects
* @param idPrefix prefix of the unique ids
* @returns `paints` for the `fill` attributes, by index, and `definitions` to render inside `<defs>`.
* Without fill objects, `definitions` is null.
*/
export function useFillPaints(fills, idPrefix) {
var id = useUniqueId(idPrefix);
var paints = (fills !== null && fills !== void 0 ? fills : []).map((fill, index) => typeof fill === 'string' ? fill : getFillUrl("".concat(id, "-").concat(index)));
if (fills == null || fills.every(fill => typeof fill === 'string')) {
return {
paints,
definitions: null
};
}
var definitions = fills.map((fill, index) => {
var _splitFill2 = splitFill(fill),
color = _splitFill2.color,
fillObject = _splitFill2.fillObject;
return fillObject == null ? null : /*#__PURE__*/React.createElement(FillObjectDefinition, {
key: index,
id: "".concat(id, "-").concat(index),
fillObject: fillObject,
color: color
});
});
return {
paints,
definitions
};
}
/**
* Returns bounds of the given size, or undefined if a side is not a positive number.
* @param width width of the painted area
* @param height height of the painted area
*/
export function getShapeBounds(width, height) {
if (typeof width !== 'number' || typeof height !== 'number' || !(width > 0) || !(height > 0)) {
return undefined;
}
return {
width,
height
};
}
/**
* Renders the definition of a fill object with a unique id, and the shape that paints with it.
* Shape components use it only when their `fill` is a fill object, so that plain colors render without any hook.
*/
export function FillObjectPaint(_ref7) {
var fill = _ref7.fill,
bounds = _ref7.bounds,
children = _ref7.children;
var id = useUniqueId('recharts-shape-fill');
return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("defs", null, /*#__PURE__*/React.createElement(FillObjectDefinition, {
id: id,
fillObject: fill,
color: fill.color,
bounds: bounds
})), children(getFillUrl(id)));
}