mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-27 01:19:25 +08:00
feat(panel): restore IDE mount compatibility, add composer dock mode, and refine chart tooltips
This commit is contained in:
File diff suppressed because it is too large
Load Diff
@@ -1,15 +1,18 @@
|
||||
/**
|
||||
* @fileoverview 交互式 SVG 三次贝塞尔平滑曲线趋势图组件 (TrendAreaChart).
|
||||
* 支持:
|
||||
* 1. 自适应整点小时(<=72h)与自然日(>72h)高精度分桶序列渲染;
|
||||
* 2. 鼠标悬停/滑动十字准星探针、高亮圆点与自适应防溢出的悬浮详情卡片(精确日期/小时区间、Token 拆分、费用与调用次数);
|
||||
* 3. 与 SVG 垂直网格线像素级对齐的多刻度底部时间轴(彻底告别首/中/末简单对半切分)。
|
||||
* @fileoverview 交互式历史用量趋势图组件 (TrendAreaChart).
|
||||
* 支持双模式自适应切换:
|
||||
* 1. <= 90 天(或整点小时分桶):渲染三次贝塞尔平滑曲线面积图、峰值气泡与对齐多刻度时间轴;
|
||||
* 2. > 90 天(自然日分桶):自动切换为类 GitHub 贡献日历的小格子热力排列(一格一天,7 行星期 × 周列、月份刻度、分位数 5 档热力色阶与底部图例);
|
||||
* 3. 两种模式共享自适应防溢出的悬浮详情卡片(精确日期/小时区间、Token 拆分、费用与调用次数)。
|
||||
*/
|
||||
|
||||
import { h, patchAttr, patchClasses, patchStyleVar, patchText } from '../../core/domPatch.js';
|
||||
import { formatTokensPrecise, formatUsd } from '../../core/formatters.js';
|
||||
import { SVG_NS } from '../../icons/SvgIcon.js';
|
||||
|
||||
/** 超过该自然日天数(> 90 天)时,趋势图切换为类 GitHub 每日小格子热力图 */
|
||||
export const HEATMAP_DAYS_THRESHOLD = 90;
|
||||
|
||||
let chartUidCounter = 0;
|
||||
|
||||
function safeSlotTokens(v) {
|
||||
@@ -60,7 +63,128 @@ function computeTickIndices(slots) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建交互式 SVG 历史趋势平滑面积图组件。
|
||||
* 基于非零活跃日的分位数阈值计算热力图 5 档色阶(0 ~ 4),避免单日极端峰值压缩其余活跃日的层次对比。
|
||||
*
|
||||
* @param {number[]} nonZeroValues 已升序排列的正数 Token 列表
|
||||
* @param {number} maxTokens
|
||||
* @returns {{ q1: number, q2: number, q3: number, maxTokens: number, count: number }}
|
||||
*/
|
||||
function computeHeatmapThresholds(nonZeroValues, maxTokens) {
|
||||
const n = nonZeroValues.length;
|
||||
if (n === 0 || maxTokens <= 0) {
|
||||
return { q1: 0, q2: 0, q3: 0, maxTokens: 0, count: 0 };
|
||||
}
|
||||
if (n < 4) {
|
||||
return {
|
||||
q1: maxTokens * 0.25,
|
||||
q2: maxTokens * 0.5,
|
||||
q3: maxTokens * 0.75,
|
||||
maxTokens,
|
||||
count: n,
|
||||
};
|
||||
}
|
||||
return {
|
||||
q1: nonZeroValues[Math.floor((n - 1) * 0.25)],
|
||||
q2: nonZeroValues[Math.floor((n - 1) * 0.5)],
|
||||
q3: nonZeroValues[Math.floor((n - 1) * 0.75)],
|
||||
maxTokens,
|
||||
count: n,
|
||||
};
|
||||
}
|
||||
|
||||
function resolveHeatmapLevel(tokens, thresholds) {
|
||||
if (tokens <= 0 || thresholds.maxTokens <= 0) return 0;
|
||||
if (tokens >= thresholds.maxTokens || tokens > thresholds.q3) return 4;
|
||||
if (tokens > thresholds.q2) return 3;
|
||||
if (tokens > thresholds.q1) return 2;
|
||||
return 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析日期槽位的年份与月份信息(兼容真实时间戳 `startMs` 与测试简写 `label`)。
|
||||
*
|
||||
* @param {object} slot
|
||||
* @returns {{ year: number, month: number, day: number }}
|
||||
*/
|
||||
function parseSlotCalendarParts(slot) {
|
||||
const sMs = Number(slot?.startMs);
|
||||
if (Number.isFinite(sMs) && sMs > 0) {
|
||||
const d = new Date(sMs);
|
||||
return { year: d.getFullYear(), month: d.getMonth() + 1, day: d.getDate() };
|
||||
}
|
||||
const m = String(slot?.label || '').match(/^(\d{1,2})\/(\d{1,2})$/);
|
||||
if (m) {
|
||||
return { year: new Date().getFullYear(), month: Number(m[1]), day: Number(m[2]) };
|
||||
}
|
||||
return { year: new Date().getFullYear(), month: 0, day: 0 };
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建热力图顶部与周列对齐的月份刻度标签(自动跳过首尾过窄残月,防止相邻月份文字重叠)。
|
||||
*
|
||||
* @param {Array<object>} slots
|
||||
* @param {number} firstDow 首日对应的星期行索引(0 = 周一 .. 6 = 周日)
|
||||
* @param {number} totalWeeks 总周列数
|
||||
* @returns {Array<{ col: number, text: string }>}
|
||||
*/
|
||||
function buildHeatmapMonthTicks(slots, firstDow, totalWeeks) {
|
||||
if (!slots.length || totalWeeks <= 0) return [];
|
||||
const firstParts = parseSlotCalendarParts(slots[0]);
|
||||
const lastParts = parseSlotCalendarParts(slots[slots.length - 1]);
|
||||
const crossYear = firstParts.year !== lastParts.year;
|
||||
|
||||
const candidates = [];
|
||||
let prevMonthKey = '';
|
||||
|
||||
for (let col = 0; col < totalWeeks; col++) {
|
||||
let chosenParts = null;
|
||||
for (let row = 0; row < 7; row++) {
|
||||
const idx = col * 7 + row - firstDow;
|
||||
if (idx < 0 || idx >= slots.length) continue;
|
||||
const parts = parseSlotCalendarParts(slots[idx]);
|
||||
if (!parts.month) continue;
|
||||
const mKey = `${parts.year}-${parts.month}`;
|
||||
if (col === 0 && !chosenParts) {
|
||||
chosenParts = parts;
|
||||
prevMonthKey = mKey;
|
||||
break;
|
||||
}
|
||||
if (mKey !== prevMonthKey) {
|
||||
chosenParts = parts;
|
||||
prevMonthKey = mKey;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (chosenParts && chosenParts.month > 0) {
|
||||
candidates.push({ col, year: chosenParts.year, month: chosenParts.month });
|
||||
}
|
||||
}
|
||||
|
||||
const baseMinGap = totalWeeks > 40 ? 4 : 3;
|
||||
if (
|
||||
candidates.length >= 2 &&
|
||||
candidates[0].col === 0 &&
|
||||
candidates[1].col - candidates[0].col < baseMinGap
|
||||
) {
|
||||
candidates.shift();
|
||||
}
|
||||
|
||||
const ticks = [];
|
||||
let nextAllowedCol = 0;
|
||||
for (let i = 0; i < candidates.length; i++) {
|
||||
const c = candidates[i];
|
||||
if (totalWeeks > 16 && c.col >= totalWeeks - 1) continue;
|
||||
if (ticks.length > 0 && c.col < nextAllowedCol) continue;
|
||||
const showYear = crossYear && (c.month === 1 || ticks.length === 0);
|
||||
const text = showYear ? `${String(c.year).slice(-2)}年${c.month}月` : `${c.month}月`;
|
||||
ticks.push({ col: c.col, text });
|
||||
nextAllowedCol = c.col + (showYear ? baseMinGap + 1 : baseMinGap);
|
||||
}
|
||||
return ticks;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建交互式历史趋势组件(<=90 天为 SVG 平滑曲线图,>90 天自动切换为类 GitHub 每日小格子热力图)。
|
||||
*
|
||||
* @returns {{
|
||||
* el: HTMLElement,
|
||||
@@ -68,17 +192,22 @@ function computeTickIndices(slots) {
|
||||
* }}
|
||||
*/
|
||||
export function createTrendAreaChart() {
|
||||
const VIEW_W = 460;
|
||||
const DEFAULT_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;
|
||||
|
||||
let viewW = DEFAULT_VIEW_W;
|
||||
|
||||
function resolvePlotBounds(w) {
|
||||
const leftX = 1;
|
||||
const rightX = Math.max(leftX + 20, w - 1);
|
||||
return { leftX, rightX, spanX: rightX - leftX };
|
||||
}
|
||||
|
||||
const svg = document.createElementNS(SVG_NS, 'svg');
|
||||
svg.setAttribute('viewBox', `0 0 ${VIEW_W} ${VIEW_H}`);
|
||||
svg.setAttribute('viewBox', `0 0 ${viewW} ${VIEW_H}`);
|
||||
svg.setAttribute('class', 'trend-svg');
|
||||
svg.setAttribute('aria-hidden', 'true');
|
||||
|
||||
@@ -107,16 +236,18 @@ export function createTrendAreaChart() {
|
||||
defs.appendChild(grad);
|
||||
svg.appendChild(defs);
|
||||
|
||||
// 背景水平与垂直参考网格线
|
||||
// 背景水平与垂直参考网格线(水平网格全宽贴边铺满 0..viewW)
|
||||
const hGridGroup = document.createElementNS(SVG_NS, 'g');
|
||||
hGridGroup.setAttribute('class', 'trend-grid');
|
||||
const hGridLines = [];
|
||||
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', String(LEFT_X));
|
||||
line.setAttribute('x1', '0');
|
||||
line.setAttribute('y1', String(y));
|
||||
line.setAttribute('x2', String(RIGHT_X));
|
||||
line.setAttribute('x2', String(viewW));
|
||||
line.setAttribute('y2', String(y));
|
||||
hGridGroup.appendChild(line);
|
||||
hGridLines.push(line);
|
||||
}
|
||||
svg.appendChild(hGridGroup);
|
||||
|
||||
@@ -158,7 +289,7 @@ export function createTrendAreaChart() {
|
||||
|
||||
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' });
|
||||
@@ -175,38 +306,56 @@ export function createTrendAreaChart() {
|
||||
]
|
||||
);
|
||||
|
||||
// 底部对齐刻度轴
|
||||
// 底部对齐刻度轴(曲线模式)
|
||||
const xAxisEl = h('div', { className: 'trend-x-axis' });
|
||||
const plotStage = h('div', { className: 'trend-plot-stage' }, [peakPill, svg]);
|
||||
|
||||
const plotStage = h('div', { className: 'trend-plot-stage' }, [peakPill, tooltipEl, svg]);
|
||||
const chartWrap = h('div', { className: 'trend-chart-wrap' }, [plotStage, xAxisEl]);
|
||||
// 类 GitHub 每日小格子热力图容器(> 90 天模式)
|
||||
const weekdayLabels = ['一', '', '三', '', '五', '', '日'];
|
||||
const hmWeekdaysEl = h('div', { className: 'trend-hm-weekdays', 'aria-hidden': 'true' }, [
|
||||
h('span', { className: 'trend-hm-month-spacer' }),
|
||||
...weekdayLabels.map((txt) => h('span', { className: 'trend-hm-wday', text: txt })),
|
||||
]);
|
||||
const hmMonthsEl = h('div', { className: 'trend-hm-months' });
|
||||
const hmGridEl = h('div', { className: 'trend-hm-grid', role: 'grid', 'aria-label': '每日用量热力格子图' });
|
||||
const hmTrackEl = h('div', { className: 'trend-hm-track' }, [hmMonthsEl, hmGridEl]);
|
||||
const hmScrollEl = h('div', { className: 'trend-hm-scroll' }, [hmTrackEl]);
|
||||
const hmBodyEl = h('div', { className: 'trend-heatmap-body' }, [hmWeekdaysEl, hmScrollEl]);
|
||||
|
||||
const hmSummaryEl = h('span', { className: 'trend-hm-summary text-mono', text: '' });
|
||||
const hmLegendEl = h('span', { className: 'trend-hm-legend', 'aria-hidden': 'true' }, [
|
||||
h('span', { text: '少' }),
|
||||
h('span', { className: 'trend-hm-swatch lv-0' }),
|
||||
h('span', { className: 'trend-hm-swatch lv-1' }),
|
||||
h('span', { className: 'trend-hm-swatch lv-2' }),
|
||||
h('span', { className: 'trend-hm-swatch lv-3' }),
|
||||
h('span', { className: 'trend-hm-swatch lv-4' }),
|
||||
h('span', { text: '多' }),
|
||||
]);
|
||||
const hmFooterEl = h('div', { className: 'trend-hm-footer' }, [hmSummaryEl, hmLegendEl]);
|
||||
const heatmapStage = h('div', { className: 'trend-heatmap-stage', hidden: true }, [
|
||||
hmBodyEl,
|
||||
hmFooterEl,
|
||||
]);
|
||||
|
||||
const chartWrap = h('div', { className: 'trend-chart-wrap' }, [
|
||||
plotStage,
|
||||
xAxisEl,
|
||||
heatmapStage,
|
||||
tooltipEl,
|
||||
]);
|
||||
|
||||
let currentSlots = [];
|
||||
let currentPts = [];
|
||||
let currentIsHeatmap = false;
|
||||
let currentHeatmapWeeks = 0;
|
||||
let currentCellEls = [];
|
||||
let tickElsByIdx = new Map();
|
||||
let hoveredIdx = -1;
|
||||
let hoveredCellEl = null;
|
||||
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);
|
||||
|
||||
function populateTooltipContent(slot) {
|
||||
patchText(tipTimeEl, slot.fullLabel || slot.label || '--');
|
||||
patchText(tipCallsEl, `${Math.max(0, Math.floor(Number(slot.calls) || 0))} 次`);
|
||||
const slotTok = safeSlotTokens(slot.tokens);
|
||||
@@ -231,47 +380,219 @@ export function createTrendAreaChart() {
|
||||
`入 ${formatTokensPrecise(safeSlotTokens(slot.inputTokens))} · 缓 ${formatTokensPrecise(safeSlotTokens(slot.cacheReadTokens))} · 出 ${formatTokensPrecise(safeSlotTokens(slot.outputTokens))}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
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%';
|
||||
function showLineHoverAtIndex(idx) {
|
||||
if (currentIsHeatmap || 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);
|
||||
patchClasses(tooltipEl, { 'is-hm-bottom': false, 'is-hm-top': false });
|
||||
patchAttr(tooltipEl, 'hidden', false);
|
||||
populateTooltipContent(slot);
|
||||
|
||||
const rawPct = (pt.x / viewW) * 100;
|
||||
const clampedPct = Math.max(1, Math.min(99, rawPct));
|
||||
patchStyleVar(tooltipEl, '--tip-x', `${clampedPct.toFixed(1)}%`);
|
||||
patchStyleVar(tooltipEl, '--tip-shift', shiftX);
|
||||
patchStyleVar(tooltipEl, '--tip-shift', `-${clampedPct.toFixed(1)}%`);
|
||||
|
||||
for (const [tIdx, el] of tickElsByIdx.entries()) {
|
||||
patchClasses(el, { 'is-hovered': tIdx === idx });
|
||||
}
|
||||
}
|
||||
|
||||
function showHeatmapHoverAtIndex(idx, cellEl) {
|
||||
if (!currentIsHeatmap || idx < 0 || idx >= currentSlots.length) {
|
||||
clearHover();
|
||||
return;
|
||||
}
|
||||
const targetCell = cellEl || currentCellEls[idx] || null;
|
||||
if (!targetCell) {
|
||||
clearHover();
|
||||
return;
|
||||
}
|
||||
hoveredIdx = idx;
|
||||
if (hoveredCellEl && hoveredCellEl !== targetCell) {
|
||||
patchClasses(hoveredCellEl, { 'is-hovered': false });
|
||||
}
|
||||
hoveredCellEl = targetCell;
|
||||
patchClasses(targetCell, { 'is-hovered': true });
|
||||
|
||||
const slot = currentSlots[idx];
|
||||
const row = Number(targetCell.getAttribute('data-hm-row') || 0);
|
||||
const col = Number(targetCell.getAttribute('data-hm-col') || 0);
|
||||
|
||||
// 上半区(周一~周四)浮层停靠底部,下半区(周五~周日)停靠顶部,互不遮挡被悬停格子且永不越界裁剪
|
||||
patchClasses(tooltipEl, {
|
||||
'is-hm-bottom': row <= 3,
|
||||
'is-hm-top': row > 3,
|
||||
});
|
||||
patchAttr(tooltipEl, 'hidden', false);
|
||||
populateTooltipContent(slot);
|
||||
|
||||
const wrapRect = chartWrap.getBoundingClientRect();
|
||||
const cellRect = targetCell.getBoundingClientRect();
|
||||
let rawPct = 50;
|
||||
if (
|
||||
wrapRect &&
|
||||
wrapRect.width > 0 &&
|
||||
cellRect &&
|
||||
cellRect.width > 0 &&
|
||||
cellRect.width < wrapRect.width
|
||||
) {
|
||||
rawPct = ((cellRect.left + cellRect.width / 2 - wrapRect.left) / wrapRect.width) * 100;
|
||||
} else if (currentHeatmapWeeks > 0) {
|
||||
rawPct = ((col + 0.5) / currentHeatmapWeeks) * 100;
|
||||
}
|
||||
const clampedPct = Math.max(1, Math.min(99, rawPct));
|
||||
patchStyleVar(tooltipEl, '--tip-x', `${clampedPct.toFixed(1)}%`);
|
||||
patchStyleVar(tooltipEl, '--tip-shift', `-${clampedPct.toFixed(1)}%`);
|
||||
}
|
||||
|
||||
function clearHover() {
|
||||
hoveredIdx = -1;
|
||||
patchAttr(hoverLine, 'hidden', true);
|
||||
patchAttr(hoverDot, 'hidden', true);
|
||||
patchAttr(tooltipEl, 'hidden', true);
|
||||
patchAttr(peakPill, 'hidden', false);
|
||||
patchClasses(tooltipEl, { 'is-hm-bottom': false, 'is-hm-top': false });
|
||||
if (!currentIsHeatmap) {
|
||||
patchAttr(peakPill, 'hidden', false);
|
||||
}
|
||||
if (hoveredCellEl) {
|
||||
patchClasses(hoveredCellEl, { 'is-hovered': false });
|
||||
hoveredCellEl = null;
|
||||
}
|
||||
for (const el of tickElsByIdx.values()) {
|
||||
patchClasses(el, { 'is-hovered': false });
|
||||
}
|
||||
}
|
||||
|
||||
function syncViewWidth() {
|
||||
const measured = Math.round(
|
||||
plotStage.clientWidth ||
|
||||
svg.clientWidth ||
|
||||
plotStage.getBoundingClientRect?.()?.width ||
|
||||
0
|
||||
);
|
||||
if (measured >= 160 && measured !== viewW) {
|
||||
viewW = measured;
|
||||
svg.setAttribute('viewBox', `0 0 ${viewW} ${VIEW_H}`);
|
||||
for (const line of hGridLines) {
|
||||
line.setAttribute('x1', '0');
|
||||
line.setAttribute('x2', String(viewW));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function handlePointerMove(e) {
|
||||
if (!currentSlots.length) return;
|
||||
if (currentIsHeatmap || !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 relX = ((e.clientX - rect.left) / rect.width) * viewW;
|
||||
const { leftX, spanX } = resolvePlotBounds(viewW);
|
||||
const ratio = (relX - leftX) / Math.max(1, spanX);
|
||||
const idx = Math.max(
|
||||
0,
|
||||
Math.min(currentSlots.length - 1, Math.round(ratio * (currentSlots.length - 1)))
|
||||
);
|
||||
showHoverAtIndex(idx);
|
||||
showLineHoverAtIndex(idx);
|
||||
}
|
||||
|
||||
function findHeatmapCellFromEvent(e) {
|
||||
let cur = e?.target || null;
|
||||
while (cur && cur !== hmGridEl) {
|
||||
const idxAttr = cur.getAttribute?.('data-slot-idx');
|
||||
if (idxAttr !== null && idxAttr !== undefined && idxAttr !== '') {
|
||||
return { idx: Number(idxAttr), cellEl: cur };
|
||||
}
|
||||
cur = cur.parentNode || null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function handleHeatmapPointer(e) {
|
||||
if (!currentIsHeatmap || !currentSlots.length) return;
|
||||
const hit = findHeatmapCellFromEvent(e);
|
||||
if (!hit || !Number.isFinite(hit.idx)) {
|
||||
clearHover();
|
||||
return;
|
||||
}
|
||||
if (hit.idx !== hoveredIdx || hit.cellEl !== hoveredCellEl) {
|
||||
showHeatmapHoverAtIndex(hit.idx, hit.cellEl);
|
||||
}
|
||||
}
|
||||
|
||||
function handleHeatmapWheel(e) {
|
||||
if (!currentIsHeatmap) return;
|
||||
const maxScrollLeft = (hmScrollEl.scrollWidth || 0) - (hmScrollEl.clientWidth || 0);
|
||||
if (maxScrollLeft <= 2) return;
|
||||
const dy = Number(e.deltaY || 0);
|
||||
const dx = Number(e.deltaX || 0);
|
||||
if (Math.abs(dy) > Math.abs(dx) && dy !== 0) {
|
||||
const prev = hmScrollEl.scrollLeft || 0;
|
||||
const next = Math.max(0, Math.min(maxScrollLeft, prev + dy));
|
||||
if (next !== prev) {
|
||||
hmScrollEl.scrollLeft = next;
|
||||
e.preventDefault?.();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
plotStage.addEventListener('mousemove', handlePointerMove);
|
||||
plotStage.addEventListener('mouseleave', clearHover);
|
||||
|
||||
hmGridEl.addEventListener('mouseover', handleHeatmapPointer);
|
||||
hmGridEl.addEventListener('mousemove', handleHeatmapPointer);
|
||||
hmGridEl.addEventListener('click', handleHeatmapPointer);
|
||||
hmGridEl.addEventListener('mouseleave', clearHover);
|
||||
hmScrollEl.addEventListener('wheel', handleHeatmapWheel);
|
||||
|
||||
let resizeObs = null;
|
||||
let onWinResize = null;
|
||||
if (typeof ResizeObserver === 'function') {
|
||||
resizeObs = new ResizeObserver(() => {
|
||||
if (!currentIsHeatmap && syncViewWidth() && currentSlots.length > 0) {
|
||||
lastRenderSig = '';
|
||||
update(currentSlots);
|
||||
}
|
||||
});
|
||||
resizeObs.observe(plotStage);
|
||||
} else if (typeof window !== 'undefined' && typeof window.addEventListener === 'function') {
|
||||
onWinResize = () => {
|
||||
if (!currentIsHeatmap && syncViewWidth() && currentSlots.length > 0) {
|
||||
lastRenderSig = '';
|
||||
update(currentSlots);
|
||||
}
|
||||
};
|
||||
window.addEventListener('resize', onWinResize);
|
||||
}
|
||||
|
||||
function destroy() {
|
||||
resizeObs?.disconnect();
|
||||
resizeObs = null;
|
||||
if (onWinResize && typeof window !== 'undefined' && typeof window.removeEventListener === 'function') {
|
||||
window.removeEventListener('resize', onWinResize);
|
||||
onWinResize = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据最新时间分桶序列重绘平滑曲线、渐变区域、峰值气泡与底部对齐刻度。
|
||||
* 根据最新时间分桶序列重绘平滑曲线(<=90天/小时级)或类 GitHub 每日小格子热力图(>90天)。
|
||||
*/
|
||||
function update(series = []) {
|
||||
const slots =
|
||||
@@ -285,39 +606,155 @@ export function createTrendAreaChart() {
|
||||
];
|
||||
currentSlots = slots;
|
||||
|
||||
const isHourly =
|
||||
slots[0]?.granularity === 'hour' || String(slots[0]?.label || '').includes(':');
|
||||
const useHeatmap = !isHourly && slots.length > HEATMAP_DAYS_THRESHOLD;
|
||||
const modeChanged = useHeatmap !== currentIsHeatmap;
|
||||
currentIsHeatmap = useHeatmap;
|
||||
|
||||
if (modeChanged) {
|
||||
clearHover();
|
||||
}
|
||||
patchClasses(chartWrap, { 'is-heatmap': useHeatmap });
|
||||
patchAttr(plotStage, 'hidden', useHeatmap);
|
||||
patchAttr(xAxisEl, 'hidden', useHeatmap);
|
||||
patchAttr(heatmapStage, 'hidden', !useHeatmap);
|
||||
|
||||
if (!useHeatmap) {
|
||||
syncViewWidth();
|
||||
}
|
||||
|
||||
let maxTokens = 0;
|
||||
let peakIdx = 0;
|
||||
let activeDays = 0;
|
||||
const nonZeroVals = [];
|
||||
|
||||
for (let i = 0; i < slots.length; i++) {
|
||||
const t = safeSlotTokens(slots[i]?.tokens);
|
||||
if (t > 0) {
|
||||
activeDays++;
|
||||
nonZeroVals.push(t);
|
||||
}
|
||||
if (t >= maxTokens) {
|
||||
maxTokens = t;
|
||||
peakIdx = i;
|
||||
}
|
||||
}
|
||||
|
||||
const sig =
|
||||
`${useHeatmap ? 'hm' : `line:${viewW}`}|` +
|
||||
slots
|
||||
.map(
|
||||
(s) =>
|
||||
`${s?.startMs || ''}:${s?.label || ''}:${s?.fullLabel || ''}:${safeSlotTokens(s?.tokens)}:${Number(s?.costUsd || 0)}:${Number(s?.calls || 0)}`
|
||||
)
|
||||
.join('|');
|
||||
|
||||
if (useHeatmap) {
|
||||
currentPts = [];
|
||||
if (sig !== lastRenderSig) {
|
||||
lastRenderSig = sig;
|
||||
nonZeroVals.sort((a, b) => a - b);
|
||||
const thresholds = computeHeatmapThresholds(nonZeroVals, maxTokens);
|
||||
|
||||
const firstStartMs = Number(slots[0]?.startMs);
|
||||
const firstDow =
|
||||
Number.isFinite(firstStartMs) && firstStartMs > 0
|
||||
? (new Date(firstStartMs).getDay() + 6) % 7
|
||||
: 0;
|
||||
const totalCells = firstDow + slots.length;
|
||||
const totalWeeks = Math.max(1, Math.ceil(totalCells / 7));
|
||||
currentHeatmapWeeks = totalWeeks;
|
||||
|
||||
patchStyleVar(hmBodyEl, '--hm-weeks', String(totalWeeks));
|
||||
patchStyleVar(hmBodyEl, '--hm-gap', totalWeeks > 42 ? '1.5px' : '2px');
|
||||
|
||||
// 重建顶部对齐月份标签
|
||||
while (hmMonthsEl.firstChild) hmMonthsEl.removeChild(hmMonthsEl.firstChild);
|
||||
const monthTicks = buildHeatmapMonthTicks(slots, firstDow, totalWeeks);
|
||||
for (const mt of monthTicks) {
|
||||
const mEl = h('span', { className: 'trend-hm-month text-mono', text: mt.text });
|
||||
patchStyleVar(mEl, '--hm-col', String(mt.col));
|
||||
hmMonthsEl.appendChild(mEl);
|
||||
}
|
||||
|
||||
// 重建 7 行 × N 周列的每日小格子(一格一天)
|
||||
while (hmGridEl.firstChild) hmGridEl.removeChild(hmGridEl.firstChild);
|
||||
hoveredCellEl = null;
|
||||
currentCellEls = new Array(slots.length);
|
||||
|
||||
for (let pad = 0; pad < firstDow; pad++) {
|
||||
hmGridEl.appendChild(
|
||||
h('span', { className: 'trend-hm-cell is-pad', 'aria-hidden': 'true' })
|
||||
);
|
||||
}
|
||||
|
||||
for (let i = 0; i < slots.length; i++) {
|
||||
const slot = slots[i];
|
||||
const tok = safeSlotTokens(slot?.tokens);
|
||||
const lv = resolveHeatmapLevel(tok, thresholds);
|
||||
const gridPos = firstDow + i;
|
||||
const col = Math.floor(gridPos / 7);
|
||||
const row = gridPos % 7;
|
||||
const cellEl = h('span', {
|
||||
className: `trend-hm-cell lv-${lv}`,
|
||||
'data-slot-idx': String(i),
|
||||
'data-hm-col': String(col),
|
||||
'data-hm-row': String(row),
|
||||
role: 'gridcell',
|
||||
});
|
||||
hmGridEl.appendChild(cellEl);
|
||||
currentCellEls[i] = cellEl;
|
||||
}
|
||||
|
||||
if (typeof requestAnimationFrame === 'function') {
|
||||
requestAnimationFrame(() => {
|
||||
if (hmScrollEl.scrollWidth > hmScrollEl.clientWidth) {
|
||||
hmScrollEl.scrollLeft = hmScrollEl.scrollWidth;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const peakSlot = slots[peakIdx];
|
||||
const summaryText =
|
||||
maxTokens > 0 && peakSlot?.label
|
||||
? `活跃 ${activeDays}/${slots.length} 天 · 峰值 ${peakSlot.label} · ${formatTokensPrecise(maxTokens)}`
|
||||
: `活跃 0/${slots.length} 天`;
|
||||
patchText(hmSummaryEl, summaryText);
|
||||
|
||||
if (hoveredIdx >= slots.length) {
|
||||
clearHover();
|
||||
} else if (hoveredIdx >= 0) {
|
||||
showHeatmapHoverAtIndex(hoveredIdx, currentCellEls[hoveredIdx]);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// --- <= 90 天(或整点小时级):渲染平滑面积曲线图(1:1 贴边对齐) ---
|
||||
currentCellEls = [];
|
||||
const { leftX, rightX, spanX } = resolvePlotBounds(viewW);
|
||||
const denom = Math.max(1, maxTokens);
|
||||
const isSingle = slots.length === 1;
|
||||
const pts = slots.map((s, idx) => {
|
||||
const tok = safeSlotTokens(s?.tokens);
|
||||
const x = isSingle ? (LEFT_X + RIGHT_X) / 2 : LEFT_X + (idx / Math.max(1, slots.length - 1)) * SPAN_X;
|
||||
const x = isSingle
|
||||
? (leftX + rightX) / 2
|
||||
: leftX + (idx / Math.max(1, slots.length - 1)) * spanX;
|
||||
const ratio = maxTokens > 0 ? tok / denom : 0;
|
||||
const y = BOTTOM_Y - ratio * SPAN_Y;
|
||||
return { x, y, tokens: tok };
|
||||
});
|
||||
currentPts = pts;
|
||||
|
||||
const sig = slots
|
||||
.map((s) => `${s?.label || ''}:${s?.fullLabel || ''}:${safeSlotTokens(s?.tokens)}:${Number(s?.costUsd || 0)}:${Number(s?.calls || 0)}`)
|
||||
.join('|');
|
||||
|
||||
if (sig !== lastRenderSig) {
|
||||
lastRenderSig = sig;
|
||||
let lineD;
|
||||
let areaD;
|
||||
if (isSingle) {
|
||||
const yStr = pts[0].y.toFixed(1);
|
||||
lineD = `M ${LEFT_X.toFixed(1)} ${yStr} L ${RIGHT_X.toFixed(1)} ${yStr}`;
|
||||
areaD = `${lineD} L ${RIGHT_X.toFixed(1)} ${BOTTOM_Y} L ${LEFT_X.toFixed(1)} ${BOTTOM_Y} Z`;
|
||||
lineD = `M ${leftX.toFixed(1)} ${yStr} L ${rightX.toFixed(1)} ${yStr}`;
|
||||
areaD = `${lineD} L ${rightX.toFixed(1)} ${BOTTOM_Y} L ${leftX.toFixed(1)} ${BOTTOM_Y} Z`;
|
||||
} else {
|
||||
lineD = buildSmoothSplinePath(pts);
|
||||
areaD = `${lineD} L ${pts[pts.length - 1].x.toFixed(1)} ${BOTTOM_Y} L ${pts[0].x.toFixed(1)} ${BOTTOM_Y} Z`;
|
||||
@@ -325,7 +762,7 @@ export function createTrendAreaChart() {
|
||||
patchAttr(linePath, 'd', lineD);
|
||||
patchAttr(areaPath, 'd', areaD);
|
||||
|
||||
// 渲染与底部刻度对齐的垂直参考网格线及底部 X 轴标签
|
||||
// 渲染与底部刻度对齐的垂直参考网格线及底部 X 轴标签(起止标签严格左右贴边)
|
||||
const tickIndices = computeTickIndices(slots);
|
||||
while (vGridGroup.firstChild) vGridGroup.removeChild(vGridGroup.firstChild);
|
||||
while (xAxisEl.firstChild) xAxisEl.removeChild(xAxisEl.firstChild);
|
||||
@@ -348,14 +785,14 @@ export function createTrendAreaChart() {
|
||||
|
||||
const isFirst = !isSingle && i === 0;
|
||||
const isLast = !isSingle && i === tickIndices.length - 1;
|
||||
const pct = (pt.x / VIEW_W) * 100;
|
||||
const pct = isFirst ? 0 : isLast ? 100 : (pt.x / viewW) * 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);
|
||||
tickEl.onclick = () => showLineHoverAtIndex(tIdx);
|
||||
xAxisEl.appendChild(tickEl);
|
||||
tickElsByIdx.set(tIdx, tickEl);
|
||||
}
|
||||
@@ -375,7 +812,7 @@ export function createTrendAreaChart() {
|
||||
}
|
||||
}
|
||||
|
||||
const peakPt = pts[peakIdx] || { x: 230, y: BOTTOM_Y };
|
||||
const peakPt = pts[peakIdx] || { x: viewW / 2, y: BOTTOM_Y };
|
||||
patchAttr(peakDot, 'cx', peakPt.x.toFixed(1));
|
||||
patchAttr(peakDot, 'cy', peakPt.y.toFixed(1));
|
||||
|
||||
@@ -385,15 +822,15 @@ export function createTrendAreaChart() {
|
||||
? `峰值 ${peakSlot.label} · ${formatTokensPrecise(maxTokens)}`
|
||||
: formatTokensPrecise(maxTokens);
|
||||
patchText(peakPill, peakText);
|
||||
const pctLeft = Math.max(12, Math.min(88, (peakPt.x / VIEW_W) * 100));
|
||||
const pctLeft = Math.max(12, Math.min(88, (peakPt.x / viewW) * 100));
|
||||
patchStyleVar(peakPill, '--peak-x', `${pctLeft.toFixed(1)}%`);
|
||||
|
||||
if (hoveredIdx >= slots.length) {
|
||||
clearHover();
|
||||
} else if (hoveredIdx >= 0) {
|
||||
showHoverAtIndex(hoveredIdx);
|
||||
showLineHoverAtIndex(hoveredIdx);
|
||||
}
|
||||
}
|
||||
|
||||
return { el: chartWrap, update };
|
||||
return { el: chartWrap, update, destroy };
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user