Files

66 lines
2.0 KiB
TypeScript
Raw Permalink Normal View History

2026-10-12 15:20:31 -04:00
import { 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-12 15:20:31 -04:00
// Type aliases, not interfaces, so a chart reads them as `ChartPoint`s.
export type ServerGraphPoint = { readonly t: number; readonly value: number | null };
export type ServerNetworkPoint = { readonly t: number; readonly rx: number | null; readonly tx: number | null };
export interface ServerGraphs {
/** CPU load in percent. */
readonly cpu: readonly ServerGraphPoint[];
/** Memory in MiB. */
readonly memory: readonly ServerGraphPoint[];
/** Bytes received and sent since the previous sample. */
readonly network: readonly ServerNetworkPoint[];
}
2026-10-08 16:53:20 -04:00
2026-10-12 15:20:31 -04:00
/** A sample value as the graphs plot it. */
export const chartValue = (value: number): number => Number(value.toFixed(2));
2026-10-08 16:53:20 -04:00
2026-10-12 15:20:31 -04:00
/** Appends a sample to a rolling buffer, dropping samples older than the chart window keeps. */
export function appendChartPoint<TPoint extends { readonly t: number }>(
points: readonly TPoint[],
point: TPoint
): TPoint[] {
const cutoff = point.t - RETAIN_MS;
let start = 0;
2026-10-05 18:10:18 -04:00
2026-10-12 15:20:31 -04:00
while (start < points.length && points[start].t < cutoff) {
start++;
}
2026-10-05 18:10:18 -04:00
2026-10-12 15:20:31 -04:00
return [...points.slice(start), point];
}
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
}