barChart.tsx 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import {useMemo} from 'react';
  2. import type {BarSeriesOption} from 'echarts';
  3. import type {Series} from 'sentry/types/echarts';
  4. import BarSeries from './series/barSeries';
  5. import type {BaseChartProps} from './baseChart';
  6. import BaseChart from './baseChart';
  7. export interface BarChartSeries
  8. extends Omit<BarSeriesOption, 'data' | 'color' | 'id'>,
  9. Series {}
  10. export interface BarChartProps extends BaseChartProps {
  11. series: BarChartSeries[];
  12. animation?: boolean;
  13. barOpacity?: number;
  14. hideZeros?: boolean;
  15. stacked?: boolean;
  16. }
  17. export function transformToBarSeries({
  18. barOpacity = 0.6,
  19. series,
  20. stacked,
  21. hideZeros = false,
  22. animation,
  23. }: Pick<BarChartProps, 'barOpacity' | 'hideZeros' | 'series' | 'stacked' | 'animation'>) {
  24. return series.map(({seriesName, data, ...options}) =>
  25. BarSeries({
  26. name: seriesName,
  27. stack: stacked ? 'stack1' : undefined,
  28. data: data?.map(({value, name, itemStyle}) => {
  29. if (itemStyle === undefined) {
  30. return {
  31. value: [name, value],
  32. itemStyle: value === 0 && hideZeros ? {opacity: 0} : {opacity: barOpacity},
  33. emphasis:
  34. value === 0 && hideZeros
  35. ? {itemStyle: {opacity: 0}}
  36. : {itemStyle: {opacity: 1}},
  37. };
  38. }
  39. return {
  40. value: [name, value],
  41. itemStyle:
  42. value === 0 && hideZeros
  43. ? {...itemStyle, opacity: 0} // Don't show bars when value = 0 (when hideZeros is enabled)
  44. : {...itemStyle, opacity: barOpacity},
  45. emphasis:
  46. value === 0 && hideZeros
  47. ? {itemStyle: {opacity: 0}}
  48. : {itemStyle: {opacity: 1}},
  49. };
  50. }),
  51. animation,
  52. ...options,
  53. })
  54. );
  55. }
  56. const EMPTY_AXIS = {};
  57. export function BarChart({
  58. barOpacity,
  59. hideZeros,
  60. series,
  61. stacked,
  62. xAxis,
  63. animation,
  64. ...props
  65. }: BarChartProps) {
  66. const transformedSeries = useMemo(() => {
  67. return transformToBarSeries({barOpacity, hideZeros, series, stacked, animation});
  68. }, [animation, barOpacity, hideZeros, series, stacked]);
  69. const xAxisOptions = useMemo(() => {
  70. const option = xAxis === null ? null : {...(xAxis || EMPTY_AXIS)};
  71. return option;
  72. }, [xAxis]);
  73. return <BaseChart {...props} xAxis={xAxisOptions} series={transformedSeries} />;
  74. }