Skip to content

Commit

Permalink
withBarValueLabel not displaying in correct positions in BarChart
Browse files Browse the repository at this point in the history
  • Loading branch information
fsd-niraj committed Oct 22, 2024
1 parent 6a067f1 commit d4c46b4
Showing 1 changed file with 20 additions and 7 deletions.
27 changes: 20 additions & 7 deletions packages/@mantine/charts/src/BarChart/BarChart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,9 @@ export type BarChartCssVariables = {

export interface BarChartProps
extends BoxProps,
GridChartBaseProps,
StylesApiProps<BarChartFactory>,
ElementProps<'div'> {
GridChartBaseProps,
StylesApiProps<BarChartFactory>,
ElementProps<'div'> {
/** Data used to display chart. */
data: Record<string, any>[];

Expand All @@ -81,8 +81,8 @@ export interface BarChartProps

/** Props passed down to recharts `Bar` component */
barProps?:
| ((series: BarChartSeries) => Partial<Omit<BarProps, 'ref'>>)
| Partial<Omit<BarProps, 'ref'>>;
| ((series: BarChartSeries) => Partial<Omit<BarProps, 'ref'>>)
| Partial<Omit<BarProps, 'ref'>>;

/** Determines whether a label with bar value should be displayed on top of each bar, incompatible with `type="stacked"` and `type="percent"`, `false` by default */
withBarValueLabel?: boolean;
Expand Down Expand Up @@ -130,10 +130,23 @@ export function BarLabel({
parentViewBox,
...others
}: Record<string, any>) {

function labelCoordinates(): { dx: number, dy: number } {
let coord: { dx: number, dy: number } = { dx: 0, dy: 0 }
if (others.props.h < 300) {
coord = { ...coord, dx: Math.ceil(others?.width + 10) }
} else {
coord.dx = Math.ceil(others?.width - others?.viewBox?.x / 2)
}
coord = { ...coord, dy: Math.ceil(others.props.h / 15) }
return coord;
}

return (
<text
{...others}
dy={-10}
dx={labelCoordinates().dx}
dy={labelCoordinates().dy}
fontSize={12}
fill="var(--chart-text-color, var(--mantine-color-dimmed))"
textAnchor="center"
Expand Down Expand Up @@ -260,7 +273,7 @@ export const BarChart = factory<BarChartFactory>((_props, ref) => {
fillOpacity={dimmed ? 0.1 : fillOpacity}
strokeOpacity={dimmed ? 0.2 : 0}
stackId={stacked ? 'stack' : item.stackId || undefined}
label={withBarValueLabel ? <BarLabel valueFormatter={valueFormatter} /> : undefined}
label={withBarValueLabel ? <BarLabel valueFormatter={valueFormatter} props={_props} /> : undefined}
yAxisId={item.yAxisId || 'left'}
minPointSize={minBarSize}
{...(typeof barProps === 'function' ? barProps(item) : barProps)}
Expand Down

0 comments on commit d4c46b4

Please sign in to comment.