mirror of
https://wget.la/https://github.com/leookun/cursor-byok
synced 2026-12-01 09:15:33 +08:00
refactor: align project directory architecture
This commit is contained in:
1 parent
88f258f184
commit
279e6bb07c
236 files changed
+1982
-57487
No files matched your search
@@ -0,0 +1,36 @@
|
||||
@use "../../../styles/typography" as type;
|
||||
|
||||
.root {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.scroller {
|
||||
width: 100%;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.canvas {
|
||||
width: 100%;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.axis {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
height: 18px;
|
||||
margin-top: 10px;
|
||||
color: var(--vscode-descriptionForeground);
|
||||
font-size: type.$font-size-2xs;
|
||||
|
||||
span {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
width: 28px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
}
|
||||
|
||||
.tooltipContent {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
import { useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import { init, Rect, type ElementEvent } from "zrender";
|
||||
import type { Locale } from "../../../i18n/runtime";
|
||||
import { useI18n } from "../../../i18n/store";
|
||||
import { Tooltip, type TooltipAnchor } from "../../../shared/ui/Tooltip";
|
||||
import styles from "./ContributionCalendarChart.module.scss";
|
||||
|
||||
export type ContributionDay = {
|
||||
date: string;
|
||||
tokens: number;
|
||||
};
|
||||
|
||||
type ContributionCalendarChartProps = {
|
||||
data: ContributionDay[];
|
||||
};
|
||||
|
||||
type CalendarCell = ContributionDay & {
|
||||
column: number;
|
||||
row: number;
|
||||
level: number;
|
||||
};
|
||||
|
||||
type CellExtra = CalendarCell & {
|
||||
kind: "calendar-cell";
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
height: number;
|
||||
};
|
||||
|
||||
type TooltipState = {
|
||||
date: string;
|
||||
tokens: number;
|
||||
anchor: TooltipAnchor;
|
||||
};
|
||||
|
||||
type AxisLabel = {
|
||||
key: string;
|
||||
text: string;
|
||||
left: number;
|
||||
};
|
||||
|
||||
const levelColors = [
|
||||
"rgba(139, 148, 158, 0.20)",
|
||||
"#9be9a8",
|
||||
"#40c463",
|
||||
"#30a14e",
|
||||
"#216e39",
|
||||
];
|
||||
const DAY_IN_MS = 24 * 60 * 60 * 1000;
|
||||
const CALENDAR_CONFIG = {
|
||||
cellAspectRatio: 0.9,
|
||||
cellGap: 3,
|
||||
resizeTransitionMs: 180,
|
||||
rowCount: 7,
|
||||
axisLabelGap: 8,
|
||||
axisLabelWidth: 28,
|
||||
} as const;
|
||||
function parseDate(date: string) {
|
||||
return new Date(`${date}T00:00:00Z`);
|
||||
}
|
||||
|
||||
function mondayIndex(date: Date) {
|
||||
return (date.getUTCDay() + 6) % 7;
|
||||
}
|
||||
|
||||
function cellOffset(index: number, cellSize: number) {
|
||||
return index * (cellSize + CALENDAR_CONFIG.cellGap);
|
||||
}
|
||||
|
||||
function isCellExtra(value: unknown): value is CellExtra {
|
||||
return typeof value === "object" && value !== null && (value as CellExtra).kind === "calendar-cell";
|
||||
}
|
||||
|
||||
function buildCalendarLayout(data: ContributionDay[], locale: Locale) {
|
||||
if (data.length === 0) return null;
|
||||
|
||||
const monthFormatter = new Intl.DateTimeFormat(locale, { month: "short", timeZone: "UTC" });
|
||||
const maximum = Math.max(1, ...data.map(({ tokens }) => tokens));
|
||||
const firstDate = parseDate(data[0].date);
|
||||
const calendarStart = new Date(firstDate.getTime() - mondayIndex(firstDate) * DAY_IN_MS);
|
||||
const cells: CalendarCell[] = data.map((day) => {
|
||||
const date = parseDate(day.date);
|
||||
const daysFromStart = Math.round((date.getTime() - calendarStart.getTime()) / DAY_IN_MS);
|
||||
const level = day.tokens === 0 ? 0 : Math.max(1, Math.ceil((day.tokens / maximum) * 4));
|
||||
return { ...day, column: Math.floor(daysFromStart / 7), row: mondayIndex(date), level };
|
||||
});
|
||||
const columnCount = cells.at(-1)!.column + 1;
|
||||
const monthTicks = cells.reduce<Array<{ key: string; text: string; column: number }>>((ticks, cell) => {
|
||||
const date = parseDate(cell.date);
|
||||
const key = `${date.getUTCFullYear()}-${date.getUTCMonth()}`;
|
||||
if (ticks.at(-1)?.key !== key) ticks.push({ key, text: monthFormatter.format(date), column: cell.column });
|
||||
return ticks;
|
||||
}, []);
|
||||
return { cells, columnCount, monthTicks };
|
||||
}
|
||||
|
||||
export function ContributionCalendarChart({ data }: ContributionCalendarChartProps) {
|
||||
const { locale } = useI18n();
|
||||
const scrollerRef = useRef<HTMLDivElement>(null);
|
||||
const canvasRef = useRef<HTMLDivElement>(null);
|
||||
const layoutRef = useRef<ReturnType<typeof buildCalendarLayout>>(null);
|
||||
const scheduleDrawRef = useRef<() => void>(() => undefined);
|
||||
const [tooltip, setTooltip] = useState<TooltipState | null>(null);
|
||||
const [axisLabels, setAxisLabels] = useState<AxisLabel[]>([]);
|
||||
const layout = useMemo(() => buildCalendarLayout(data, locale), [data, locale]);
|
||||
const tokenFormatter = useMemo(() => new Intl.NumberFormat(locale), [locale]);
|
||||
layoutRef.current = layout;
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const scroller = scrollerRef.current;
|
||||
const node = canvasRef.current;
|
||||
if (!scroller || !node) return;
|
||||
|
||||
const chart = init(node, {
|
||||
renderer: "canvas",
|
||||
width: 1,
|
||||
height: 1,
|
||||
useDirtyRect: true,
|
||||
});
|
||||
|
||||
const handleMouseOver = (event: ElementEvent) => {
|
||||
const extra = event.target?.extra;
|
||||
if (!isCellExtra(extra)) return;
|
||||
const anchor: TooltipAnchor = {
|
||||
contextElement: node,
|
||||
getBoundingClientRect: () => {
|
||||
const bounds = node.getBoundingClientRect();
|
||||
return new DOMRect(bounds.left + extra.x, bounds.top + extra.y, extra.width, extra.height);
|
||||
},
|
||||
};
|
||||
setTooltip({ date: extra.date, tokens: extra.tokens, anchor });
|
||||
};
|
||||
const handleMouseOut = (event: ElementEvent) => {
|
||||
if (isCellExtra(event.target?.extra)) setTooltip(null);
|
||||
};
|
||||
|
||||
chart.on("mouseover", handleMouseOver);
|
||||
chart.on("mouseout", handleMouseOut);
|
||||
|
||||
const cellRects = new Map<string, Rect>();
|
||||
let drawFrame = 0;
|
||||
let lastAvailableWidth = -1;
|
||||
let lastCanvasHeight = -1;
|
||||
let lastLayout: typeof layout = null;
|
||||
const draw = () => {
|
||||
const currentLayout = layoutRef.current;
|
||||
if (!currentLayout) return;
|
||||
const availableWidth = Math.floor(scroller.getBoundingClientRect().width);
|
||||
if (availableWidth <= 0 || (availableWidth === lastAvailableWidth && currentLayout === lastLayout)) return;
|
||||
const gapsWidth = (currentLayout.columnCount - 1) * CALENDAR_CONFIG.cellGap;
|
||||
const cellWidth = Math.max(0, (availableWidth - gapsWidth) / currentLayout.columnCount);
|
||||
const cellHeight = cellWidth / CALENDAR_CONFIG.cellAspectRatio;
|
||||
const width = availableWidth;
|
||||
const height = CALENDAR_CONFIG.rowCount * cellHeight
|
||||
+ (CALENDAR_CONFIG.rowCount - 1) * CALENDAR_CONFIG.cellGap;
|
||||
|
||||
let lastLabelEnd = -Infinity;
|
||||
const nextAxisLabels = currentLayout.monthTicks.flatMap((tick) => {
|
||||
const left = Math.min(
|
||||
cellOffset(tick.column, cellWidth),
|
||||
availableWidth - CALENDAR_CONFIG.axisLabelWidth,
|
||||
);
|
||||
if (left < lastLabelEnd + CALENDAR_CONFIG.axisLabelGap) return [];
|
||||
lastLabelEnd = left + CALENDAR_CONFIG.axisLabelWidth;
|
||||
return [{ ...tick, left }];
|
||||
});
|
||||
setAxisLabels(nextAxisLabels);
|
||||
|
||||
if (availableWidth !== lastAvailableWidth || height !== lastCanvasHeight) {
|
||||
node.style.width = "100%";
|
||||
node.style.height = `${height}px`;
|
||||
chart.resize({ width, height });
|
||||
lastAvailableWidth = availableWidth;
|
||||
lastCanvasHeight = height;
|
||||
}
|
||||
lastLayout = currentLayout;
|
||||
|
||||
const currentDates = new Set(currentLayout.cells.map((cell) => cell.date));
|
||||
for (const [date, rect] of cellRects) {
|
||||
if (currentDates.has(date)) continue;
|
||||
chart.remove(rect);
|
||||
cellRects.delete(date);
|
||||
}
|
||||
|
||||
for (const cell of currentLayout.cells) {
|
||||
const x = cellOffset(cell.column, cellWidth);
|
||||
const y = cellOffset(cell.row, cellHeight);
|
||||
const shape = {
|
||||
x,
|
||||
y,
|
||||
width: cellWidth,
|
||||
height: cellHeight,
|
||||
r: Math.min(3, Math.min(cellWidth, cellHeight) / 4),
|
||||
};
|
||||
const extra = {
|
||||
...cell,
|
||||
kind: "calendar-cell" as const,
|
||||
x,
|
||||
y,
|
||||
width: cellWidth,
|
||||
height: cellHeight,
|
||||
} satisfies CellExtra;
|
||||
const current = cellRects.get(cell.date);
|
||||
|
||||
if (current) {
|
||||
current.extra = extra;
|
||||
current.stopAnimation();
|
||||
current.animateTo(
|
||||
{ shape, style: { fill: levelColors[cell.level] } },
|
||||
{ duration: CALENDAR_CONFIG.resizeTransitionMs, easing: "cubicOut" },
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
const rect = new Rect({
|
||||
shape,
|
||||
style: {
|
||||
fill: levelColors[cell.level],
|
||||
stroke: "rgba(139, 148, 158, 0.10)",
|
||||
lineWidth: 1,
|
||||
},
|
||||
cursor: "default",
|
||||
extra,
|
||||
});
|
||||
cellRects.set(cell.date, rect);
|
||||
chart.add(rect);
|
||||
}
|
||||
setTooltip(null);
|
||||
};
|
||||
const scheduleDraw = () => {
|
||||
window.cancelAnimationFrame(drawFrame);
|
||||
drawFrame = window.requestAnimationFrame(draw);
|
||||
};
|
||||
scheduleDrawRef.current = scheduleDraw;
|
||||
const observer = new ResizeObserver(scheduleDraw);
|
||||
observer.observe(scroller);
|
||||
scheduleDraw();
|
||||
|
||||
return () => {
|
||||
observer.disconnect();
|
||||
window.cancelAnimationFrame(drawFrame);
|
||||
scheduleDrawRef.current = () => undefined;
|
||||
chart.dispose();
|
||||
};
|
||||
}, [layout !== null]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
scheduleDrawRef.current();
|
||||
}, [layout]);
|
||||
|
||||
if (!layout) return null;
|
||||
|
||||
return (
|
||||
<section className={styles.root} aria-label={t("过去一年的 Token 用量")}>
|
||||
<div ref={scrollerRef} className={styles.scroller}>
|
||||
<div
|
||||
ref={canvasRef}
|
||||
className={styles.canvas}
|
||||
role="img"
|
||||
aria-label={t("过去一年的 Token 用量日历")}
|
||||
/>
|
||||
<div className={styles.axis} aria-hidden="true">
|
||||
{axisLabels.map((label) => <span key={label.key} style={{ left: label.left }}>{label.text}</span>)}
|
||||
</div>
|
||||
</div>
|
||||
<Tooltip anchor={tooltip?.anchor ?? null}>
|
||||
<div className={styles.tooltipContent}>
|
||||
<strong>{tooltip?.date}</strong>
|
||||
<span>{t("Token 用量:{tokens}", { tokens: tokenFormatter.format(tooltip?.tokens ?? 0) })}</span>
|
||||
</div>
|
||||
</Tooltip>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
@use "../../../styles/typography" as type;
|
||||
|
||||
.root {
|
||||
--daily-token-tooltip-font-size: #{type.$font-size-2xs};
|
||||
width: 100%;
|
||||
height: 200px;
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
import type { EChartsCoreOption } from "echarts/core";
|
||||
import { useMemo, useState } from "react";
|
||||
import type { TokenUsageGranularity } from "../../../shared/api";
|
||||
import { formatCompactInteger } from "../../../shared/utils/numberFormat";
|
||||
import { EChart } from "./EChart";
|
||||
import styles from "./DailyTokenUsageChart.module.scss";
|
||||
|
||||
export type DailyTokenUsage = {
|
||||
bucketStartMs: number;
|
||||
inputTokens: number;
|
||||
cacheReadTokens: number;
|
||||
cacheWriteTokens: number;
|
||||
outputTokens: number;
|
||||
};
|
||||
|
||||
type TooltipItem = {
|
||||
dataIndex: number;
|
||||
};
|
||||
|
||||
const seriesColors = {
|
||||
input: "#0091ff",
|
||||
cacheRead: "#40c463",
|
||||
cacheWrite: "#3A62BA",
|
||||
output: "#E7B40B",
|
||||
} as const;
|
||||
const levelLineColor = "#E7B40B";
|
||||
const emptyBarColor = "rgba(139, 148, 158, 0.20)";
|
||||
const EMPTY_BAR_RATIO = 1;
|
||||
const DATA_HEIGHT_RATIO = 1;
|
||||
|
||||
const seriesFocus = {
|
||||
emphasis: { focus: "series" },
|
||||
blur: { itemStyle: { opacity: 0.2 } },
|
||||
} as const;
|
||||
|
||||
function colorMark(color: string): string {
|
||||
return `<span style="display:inline-block;width:8px;height:8px;margin-right:6px;border-radius:50%;background-color:${color};vertical-align:middle"></span>`;
|
||||
}
|
||||
|
||||
function formatDay(value: Date) {
|
||||
return `${value.getUTCMonth() + 1}/${value.getUTCDate()}`;
|
||||
}
|
||||
|
||||
function pad(value: number) {
|
||||
return String(value).padStart(2, "0");
|
||||
}
|
||||
|
||||
function formatAxisLabel(bucketStartMs: number, granularity: TokenUsageGranularity) {
|
||||
const value = new Date(bucketStartMs);
|
||||
if (granularity === "minute") return `${pad(value.getHours())}:${pad(value.getMinutes())}`;
|
||||
if (granularity === "hour") return `${pad(value.getHours())}:00`;
|
||||
const day = value.getUTCDay();
|
||||
if (day === 6) return t("周六");
|
||||
if (day === 0) return t("周日");
|
||||
return formatDay(value);
|
||||
}
|
||||
|
||||
function formatTooltipTime(bucketStartMs: number, granularity: TokenUsageGranularity) {
|
||||
const value = new Date(bucketStartMs);
|
||||
if (granularity === "day") return formatDay(value);
|
||||
const time = `${pad(value.getHours())}:${pad(value.getMinutes())}`;
|
||||
return `${value.getMonth() + 1}/${value.getDate()} ${time}`;
|
||||
}
|
||||
|
||||
function totalTokens(day: DailyTokenUsage) {
|
||||
return day.inputTokens + day.cacheReadTokens + day.cacheWriteTokens + day.outputTokens;
|
||||
}
|
||||
|
||||
export function DailyTokenUsageChart({
|
||||
data,
|
||||
granularity,
|
||||
}: {
|
||||
data: DailyTokenUsage[];
|
||||
granularity: TokenUsageGranularity;
|
||||
}) {
|
||||
const [hovered, setHovered] = useState(false);
|
||||
const maximumTotal = data.reduce((maximum, day) => Math.max(maximum, totalTokens(day)), 0);
|
||||
const axisMaximum = Math.max(1, maximumTotal / DATA_HEIGHT_RATIO);
|
||||
const emptyBarHeight = axisMaximum * EMPTY_BAR_RATIO;
|
||||
const nonZeroTotals = data.map(totalTokens).filter((total) => total !== 0);
|
||||
const averageLevel = nonZeroTotals.length === 0
|
||||
? 0
|
||||
: nonZeroTotals.reduce((sum, total) => sum + total, 0) / nonZeroTotals.length;
|
||||
|
||||
const option = useMemo<EChartsCoreOption>(() => ({
|
||||
animationDuration: 450,
|
||||
animationEasing: "cubicOut",
|
||||
grid: { top: 8, right: 0, bottom: 0, left: 0 },
|
||||
tooltip: {
|
||||
trigger: "axis",
|
||||
confine: true,
|
||||
backgroundColor: "var(--vscode-editorHoverWidget-background)",
|
||||
borderColor: "var(--vscode-editorHoverWidget-border)",
|
||||
textStyle: { color: "var(--vscode-foreground)", fontFamily: "PingFang-Medium" },
|
||||
extraCssText: "border-radius: 8px; box-shadow: 0 12px 32px rgb(0 0 0 / 30%); font-size: var(--daily-token-tooltip-font-size); line-height: 1.5;",
|
||||
axisPointer: {
|
||||
type: "shadow",
|
||||
shadowStyle: { color: "rgba(139, 148, 158, 0.14)" },
|
||||
},
|
||||
formatter: (params: unknown) => {
|
||||
const first = (params as TooltipItem[])[0];
|
||||
const day = data[first.dataIndex];
|
||||
return [
|
||||
formatTooltipTime(day.bucketStartMs, granularity),
|
||||
`${t("总请求")}:${formatCompactInteger(totalTokens(day))}`,
|
||||
`${colorMark(seriesColors.input)}${t("输入(非缓存)")}:${formatCompactInteger(day.inputTokens)}`,
|
||||
`${colorMark(seriesColors.cacheRead)}${t("缓存输入")}:${formatCompactInteger(day.cacheReadTokens)}`,
|
||||
`${colorMark(seriesColors.cacheWrite)}${t("缓存写入")}:${formatCompactInteger(day.cacheWriteTokens)}`,
|
||||
`${colorMark(seriesColors.output)}${t("模型输出")}:${formatCompactInteger(day.outputTokens)}`,
|
||||
].join("<br/>");
|
||||
},
|
||||
},
|
||||
xAxis: {
|
||||
type: "category",
|
||||
data: data.map(({ bucketStartMs }) => bucketStartMs),
|
||||
axisTick: { show: false },
|
||||
axisLine: { lineStyle: { color: "rgba(139, 148, 158, 0.32)" } },
|
||||
axisLabel: {
|
||||
interval: "auto",
|
||||
hideOverlap: true,
|
||||
formatter: (_value: string, index: number) => formatAxisLabel(data[index].bucketStartMs, granularity),
|
||||
color: "#8c8c8c",
|
||||
fontFamily: "HFKos",
|
||||
margin: 14,
|
||||
},
|
||||
},
|
||||
yAxis: {
|
||||
type: "value",
|
||||
show: false,
|
||||
min: 0,
|
||||
max: axisMaximum,
|
||||
},
|
||||
series: [
|
||||
{
|
||||
name: t("无用量"),
|
||||
type: "bar",
|
||||
stack: "empty-placeholder",
|
||||
data: data.map((day) => totalTokens(day) === 0 ? emptyBarHeight : 0),
|
||||
barMaxWidth: 18,
|
||||
silent: true,
|
||||
z: 0,
|
||||
itemStyle: { color: emptyBarColor, borderRadius: [2, 2, 0, 0] },
|
||||
emphasis: { disabled: true },
|
||||
},
|
||||
{
|
||||
name: t("输入(非缓存)"),
|
||||
type: "bar",
|
||||
stack: "tokens",
|
||||
data: data.map(({ inputTokens }) => inputTokens),
|
||||
barMaxWidth: 18,
|
||||
itemStyle: { color: seriesColors.input },
|
||||
...seriesFocus,
|
||||
},
|
||||
{
|
||||
name: t("缓存输入"),
|
||||
type: "bar",
|
||||
stack: "tokens",
|
||||
data: data.map(({ cacheReadTokens }) => cacheReadTokens),
|
||||
barMaxWidth: 18,
|
||||
itemStyle: { color: seriesColors.cacheRead },
|
||||
...seriesFocus,
|
||||
},
|
||||
{
|
||||
name: t("缓存写入"),
|
||||
type: "bar",
|
||||
stack: "tokens",
|
||||
data: data.map(({ cacheWriteTokens }) => cacheWriteTokens),
|
||||
barMaxWidth: 18,
|
||||
itemStyle: { color: seriesColors.cacheWrite },
|
||||
...seriesFocus,
|
||||
},
|
||||
{
|
||||
name: t("模型输出"),
|
||||
type: "bar",
|
||||
stack: "tokens",
|
||||
data: data.map(({ outputTokens }) => outputTokens),
|
||||
barMaxWidth: 18,
|
||||
barGap: "-100%",
|
||||
itemStyle: { color: seriesColors.output, borderRadius: [2, 2, 0, 0] },
|
||||
markLine: {
|
||||
silent: true,
|
||||
symbol: "none",
|
||||
lineStyle: { color: levelLineColor, opacity: hovered ? 1 : 0, type: "dashed", width: 2 },
|
||||
label: {
|
||||
show: hovered,
|
||||
position: "insideStartTop",
|
||||
formatter: t("平均"),
|
||||
color: levelLineColor,
|
||||
distance: 8,
|
||||
},
|
||||
data: [{ yAxis: averageLevel }],
|
||||
},
|
||||
...seriesFocus,
|
||||
},
|
||||
],
|
||||
}), [averageLevel, axisMaximum, data, emptyBarHeight, granularity, hovered]);
|
||||
|
||||
return <EChart
|
||||
option={option}
|
||||
className={styles.root}
|
||||
onMouseEnter={() => setHovered(true)}
|
||||
onMouseLeave={() => setHovered(false)}
|
||||
/>;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
.root {
|
||||
width: 100%;
|
||||
height: 260px;
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { BarChart, GaugeChart, LineChart } from "echarts/charts";
|
||||
import { GridComponent, LegendComponent, MarkLineComponent, TooltipComponent } from "echarts/components";
|
||||
import { getInstanceByDom, init, use, type EChartsCoreOption } from "echarts/core";
|
||||
import { CanvasRenderer } from "echarts/renderers";
|
||||
import { useEffect, useRef, type MouseEventHandler } from "react";
|
||||
import styles from "./EChart.module.scss";
|
||||
|
||||
use([BarChart, GaugeChart, LineChart, GridComponent, LegendComponent, MarkLineComponent, TooltipComponent, CanvasRenderer]);
|
||||
|
||||
type EChartProps = {
|
||||
option: EChartsCoreOption;
|
||||
className?: string;
|
||||
onMouseEnter?: MouseEventHandler<HTMLDivElement>;
|
||||
onMouseLeave?: MouseEventHandler<HTMLDivElement>;
|
||||
};
|
||||
|
||||
export function EChart({ option, className = styles.root, onMouseEnter, onMouseLeave }: EChartProps) {
|
||||
const element = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const node = element.current;
|
||||
if (!node) return;
|
||||
const chart = init(node, undefined, { renderer: "canvas" });
|
||||
const observer = new ResizeObserver(() => chart.resize());
|
||||
observer.observe(node);
|
||||
return () => {
|
||||
observer.disconnect();
|
||||
chart.dispose();
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const node = element.current;
|
||||
if (node) getInstanceByDom(node)?.setOption(option, { notMerge: true });
|
||||
}, [option]);
|
||||
|
||||
return <div ref={element} className={className} onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave} />;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { EChartsCoreOption } from "echarts/core";
|
||||
import type { LlmCall } from "../../../shared/api";
|
||||
import { EChart } from "./EChart";
|
||||
|
||||
export function LatencyChart({ calls }: { calls: LlmCall[] }) {
|
||||
const points = calls.slice(0, 20).reverse();
|
||||
const option: EChartsCoreOption = {
|
||||
animationDuration: 280,
|
||||
color: ["#d79a62", "#ad84cf", "#72a8d8"],
|
||||
grid: { top: 22, right: 18, bottom: 30, left: 48 },
|
||||
legend: { top: 0, right: 8, textStyle: { color: "#999" } },
|
||||
tooltip: { trigger: "axis" },
|
||||
xAxis: { type: "category", data: points.map((call) => new Date(call.created_at_ms).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })), axisLabel: { color: "#888" }, axisLine: { lineStyle: { color: "#5555" } } },
|
||||
yAxis: { type: "value", axisLabel: { color: "#888", formatter: "{value} ms" }, splitLine: { lineStyle: { color: "#8882" } } },
|
||||
series: [
|
||||
{ name: "TTFR", type: "line", smooth: true, symbol: "none", data: points.map((call) => call.ttfr_ms ?? 0) },
|
||||
{ name: "TTFT", type: "line", smooth: true, symbol: "none", data: points.map((call) => call.ttft_ms ?? 0) },
|
||||
{ name: t("总耗时"), type: "line", smooth: true, symbol: "none", data: points.map((call) => call.duration_ms ?? 0) },
|
||||
],
|
||||
};
|
||||
return <EChart option={option} />;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { EChartsCoreOption } from "echarts/core";
|
||||
import type { LlmCall } from "../../../shared/api";
|
||||
import { EChart } from "./EChart";
|
||||
|
||||
export function TokenTrendChart({ calls }: { calls: LlmCall[] }) {
|
||||
const points = calls.slice(0, 20).reverse();
|
||||
const option: EChartsCoreOption = {
|
||||
animationDuration: 280,
|
||||
color: ["#6f91f4", "#62c6a3"],
|
||||
grid: { top: 22, right: 18, bottom: 30, left: 48 },
|
||||
legend: { top: 0, right: 8, textStyle: { color: "#999" } },
|
||||
tooltip: { trigger: "axis" },
|
||||
xAxis: { type: "category", data: points.map((call) => new Date(call.created_at_ms).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })), axisLabel: { color: "#888" }, axisLine: { lineStyle: { color: "#5555" } } },
|
||||
yAxis: { type: "value", axisLabel: { color: "#888" }, splitLine: { lineStyle: { color: "#8882" } } },
|
||||
series: [
|
||||
{ name: t("输入 Token"), type: "bar", stack: "tokens", data: points.map((call) => call.input_tokens ?? 0), barMaxWidth: 22 },
|
||||
{ name: t("输出 Token"), type: "bar", stack: "tokens", data: points.map((call) => call.output_tokens ?? 0), barMaxWidth: 22 },
|
||||
],
|
||||
};
|
||||
return <EChart option={option} />;
|
||||
}
|
||||
Reference in new issue
Block a user