@lobehub/charts
Version:
React modern charts components built on recharts
240 lines (239 loc) • 14.7 kB
JavaScript
'use client';
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
var _templateObject;
var _excluded = ["data", "category", "index", "colors", "variant", "valueFormatter", "label", "showLabel", "animationDuration", "showAnimation", "showTooltip", "noDataText", "onValueChange", "customTooltip", "className", "width", "loading", "height", "style", "customCategories", "donutLabel"];
function _taggedTemplateLiteral(strings, raw) { if (!raw) { raw = strings.slice(0); } return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); }
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(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(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); }
function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _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(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
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(arr) { if (Array.isArray(arr)) return arr; }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
import { Skeleton } from 'antd';
import { css, useThemeMode } from 'antd-style';
import { forwardRef, useEffect, useState } from 'react';
import { Flexbox } from 'react-layout-kit';
import { Pie, PieChart as ReChartsDonutChart, ResponsiveContainer, Tooltip } from 'recharts';
import NoData from "../common/NoData";
import { useThemeColorRange } from "../hooks/useThemeColorRange";
import { defaultValueFormatter, isOnSeverSide } from "../utils";
import { DonutChartTooltip } from "./DonutChartTooltip";
import { parseLabelInput } from "./inputParser";
import { renderInactiveShape } from "./renderInactiveShape";
import { useStyles } from "./styles";
import { jsx as _jsx } from "react/jsx-runtime";
import { jsxs as _jsxs } from "react/jsx-runtime";
var DonutChart = /*#__PURE__*/forwardRef(function (props, ref) {
var _data;
var _useStyles = useStyles(),
cx = _useStyles.cx,
theme = _useStyles.theme,
styles = _useStyles.styles;
var themeColorRange = useThemeColorRange();
var _props$data = props.data,
data = _props$data === void 0 ? [] : _props$data,
_props$category = props.category,
category = _props$category === void 0 ? 'value' : _props$category,
_props$index = props.index,
index = _props$index === void 0 ? 'name' : _props$index,
_props$colors = props.colors,
colors = _props$colors === void 0 ? themeColorRange : _props$colors,
_props$variant = props.variant,
variant = _props$variant === void 0 ? 'donut' : _props$variant,
_props$valueFormatter = props.valueFormatter,
valueFormatter = _props$valueFormatter === void 0 ? defaultValueFormatter : _props$valueFormatter,
label = props.label,
_props$showLabel = props.showLabel,
showLabel = _props$showLabel === void 0 ? true : _props$showLabel,
_props$animationDurat = props.animationDuration,
animationDuration = _props$animationDurat === void 0 ? 900 : _props$animationDurat,
_props$showAnimation = props.showAnimation,
showAnimation = _props$showAnimation === void 0 ? false : _props$showAnimation,
_props$showTooltip = props.showTooltip,
showTooltip = _props$showTooltip === void 0 ? true : _props$showTooltip,
noDataText = props.noDataText,
onValueChange = props.onValueChange,
customTooltip = props.customTooltip,
className = props.className,
_props$width = props.width,
width = _props$width === void 0 ? '100%' : _props$width,
loading = props.loading,
_props$height = props.height,
height = _props$height === void 0 ? '10rem' : _props$height,
style = props.style,
customCategories = props.customCategories,
donutLabel = props.donutLabel,
rest = _objectWithoutProperties(props, _excluded);
var _useThemeMode = useThemeMode(),
isDarkMode = _useThemeMode.isDarkMode;
var CustomTooltip = customTooltip;
var isDonut = variant === 'donut';
var parsedLabelInput = parseLabelInput(label, valueFormatter, data, category);
var _useState = useState(),
_useState2 = _slicedToArray(_useState, 2),
activeIndex = _useState2[0],
setActiveIndex = _useState2[1];
var hasOnValueChange = !!onValueChange;
useEffect(function () {
if (isOnSeverSide) return;
var pieSectors = document.querySelectorAll('.recharts-pie-sector');
if (pieSectors) {
var _iterator = _createForOfIteratorHelper(pieSectors),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var sector = _step.value;
sector.setAttribute('style', 'outline: none');
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
}
}, [activeIndex]);
if (loading || !data) return /*#__PURE__*/_jsx(Skeleton.Button, {
active: true,
block: true,
style: {
height: height,
width: width
}
});
var onShapeClick = function onShapeClick(data, index, event) {
event.stopPropagation();
if (!hasOnValueChange) return;
if (activeIndex === index) {
setActiveIndex(undefined);
onValueChange === null || onValueChange === void 0 || onValueChange(null);
} else {
setActiveIndex(index);
onValueChange === null || onValueChange === void 0 || onValueChange(_objectSpread({
eventType: 'slice'
}, data.payload.payload));
}
};
var parseData = function parseData(data, colors) {
return data.map(function (dataPoint, idx) {
var baseColor = idx < colors.length ? colors[idx] : theme.colorPrimary;
return _objectSpread(_objectSpread({}, dataPoint), {}, {
className: cx(css(_templateObject || (_templateObject = _taggedTemplateLiteral(["\n fill: ", ";\n "])), baseColor !== null && baseColor !== void 0 ? baseColor : theme.colorPrimary)),
color: baseColor,
fill: ''
});
});
};
return /*#__PURE__*/_jsx(Flexbox, _objectSpread(_objectSpread({
className: className,
height: height,
ref: ref,
style: _objectSpread({
position: 'relative'
}, style),
width: width
}, rest), {}, {
children: /*#__PURE__*/_jsx(ResponsiveContainer, {
children: data !== null && data !== void 0 && data.length ? /*#__PURE__*/_jsxs(ReChartsDonutChart, {
margin: {
bottom: 0,
left: 0,
right: 0,
top: 0
},
onClick: hasOnValueChange && activeIndex ? function () {
setActiveIndex(undefined);
onValueChange === null || onValueChange === void 0 || onValueChange(null);
} : undefined,
children: [showLabel && isDonut ? /*#__PURE__*/_jsx("text", {
className: cx(styles.strongLabel, styles.emphasis),
dominantBaseline: "middle",
textAnchor: "middle",
x: "50%",
y: "50%",
children: donutLabel || (typeof activeIndex === 'number' ? valueFormatter(data === null || data === void 0 || (_data = data[activeIndex]) === null || _data === void 0 ? void 0 : _data[category]) : parsedLabelInput)
}) : null, /*#__PURE__*/_jsx(Pie, {
activeIndex: activeIndex,
animationDuration: animationDuration,
cx: "50%",
cy: "50%",
data: parseData(data, colors),
dataKey: category,
endAngle: -270,
inactiveShape: renderInactiveShape,
innerRadius: isDonut ? '75%' : '0%',
isAnimationActive: showAnimation,
nameKey: index,
onClick: onShapeClick,
outerRadius: "100%",
startAngle: 90,
stroke: "",
strokeLinejoin: "round",
style: {
cursor: onValueChange ? 'pointer' : undefined,
outline: 'none',
stroke: theme.colorBgContainer
}
}), isDonut && /*#__PURE__*/_jsx(Pie, {
activeIndex: activeIndex,
animationDuration: animationDuration,
cx: "50%",
cy: "50%",
data: parseData([_defineProperty({}, category, 1)], [isDarkMode ? 'rgba(0,0,0,.33)' : 'rgba(0,0,0,.1)']),
dataKey: category,
endAngle: -270,
inactiveShape: renderInactiveShape,
innerRadius: isDonut ? '75%' : '0%',
isAnimationActive: false,
nameKey: index,
outerRadius: "80%",
startAngle: 90,
stroke: "",
strokeLinejoin: "round",
style: {
outline: 'none',
pointerEvents: 'none'
}
}), /*#__PURE__*/_jsx(Tooltip, {
content: showTooltip ? function (_ref2) {
var _payload$;
var active = _ref2.active,
payload = _ref2.payload;
return CustomTooltip ? /*#__PURE__*/_jsx(CustomTooltip, {
active: active,
customCategories: customCategories,
label: payload === null || payload === void 0 || (_payload$ = payload[0]) === null || _payload$ === void 0 ? void 0 : _payload$.name,
payload: payload === null || payload === void 0 ? void 0 : payload.map(function (payloadItem) {
var _payload$0$payload$co, _payload$2;
return _objectSpread(_objectSpread({}, payloadItem), {}, {
color: (_payload$0$payload$co = payload === null || payload === void 0 || (_payload$2 = payload[0]) === null || _payload$2 === void 0 || (_payload$2 = _payload$2.payload) === null || _payload$2 === void 0 ? void 0 : _payload$2.color) !== null && _payload$0$payload$co !== void 0 ? _payload$0$payload$co : theme.colorPrimary
});
}),
valueFormatter: valueFormatter
}) : /*#__PURE__*/_jsx(DonutChartTooltip, {
active: active,
customCategories: customCategories,
payload: payload,
valueFormatter: valueFormatter
});
} : undefined,
isAnimationActive: false,
wrapperStyle: {
outline: 'none'
}
})]
}) : /*#__PURE__*/_jsx(NoData, {
noDataText: noDataText
})
})
}));
});
DonutChart.displayName = 'DonutChart';
export default DonutChart;