Headroom reads bar traces through a local shape; Plotly types export no PlotData here
This commit is contained in:
@@ -4,12 +4,20 @@ export const HEADROOM = 1.15;
|
||||
|
||||
const AXES = ['xaxis', 'yaxis'] as const;
|
||||
|
||||
interface BarTrace {
|
||||
type?: string;
|
||||
textposition?: unknown;
|
||||
orientation?: string;
|
||||
x?: unknown;
|
||||
y?: unknown;
|
||||
}
|
||||
|
||||
export function headroom(
|
||||
data: Partial<Plotly.Data>[],
|
||||
layout: Partial<Plotly.Layout>,
|
||||
): Partial<Plotly.Layout> {
|
||||
const labelled: Record<(typeof AXES)[number], number[]> = { xaxis: [], yaxis: [] };
|
||||
for (const trace of data as Partial<Plotly.PlotData>[]) {
|
||||
for (const trace of data as BarTrace[]) {
|
||||
if (trace.type !== 'bar' || trace.textposition !== 'outside') continue;
|
||||
const horizontal = trace.orientation === 'h';
|
||||
const values = ((horizontal ? trace.x : trace.y) ?? []) as unknown[];
|
||||
@@ -17,15 +25,15 @@ export function headroom(
|
||||
...values.filter((v): v is number => typeof v === 'number' && Number.isFinite(v)),
|
||||
);
|
||||
}
|
||||
return Object.fromEntries(
|
||||
AXES.flatMap((key) => {
|
||||
const room: Partial<Plotly.Layout> = {};
|
||||
for (const key of AXES) {
|
||||
const values = labelled[key];
|
||||
const axis = layout[key];
|
||||
if (!values.length || axis?.range) return [];
|
||||
if (!values.length || axis?.range) continue;
|
||||
const low = Math.min(0, ...values);
|
||||
const high = Math.max(0, ...values);
|
||||
if (low === high) return [];
|
||||
return [[key, { ...axis, range: [low * HEADROOM, high * HEADROOM] as [number, number] }]];
|
||||
}),
|
||||
);
|
||||
if (low === high) continue;
|
||||
room[key] = { ...axis, range: [low * HEADROOM, high * HEADROOM] };
|
||||
}
|
||||
return room;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user