sh2/d2ypp2/web-console/components/live-product/LiveYoutubeRelayLogCharts.tsx
eric ff70c9f5f6 Update Studio auto-dismiss to avoid synthetic clicks and add relay log charts.
Prefer location.assign for endscreen leave, and ship hub analytics/charts plus host deploy helpers.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-12 20:23:44 -05:00

385 lines
16 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"use client";
import { useEffect, useMemo, useRef } from "react";
export type RelayStats = {
overview?: {
sessions?: number;
unique_anchors?: number;
active_sessions?: number;
total_hours?: number;
avg_duration_seconds?: number;
median_duration_seconds?: number;
days_span?: number;
date_from?: string;
date_to?: string;
};
top_anchors?: Array<{
anchor_name?: string;
sessions?: number;
hours_total?: number;
avg_duration_seconds?: number;
peak_hour?: number;
peak_weekday_label?: string;
dates_active?: number;
sessions_per_active_day?: number;
avg_gap_hours?: number | null;
source_room_id?: string;
}>;
by_hour?: { starts?: number[]; minutes?: number[]; labels?: string[] };
by_weekday?: { starts?: number[]; minutes?: number[]; labels?: string[]; labels_zh?: string[] };
heatmap?: {
starts?: number[][];
minutes?: number[][];
weekday_labels?: string[];
weekday_labels_zh?: string[];
hour_labels?: string[];
};
by_date?: Array<{ date: string; sessions: number; hours: number; unique_anchors: number }>;
duration_buckets?: Record<string, number>;
insights?: Array<{ zh: string; en: string }>;
};
function useEchart(option: Record<string, unknown> | null, height: number) {
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
const el = ref.current;
if (!el || !option) return;
let disposed = false;
let chart: import("echarts").ECharts | null = null;
const onResize = () => chart?.resize();
import("echarts").then((echarts) => {
if (disposed || !ref.current) return;
chart = echarts.init(ref.current, undefined, { renderer: "canvas" });
chart.setOption(option, true);
window.addEventListener("resize", onResize);
});
return () => {
disposed = true;
window.removeEventListener("resize", onResize);
chart?.dispose();
};
}, [option]);
return <div ref={ref} style={{ height }} className="w-full" />;
}
const FG = "#f4f4f5";
const MUTED = "#a1a1aa";
const GRID = "rgba(255,255,255,0.06)";
const TOOLTIP = {
backgroundColor: "#18181b",
borderColor: GRID,
textStyle: { color: FG, fontSize: 12 },
};
export function LiveYoutubeRelayLogCharts({
stats,
lang,
t,
}: {
stats: RelayStats | null;
lang: "zh" | "en";
t: (zh: string, en: string) => string;
}) {
const overview = stats?.overview;
const weekdayLabels = lang === "zh" ? stats?.by_weekday?.labels_zh || stats?.by_weekday?.labels : stats?.by_weekday?.labels;
const heatWeekday = lang === "zh" ? stats?.heatmap?.weekday_labels_zh || stats?.heatmap?.weekday_labels : stats?.heatmap?.weekday_labels;
const dailyOption = useMemo(() => {
const rows = stats?.by_date || [];
if (!rows.length) return null;
return {
color: ["#22d3ee", "#a78bfa"],
textStyle: { color: FG },
tooltip: { ...TOOLTIP, trigger: "axis" },
legend: { data: [t("场次", "Sessions"), t("时长(小时)", "Hours")], textStyle: { color: MUTED } },
grid: { left: 48, right: 48, top: 40, bottom: 48 },
xAxis: {
type: "category",
data: rows.map((r) => r.date.slice(5)),
axisLabel: { color: MUTED, rotate: rows.length > 14 ? 45 : 0 },
axisLine: { lineStyle: { color: GRID } },
},
yAxis: [
{ type: "value", name: t("场次", "Sessions"), nameTextStyle: { color: MUTED }, axisLabel: { color: MUTED }, splitLine: { lineStyle: { color: GRID } } },
{ type: "value", name: t("小时", "Hours"), nameTextStyle: { color: MUTED }, axisLabel: { color: MUTED }, splitLine: { show: false } },
],
series: [
{ name: t("场次", "Sessions"), type: "bar", data: rows.map((r) => r.sessions), barMaxWidth: 18 },
{ name: t("时长(小时)", "Hours"), type: "line", yAxisIndex: 1, smooth: true, data: rows.map((r) => Number(r.hours.toFixed(2))) },
],
};
}, [stats?.by_date, t]);
const anchorOption = useMemo(() => {
const rows = (stats?.top_anchors || []).slice(0, 12).reverse();
if (!rows.length) return null;
return {
color: ["#34d399", "#38bdf8"],
textStyle: { color: FG },
tooltip: { ...TOOLTIP, trigger: "axis", axisPointer: { type: "shadow" } },
legend: { data: [t("场次", "Sessions"), t("累计小时", "Hours")], textStyle: { color: MUTED } },
grid: { left: 110, right: 48, top: 36, bottom: 28 },
xAxis: { type: "value", axisLabel: { color: MUTED }, splitLine: { lineStyle: { color: GRID } } },
yAxis: {
type: "category",
data: rows.map((r) => (r.anchor_name || "—").slice(0, 14)),
axisLabel: { color: MUTED, fontSize: 11 },
axisLine: { lineStyle: { color: GRID } },
},
series: [
{ name: t("场次", "Sessions"), type: "bar", data: rows.map((r) => r.sessions || 0), barMaxWidth: 14 },
{ name: t("累计小时", "Hours"), type: "bar", data: rows.map((r) => Number((r.hours_total || 0).toFixed(2))), barMaxWidth: 14 },
],
};
}, [stats?.top_anchors, t]);
const hourOption = useMemo(() => {
const starts = stats?.by_hour?.starts || [];
const minutes = stats?.by_hour?.minutes || [];
if (!starts.some((n) => n > 0) && !minutes.some((n) => n > 0)) return null;
return {
color: ["#fbbf24", "#fb7185"],
textStyle: { color: FG },
tooltip: { ...TOOLTIP, trigger: "axis" },
legend: { data: [t("开播次数", "Starts"), t("在播分钟", "On-air minutes")], textStyle: { color: MUTED } },
grid: { left: 48, right: 48, top: 40, bottom: 36 },
xAxis: {
type: "category",
data: stats?.by_hour?.labels || Array.from({ length: 24 }, (_, h) => `${String(h).padStart(2, "0")}:00`),
axisLabel: { color: MUTED, fontSize: 10 },
axisLine: { lineStyle: { color: GRID } },
},
yAxis: [
{ type: "value", axisLabel: { color: MUTED }, splitLine: { lineStyle: { color: GRID } } },
{ type: "value", axisLabel: { color: MUTED }, splitLine: { show: false } },
],
series: [
{ name: t("开播次数", "Starts"), type: "bar", data: starts, barMaxWidth: 12 },
{ name: t("在播分钟", "On-air minutes"), type: "line", yAxisIndex: 1, smooth: true, areaStyle: { opacity: 0.12 }, data: minutes.map((n) => Number(n.toFixed(1))) },
],
};
}, [stats?.by_hour, t]);
const weekdayOption = useMemo(() => {
const starts = stats?.by_weekday?.starts || [];
if (!starts.some((n) => n > 0)) return null;
return {
color: ["#818cf8"],
textStyle: { color: FG },
tooltip: { ...TOOLTIP, trigger: "axis" },
grid: { left: 48, right: 16, top: 28, bottom: 36 },
xAxis: {
type: "category",
data: weekdayLabels || [],
axisLabel: { color: MUTED },
axisLine: { lineStyle: { color: GRID } },
},
yAxis: { type: "value", axisLabel: { color: MUTED }, splitLine: { lineStyle: { color: GRID } } },
series: [{ type: "bar", data: starts, barMaxWidth: 28, name: t("开播场次", "Starts") }],
};
}, [stats?.by_weekday, weekdayLabels, t]);
const heatmapOption = useMemo(() => {
const matrix = stats?.heatmap?.starts || [];
if (!matrix.length) return null;
const data: [number, number, number][] = [];
let max = 0;
matrix.forEach((row, wd) => {
row.forEach((val, hour) => {
data.push([hour, wd, val]);
if (val > max) max = val;
});
});
if (max <= 0) return null;
return {
textStyle: { color: FG },
tooltip: {
...TOOLTIP,
formatter: (p: { data?: [number, number, number] }) => {
const d = p.data;
if (!d) return "";
const hour = d[0];
const wd = d[1];
const label = (heatWeekday || [])[wd] || String(wd);
return `${label} ${hour.toString().padStart(2, "0")}:00<br/>${t("开播", "Starts")}: <b>${d[2]}</b>`;
},
},
grid: { left: 56, right: 24, top: 16, bottom: 40 },
xAxis: {
type: "category",
data: stats?.heatmap?.hour_labels || Array.from({ length: 24 }, (_, h) => `${h}`),
splitArea: { show: true },
axisLabel: { color: MUTED, fontSize: 10 },
},
yAxis: {
type: "category",
data: heatWeekday || [],
splitArea: { show: true },
axisLabel: { color: MUTED },
},
visualMap: {
min: 0,
max: Math.max(1, max),
calculable: true,
orient: "horizontal",
left: "center",
bottom: 0,
textStyle: { color: MUTED },
inRange: { color: ["#18181b", "#0e7490", "#22d3ee", "#fbbf24", "#fb7185"] },
},
series: [
{
type: "heatmap",
data,
label: { show: false },
emphasis: { itemStyle: { shadowBlur: 8, shadowColor: "rgba(0,0,0,0.4)" } },
},
],
};
}, [stats?.heatmap, heatWeekday, t]);
const durationOption = useMemo(() => {
const buckets = stats?.duration_buckets || {};
const keys = Object.keys(buckets);
if (!keys.length || !Object.values(buckets).some((n) => n > 0)) return null;
return {
color: ["#2dd4bf"],
textStyle: { color: FG },
tooltip: { ...TOOLTIP, trigger: "item" },
series: [
{
type: "pie",
radius: ["42%", "68%"],
center: ["50%", "52%"],
data: keys.map((k) => ({ name: k, value: buckets[k] })),
label: { color: MUTED, formatter: "{b}\n{c}" },
},
],
};
}, [stats?.duration_buckets]);
const dailyChart = useEchart(dailyOption, 280);
const anchorChart = useEchart(anchorOption, 340);
const hourChart = useEchart(hourOption, 280);
const weekdayChart = useEchart(weekdayOption, 240);
const heatChart = useEchart(heatmapOption, 300);
const durationChart = useEchart(durationOption, 260);
if (!stats || !(overview?.sessions || 0)) {
return (
<div className="mb-4 rounded-xl border border-dashed border-white/10 bg-black/20 px-4 py-8 text-center text-sm text-zinc-500">
{t("暂无统计数据。导入或积累推流记录后,这里会显示主播频率与时段规律。", "No analytics yet. Import or accumulate relay sessions to see patterns.")}
</div>
);
}
const fmtDur = (seconds: number | undefined) => {
const total = Math.max(0, Math.floor(Number(seconds) || 0));
const h = Math.floor(total / 3600);
const m = Math.floor((total % 3600) / 60);
if (h > 0) return `${h}${t("小时", "h")}${m}${t("分", "m")}`;
return `${m}${t("分", "m")}`;
};
return (
<div className="mb-6 space-y-4">
<div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-6">
{[
[t("总场次", "Sessions"), String(overview?.sessions ?? 0)],
[t("主播数", "Anchors"), String(overview?.unique_anchors ?? 0)],
[t("累计时长", "Total hours"), `${Number(overview?.total_hours || 0).toFixed(1)}h`],
[t("平均场长", "Avg length"), fmtDur(overview?.avg_duration_seconds)],
[t("中位场长", "Median"), fmtDur(overview?.median_duration_seconds)],
[t("进行中", "Active"), String(overview?.active_sessions ?? 0)],
].map(([label, value]) => (
<div key={label} className="rounded-xl border border-white/10 bg-gradient-to-br from-white/[0.06] to-transparent px-4 py-3">
<div className="text-[11px] uppercase tracking-wide text-zinc-500">{label}</div>
<div className="mt-1 text-xl font-semibold tabular-nums text-zinc-50">{value}</div>
</div>
))}
</div>
{stats.insights?.length ? (
<div className="rounded-xl border border-cyan-500/20 bg-cyan-500/5 px-4 py-3 text-sm text-cyan-50/90">
<div className="mb-1 text-xs font-medium uppercase tracking-wide text-cyan-300/80">{t("规律速览", "Pattern snapshot")}</div>
<ul className="space-y-1 text-zinc-200">
{stats.insights.map((item, idx) => (
<li key={idx}>· {lang === "zh" ? item.zh : item.en}</li>
))}
</ul>
</div>
) : null}
<div className="grid gap-4 xl:grid-cols-2">
<section className="rounded-xl border border-white/10 bg-black/25 p-4">
<h3 className="mb-1 text-sm font-medium text-zinc-200">{t("每日推流频率与时长", "Daily session frequency & hours")}</h3>
<p className="mb-2 text-xs text-zinc-500">{t("柱:当天开播场次;线:当天累计推流小时。", "Bars: sessions/day; line: total hours/day.")}</p>
{dailyChart}
</section>
<section className="rounded-xl border border-white/10 bg-black/25 p-4">
<h3 className="mb-1 text-sm font-medium text-zinc-200">{t("主播排行(场次 / 累计小时)", "Anchor ranking (sessions / hours)")}</h3>
<p className="mb-2 text-xs text-zinc-500">{t("看谁最常被转、谁播得最久。", "Who is relayed most often and longest.")}</p>
{anchorChart}
</section>
<section className="rounded-xl border border-white/10 bg-black/25 p-4">
<h3 className="mb-1 text-sm font-medium text-zinc-200">{t("一天内时段分布", "Time-of-day distribution")}</h3>
<p className="mb-2 text-xs text-zinc-500">{t("开播次数 vs 实际在播占用(分钟)。", "Start counts vs on-air occupancy (minutes).")}</p>
{hourChart}
</section>
<section className="rounded-xl border border-white/10 bg-black/25 p-4">
<h3 className="mb-1 text-sm font-medium text-zinc-200">{t("星期分布", "Weekday distribution")}</h3>
<p className="mb-2 text-xs text-zinc-500">{t("哪天更容易开播。", "Which weekdays see more starts.")}</p>
{weekdayChart}
</section>
<section className="rounded-xl border border-white/10 bg-black/25 p-4 xl:col-span-2">
<h3 className="mb-1 text-sm font-medium text-zinc-200">{t("星期 × 小时 热力图(开播次数)", "Weekday × hour heatmap (starts)")}</h3>
<p className="mb-2 text-xs text-zinc-500">{t("颜色越亮表示该时段开播越频繁,适合找固定档期。", "Brighter = more frequent starts; useful for spotting fixed slots.")}</p>
{heatChart}
</section>
<section className="rounded-xl border border-white/10 bg-black/25 p-4">
<h3 className="mb-1 text-sm font-medium text-zinc-200">{t("单场时长分布", "Duration distribution")}</h3>
<p className="mb-2 text-xs text-zinc-500">{t("短场/长场比例。", "Short vs long session mix.")}</p>
{durationChart}
</section>
<section className="rounded-xl border border-white/10 bg-black/25 p-4">
<h3 className="mb-3 text-sm font-medium text-zinc-200">{t("主播明细(可对照图表)", "Anchor detail")}</h3>
<div className="max-h-[260px] overflow-auto">
<table className="min-w-full text-left text-xs">
<thead className="sticky top-0 bg-zinc-950 text-zinc-500">
<tr>
<th className="px-2 py-2">{t("主播", "Anchor")}</th>
<th className="px-2 py-2">{t("场次", "N")}</th>
<th className="px-2 py-2">{t("小时", "Hours")}</th>
<th className="px-2 py-2">{t("日均场", "/day")}</th>
<th className="px-2 py-2">{t("峰值", "Peak")}</th>
<th className="px-2 py-2">{t("间隔", "Gap")}</th>
</tr>
</thead>
<tbody>
{(stats.top_anchors || []).map((row) => (
<tr key={`${row.anchor_name}-${row.source_room_id}`} className="border-t border-white/5 text-zinc-300">
<td className="px-2 py-2 font-medium text-zinc-100">{row.anchor_name || "—"}</td>
<td className="px-2 py-2 tabular-nums">{row.sessions ?? 0}</td>
<td className="px-2 py-2 tabular-nums">{Number(row.hours_total || 0).toFixed(1)}</td>
<td className="px-2 py-2 tabular-nums">{Number(row.sessions_per_active_day || 0).toFixed(2)}</td>
<td className="px-2 py-2">
{String(row.peak_hour ?? 0).padStart(2, "0")}:00
{row.peak_weekday_label ? ` · ${row.peak_weekday_label}` : ""}
</td>
<td className="px-2 py-2 tabular-nums">
{row.avg_gap_hours == null ? "—" : `${Number(row.avg_gap_hours).toFixed(1)}h`}
</td>
</tr>
))}
</tbody>
</table>
</div>
</section>
</div>
</div>
);
}
export default LiveYoutubeRelayLogCharts;