Files
manage/frontend/src/components/chartRanges.ts
T
2026-07-15 18:55:57 +00:00

82 lines
2.5 KiB
TypeScript

export type ChartRangeValue = number | "all";
export interface ChartRangeOption {
value: ChartRangeValue;
label: string;
}
interface FiniteChartRange extends ChartRangeOption {
key: string;
value: number;
}
/** Canonical finite windows for chart configuration and display filtering. */
const FINITE_CHART_RANGES: readonly FiniteChartRange[] = [
{ key: "5m", value: 300, label: "5 minutes" },
{ key: "15m", value: 900, label: "15 minutes" },
{ key: "30m", value: 1800, label: "30 minutes" },
{ key: "1h", value: 3600, label: "1 hour" },
{ key: "3h", value: 10800, label: "3 hours" },
{ key: "6h", value: 21600, label: "6 hours" },
{ key: "12h", value: 43200, label: "12 hours" },
{ key: "24h", value: 86400, label: "24 hours" },
{ key: "2d", value: 172800, label: "2 days" },
{ key: "7d", value: 604800, label: "7 days" },
{ key: "14d", value: 1209600, label: "14 days" },
{ key: "30d", value: 2592000, label: "30 days" },
];
/** Shared range choices used by every time-series chart. */
export const DEFAULT_CHART_RANGES: readonly ChartRangeOption[] =
FINITE_CHART_RANGES;
/** Symbolic range values persisted by Prometheus chart and mean widgets. */
export const PROMETHEUS_WINDOW_VALUES = FINITE_CHART_RANGES.map(
(range) => range.key,
);
export const ALL_VALUES_CHART_RANGE: ChartRangeOption = {
value: "all",
label: "All values",
};
function formatRangeLabel(seconds: number): string {
if (seconds % 604800 === 0) return `${seconds / 604800} days`;
if (seconds % 3600 === 0) return `${seconds / 3600} hours`;
if (seconds % 60 === 0) return `${seconds / 60} minutes`;
return `${seconds} seconds`;
}
export function chartRangesThrough(maxSeconds: number): ChartRangeOption[] {
if (!Number.isFinite(maxSeconds) || maxSeconds <= 0) {
return [DEFAULT_CHART_RANGES[0], ALL_VALUES_CHART_RANGE];
}
const ranges = FINITE_CHART_RANGES.filter(
(range) => range.value < maxSeconds,
);
const exact = FINITE_CHART_RANGES.find((range) => range.value === maxSeconds);
return [
...(exact
? [...ranges, exact]
: [
...ranges,
{ value: maxSeconds, label: formatRangeLabel(maxSeconds) },
]),
ALL_VALUES_CHART_RANGE,
];
}
export function rangeSecondsFromWindow(window: unknown): number {
return (
FINITE_CHART_RANGES.find((range) => range.key === String(window))?.value ??
3600
);
}
/** Numeric chart windows suitable for sources with bounded local retention. */
export function numericChartRangesThrough(maxSeconds: number): number[] {
return FINITE_CHART_RANGES.flatMap((range) =>
range.value <= maxSeconds ? [range.value] : [],
);
}