feat(panel): live task cards, interactive usage trend chart, and Gemini 4 Carbon support (v1.4.2)

This commit is contained in:
fish
2026-11-11 01:06:31 +09:00
parent c6f512413f
commit 8ac5da8d11
39 changed files with 4857 additions and 1099 deletions
@@ -1,16 +1,18 @@
/**
* @fileoverview 纯 SVG 三次贝塞尔平滑曲线趋势图组件 (TrendAreaChart).
* 负责将按时间分桶的 Token 消耗序列渲染为带垂直渐变填充、虚线参考网格、
* 峰值描点与自适应防溢出的顶部峰值胶囊标签的面积图。
* @fileoverview 交互式 SVG 三次贝塞尔平滑曲线趋势图组件 (TrendAreaChart).
* 支持:
* 1. 自适应整点小时(<=72h)与自然日(>72h)高精度分桶序列渲染;
* 2. 鼠标悬停/滑动十字准星探针、高亮圆点与自适应防溢出的悬浮详情卡片(精确日期/小时区间、Token 拆分、费用与调用次数);
* 3. 与 SVG 垂直网格线像素级对齐的多刻度底部时间轴(彻底告别首/中/末简单对半切分)。
*/
import { h, patchAttr, patchStyleVar, patchText } from '../../core/domPatch.js';
import { formatTokensPrecise } from '../../core/formatters.js';
import { h, patchAttr, patchClasses, patchStyleVar, patchText } from '../../core/domPatch.js';
import { formatTokensPrecise, formatUsd } from '../../core/formatters.js';
import { SVG_NS } from '../../icons/SvgIcon.js';
/**
* 将二维采样点序列转换为水平张力平滑的三次贝塞尔曲线 SVG 路径 (`M ... C ...`)。
* 控制点沿 X 轴取相邻点间距的 `0.45` 张力系数,Y 轴与各自端点齐平,
* 控制点沿 X 轴取相邻点间距的 `0.42` 张力系数,Y 轴与各自端点齐平,
* 保证曲线在极值点处平缓过渡且不会产生上下过冲 (Overshoot)。
*
* @param {Array<{ x: number, y: number }>} points SVG 坐标系下的采样点数组
@@ -23,33 +25,59 @@ function buildSmoothSplinePath(points) {
for (let i = 0; i < points.length - 1; i++) {
const p0 = points[i];
const p1 = points[i + 1];
const cpx1 = p0.x + (p1.x - p0.x) * 0.45;
const cpx2 = p1.x - (p1.x - p0.x) * 0.45;
const cpx1 = p0.x + (p1.x - p0.x) * 0.42;
const cpx2 = p1.x - (p1.x - p0.x) * 0.42;
d += ` C ${cpx1.toFixed(1)} ${p0.y.toFixed(1)}, ${cpx2.toFixed(1)} ${p1.y.toFixed(1)}, ${p1.x.toFixed(1)} ${p1.y.toFixed(1)}`;
}
return d;
}
/**
* 创建 SVG 历史趋势平滑面积图组件。
* 根据分桶总数与标签平均长度,计算底部 X 轴应当展示的均匀刻度下标列表。
*
* SVG 视口坐标系 (`viewBox="0 0 460 116"`) 布局约定:
* - 水平绘图区:`leftX = 12` 至 `rightX = 448`(总跨度 `spanX = 436`),左右预留边距容纳端点圆点描边;
* - 垂直绘图区:顶部峰值线 `topY = 26` 至底部零基线 `bottomY = 98`(总跨度 `spanY = 72`),
* 顶部预留 26px 空间给 HTML 峰值胶囊 (`.trend-peak-pill`)。
* @param {Array<{ label?: string }>} slots
* @returns {number[]}
*/
function computeTickIndices(slots) {
const n = slots.length;
if (n <= 1) return [0];
if (n <= 8) {
return Array.from({ length: n }, (_, i) => i);
}
const sampleLabel = String(slots[Math.floor(n / 2)]?.label || slots[0]?.label || '');
const maxTicks = sampleLabel.length > 6 ? 5 : 6;
const set = new Set();
for (let k = 0; k < maxTicks; k++) {
const idx = Math.round((k / (maxTicks - 1)) * (n - 1));
set.add(idx);
}
return Array.from(set).sort((a, b) => a - b);
}
/**
* 创建交互式 SVG 历史趋势平滑面积图组件。
*
* @returns {{
* el: HTMLElement,
* update: (series?: Array<{ label: string, tokens: number }>) => void
* }} 图表容器节点与序列更新方法
* update: (series?: Array<object>) => void
* }}
*/
export function createTrendAreaChart() {
const VIEW_W = 460;
const VIEW_H = 120;
const LEFT_X = 14;
const RIGHT_X = 446;
const TOP_Y = 24;
const BOTTOM_Y = 102;
const SPAN_X = RIGHT_X - LEFT_X;
const SPAN_Y = BOTTOM_Y - TOP_Y;
const svg = document.createElementNS(SVG_NS, 'svg');
svg.setAttribute('viewBox', '0 0 460 116');
svg.setAttribute('viewBox', `0 0 ${VIEW_W} ${VIEW_H}`);
svg.setAttribute('class', 'trend-svg');
svg.setAttribute('aria-hidden', 'true');
// 垂直线性渐变:由顶部 36% 不透明度的主题色平滑衰减至底部全透明
// 垂直线性渐变
const defs = document.createElementNS(SVG_NS, 'defs');
const grad = document.createElementNS(SVG_NS, 'linearGradient');
grad.setAttribute('id', 'trend-area-grad');
@@ -61,7 +89,7 @@ export function createTrendAreaChart() {
const stop1 = document.createElementNS(SVG_NS, 'stop');
stop1.setAttribute('offset', '0%');
stop1.setAttribute('stop-color', 'var(--ctx-cached)');
stop1.setAttribute('stop-opacity', '0.36');
stop1.setAttribute('stop-opacity', '0.34');
const stop2 = document.createElementNS(SVG_NS, 'stop');
stop2.setAttribute('offset', '100%');
@@ -73,26 +101,22 @@ export function createTrendAreaChart() {
defs.appendChild(grad);
svg.appendChild(defs);
// 背景辅助参考网格线:3 条水平分位线 + 3 条垂直时间锚点分割线
const gridGroup = document.createElementNS(SVG_NS, 'g');
gridGroup.setAttribute('class', 'trend-grid');
for (const y of [26, 62, 98]) {
// 背景水平与垂直参考网格线
const hGridGroup = document.createElementNS(SVG_NS, 'g');
hGridGroup.setAttribute('class', 'trend-grid');
for (const y of [TOP_Y, Math.round((TOP_Y + BOTTOM_Y) / 2), BOTTOM_Y]) {
const line = document.createElementNS(SVG_NS, 'line');
line.setAttribute('x1', '10');
line.setAttribute('x1', String(LEFT_X));
line.setAttribute('y1', String(y));
line.setAttribute('x2', '450');
line.setAttribute('x2', String(RIGHT_X));
line.setAttribute('y2', String(y));
gridGroup.appendChild(line);
hGridGroup.appendChild(line);
}
for (const x of [118, 230, 342]) {
const line = document.createElementNS(SVG_NS, 'line');
line.setAttribute('x1', String(x));
line.setAttribute('y1', '16');
line.setAttribute('x2', String(x));
line.setAttribute('y2', '98');
gridGroup.appendChild(line);
}
svg.appendChild(gridGroup);
svg.appendChild(hGridGroup);
const vGridGroup = document.createElementNS(SVG_NS, 'g');
vGridGroup.setAttribute('class', 'trend-grid trend-v-grid');
svg.appendChild(vGridGroup);
const areaPath = document.createElementNS(SVG_NS, 'path');
areaPath.setAttribute('fill', 'url(#trend-area-grad)');
@@ -103,25 +127,157 @@ export function createTrendAreaChart() {
linePath.setAttribute('fill', 'none');
svg.appendChild(linePath);
const dotsGroup = document.createElementNS(SVG_NS, 'g');
dotsGroup.setAttribute('class', 'trend-dots-group');
svg.appendChild(dotsGroup);
const peakDot = document.createElementNS(SVG_NS, 'circle');
peakDot.setAttribute('r', '3');
peakDot.setAttribute('class', 'trend-peak-dot');
svg.appendChild(peakDot);
const peakPill = h('span', { className: 'trend-peak-pill text-mono', text: '0' });
const chartWrap = h('div', { className: 'trend-chart-wrap' }, [peakPill, svg]);
// 悬停十字准星与焦点圆点
const hoverLine = document.createElementNS(SVG_NS, 'line');
hoverLine.setAttribute('class', 'trend-hover-line');
hoverLine.setAttribute('y1', '12');
hoverLine.setAttribute('y2', String(BOTTOM_Y));
hoverLine.setAttribute('hidden', 'true');
svg.appendChild(hoverLine);
let lastLineD = '';
const hoverDot = document.createElementNS(SVG_NS, 'circle');
hoverDot.setAttribute('r', '3.2');
hoverDot.setAttribute('class', 'trend-hover-dot');
hoverDot.setAttribute('hidden', 'true');
svg.appendChild(hoverDot);
const peakPill = h('span', { className: 'trend-peak-pill text-mono', text: '0' });
// 悬停详情浮层卡片
const tipTimeEl = h('span', { className: 'trend-tip-time text-mono' });
const tipCallsEl = h('span', { className: 'trend-tip-calls text-mono' });
const tipTokensEl = h('strong', { className: 'trend-tip-tokens text-mono' });
const tipCostEl = h('span', { className: 'trend-tip-cost text-mono' });
const tipSubEl = h('div', { className: 'trend-tip-sub text-mono', hidden: true });
const tooltipEl = h(
'div',
{ className: 'trend-tooltip', hidden: true },
[
h('div', { className: 'trend-tip-head' }, [tipTimeEl, tipCallsEl]),
h('div', { className: 'trend-tip-main' }, [tipTokensEl, tipCostEl]),
tipSubEl,
]
);
// 底部对齐刻度轴
const xAxisEl = h('div', { className: 'trend-x-axis' });
const plotStage = h('div', { className: 'trend-plot-stage' }, [peakPill, tooltipEl, svg]);
const chartWrap = h('div', { className: 'trend-chart-wrap' }, [plotStage, xAxisEl]);
let currentSlots = [];
let currentPts = [];
let tickElsByIdx = new Map();
let hoveredIdx = -1;
let lastRenderSig = '';
function showHoverAtIndex(idx) {
if (idx < 0 || idx >= currentSlots.length || !currentPts[idx]) {
clearHover();
return;
}
hoveredIdx = idx;
const slot = currentSlots[idx];
const pt = currentPts[idx];
patchAttr(hoverLine, 'hidden', false);
patchAttr(hoverLine, 'x1', pt.x.toFixed(1));
patchAttr(hoverLine, 'x2', pt.x.toFixed(1));
patchAttr(hoverDot, 'hidden', false);
patchAttr(hoverDot, 'cx', pt.x.toFixed(1));
patchAttr(hoverDot, 'cy', pt.y.toFixed(1));
patchAttr(peakPill, 'hidden', true);
patchAttr(tooltipEl, 'hidden', false);
patchText(tipTimeEl, slot.fullLabel || slot.label || '--');
patchText(tipCallsEl, `${Number(slot.calls || 0)} 次`);
patchText(tipTokensEl, `${formatTokensPrecise(Number(slot.tokens || 0))} tok`);
patchText(
tipCostEl,
formatUsd(Number(slot.costUsd || 0), {
unpricedCalls: slot.unpricedCalls,
precise: Number(slot.costUsd || 0) > 0 && Number(slot.costUsd || 0) < 0.1,
})
);
const hasSubBreakdown =
Number(slot.tokens || 0) > 0 &&
(slot.inputTokens !== undefined ||
slot.cacheReadTokens !== undefined ||
slot.outputTokens !== undefined);
patchAttr(tipSubEl, 'hidden', !hasSubBreakdown);
if (hasSubBreakdown) {
patchText(
tipSubEl,
`入 ${formatTokensPrecise(slot.inputTokens || 0)} · 缓 ${formatTokensPrecise(slot.cacheReadTokens || 0)} · 出 ${formatTokensPrecise(slot.outputTokens || 0)}`
);
}
const rawPct = (pt.x / VIEW_W) * 100;
const clampedPct = Math.max(2, Math.min(98, rawPct));
const shiftX = rawPct < 28 ? '0%' : rawPct > 72 ? '-100%' : '-50%';
patchStyleVar(tooltipEl, '--tip-x', `${clampedPct.toFixed(1)}%`);
patchStyleVar(tooltipEl, '--tip-shift', shiftX);
for (const [tIdx, el] of tickElsByIdx.entries()) {
patchClasses(el, { 'is-hovered': tIdx === idx });
}
}
function clearHover() {
hoveredIdx = -1;
patchAttr(hoverLine, 'hidden', true);
patchAttr(hoverDot, 'hidden', true);
patchAttr(tooltipEl, 'hidden', true);
patchAttr(peakPill, 'hidden', false);
for (const el of tickElsByIdx.values()) {
patchClasses(el, { 'is-hovered': false });
}
}
function handlePointerMove(e) {
if (!currentSlots.length) return;
const rect = svg.getBoundingClientRect();
if (!rect || rect.width <= 0) return;
const relX = ((e.clientX - rect.left) / rect.width) * VIEW_W;
const ratio = (relX - LEFT_X) / Math.max(1, SPAN_X);
const idx = Math.max(
0,
Math.min(currentSlots.length - 1, Math.round(ratio * (currentSlots.length - 1)))
);
showHoverAtIndex(idx);
}
plotStage.addEventListener('mousemove', handlePointerMove);
plotStage.addEventListener('mouseleave', clearHover);
/**
* 根据最新时间分桶序列重绘平滑曲线、闭合渐变区域以及最高峰标记位置。
* 根据最新时间分桶序列重绘平滑曲线、渐变区域、峰值气泡与底部对齐刻度。
*/
function update(series = []) {
const slots = series.length >= 2 ? series : [
{ label: '00:00', tokens: 0 },
{ label: '06:00', tokens: 0 },
{ label: '12:00', tokens: 0 },
];
const slots =
Array.isArray(series) && series.length >= 2
? series
: [
{ label: '00:00', fullLabel: '00:00 - 01:00', tokens: 0, calls: 0, costUsd: 0 },
{ label: '06:00', fullLabel: '06:00 - 07:00', tokens: 0, calls: 0, costUsd: 0 },
{ label: '12:00', fullLabel: '12:00 - 13:00', tokens: 0, calls: 0, costUsd: 0 },
{ label: '18:00', fullLabel: '18:00 - 19:00', tokens: 0, calls: 0, costUsd: 0 },
];
currentSlots = slots;
let maxTokens = 0;
let peakIdx = 0;
for (let i = 0; i < slots.length; i++) {
@@ -132,39 +288,92 @@ export function createTrendAreaChart() {
}
}
// SVG 绘图区边界与跨度参数(Y 轴向下递增,因此数值越大对应的 y 坐标越小)
const leftX = 12;
const rightX = 448;
const topY = 26;
const bottomY = 98;
const spanX = rightX - leftX;
const spanY = bottomY - topY;
const denom = Math.max(1, maxTokens);
const pts = slots.map((s, idx) => {
const x = leftX + (idx / Math.max(1, slots.length - 1)) * spanX;
const x = LEFT_X + (idx / Math.max(1, slots.length - 1)) * SPAN_X;
const ratio = maxTokens > 0 ? Number(s.tokens || 0) / denom : 0;
const y = bottomY - ratio * spanY;
return { x, y };
const y = BOTTOM_Y - ratio * SPAN_Y;
return { x, y, tokens: Number(s.tokens || 0) };
});
currentPts = pts;
// 仅在曲线路径发生变化时更新 DOM 属性,避免无意义的 SVG 重绘
const lineD = buildSmoothSplinePath(pts);
if (lineD !== lastLineD) {
lastLineD = lineD;
const areaD = `${lineD} L ${pts[pts.length - 1].x.toFixed(1)} ${bottomY} L ${pts[0].x.toFixed(1)} ${bottomY} Z`;
const sig = slots
.map((s) => `${s.label}:${s.fullLabel || ''}:${s.tokens}:${s.costUsd}:${s.calls}`)
.join('|');
if (sig !== lastRenderSig) {
lastRenderSig = sig;
const lineD = buildSmoothSplinePath(pts);
const areaD = `${lineD} L ${pts[pts.length - 1].x.toFixed(1)} ${BOTTOM_Y} L ${pts[0].x.toFixed(1)} ${BOTTOM_Y} Z`;
patchAttr(linePath, 'd', lineD);
patchAttr(areaPath, 'd', areaD);
// 渲染与底部刻度对齐的垂直参考网格线及底部 X 轴标签
const tickIndices = computeTickIndices(slots);
while (vGridGroup.firstChild) vGridGroup.removeChild(vGridGroup.firstChild);
while (xAxisEl.firstChild) xAxisEl.removeChild(xAxisEl.firstChild);
tickElsByIdx = new Map();
for (let i = 0; i < tickIndices.length; i++) {
const tIdx = tickIndices[i];
const pt = pts[tIdx];
const slot = slots[tIdx];
if (!pt || !slot) continue;
if (i > 0 && i < tickIndices.length - 1) {
const vLine = document.createElementNS(SVG_NS, 'line');
vLine.setAttribute('x1', pt.x.toFixed(1));
vLine.setAttribute('y1', '16');
vLine.setAttribute('x2', pt.x.toFixed(1));
vLine.setAttribute('y2', String(BOTTOM_Y));
vGridGroup.appendChild(vLine);
}
const isFirst = i === 0;
const isLast = i === tickIndices.length - 1;
const pct = (pt.x / VIEW_W) * 100;
const tickEl = h('span', {
className: `trend-x-tick text-mono${isFirst ? ' is-start' : isLast ? ' is-end' : ''}`,
text: slot.label || '',
title: slot.fullLabel || slot.label || '',
});
patchStyleVar(tickEl, '--tick-x', `${pct.toFixed(2)}%`);
tickEl.onclick = () => showHoverAtIndex(tIdx);
xAxisEl.appendChild(tickEl);
tickElsByIdx.set(tIdx, tickEl);
}
// 渲染采样点小圆点(当点数 <= 36 时展示,突出有消耗的整点/日期)
while (dotsGroup.firstChild) dotsGroup.removeChild(dotsGroup.firstChild);
if (pts.length <= 36) {
for (let i = 0; i < pts.length; i++) {
if (pts[i].tokens <= 0) continue;
const dot = document.createElementNS(SVG_NS, 'circle');
dot.setAttribute('cx', pts[i].x.toFixed(1));
dot.setAttribute('cy', pts[i].y.toFixed(1));
dot.setAttribute('r', '2');
dot.setAttribute('class', 'trend-node-dot');
dotsGroup.appendChild(dot);
}
}
}
// 定位峰值圆点,并将顶部峰值气泡水平位置钳制在 [8%, 92%] 区间内以防贴边裁切
const peakPt = pts[peakIdx] || { x: 230, y: bottomY };
const peakPt = pts[peakIdx] || { x: 230, y: BOTTOM_Y };
patchAttr(peakDot, 'cx', peakPt.x.toFixed(1));
patchAttr(peakDot, 'cy', peakPt.y.toFixed(1));
patchText(peakPill, formatTokensPrecise(maxTokens));
const pctLeft = Math.max(8, Math.min(92, (peakPt.x / 460) * 100));
const peakSlot = slots[peakIdx];
const peakText =
maxTokens > 0 && peakSlot?.label
? `峰值 ${peakSlot.label} · ${formatTokensPrecise(maxTokens)}`
: formatTokensPrecise(maxTokens);
patchText(peakPill, peakText);
const pctLeft = Math.max(12, Math.min(88, (peakPt.x / VIEW_W) * 100));
patchStyleVar(peakPill, '--peak-x', `${pctLeft.toFixed(1)}%`);
if (hoveredIdx >= 0 && hoveredIdx < slots.length) {
showHoverAtIndex(hoveredIdx);
}
}
return { el: chartWrap, update };