feat: add someIterable utility function and update Metric components for consistent metric handling

- Introduced `someIterable` function to check for the presence of a metric in an iterable.
- Updated `CustomTooltip` and `Metric` components to use `metric` instead of `stat` for improved clarity.
- Refactored `StatChart` to align with the new metric naming convention.
This commit is contained in:
Adam Shiervani 2025-08-26 16:47:16 +02:00
parent 5acfb67d29
commit 3bd9f841e0
6 changed files with 90 additions and 87 deletions

View File

@ -1,25 +1,25 @@
import Card from "@components/Card";
export interface CustomTooltipProps {
payload: { payload: { date: number; stat: number }; unit: string }[];
payload: { payload: { date: number; metric: number }; unit: string }[];
}
export default function CustomTooltip({ payload }: CustomTooltipProps) {
if (payload?.length) {
const toolTipData = payload[0];
const { date, stat } = toolTipData.payload;
const { date, metric } = toolTipData.payload;
return (
<Card>
<div className="p-2 text-black dark:text-white">
<div className="font-semibold">
<div className="px-2 py-1.5 text-black dark:text-white">
<div className="text-[13px] font-semibold">
{new Date(date * 1000).toLocaleTimeString()}
</div>
<div className="space-y-1">
<div className="flex items-center gap-x-1">
<div className="h-[2px] w-2 bg-blue-700" />
<span >
{stat} {toolTipData?.unit}
<span className="text-[13px]">
{metric} {toolTipData?.unit}
</span>
</div>
</div>

View File

@ -1,12 +1,14 @@
import { ComponentProps } from "react";
import { cva, cx } from "cva";
import { someIterable } from "../utils";
import { GridCard } from "./Card";
import StatChart from "./StatChart";
import MetricsChart from "./MetricsChart";
interface ChartPoint {
date: number;
stat: number | null;
metric: number | null;
}
interface MetricProps<T, K extends keyof T> {
@ -17,45 +19,42 @@ interface MetricProps<T, K extends keyof T> {
data?: ChartPoint[];
gate?: Map<number, unknown>;
supported?: boolean;
map?: (p: { date: number; stat: T[K] | null }) => ChartPoint;
map?: (p: { date: number; metric: number | null }) => ChartPoint;
domain?: [number, number];
unit?: string;
unit: string;
heightClassName?: string;
referenceValue?: number;
badge?: ComponentProps<typeof MetricHeader>["badge"];
badgeTheme?: ComponentProps<typeof MetricHeader>["badgeTheme"];
}
/* eslint-disable-next-line */
export function createChartArray<T, K extends keyof T>(
stream: Map<number, T>,
metric: K,
): { date: number; stat: T[K] | null }[] {
const stat = Array.from(stream).map(([key, stats]) => {
return { date: key, stat: stats[metric] };
});
// Sort the dates to ensure they are in chronological order
const sortedStat = stat.map(x => x.date).sort((a, b) => a - b);
// Determine the earliest statistic date
const earliestStat = sortedStat[0];
// Current time in seconds since the Unix epoch
metrics: Map<number, T>,
metricName: K,
) {
const result: { date: number; metric: number | null }[] = [];
const iter = metrics.entries();
let next = iter.next() as IteratorResult<[number, T]>;
const now = Math.floor(Date.now() / 1000);
// Determine the starting point for the chart data
const firstChartDate = earliestStat ? Math.min(earliestStat, now - 120) : now - 120;
// We want 120 data points, in the chart.
const firstDate = Math.min(next.value?.[0] ?? now, now - 120);
// Generate the chart array for the range between 'firstChartDate' and 'now'
return Array.from({ length: now - firstChartDate }, (_, i) => {
const currentDate = firstChartDate + i;
return {
date: currentDate,
// Find the statistic for 'currentDate', or use the last known statistic if none exists for that date
stat: stat.find(x => x.date === currentDate)?.stat ?? null,
};
});
for (let t = firstDate; t < now; t++) {
while (!next.done && next.value[0] < t) next = iter.next();
const has = !next.done && next.value[0] === t;
let metric = null;
if (has) metric = next.value[1][metricName] as number;
result.push({ date: t, metric });
if (has) next = iter.next();
}
return result;
}
const theme = {
light:
"bg-white text-black border border-slate-800/20 dark:border dark:border-slate-700 dark:bg-slate-800 dark:text-slate-300",
@ -110,26 +109,30 @@ export function Metric<T, K extends keyof T>({
domain = [0, 600],
unit = "",
heightClassName = "h-[127px]",
referenceValue,
badge,
badgeTheme,
}: MetricProps<T, K>) {
const ready = gate ? gate.size > 0 : stream ? stream.size > 0 : true;
const supportedFinal =
supported ??
(stream && metric
? Array.from(stream).some(([, s]) => s[metric] !== undefined)
: true);
(stream && metric ? someIterable(stream, ([, s]) => s[metric] !== undefined) : true);
const raw = stream && metric ? createChartArray(stream, metric) : [];
const dataFinal: ChartPoint[] =
data ??
(map
? raw.map(map)
: raw.map(x => ({
date: x.date,
stat: typeof x.stat === "number" ? (x.stat as unknown as number) : null,
})));
// Either we let the consumer provide their own chartArray, or we create one from the stream and metric.
const raw = data ?? ((stream && metric && createChartArray(stream, metric)) || []);
// If the consumer provides a map function, we apply it to the raw data.
const dataFinal: ChartPoint[] = map ? raw.map(map) : raw;
const recent = dataFinal
.slice(-(raw.length - 1))
.filter(x => x.metric != null) as ChartPoint[];
// Average the recent values
const computedReferenceValue =
recent.length > 0
? Math.round(
recent.reduce((sum, x) => sum + (x.metric as number), 0) / recent.length,
)
: undefined;
return (
<div className="space-y-2">
@ -149,11 +152,11 @@ export function Metric<T, K extends keyof T>({
<p className="text-slate-700">Waiting for data...</p>
</div>
) : supportedFinal ? (
<StatChart
<MetricsChart
data={dataFinal}
domain={domain}
unit={unit}
referenceValue={referenceValue}
referenceValue={computedReferenceValue}
/>
) : (
<div className="flex flex-col items-center space-y-1">

View File

@ -12,13 +12,13 @@ import {
import CustomTooltip, { CustomTooltipProps } from "@components/CustomTooltip";
export default function StatChart({
export default function MetricsChart({
data,
domain,
unit,
referenceValue,
}: {
data: { date: number; stat: number | null | undefined }[];
data: { date: number; metric: number | null | undefined }[];
domain?: [string | number, string | number];
unit?: string;
referenceValue?: number;
@ -33,7 +33,7 @@ export default function StatChart({
strokeLinecap="butt"
stroke="rgba(30, 41, 59, 0.1)"
/>
{referenceValue && (
{referenceValue !== undefined && (
<ReferenceLine
y={referenceValue}
strokeDasharray="3 3"
@ -64,7 +64,7 @@ export default function StatChart({
.map(x => x.date)}
/>
<YAxis
dataKey="stat"
dataKey="metric"
axisLine={false}
orientation="right"
tick={{
@ -73,6 +73,7 @@ export default function StatChart({
fill: "rgba(107, 114, 128, 1)",
}}
padding={{ top: 0, bottom: 0 }}
allowDecimals
tickLine={false}
unit={unit}
domain={domain || ["auto", "auto"]}
@ -87,7 +88,7 @@ export default function StatChart({
<Line
type="monotone"
isAnimationActive={false}
dataKey="stat"
dataKey="metric"
stroke="rgb(29 78 216)"
strokeLinecap="round"
strokeWidth={2}

View File

@ -5,19 +5,13 @@ import { useRTCStore, useUiStore } from "@/hooks/stores";
import { createChartArray, Metric } from "../Metric";
import { SettingsSectionHeader } from "../SettingsSectionHeader";
import { someIterable } from "../../utils";
export default function ConnectionStatsSidebar() {
const inboundVideoRtpStats = useRTCStore(state => state.inboundRtpStats);
const iceCandidatePairStats = useRTCStore(state => state.candidatePairStats);
const setSidebarView = useUiStore(state => state.setSidebarView);
function isMetricSupported<T, K extends keyof T>(
stream: Map<number, T>,
metric: K,
): boolean {
return Array.from(stream).some(([, stat]) => stat[metric] !== undefined);
}
const appendInboundVideoRtpStats = useRTCStore(state => state.appendInboundRtpStats);
const appendIceCandidatePair = useRTCStore(state => state.appendCandidatePairStats);
const appendDiskDataChannelStats = useRTCStore(
@ -72,13 +66,13 @@ export default function ConnectionStatsSidebar() {
);
const jitterBufferAvgDelayData = jitterBufferDelay.map((d, idx) => {
if (idx === 0) return { date: d.date, stat: null };
const prevDelay = jitterBufferDelay[idx - 1]?.stat as number | null | undefined;
const currDelay = d.stat as number | null | undefined;
if (idx === 0) return { date: d.date, metric: null };
const prevDelay = jitterBufferDelay[idx - 1]?.metric as number | null | undefined;
const currDelay = d.metric as number | null | undefined;
const prevEmitted =
(jitterBufferEmittedCount[idx - 1]?.stat as number | null | undefined) ?? null;
(jitterBufferEmittedCount[idx - 1]?.metric as number | null | undefined) ?? null;
const currEmitted =
(jitterBufferEmittedCount[idx]?.stat as number | null | undefined) ?? null;
(jitterBufferEmittedCount[idx]?.metric as number | null | undefined) ?? null;
if (
prevDelay == null ||
@ -86,7 +80,7 @@ export default function ConnectionStatsSidebar() {
prevEmitted == null ||
currEmitted == null
) {
return { date: d.date, stat: null };
return { date: d.date, metric: null };
}
const deltaDelay = currDelay - prevDelay;
@ -94,23 +88,13 @@ export default function ConnectionStatsSidebar() {
// Guard counter resets or no emitted frames
if (deltaDelay < 0 || deltaEmitted <= 0) {
return { date: d.date, stat: null };
return { date: d.date, metric: null };
}
const valueMs = Math.round((deltaDelay / deltaEmitted) * 1000);
return { date: d.date, stat: valueMs };
return { date: d.date, metric: valueMs };
});
// Rolling average over the last N seconds for the reference line
const rollingWindowSeconds = 20;
const recent = jitterBufferAvgDelayData
.slice(-rollingWindowSeconds)
.filter(x => x.stat != null) as { date: number; stat: number }[];
const referenceValue =
recent.length > 0
? Math.round(recent.reduce((sum, x) => sum + (x.stat as number), 0) / recent.length)
: undefined;
return (
<div className="grid h-full grid-rows-(--grid-headerBody) shadow-xs">
<SidebarHeader title="Connection Stats" setSidebarView={setSidebarView} />
@ -128,11 +112,10 @@ export default function ConnectionStatsSidebar() {
title="Round-Trip Time"
description="Round-trip time for the active ICE candidate pair between peers."
stream={iceCandidatePairStats}
gate={inboundVideoRtpStats}
metric="currentRoundTripTime"
map={x => ({
date: x.date,
stat: x.stat ? Math.round((x.stat as number) * 1000) : null,
metric: x.metric != null ? Math.round(x.metric * 1000) : null,
})}
domain={[0, 600]}
unit=" ms"
@ -156,7 +139,7 @@ export default function ConnectionStatsSidebar() {
metric="jitter"
map={x => ({
date: x.date,
stat: x.stat ? Math.round((x.stat as number) * 1000) : null,
metric: x.metric != null ? Math.round(x.metric * 1000) : null,
})}
domain={[0, 10]}
unit=" ms"
@ -171,12 +154,17 @@ export default function ConnectionStatsSidebar() {
data={jitterBufferAvgDelayData}
gate={inboundVideoRtpStats}
supported={
isMetricSupported(inboundVideoRtpStats, "jitterBufferDelay") &&
isMetricSupported(inboundVideoRtpStats, "jitterBufferEmittedCount")
someIterable(
inboundVideoRtpStats,
([, x]) => x.jitterBufferDelay != null,
) &&
someIterable(
inboundVideoRtpStats,
([, x]) => x.jitterBufferEmittedCount != null,
)
}
domain={[0, 30]}
unit=" ms"
referenceValue={referenceValue}
/>
{/* Packets Lost */}

View File

@ -94,6 +94,17 @@ export const formatters = {
},
};
export function someIterable<T>(
iterable: Iterable<T>,
predicate: (item: T) => boolean,
): boolean {
for (const item of iterable) {
if (predicate(item)) return true;
}
return false;
}
export const VIDEO = new Blob(
[
new Uint8Array([