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
8 changes: 8 additions & 0 deletions .changeset/termchart-legend-matches-chart.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
'@hyperdx/cli': patch
---

fix: stacked bar charts in `hdx` give palette colors to the largest series
first, list only series that are visible in the legend (with a count of the
rest), color a partial top cell by the series filling most of it, and separate
wide bars with a gap.
22 changes: 22 additions & 0 deletions packages/cli/src/__tests__/chartData.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,4 +52,26 @@ describe('formatResponseForTimeChart', () => {
expect(graphResults.length).toBe(2);
},
);

it('colors series largest first so the biggest get distinct palette colors', () => {
const { series } = formatResponseForTimeChart({
response: {
meta: [
{ name: 'ts', type: 'DateTime' },
{ name: 'count()', type: 'UInt64' },
{ name: 'service', type: 'String' },
],
data: [
{ ts: '2026-07-02T00:00:00Z', 'count()': '1', service: 'small' },
{ ts: '2026-07-02T00:00:00Z', 'count()': '900', service: 'big' },
{ ts: '2026-07-03T00:00:00Z', 'count()': '50', service: 'mid' },
],
rows: 3,
},
dateRange,
generateEmptyBuckets: false,
});
expect(series.map(s => s.displayName)).toEqual(['big', 'mid', 'small']);
expect(series[0].color).toBe('blue');
});
});
108 changes: 108 additions & 0 deletions packages/cli/src/__tests__/termchart.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { describe, expect, it } from '@jest/globals';

import { renderLegend } from '@/termchart/ansi';
import {
niceTicks,
renderLineChart,
Expand Down Expand Up @@ -297,4 +298,111 @@ describe('renderStackedBarChart', () => {
expect(topRow).toContain('█');
expect(topRow).toContain('100');
});

it('leaves series too small to draw out of the legend', () => {
const output = stripAnsi(
renderStackedBarChart({
data: makeTimeChartData({
big: [1000, 1000, 1000],
mid: [400, 400, 400],
tiny: [0.001, 0.001, 0.001],
none: [0, 0, 0],
}),
width: 60,
height: 14,
}),
);
const legend = output.split('\n').at(-1);
expect(legend).toContain('● big');
expect(legend).toContain('● mid');
expect(legend).not.toContain('tiny');
expect(legend).toContain('+2 not shown');
});

it('credits a partial top cell to the series filling most of it, not a sliver on top', () => {
const output = stripAnsi(
renderStackedBarChart({
data: makeTimeChartData({
base: [1000, 1000],
sliver: [60, 60],
crumb: [1, 1],
}),
width: 60,
height: 14,
}),
);
const legend = output.split('\n').at(-1);
expect(legend).toContain('● sliver');
expect(legend).not.toContain('crumb');
});

it('gives a partial cell to the series covering most of it', () => {
// Top cell holds ~0.26 rows of b, 0.22 of c and 0.12 of d.
const output = stripAnsi(
renderStackedBarChart({
data: makeTimeChartData({ a: [1000], b: [13], c: [11], d: [6] }),
width: 60,
height: 28,
}),
);
const legend = output.split('\n').at(-1);
expect(legend).toContain('● b');
expect(legend).not.toContain('● c');
});

it('keeps the legend and its hidden count within the width', () => {
const name = (c: string) => c.repeat(25);
const output = stripAnsi(
renderStackedBarChart({
data: makeTimeChartData({
[name('a')]: [1000, 1000],
[name('b')]: [900, 900],
[name('c')]: [0.001, 0.001],
}),
width: 60,
height: 14,
}),
);
const legendLines = output.split('\n').slice(-2);
for (const line of legendLines) expect(line.length).toBeLessThanOrEqual(60);
// Both drawn series stay listed; the count moves to the spare legend row.
expect(legendLines[0]).toContain(name('a'));
expect(legendLines[0]).toContain(name('b'));
expect(legendLines[1]).toBe('+1 not shown');
});

it('separates wide bars with a gap column', () => {
const output = stripAnsi(
renderStackedBarChart({
data: makeTimeChartData({ events: [5, 5, 5] }),
width: 42,
height: 8,
showLegend: false,
}),
);
const bottomRow = output.split('\n').at(-2)!;
const bars = bottomRow.slice(bottomRow.indexOf('┤') + 1);
expect(bars.trimEnd().split(/ +/)).toHaveLength(3);
});
});

describe('renderLegend', () => {
const series = Array.from({ length: 8 }, (_, i) => ({
displayName: `service-${i}-${'x'.repeat(12)}`,
color: 'blue',
}));

it('fits a "+K more" overflow within the width on the last allowed line', () => {
const lines = stripAnsi(renderLegend(series, 60, 2)).split('\n');
expect(lines).toHaveLength(2);
for (const line of lines) expect(line.length).toBeLessThanOrEqual(60);
const listed = (lines.join(' ').match(/●/g) ?? []).length;
expect(lines[1]).toMatch(new RegExp(`\\+${series.length - listed} more$`));
});

it('counts hidden series in a "+N not shown" tail, even with one line', () => {
const line = stripAnsi(renderLegend(series.slice(0, 2), 60, 1, 3));
expect(line.length).toBeLessThanOrEqual(60);
expect(line).toMatch(/\+\d+ not shown$/);
});
});
14 changes: 12 additions & 2 deletions packages/cli/src/shared/chartData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,7 @@ export function formatResponseForTimeChart({
> = {};

const firstGroupIsLogLevel = firstGroupColumnIsLogLevel(source, groupColumns);
const peakByKey = new Map<string, number>();

for (const row of response.data) {
const date = new Date(row[timestampColumn.name] as string | number);
Expand Down Expand Up @@ -319,6 +320,12 @@ export function formatResponseForTimeChart({
: Number.parseFloat(String(rawValue));

tsBucket[keyName] = value;
if (Number.isFinite(value)) {
peakByKey.set(
keyName,
Math.max(peakByKey.get(keyName) ?? 0, Math.abs(value)),
);
}

// Special handling for log level / trace severity colors
let color: string | undefined = undefined;
Expand All @@ -337,12 +344,15 @@ export function formatResponseForTimeChart({
}
}

// Sort log-level series info < warn < error, matching the web ordering
// Sort log-level series info < warn < error, then by peak per series so the
// 8-color palette goes to the largest first. The web ranks by peak only to cap
// series counts, and by group rather than per value column.
const logLevelColorOrder = ['green', 'yellow', 'red'];
const sortedSeries = Object.values(seriesMap).sort((a, b) => {
return (
logLevelColorOrder.findIndex(color => color === a.color) -
logLevelColorOrder.findIndex(color => color === b.color)
logLevelColorOrder.findIndex(color => color === b.color) ||
(peakByKey.get(b.dataKey) ?? 0) - (peakByKey.get(a.dataKey) ?? 0)
);
});

Expand Down
75 changes: 51 additions & 24 deletions packages/cli/src/termchart/ansi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,31 +148,58 @@ export function renderLegend(
series: Pick<TimeChartSeries, 'displayName' | 'color'>[],
width: number,
maxLines = 2,
/** Series left out before layout (e.g. never drawn), counted in the tail */
hiddenCount = 0,
): string {
const lines: string[] = [];
let current = '';
let currentLen = 0;
let shown = 0;

for (const s of series) {
const label = `● ${truncate(s.displayName, 40)}`;
const sep = currentLen > 0 ? ' ' : '';
if (currentLen + sep.length + label.length > width) {
lines.push(current);
if (lines.length >= maxLines) {
const remaining = series.length - shown;
if (remaining > 0) {
lines[lines.length - 1] += chalk.dim(` +${remaining} more`);
}
return lines.join('\n');
}
current = '';
currentLen = 0;
const labels = series.map(s => ({
text: `● ${truncate(s.displayName, 40)}`,
color: s.color,
}));
const lines: (typeof labels)[] = [[]];
const lineLen = (line: typeof labels) =>
line.reduce((n, l, i) => n + (i > 0 ? 2 : 0) + l.text.length, 0);
for (const label of labels) {
const last = lines[lines.length - 1];
if (last.length > 0 && lineLen(last) + 2 + label.text.length > width) {
if (lines.length >= maxLines) break;
lines.push([]);
}
current += (currentLen > 0 ? ' ' : '') + chalkColor(s.color)(label);
currentLen += (currentLen > 0 ? 2 : 0) + label.length;
shown++;
lines[lines.length - 1].push(label);
}
if (current) lines.push(current);
return lines.join('\n');

// The tail must fit on the last line, so drop labels until it does.
const tail = (listed: number) => {
const missing = series.length - listed + hiddenCount;
if (missing <= 0) return '';
return hiddenCount > 0 ? `+${missing} not shown` : `+${missing} more`;
};
const listed = () => lines.reduce((n, l) => n + l.length, 0);
const fits = (line: typeof labels) =>
lineLen(line) + (line.length > 0 ? 2 : 0) + tail(listed()).length <= width;
if (
tail(listed()) &&
!fits(lines[lines.length - 1]) &&
lines.length < maxLines
) {
lines.push([]);
}
const last = lines[lines.length - 1];
while (
tail(listed()) &&
last.length > 0 &&
lineLen(last) + 2 + tail(listed()).length > width
) {
last.pop();
}

const text = lines.map(line =>
line.map(l => chalkColor(l.color)(l.text)).join(' '),
);
const tailText = tail(listed());
if (tailText) {
text[text.length - 1] = [text[text.length - 1], chalk.dim(tailText)]
.filter(Boolean)
.join(' ');
}
return text.filter(Boolean).join('\n');
}
3 changes: 2 additions & 1 deletion packages/cli/src/termchart/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ export {
renderTableChart,
} from '@/termchart/charts';
export { niceTicks, resampleSeries } from '@/termchart/scale';
export { renderLineChart, renderStackedBarChart } from '@/termchart/timeseries';
export { renderStackedBarChart } from '@/termchart/stackedBar';
export { renderLineChart } from '@/termchart/timeseries';
export type {
CategoricalEntry,
TableColumn,
Expand Down
Loading
Loading