Files
pterodactyl-panel/resources/scripts/components/server/console/chart.ts
T

68 lines
1.9 KiB
TypeScript
Raw Normal View History

2026-10-05 18:10:18 -04:00
import { useCallback, useEffect, useState, type RefObject } from 'react';
2026-10-05 18:10:18 -04:00
export const CHART_WINDOW_MS = 20_000;
2026-10-05 18:10:18 -04:00
const RETAIN_MS = CHART_WINDOW_MS + 2_000;
2026-10-05 18:10:18 -04:00
// `t` is a performance.now() timestamp; a series value is null until its first sample.
export type ChartPoint = { t: number } & Record<string, number | null>;
2026-10-05 18:10:18 -04:00
/** Rolling buffer of timestamped samples; `keys` must be referentially stable. */
export function useRollingData(keys: readonly string[]) {
const [data, setData] = useState<ChartPoint[]>([]);
const push = useCallback(
(values: Record<string, number | null>, t: number) =>
setData((prev) => {
const point: ChartPoint = { t };
2026-10-08 16:53:20 -04:00
2026-10-05 18:10:18 -04:00
for (const key of keys) {
const value = values[key];
2026-10-08 16:53:20 -04:00
2026-10-05 18:10:18 -04:00
point[key] = value === null || value === undefined ? null : Number(value.toFixed(2));
}
2026-10-08 16:53:20 -04:00
2026-10-05 18:10:18 -04:00
const cutoff = t - RETAIN_MS;
let start = 0;
2026-10-08 16:53:20 -04:00
while (start < prev.length && prev[start].t < cutoff) {
start++;
}
2026-10-05 18:10:18 -04:00
return [...prev.slice(start), point];
}),
[keys]
);
2026-10-05 18:10:18 -04:00
const clear = useCallback(() => setData([]), []);
return { data, push, clear };
}
2026-10-08 17:40:00 -04:00
/** The element's width in whole pixels; 0 until it has been measured. */
export function useElementWidth(ref: RefObject<Element | null>): number {
const [width, setWidth] = useState(0);
2026-10-05 18:10:18 -04:00
useEffect(() => {
const element = ref.current;
2026-10-08 16:53:20 -04:00
if (!element) {
return;
}
2026-10-05 18:10:18 -04:00
2026-10-08 17:40:00 -04:00
const observer = new ResizeObserver((entries) => {
2026-10-08 16:53:20 -04:00
const entry = entries.at(-1);
2026-10-05 18:10:18 -04:00
if (entry) {
2026-10-08 17:40:00 -04:00
setWidth(Math.floor(entry.contentRect.width));
2026-10-05 18:10:18 -04:00
}
});
2026-10-08 16:53:20 -04:00
2026-10-05 18:10:18 -04:00
observer.observe(element);
return () => observer.disconnect();
}, [ref]);
2026-10-08 17:40:00 -04:00
return width;
2026-10-05 18:10:18 -04:00
}