import type * as Plotly from 'plotly.js'; 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[], layout: Partial, ): Partial { const labelled: Record<(typeof AXES)[number], number[]> = { xaxis: [], yaxis: [] }; 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[]; labelled[horizontal ? 'xaxis' : 'yaxis'].push( ...values.filter((v): v is number => typeof v === 'number' && Number.isFinite(v)), ); } const room: Partial = {}; for (const key of AXES) { const values = labelled[key]; const axis = layout[key]; if (!values.length || axis?.range) continue; const low = Math.min(0, ...values); const high = Math.max(0, ...values); if (low === high) continue; room[key] = { ...axis, range: [low * HEADROOM, high * HEADROOM] }; } return room; }