douyinWEB/desktop/src/components/SessionCharts.tsx
eric 1112a4d055 Handle YouTube Video Uploads daily quota (429) with project budget and pause-until-reset.
Add shorts_yt_quota module, Shorts UI quota banner, overview tweaks (hide upcoming opens, align events panel height), Electron desktop client scaffold, and deploy scripts; update README.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-11 02:04:44 -05:00

340 lines
14 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.

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;
};
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[][];
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 = "#edf3ff";
const MUTED = "#93a4bd";
const GRID = "rgba(255,255,255,0.06)";
const TOOLTIP = {
backgroundColor: "#0f1c2e",
borderColor: GRID,
textStyle: { color: FG, fontSize: 12 },
};
export function SessionCharts({ stats }: { stats: RelayStats | null }) {
const overview = stats?.overview;
const weekdayLabels = stats?.by_weekday?.labels_zh || stats?.by_weekday?.labels;
const heatWeekday = stats?.heatmap?.weekday_labels_zh || stats?.heatmap?.weekday_labels;
const dailyOption = useMemo(() => {
const rows = stats?.by_date || [];
if (!rows.length) return null;
return {
color: ["#2dd4bf", "#fb7185"],
textStyle: { color: FG },
tooltip: { ...TOOLTIP, trigger: "axis" },
legend: { data: ["场次", "时长(小时)"], 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", axisLabel: { color: MUTED }, splitLine: { lineStyle: { color: GRID } } },
{ type: "value", axisLabel: { color: MUTED }, splitLine: { show: false } },
],
series: [
{ name: "场次", type: "bar", data: rows.map((r) => r.sessions), barMaxWidth: 18 },
{ name: "时长(小时)", type: "line", yAxisIndex: 1, smooth: true, data: rows.map((r) => Number(r.hours.toFixed(2))) },
],
};
}, [stats?.by_date]);
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: ["场次", "累计小时"], 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 },
},
series: [
{ name: "场次", type: "bar", data: rows.map((r) => r.sessions || 0), barMaxWidth: 14 },
{ name: "累计小时", type: "bar", data: rows.map((r) => Number((r.hours_total || 0).toFixed(2))), barMaxWidth: 14 },
],
};
}, [stats?.top_anchors]);
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: ["开播次数", "在播分钟"], 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 },
},
yAxis: [
{ type: "value", axisLabel: { color: MUTED }, splitLine: { lineStyle: { color: GRID } } },
{ type: "value", axisLabel: { color: MUTED }, splitLine: { show: false } },
],
series: [
{ name: "开播次数", type: "bar", data: starts, barMaxWidth: 12 },
{ name: "在播分钟", type: "line", yAxisIndex: 1, smooth: true, areaStyle: { opacity: 0.12 }, data: minutes.map((n) => Number(n.toFixed(1))) },
],
};
}, [stats?.by_hour]);
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 } },
yAxis: { type: "value", axisLabel: { color: MUTED }, splitLine: { lineStyle: { color: GRID } } },
series: [{ type: "bar", data: starts, barMaxWidth: 28, name: "开播场次" }],
};
}, [stats?.by_weekday, weekdayLabels]);
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 label = (heatWeekday || [])[d[1]] || String(d[1]);
return `${label} ${String(d[0]).padStart(2, "0")}:00<br/>开播: <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: ["#0f1c2e", "#0e7490", "#2dd4bf", "#fbbf24", "#ff2d55"] },
},
series: [{ type: "heatmap", data, label: { show: false } }],
};
}, [stats?.heatmap, heatWeekday]);
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"],
tooltip: { ...TOOLTIP, trigger: "item" },
series: [
{
type: "pie",
radius: ["42%", "68%"],
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="animate-fade-up rounded-2xl border border-dashed border-white/10 bg-black/20 px-4 py-10 text-center">
<div className="mx-auto mb-3 text-4xl">📈</div>
<div className="font-display text-base text-white">暂无统计数据</div>
<p className="mt-1 text-sm text-slate-500">添加直播间并积累开播记录后,这里会显示频率与时段规律。</p>
</div>
);
}
const fmtDur = (seconds?: number) => {
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}小时${m}分`;
return `${m}分`;
};
return (
<div className="space-y-4">
<div className="stagger grid gap-3 sm:grid-cols-2 xl:grid-cols-6">
{[
["🎬 总场次", String(overview?.sessions ?? 0)],
["👤 主播数", String(overview?.unique_anchors ?? 0)],
["⏱️ 累计时长", `${Number(overview?.total_hours || 0).toFixed(1)}h`],
["📏 平均场长", fmtDur(overview?.avg_duration_seconds)],
["📐 中位场长", fmtDur(overview?.median_duration_seconds)],
["🔴 进行中", String(overview?.active_sessions ?? 0)],
].map(([label, value]) => (
<div key={label} className="hover-lift rounded-xl border border-white/10 bg-gradient-to-br from-white/[0.07] to-transparent px-4 py-3">
<div className="text-[11px] tracking-wide text-slate-500">{label}</div>
<div className="mt-1 font-display text-xl font-semibold tabular-nums text-white">{value}</div>
</div>
))}
</div>
{stats.insights?.length ? (
<div className="animate-fade-up rounded-xl border border-teal-500/20 bg-teal-500/5 px-4 py-3 text-sm text-teal-50/90">
<div className="mb-1 text-xs font-medium uppercase tracking-wide text-teal-300/80">💡 规律速览</div>
<ul className="space-y-1 text-slate-200">
{stats.insights.map((item, idx) => (
<li key={idx}>· {item.zh}</li>
))}
</ul>
</div>
) : null}
<div className="stagger grid gap-4 xl:grid-cols-2">
<section className="hover-lift rounded-xl border border-white/10 bg-black/25 p-4">
<h3 className="mb-1 text-sm font-medium text-slate-200">📅 每日开播频率与时长</h3>
{dailyChart}
</section>
<section className="hover-lift rounded-xl border border-white/10 bg-black/25 p-4">
<h3 className="mb-1 text-sm font-medium text-slate-200">🏆 主播排行(场次 / 累计小时)</h3>
{anchorChart}
</section>
<section className="hover-lift rounded-xl border border-white/10 bg-black/25 p-4">
<h3 className="mb-1 text-sm font-medium text-slate-200">🕐 一天内时段分布</h3>
{hourChart}
</section>
<section className="hover-lift rounded-xl border border-white/10 bg-black/25 p-4">
<h3 className="mb-1 text-sm font-medium text-slate-200">📆 星期分布</h3>
{weekdayChart}
</section>
<section className="hover-lift rounded-xl border border-white/10 bg-black/25 p-4 xl:col-span-2">
<h3 className="mb-1 text-sm font-medium text-slate-200">🔥 星期 × 小时 热力图</h3>
{heatChart}
</section>
<section className="hover-lift rounded-xl border border-white/10 bg-black/25 p-4">
<h3 className="mb-1 text-sm font-medium text-slate-200">🥧 单场时长分布</h3>
{durationChart}
</section>
<section className="hover-lift rounded-xl border border-white/10 bg-black/25 p-4">
<h3 className="mb-3 text-sm font-medium text-slate-200">📋 主播明细</h3>
<div className="max-h-[260px] overflow-auto">
<table className="min-w-full text-left text-xs">
<thead className="sticky top-0 bg-[#0b1626] text-slate-500">
<tr>
<th className="px-2 py-2">主播</th>
<th className="px-2 py-2">场次</th>
<th className="px-2 py-2">小时</th>
<th className="px-2 py-2">日均场</th>
<th className="px-2 py-2">峰值</th>
<th className="px-2 py-2">间隔</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-slate-300">
<td className="px-2 py-2 font-medium text-slate-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>
);
}