Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/stacked-combo-bars.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@agent-native/toolkit": patch
---

Fix stacked bar series in combo charts while preserving independent target lines.
265 changes: 263 additions & 2 deletions packages/toolkit/src/app/dashboard-charts/DashboardPanelChart.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,21 @@ describe("DashboardPanelChart", () => {
{ configurable: true, value },
);
}
HTMLElement.prototype.getBoundingClientRect = () =>
({ ...CHART_SIZE, top: 0, left: 0, right: 640, bottom: 320 }) as DOMRect;
HTMLElement.prototype.getBoundingClientRect = function () {
if (this.id === "recharts_measurement_span") {
return {
width: this.textContent.length * 7,
height: 12,
} as DOMRect;
}
return {
...CHART_SIZE,
top: 0,
left: 0,
right: 640,
bottom: 320,
} as DOMRect;
};
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
Expand Down Expand Up @@ -108,6 +121,254 @@ describe("DashboardPanelChart", () => {
},
);

it("stacks combo bars under a target line on its own axis and groups them by default", async () => {
const rows = [
{ day: "2026-10-11", north: 30, south: 20, target: 500 },
{ day: "2026-10-12", north: 40, south: 30, target: 1000 },
];
const config = {
xKey: "day",
yKeys: ["north", "south", "target"],
barKeys: ["north", "south"],
rightYKeys: ["target"],
};
const rectangles = () =>
[...container.querySelectorAll(".recharts-bar-rectangle path")].map(
(path) => ({
x: Number(path.getAttribute("x")),
y: Number(path.getAttribute("y")),
width: Number(path.getAttribute("width")),
height: Number(path.getAttribute("height")),
}),
);

await render(
<DashboardPanelChart
panel={panel("combo", { ...config, stacked: true })}
rows={rows}
/>,
);
const stacked = rectangles();
expect(stacked).toHaveLength(4);
const [northFirst, northSecond, southFirst] = stacked;
expect(northFirst.height).toBeGreaterThan(0);
expect(southFirst.height).toBeGreaterThan(0);
expect(northFirst.x).toBeCloseTo(southFirst.x);
expect(northFirst.width).toBeCloseTo(southFirst.width);
expect(southFirst.y + southFirst.height).toBeCloseTo(northFirst.y);
const targetLine = container
.querySelector(".recharts-line-curve")
?.getAttribute("d");
const points = targetLine?.match(/^M([\d.]+),([\d.]+)L([\d.]+),([\d.]+)$/);
if (!points) throw new Error("Missing target line");
const [, x1, y1, x2, y2] = points.map(Number);
const grid = [
...container.querySelectorAll(".recharts-cartesian-grid-horizontal line"),
].map((line) => Number(line.getAttribute("y1")));
expect(grid).toHaveLength(2);
const [top, bottom] = grid;
expect(container.querySelectorAll(".recharts-yAxis")).toHaveLength(2);
expect(x1).toBeCloseTo(northFirst.x + northFirst.width / 2);
expect(x2).toBeCloseTo(northSecond.x + northSecond.width / 2);
expect(y1).toBeCloseTo((top + bottom) / 2);
expect(y2).toBeCloseTo(top);

await render(
<DashboardPanelChart panel={panel("combo", config)} rows={rows} />,
);
const grouped = rectangles();
expect(grouped).toHaveLength(4);
const [groupNorth, , groupSouth] = grouped;
expect(groupNorth.x).not.toBeCloseTo(groupSouth.x);
expect(groupNorth.y + groupNorth.height).toBeCloseTo(
groupSouth.y + groupSouth.height,
);
expect(
container.querySelector(".recharts-line-curve")?.getAttribute("d"),
).toBe(targetLine);
});

it("stacks positive and negative combo bars on opposite sides of zero", async () => {
const config = {
xKey: "day",
yKeys: ["positive", "negative", "morePositive", "moreNegative", "target"],
barKeys: ["positive", "negative", "morePositive", "moreNegative"],
};
const rows = [
{
day: "2026-10-11",
positive: 30,
negative: -20,
morePositive: 10,
moreNegative: -10,
target: 5,
},
];
const bars = () =>
[...container.querySelectorAll(".recharts-bar-rectangle path")].map(
(path) => {
const y = Number(path.getAttribute("y"));
const height = Number(path.getAttribute("height"));
return {
x: Number(path.getAttribute("x")),
y: Math.min(y, y + height),
height: Math.abs(height),
};
},
);

await render(
<DashboardPanelChart
panel={panel("combo", { ...config, stacked: true })}
rows={rows}
/>,
);
const [positive, negative, morePositive, moreNegative] = bars();
expect(bars()).toHaveLength(4);
expect(positive.height).toBeGreaterThan(0);
expect(negative.height).toBeGreaterThan(0);
expect(morePositive.height).toBeGreaterThan(0);
expect(moreNegative.height).toBeGreaterThan(0);
expect(positive.x).toBeCloseTo(negative.x);
expect(negative.y).toBeCloseTo(positive.y + positive.height);
expect(morePositive.y + morePositive.height).toBeCloseTo(positive.y);
expect(moreNegative.y).toBeCloseTo(negative.y + negative.height);

await render(
<DashboardPanelChart panel={panel("combo", config)} rows={rows} />,
);
const [groupedPositive, groupedNegative] = bars();
expect(groupedPositive.x).not.toBeCloseTo(groupedNegative.x);
expect(groupedNegative.y).toBeCloseTo(
groupedPositive.y + groupedPositive.height,
);
});

it("positions stacks on different value axes side by side", async () => {
await render(
<DashboardPanelChart
panel={panel("combo", {
xKey: "day",
yKeys: ["north", "south", "east", "west", "target"],
barKeys: ["north", "south", "east", "west"],
rightYKeys: ["east", "west", "target"],
stacked: true,
})}
rows={[
{
day: "2026-10-11",
north: 30,
south: 20,
east: 40,
west: 30,
target: 100,
},
]}
/>,
);
const bars = [
...container.querySelectorAll(".recharts-bar-rectangle path"),
].map((path) => ({
x: Number(path.getAttribute("x")),
y: Number(path.getAttribute("y")),
width: Number(path.getAttribute("width")),
height: Number(path.getAttribute("height")),
}));
expect(bars).toHaveLength(4);
const [north, south, east, west] = bars;
expect(north.x).toBeCloseTo(south.x);
expect(south.y + south.height).toBeCloseTo(north.y);
expect(east.x).toBeCloseTo(west.x);
expect(west.y + west.height).toBeCloseTo(east.y);
expect(north.x + north.width).toBeLessThanOrEqual(east.x);
});

it("sizes duration axes to visible stacked bars and independent lines", async () => {
const hour = 3600;
const config = {
xKey: "day",
yKeys: ["north", "south", "east", "west", "target"],
barKeys: ["north", "south", "east", "west"],
rightYKeys: ["east", "west", "target"],
yFormatter: "duration" as const,
rightYFormatter: "duration" as const,
stacked: true,
};
const row = {
day: "2026-10-11",
north: 6 * hour,
south: 6 * hour,
east: 12 * hour,
west: 12 * hour,
target: 15 * hour,
};
await render(
<DashboardPanelChart panel={panel("combo", config)} rows={[row]} />,
);
const labels = () =>
[...container.querySelectorAll(".recharts-yAxis-tick-labels")].map(
(axis) =>
[...axis.querySelectorAll(".recharts-cartesian-axis-tick-value")].map(
(tick) => tick.textContent,
),
);
expect(labels()).toEqual([
["0 sec", "3 hours", "6 hours", "9 hours", "12 hours"],
["0 sec", "6 hours", "12 hours", "18 hours", "24 hours"],
]);
await render(
<DashboardPanelChart
panel={panel("combo", config)}
rows={[{ ...row, target: 30 * hour }]}
/>,
);
expect(labels()[1]).toEqual(["0 sec", "12 hours", "24 hours", "36 hours"]);
const south = container.querySelector<HTMLButtonElement>(
'[data-chart-legend-item="south"]',
);
if (!south) throw new Error("Missing south legend item");
await act(async () => south.click());
expect(labels()[0]).toEqual(["0 sec", "2 hours", "4 hours", "6 hours"]);
});

it("uses the same duration scale as stacked bars without stacking the line", async () => {
const hour = 3600;
const rows = [
{ day: "2026-10-11", north: 6 * hour, south: 6 * hour, target: 3 * hour },
];
const config = {
xKey: "day",
yKeys: ["north", "south", "target"],
barKeys: ["north", "south"],
yFormatter: "duration" as const,
};
const labels = () =>
[
...container.querySelectorAll(
".recharts-yAxis-tick-labels .recharts-cartesian-axis-tick-value",
),
].map((tick) => tick.textContent);

await render(
<DashboardPanelChart
panel={panel("combo", { ...config, stacked: true })}
rows={rows}
/>,
);
expect(labels()).toEqual([
"0 sec",
"3 hours",
"6 hours",
"9 hours",
"12 hours",
]);

await render(
<DashboardPanelChart panel={panel("combo", config)} rows={rows} />,
);
expect(labels()).toEqual(["0 sec", "2 hours", "4 hours", "6 hours"]);
});

it("dashes the day the rows were read as unfinished, not today", async () => {
const line = panel("line", { xKey: "day", yKeys: ["people"] });
await render(<DashboardPanelChart panel={line} rows={DAYS} />);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,7 @@ export function DashboardPanelChart({
colors={seriesColors}
yFormatter={yFormatter}
barKeys={panel.config?.barKeys ?? []}
stacked={panel.config?.stacked === true}
panel={panel}
onDatumClick={onDatumClick}
/>,
Expand Down
14 changes: 13 additions & 1 deletion packages/toolkit/src/app/dashboard-charts/panel-chart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,7 @@
rows: Record<string, unknown>[];
keys: string[];
stacked?: boolean | undefined;
stackedKeys?: ReadonlySet<string> | undefined;
};

// Duration axes step in clean units ("6 hours") rather than the decimal
Expand All @@ -324,7 +325,7 @@
for (const key of keys) {
const value = Number(row[key]);
if (!Number.isFinite(value)) continue;
if (values.stacked) {
if (values.stacked || values.stackedKeys?.has(key)) {
if (value < 0) below += value;
else above += value;
} else {
Expand Down Expand Up @@ -772,7 +773,7 @@
const [hiddenKeys, setHiddenKeys] = useState<Set<string>>(() => new Set());

useEffect(() => {
setHiddenKeys((prev) => {

Check warning on line 776 in packages/toolkit/src/app/dashboard-charts/panel-chart.tsx

View workflow job for this annotation

GitHub Actions / Lint & format

react(set-state-in-effect)

packages/toolkit/src/app/dashboard-charts/panel-chart.tsx:776:5: Calling setState synchronously within an effect can trigger cascading renders
const next = new Set(
Array.from(prev).filter((key) => keys.includes(key)),
);
Expand Down Expand Up @@ -2042,7 +2043,7 @@
if (configured.length > 0) return configured;
}
return Object.keys(rows[0]).map((key) => ({ key }));
}, [config?.columns, rows, rowKeys]);

Check warning on line 2046 in packages/toolkit/src/app/dashboard-charts/panel-chart.tsx

View workflow job for this annotation

GitHub Actions / Lint & format

react(preserve-manual-memoization)

packages/toolkit/src/app/dashboard-charts/panel-chart.tsx:2046:6: Existing memoization could not be preserved

// A viewer's own widths are drawn over the saved ones but never saved:
// edits start from `editableColumns`, which reads the panel config.
Expand All @@ -2068,7 +2069,7 @@
...base,
...columns.filter((c) => !listed.has(c.key)).map((c) => ({ key: c.key })),
];
}, [config?.columns, rows, columns]);

Check warning on line 2072 in packages/toolkit/src/app/dashboard-charts/panel-chart.tsx

View workflow job for this annotation

GitHub Actions / Lint & format

react(preserve-manual-memoization)

packages/toolkit/src/app/dashboard-charts/panel-chart.tsx:2072:6: Existing memoization could not be preserved

const hiddenColumns = editable
? editableColumns.filter((c) => c.hidden && rowKeys.has(c.key))
Expand Down Expand Up @@ -2373,7 +2374,7 @@
const [pageSize, setPageSize] = useState(DEFAULT_TABLE_PAGE_SIZE);

// Formats, not widths, decide these, so resizing a column doesn't redo it.
const numberColumns = useMemo(

Check warning on line 2377 in packages/toolkit/src/app/dashboard-charts/panel-chart.tsx

View workflow job for this annotation

GitHub Actions / Lint & format

react(preserve-manual-memoization)

packages/toolkit/src/app/dashboard-charts/panel-chart.tsx:2377:25: Existing memoization could not be preserved
() => numberTableColumns(savedColumns, limitedRows),
[savedColumns, limitedRows],
);
Expand All @@ -2382,7 +2383,7 @@
return sortable
? sortTableRows(limitedRows, sortColumns, savedColumns, numberColumns)
: limitedRows;
}, [limitedRows, sortColumns, sortable, savedColumns, numberColumns]);

Check warning on line 2386 in packages/toolkit/src/app/dashboard-charts/panel-chart.tsx

View workflow job for this annotation

GitHub Actions / Lint & format

react(preserve-manual-memoization)

packages/toolkit/src/app/dashboard-charts/panel-chart.tsx:2386:57: Existing memoization could not be preserved

Check warning on line 2386 in packages/toolkit/src/app/dashboard-charts/panel-chart.tsx

View workflow job for this annotation

GitHub Actions / Lint & format

react(preserve-manual-memoization)

packages/toolkit/src/app/dashboard-charts/panel-chart.tsx:2386:20: Existing memoization could not be preserved

const pageCount = Math.ceil(sortedRows.length / pageSize);
// A refresh can return fewer rows than the page a viewer was on; show the
Expand Down Expand Up @@ -3137,6 +3138,7 @@
colors,
yFormatter,
barKeys,
stacked,
panel,
onDatumClick,
}: {
Expand All @@ -3146,6 +3148,7 @@
colors: string[];
yFormatter?: ChartValueFormatter | undefined;
barKeys: string[];
stacked?: boolean;
panel: SqlPanel;
onDatumClick?: DatumClickHandler | undefined;
}) {
Expand Down Expand Up @@ -3225,6 +3228,7 @@
<ComposedChart
data={rows}
margin={chartMargin.margin}
stackOffset={stacked ? "sign" : undefined}
{...chartClick.props}
>
{chartClick.locator}
Expand All @@ -3248,6 +3252,7 @@
{renderChartYAxes(dualAxis, yFormatter, {
rows,
keys: yKeys.filter((key) => !hiddenKeys.has(key)),
stackedKeys: stacked ? barKeySet : undefined,
})}
<CartesianGrid
strokeDasharray="3 3"
Expand Down Expand Up @@ -3285,6 +3290,13 @@
yAxisId={seriesAxisId(dualAxis, key)}
fill={colors[i % colors.length]}
radius={[4, 4, 0, 0]}
stackId={
stacked
? dualAxis.enabled
? `stack-${seriesAxisId(dualAxis, key)}`
: "stack"
: undefined
}
hide={hiddenKeys.has(key)}
isAnimationActive={false}
{...chartSeriesClickProps(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,10 +106,10 @@
}`}
>
<div className="relative overflow-x-auto">
<div className="min-w-[480px]">

Check warning on line 109 in templates/analytics/app/components/dashboard/SqlChartQuery.tsx

View workflow job for this annotation

GitHub Actions / Lint & format

shadcn(no-arbitrary-values)

templates/analytics/app/components/dashboard/SqlChartQuery.tsx:109:24: "min-w-[480px]" hardcodes an off-token value. Use "min-w-120" instead (same value, on the scale). Use the component's props, variants, and theme tokens. Read .agents/skills/shadcn-ui/SKILL.md before changing UI.
<div className="grid h-8 grid-cols-4 items-center border-b border-border px-2">
{columnWidths.map((width, index) => (
<DashboardPanelSkeleton key={index} className={`h-3 ${width}`} />

Check warning on line 112 in templates/analytics/app/components/dashboard/SqlChartQuery.tsx

View workflow job for this annotation

GitHub Actions / Lint & format

shadcn(require-static-classes)

templates/analytics/app/components/dashboard/SqlChartQuery.tsx:112:69: Dynamically built className on <Skeleton> cannot be checked. Use static class strings. Use the component's props, variants, and theme tokens. Read .agents/skills/shadcn-ui/SKILL.md before changing UI.
))}
</div>
{Array.from({ length: rows }).map((_, row) => (
Expand Down Expand Up @@ -349,10 +349,10 @@
() =>
planPanelRender(
rawRows,
panel,

Check warning on line 352 in templates/analytics/app/components/dashboard/SqlChartQuery.tsx

View workflow job for this annotation

GitHub Actions / Lint & format

react-hooks(exhaustive-deps)

templates/analytics/app/components/dashboard/SqlChartQuery.tsx:352:9: React Hook useMemo has a missing dependency: 'panel'
timeRange === undefined ? {} : { timeRange },
),
[rawRows, panel.chartType, panel.config, timeRange],

Check warning on line 355 in templates/analytics/app/components/dashboard/SqlChartQuery.tsx

View workflow job for this annotation

GitHub Actions / Lint & format

react-hooks(exhaustive-deps)

templates/analytics/app/components/dashboard/SqlChartQuery.tsx:355:6: React hook useMemo depends on `rawRows`, which changes every render
);
const { rows: queryRows, xKey, yKeys } = plan;
const shouldCreateDemoTrend =
Expand Down Expand Up @@ -721,6 +721,7 @@
colors={seriesColors}
yFormatter={yFormatter}
barKeys={panel.config?.barKeys ?? []}
stacked={panel.config?.stacked === true}
panel={panel}
onDatumClick={onDatumClick}
/>,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
type: fixed
date: 2026-11-20
---

Stacked combo charts now display bar series correctly alongside target lines.
Loading