mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-26 17:09:28 +08:00
feat(panel): upgrade consumption rankings, pointer-following breakdown popovers, full session search, sortable steps, and settings backup
This commit is contained in:
@@ -10,13 +10,13 @@ import {
|
||||
h,
|
||||
patchAttr,
|
||||
patchClasses,
|
||||
patchKeyedList,
|
||||
patchStyleVar,
|
||||
patchText,
|
||||
} from '../../core/domPatch.js';
|
||||
import { formatTokensPrecise, formatUsd } from '../../core/formatters.js';
|
||||
import { SVG_NS } from '../../icons/SvgIcon.js';
|
||||
import { getEffectiveLocale, t } from '../../i18n/index.js';
|
||||
import { createConsumptionBreakdownContent } from '../ui/ConsumptionTooltipContent.js';
|
||||
|
||||
/** 超过该自然日天数(> 90 天)时,趋势图切换为类 GitHub 每日小格子热力图 */
|
||||
export const HEATMAP_DAYS_THRESHOLD = 90;
|
||||
@@ -196,12 +196,14 @@ function buildHeatmapMonthTicks(slots, firstDow, totalWeeks) {
|
||||
/**
|
||||
* 创建交互式历史趋势组件(<=90 天为 SVG 平滑曲线图,>90 天自动切换为类 GitHub 每日小格子热力图)。
|
||||
*
|
||||
* @param {{ onSelectSlot?: (slot: object) => void }} [options]
|
||||
* @returns {{
|
||||
* el: HTMLElement,
|
||||
* update: (series?: Array<object>) => void
|
||||
* update: (series?: Array<object>) => void,
|
||||
* destroy: () => void
|
||||
* }}
|
||||
*/
|
||||
export function createTrendAreaChart() {
|
||||
export function createTrendAreaChart({ onSelectSlot = null } = {}) {
|
||||
const DEFAULT_VIEW_W = 460;
|
||||
const VIEW_H = 184;
|
||||
const TOP_Y = 26;
|
||||
@@ -304,53 +306,25 @@ export function createTrendAreaChart() {
|
||||
|
||||
const peakPill = h('span', { className: 'trend-peak-pill text-mono', text: '0' });
|
||||
|
||||
function createTooltipModelRow() {
|
||||
const dotEl = h('span', { className: 'dot-swatch cons-model-dot' });
|
||||
const nameEl = h('span', { className: 'cons-pop-model-name' });
|
||||
const tokEl = h('span', { className: 'cons-pop-model-tok' });
|
||||
const pctEl = h('strong', { className: 'cons-pop-model-pct' });
|
||||
const rowEl = h('div', { className: 'cons-pop-model-row' }, [
|
||||
h('span', { className: 'cons-pop-model-left' }, [dotEl, nameEl]),
|
||||
h('span', { className: 'cons-pop-model-right text-mono' }, [tokEl, pctEl]),
|
||||
]);
|
||||
return {
|
||||
el: rowEl,
|
||||
refs: { rowEl, dotEl, nameEl, tokEl, pctEl },
|
||||
};
|
||||
}
|
||||
|
||||
// 共享悬停详情浮层卡片(曲线图与热力格子图共用,含该时段分模型占比明细)
|
||||
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 tipInLabelEl = h('span', { className: 'trend-tip-stat-label', text: t('cons.legInput') });
|
||||
const tipInValEl = h('span', { className: 'trend-tip-stat-val text-mono' });
|
||||
const tipCacheLabelEl = h('span', { className: 'trend-tip-stat-label', text: t('cons.legCache') });
|
||||
const tipCacheValEl = h('span', { className: 'trend-tip-stat-val text-mono' });
|
||||
const tipOutLabelEl = h('span', { className: 'trend-tip-stat-label', text: t('cons.legOutput') });
|
||||
const tipOutValEl = h('span', { className: 'trend-tip-stat-val text-mono' });
|
||||
const tipSubEl = h('div', { className: 'trend-tip-sub is-grid', hidden: true }, [
|
||||
h('div', { className: 'trend-tip-stat' }, [tipInLabelEl, tipInValEl]),
|
||||
h('div', { className: 'trend-tip-stat' }, [tipCacheLabelEl, tipCacheValEl]),
|
||||
h('div', { className: 'trend-tip-stat' }, [tipOutLabelEl, tipOutValEl]),
|
||||
]);
|
||||
const tipModelsEl = h('div', { className: 'cons-pop-models', hidden: true });
|
||||
// 共享悬停详情浮层卡片(曲线图和热力格子图共用,含分模型四段进度条及底部四通道明细)
|
||||
const tooltipContent = createConsumptionBreakdownContent({
|
||||
showModelDot: false,
|
||||
monoTitle: 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,
|
||||
tipModelsEl,
|
||||
]
|
||||
{ className: 'trend-tooltip is-rich-breakdown', hidden: true },
|
||||
tooltipContent.children
|
||||
);
|
||||
|
||||
// 底部对齐刻度轴(曲线模式)
|
||||
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${typeof onSelectSlot === 'function' ? ' is-clickable' : ''}` },
|
||||
[peakPill, svg]
|
||||
);
|
||||
|
||||
// 类 GitHub 每日小格子热力图容器(> 90 天模式)
|
||||
const wdayMonEl = h('span', { className: 'trend-hm-wday', text: t('chart.trend.wdayMon') });
|
||||
@@ -412,6 +386,7 @@ export function createTrendAreaChart() {
|
||||
let tickElsByIdx = new Map();
|
||||
let hoveredIdx = -1;
|
||||
let hoveredCellEl = null;
|
||||
let lastPointer = null;
|
||||
let lastRenderSig = '';
|
||||
let tipTrackRaf = 0;
|
||||
|
||||
@@ -443,102 +418,133 @@ export function createTrendAreaChart() {
|
||||
}
|
||||
|
||||
function populateTooltipContent(slot) {
|
||||
patchText(tipTimeEl, slot.fullLabel || slot.label || '--');
|
||||
patchText(
|
||||
tipCallsEl,
|
||||
t('cons.callsCount', { calls: Math.max(0, Math.floor(Number(slot.calls) || 0)) })
|
||||
);
|
||||
const slotTok = safeSlotTokens(slot.tokens);
|
||||
patchText(tipTokensEl, `${formatTokensPrecise(slotTok)} tok`);
|
||||
const slotCost = Number.isFinite(Number(slot.costUsd)) ? Math.max(0, Number(slot.costUsd)) : 0;
|
||||
patchText(
|
||||
tipCostEl,
|
||||
formatUsd(slotCost, {
|
||||
tooltipContent.update({
|
||||
title: slot.fullLabel || slot.label || '--',
|
||||
calls: slot.calls,
|
||||
totalTokens: slotTok,
|
||||
costText: formatUsd(slotCost, {
|
||||
precise: slotCost > 0 && slotCost < 0.1,
|
||||
})
|
||||
);
|
||||
|
||||
const hasSubBreakdown =
|
||||
slotTok > 0 &&
|
||||
(slot.inputTokens !== undefined ||
|
||||
slot.cacheReadTokens !== undefined ||
|
||||
slot.outputTokens !== undefined);
|
||||
patchAttr(tipSubEl, 'hidden', !hasSubBreakdown);
|
||||
if (hasSubBreakdown) {
|
||||
patchText(tipInLabelEl, t('cons.legInput'));
|
||||
patchText(tipCacheLabelEl, t('cons.legCache'));
|
||||
patchText(tipOutLabelEl, t('cons.legOutput'));
|
||||
patchText(tipInValEl, formatTokensPrecise(safeSlotTokens(slot.inputTokens)));
|
||||
patchText(tipCacheValEl, formatTokensPrecise(safeSlotTokens(slot.cacheReadTokens)));
|
||||
patchText(tipOutValEl, formatTokensPrecise(safeSlotTokens(slot.outputTokens)));
|
||||
}
|
||||
|
||||
const modelSegs = Array.isArray(slot.modelSegments) ? slot.modelSegments : [];
|
||||
patchAttr(tipModelsEl, 'hidden', modelSegs.length === 0);
|
||||
patchKeyedList(tipModelsEl, modelSegs, {
|
||||
keyFn: (r) => r.key,
|
||||
sigFn: (r) => `${r.key}:${r.label}:${r.color}:${r.tokText}:${r.pctText}:${r.isOther}`,
|
||||
createRow: createTooltipModelRow,
|
||||
updateRow: (rRefs, r) => {
|
||||
patchClasses(rRefs.rowEl, { 'is-other': Boolean(r.isOther) });
|
||||
patchStyleVar(rRefs.dotEl, '--dot-color', r.color);
|
||||
patchText(rRefs.nameEl, r.label);
|
||||
patchText(rRefs.tokEl, r.tokText);
|
||||
patchText(rRefs.pctEl, r.pctText);
|
||||
},
|
||||
}),
|
||||
inputTokens: slot.inputTokens,
|
||||
cacheReadTokens: slot.cacheReadTokens,
|
||||
thinkingTokens: slot.thinkingTokens,
|
||||
responseTokens: slot.responseTokens,
|
||||
outputTokens: slot.outputTokens,
|
||||
segments: Array.isArray(slot.modelSegments) ? slot.modelSegments : [],
|
||||
});
|
||||
}
|
||||
|
||||
function showLineHoverAtIndex(idx) {
|
||||
function positionTooltipNearAnchor(fallbackX, fallbackY, pointer = null) {
|
||||
const wrapRect = chartWrap.getBoundingClientRect?.() || null;
|
||||
const wrapW =
|
||||
wrapRect && wrapRect.width > 0
|
||||
? wrapRect.width
|
||||
: Number(chartWrap.clientWidth || viewW || DEFAULT_VIEW_W);
|
||||
const wrapH =
|
||||
wrapRect && wrapRect.height > 0
|
||||
? wrapRect.height
|
||||
: Number(chartWrap.offsetHeight || VIEW_H);
|
||||
|
||||
const tipRect = tooltipEl.getBoundingClientRect?.() || null;
|
||||
const tipW =
|
||||
Number(tooltipEl.offsetWidth || 0) ||
|
||||
(tipRect && tipRect.width > 0 ? tipRect.width : 216);
|
||||
const tipH =
|
||||
Number(tooltipEl.offsetHeight || 0) ||
|
||||
(tipRect && tipRect.height > 0 ? tipRect.height : 104);
|
||||
|
||||
const hasPointer =
|
||||
pointer &&
|
||||
Number.isFinite(Number(pointer.clientX)) &&
|
||||
Number.isFinite(Number(pointer.clientY)) &&
|
||||
wrapRect &&
|
||||
wrapRect.width > 0 &&
|
||||
wrapRect.height > 0;
|
||||
|
||||
const anchorX = hasPointer ? Number(pointer.clientX) - wrapRect.left : fallbackX;
|
||||
const anchorY = hasPointer ? Number(pointer.clientY) - wrapRect.top : fallbackY;
|
||||
|
||||
const clipEl = chartWrap.closest?.('.view-pane, .cons-view-stage') || null;
|
||||
const clipRect = clipEl?.getBoundingClientRect?.() || null;
|
||||
const hasClip = Boolean(
|
||||
clipRect && clipRect.height > 0 && wrapRect && wrapRect.height > 0
|
||||
);
|
||||
const minY = hasClip ? clipRect.top - wrapRect.top + 6 : -tipH - 16;
|
||||
const maxY = hasClip ? clipRect.bottom - wrapRect.top - tipH - 6 : wrapH + 16;
|
||||
|
||||
const maxLeft = Math.max(4, wrapW - tipW - 4);
|
||||
let leftPx = Math.max(4, Math.min(maxLeft, anchorX - tipW / 2));
|
||||
const aboveY = anchorY - tipH - 14;
|
||||
let topPx;
|
||||
|
||||
if (aboveY >= minY) {
|
||||
topPx = Math.min(maxY, aboveY);
|
||||
} else if (anchorX + 16 + tipW <= wrapW - 4) {
|
||||
leftPx = anchorX + 16;
|
||||
topPx = Math.max(minY, Math.min(maxY, anchorY - tipH / 2));
|
||||
} else if (anchorX - 16 - tipW >= 4) {
|
||||
leftPx = anchorX - 16 - tipW;
|
||||
topPx = Math.max(minY, Math.min(maxY, anchorY - tipH / 2));
|
||||
} else {
|
||||
topPx = Math.max(minY, Math.min(maxY, anchorY + 18));
|
||||
}
|
||||
|
||||
patchStyleVar(tooltipEl, '--tip-x', `${Math.round(leftPx)}px`);
|
||||
patchStyleVar(tooltipEl, '--tip-shift', '0px');
|
||||
patchStyleVar(tooltipEl, '--tip-y', `${Math.round(topPx)}px`);
|
||||
}
|
||||
|
||||
function showLineHoverAtIndex(idx, pointer = null) {
|
||||
if (currentIsHeatmap || idx < 0 || idx >= currentSlots.length || !currentPts[idx]) {
|
||||
clearHover();
|
||||
return;
|
||||
}
|
||||
const wasHidden = tooltipEl.hasAttribute('hidden');
|
||||
const changedIdx = idx !== hoveredIdx;
|
||||
hoveredIdx = idx;
|
||||
if (pointer) {
|
||||
lastPointer = pointer;
|
||||
}
|
||||
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));
|
||||
if (wasHidden || changedIdx) {
|
||||
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(hoverDot, 'hidden', false);
|
||||
patchAttr(hoverDot, 'cx', pt.x.toFixed(1));
|
||||
patchAttr(hoverDot, 'cy', pt.y.toFixed(1));
|
||||
|
||||
const isLineLow = pt.y < Math.round((TOP_Y + BOTTOM_Y) / 2);
|
||||
patchAttr(peakPill, 'hidden', true);
|
||||
patchClasses(tooltipEl, {
|
||||
'is-hm-bottom': false,
|
||||
'is-hm-top': false,
|
||||
'is-line-low': isLineLow,
|
||||
});
|
||||
patchAttr(tooltipEl, 'hidden', false);
|
||||
populateTooltipContent(slot);
|
||||
patchAttr(peakPill, 'hidden', true);
|
||||
patchClasses(tooltipEl, {
|
||||
'is-hm-bottom': false,
|
||||
'is-hm-top': false,
|
||||
'is-line-low': false,
|
||||
});
|
||||
patchAttr(tooltipEl, 'hidden', false);
|
||||
populateTooltipContent(slot);
|
||||
|
||||
let tipY = 0;
|
||||
if (isLineLow) {
|
||||
const wrapH = Number(chartWrap.offsetHeight || 0);
|
||||
const tipH = Number(tooltipEl.offsetHeight || 0);
|
||||
if (wrapH > 0 && tipH > 0) {
|
||||
tipY = Math.max(0, wrapH - tipH - 22);
|
||||
for (const [tIdx, el] of tickElsByIdx.entries()) {
|
||||
patchClasses(el, { 'is-hovered': tIdx === idx });
|
||||
}
|
||||
}
|
||||
|
||||
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', `-${clampedPct.toFixed(1)}%`);
|
||||
patchStyleVar(tooltipEl, '--tip-y', `${Math.round(tipY)}px`);
|
||||
const wrapRect = chartWrap.getBoundingClientRect?.() || null;
|
||||
const wrapW =
|
||||
wrapRect && wrapRect.width > 0
|
||||
? wrapRect.width
|
||||
: Number(chartWrap.clientWidth || viewW || DEFAULT_VIEW_W);
|
||||
const fallbackX = (pt.x / Math.max(1, viewW)) * wrapW;
|
||||
const fallbackY = pt.y + 6;
|
||||
positionTooltipNearAnchor(fallbackX, fallbackY, pointer || lastPointer);
|
||||
armTooltipTracking(wasHidden);
|
||||
|
||||
for (const [tIdx, el] of tickElsByIdx.entries()) {
|
||||
patchClasses(el, { 'is-hovered': tIdx === idx });
|
||||
}
|
||||
}
|
||||
|
||||
function showHeatmapHoverAtIndex(idx, cellEl) {
|
||||
function showHeatmapHoverAtIndex(idx, cellEl, pointer = null) {
|
||||
if (!currentIsHeatmap || idx < 0 || idx >= currentSlots.length) {
|
||||
clearHover();
|
||||
return;
|
||||
@@ -548,7 +554,12 @@ export function createTrendAreaChart() {
|
||||
clearHover();
|
||||
return;
|
||||
}
|
||||
const wasHidden = tooltipEl.hasAttribute('hidden');
|
||||
const changedCell = idx !== hoveredIdx || hoveredCellEl !== targetCell;
|
||||
hoveredIdx = idx;
|
||||
if (pointer) {
|
||||
lastPointer = pointer;
|
||||
}
|
||||
if (hoveredCellEl && hoveredCellEl !== targetCell) {
|
||||
patchClasses(hoveredCellEl, { 'is-hovered': false });
|
||||
}
|
||||
@@ -559,19 +570,25 @@ export function createTrendAreaChart() {
|
||||
const row = Number(targetCell.getAttribute('data-hm-row') || 0);
|
||||
const col = Number(targetCell.getAttribute('data-hm-col') || 0);
|
||||
|
||||
const wasHidden = tooltipEl.hasAttribute('hidden');
|
||||
// 上半区(周一~周四)浮层停靠热力图下方,下半区(周五~周日)停靠热力图上方,互不遮挡被悬停格子且永不越界裁剪
|
||||
patchClasses(tooltipEl, {
|
||||
'is-hm-bottom': row <= 3,
|
||||
'is-hm-top': row > 3,
|
||||
'is-line-low': false,
|
||||
});
|
||||
patchAttr(tooltipEl, 'hidden', false);
|
||||
populateTooltipContent(slot);
|
||||
if (wasHidden || changedCell) {
|
||||
patchClasses(tooltipEl, {
|
||||
'is-hm-bottom': false,
|
||||
'is-hm-top': false,
|
||||
'is-line-low': false,
|
||||
});
|
||||
patchAttr(tooltipEl, 'hidden', false);
|
||||
populateTooltipContent(slot);
|
||||
}
|
||||
|
||||
const wrapRect = chartWrap.getBoundingClientRect();
|
||||
const cellRect = targetCell.getBoundingClientRect();
|
||||
let rawPct = 50;
|
||||
const wrapRect = chartWrap.getBoundingClientRect?.() || null;
|
||||
const cellRect = targetCell.getBoundingClientRect?.() || null;
|
||||
const wrapW =
|
||||
wrapRect && wrapRect.width > 0
|
||||
? wrapRect.width
|
||||
: Number(chartWrap.clientWidth || viewW || DEFAULT_VIEW_W);
|
||||
let fallbackX =
|
||||
currentHeatmapWeeks > 0 ? ((col + 0.5) / currentHeatmapWeeks) * wrapW : wrapW / 2;
|
||||
let fallbackY = 20 + row * 14;
|
||||
if (
|
||||
wrapRect &&
|
||||
wrapRect.width > 0 &&
|
||||
@@ -579,20 +596,18 @@ export function createTrendAreaChart() {
|
||||
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;
|
||||
fallbackX = cellRect.left + cellRect.width / 2 - wrapRect.left;
|
||||
fallbackY = cellRect.top + cellRect.height / 2 - wrapRect.top;
|
||||
}
|
||||
const clampedPct = Math.max(1, Math.min(99, rawPct));
|
||||
patchStyleVar(tooltipEl, '--tip-x', `${clampedPct.toFixed(1)}%`);
|
||||
patchStyleVar(tooltipEl, '--tip-shift', `-${clampedPct.toFixed(1)}%`);
|
||||
patchStyleVar(tooltipEl, '--tip-y', '0px');
|
||||
|
||||
positionTooltipNearAnchor(fallbackX, fallbackY, pointer || lastPointer);
|
||||
armTooltipTracking(wasHidden);
|
||||
}
|
||||
|
||||
function clearHover() {
|
||||
cancelTipTrackRaf();
|
||||
hoveredIdx = -1;
|
||||
lastPointer = null;
|
||||
patchAttr(hoverLine, 'hidden', true);
|
||||
patchAttr(hoverDot, 'hidden', true);
|
||||
patchAttr(tooltipEl, 'hidden', true);
|
||||
@@ -645,7 +660,11 @@ export function createTrendAreaChart() {
|
||||
0,
|
||||
Math.min(currentSlots.length - 1, Math.round(ratio * (currentSlots.length - 1)))
|
||||
);
|
||||
showLineHoverAtIndex(idx);
|
||||
const pointer =
|
||||
Number.isFinite(Number(e?.clientX)) && Number.isFinite(Number(e?.clientY))
|
||||
? { clientX: Number(e.clientX), clientY: Number(e.clientY) }
|
||||
: null;
|
||||
showLineHoverAtIndex(idx, pointer);
|
||||
}
|
||||
|
||||
function findDirectHeatmapCell(e) {
|
||||
@@ -763,8 +782,12 @@ export function createTrendAreaChart() {
|
||||
clearHover();
|
||||
return;
|
||||
}
|
||||
if (hit.idx !== hoveredIdx || hit.cellEl !== hoveredCellEl) {
|
||||
showHeatmapHoverAtIndex(hit.idx, hit.cellEl);
|
||||
const pointer =
|
||||
Number.isFinite(Number(e?.clientX)) && Number.isFinite(Number(e?.clientY))
|
||||
? { clientX: Number(e.clientX), clientY: Number(e.clientY) }
|
||||
: null;
|
||||
if (hit.idx !== hoveredIdx || hit.cellEl !== hoveredCellEl || pointer) {
|
||||
showHeatmapHoverAtIndex(hit.idx, hit.cellEl, pointer);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -784,12 +807,43 @@ export function createTrendAreaChart() {
|
||||
}
|
||||
}
|
||||
|
||||
function handleLineClick(e) {
|
||||
if (currentIsHeatmap || !currentSlots.length || typeof onSelectSlot !== 'function') return;
|
||||
let idx = hoveredIdx;
|
||||
const rect = svg.getBoundingClientRect?.();
|
||||
if (rect && rect.width > 0 && Number.isFinite(Number(e?.clientX))) {
|
||||
const relX = ((e.clientX - rect.left) / rect.width) * viewW;
|
||||
const { leftX, spanX } = resolvePlotBounds(viewW);
|
||||
const ratio = (relX - leftX) / Math.max(1, spanX);
|
||||
idx = Math.max(
|
||||
0,
|
||||
Math.min(currentSlots.length - 1, Math.round(ratio * (currentSlots.length - 1)))
|
||||
);
|
||||
}
|
||||
const slot = currentSlots[idx];
|
||||
if (slot && Number(slot.startMs) > 0 && Number(slot.endMs) > Number(slot.startMs)) {
|
||||
onSelectSlot(slot);
|
||||
}
|
||||
}
|
||||
|
||||
function handleHeatmapClick(e) {
|
||||
handleHeatmapPointer(e);
|
||||
if (!currentIsHeatmap || !currentSlots.length || typeof onSelectSlot !== 'function') return;
|
||||
const hit = resolveHeatmapCellFromPointer(e);
|
||||
if (!hit || !Number.isFinite(hit.idx)) return;
|
||||
const slot = currentSlots[hit.idx];
|
||||
if (slot && Number(slot.startMs) > 0 && Number(slot.endMs) > Number(slot.startMs)) {
|
||||
onSelectSlot(slot);
|
||||
}
|
||||
}
|
||||
|
||||
plotStage.addEventListener('mousemove', handlePointerMove);
|
||||
plotStage.addEventListener('click', handleLineClick);
|
||||
plotStage.addEventListener('mouseleave', clearHover);
|
||||
|
||||
hmGridEl.addEventListener('mouseover', handleHeatmapPointer);
|
||||
hmGridEl.addEventListener('mousemove', handleHeatmapPointer);
|
||||
hmGridEl.addEventListener('click', handleHeatmapPointer);
|
||||
hmGridEl.addEventListener('click', handleHeatmapClick);
|
||||
hmGridEl.addEventListener('mouseleave', clearHover);
|
||||
hmScrollEl.addEventListener('wheel', handleHeatmapWheel);
|
||||
|
||||
@@ -815,6 +869,14 @@ export function createTrendAreaChart() {
|
||||
|
||||
function destroy() {
|
||||
cancelTipTrackRaf();
|
||||
plotStage.removeEventListener('mousemove', handlePointerMove);
|
||||
plotStage.removeEventListener('click', handleLineClick);
|
||||
plotStage.removeEventListener('mouseleave', clearHover);
|
||||
hmGridEl.removeEventListener('mouseover', handleHeatmapPointer);
|
||||
hmGridEl.removeEventListener('mousemove', handleHeatmapPointer);
|
||||
hmGridEl.removeEventListener('click', handleHeatmapClick);
|
||||
hmGridEl.removeEventListener('mouseleave', clearHover);
|
||||
hmScrollEl.removeEventListener('wheel', handleHeatmapWheel);
|
||||
resizeObs?.disconnect();
|
||||
resizeObs = null;
|
||||
if (onWinResize && typeof window !== 'undefined' && typeof window.removeEventListener === 'function') {
|
||||
@@ -887,9 +949,14 @@ export function createTrendAreaChart() {
|
||||
slots
|
||||
.map((s) => {
|
||||
const mSig = Array.isArray(s?.modelSegments)
|
||||
? s.modelSegments.map((m) => `${m.key}:${m.color}:${m.pctText}`).join(',')
|
||||
? s.modelSegments
|
||||
.map(
|
||||
(m) =>
|
||||
`${m.key}:${m.color}:${m.pctText}:${m.inputTokens || 0}:${m.cacheReadTokens || 0}:${m.thinkingTokens || 0}:${m.responseTokens || 0}`
|
||||
)
|
||||
.join(',')
|
||||
: '';
|
||||
return `${s?.startMs || ''}:${s?.label || ''}:${s?.fullLabel || ''}:${safeSlotTokens(s?.tokens)}:${Number(s?.costUsd || 0)}:${Number(s?.calls || 0)}:${mSig}`;
|
||||
return `${s?.startMs || ''}:${s?.label || ''}:${s?.fullLabel || ''}:${safeSlotTokens(s?.tokens)}:${safeSlotTokens(s?.inputTokens)}:${safeSlotTokens(s?.cacheReadTokens)}:${safeSlotTokens(s?.thinkingTokens)}:${safeSlotTokens(s?.responseTokens)}:${Number(s?.costUsd || 0)}:${Number(s?.calls || 0)}:${mSig}`;
|
||||
})
|
||||
.join('|');
|
||||
|
||||
@@ -989,7 +1056,7 @@ export function createTrendAreaChart() {
|
||||
if (hoveredIdx >= slots.length) {
|
||||
clearHover();
|
||||
} else if (hoveredIdx >= 0) {
|
||||
showHeatmapHoverAtIndex(hoveredIdx, currentCellEls[hoveredIdx]);
|
||||
showHeatmapHoverAtIndex(hoveredIdx, currentCellEls[hoveredIdx], lastPointer);
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -1055,7 +1122,10 @@ export function createTrendAreaChart() {
|
||||
title: slot.fullLabel || slot.label || '',
|
||||
});
|
||||
patchStyleVar(tickEl, '--tick-x', `${pct.toFixed(2)}%`);
|
||||
tickEl.onclick = () => showLineHoverAtIndex(tIdx);
|
||||
tickEl.onclick = () => {
|
||||
lastPointer = null;
|
||||
showLineHoverAtIndex(tIdx);
|
||||
};
|
||||
xAxisEl.appendChild(tickEl);
|
||||
tickElsByIdx.set(tIdx, tickEl);
|
||||
}
|
||||
@@ -1094,7 +1164,7 @@ export function createTrendAreaChart() {
|
||||
if (hoveredIdx >= slots.length) {
|
||||
clearHover();
|
||||
} else if (hoveredIdx >= 0) {
|
||||
showLineHoverAtIndex(hoveredIdx);
|
||||
showLineHoverAtIndex(hoveredIdx, lastPointer);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -31,6 +31,9 @@ export const TopSessionHeader = defineComponent({
|
||||
const convSelect = CustomSelect({
|
||||
modelValue: telemetryStore.getState().selectedConversationId,
|
||||
placeholder: t('header.followLatest'),
|
||||
searchable: true,
|
||||
searchThreshold: 6,
|
||||
searchPlaceholder: t('header.searchSessionPlaceholder'),
|
||||
options: [{ value: '', label: t('header.followLatest') }],
|
||||
onUpdateModelValue: (nextConvId) => {
|
||||
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' });
|
||||
@@ -236,6 +239,7 @@ export const TopSessionHeader = defineComponent({
|
||||
convSelect.setProps({
|
||||
modelValue: telSt.selectedConversationId,
|
||||
placeholder: t('header.followLatest'),
|
||||
searchPlaceholder: t('header.searchSessionPlaceholder'),
|
||||
options,
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,256 @@
|
||||
/**
|
||||
* @fileoverview 消耗统计统一悬浮详情内容组件 (ConsumptionTooltipContent).
|
||||
* 供历史趋势(折线/热力图)、客户端来源、会话排行及月度统计悬浮卡片复用:
|
||||
* 1. 顶部标题/日期行 + 右侧调用次数;
|
||||
* 2. 核心大字总量 (`TOKEN`) + 右侧预估费用;
|
||||
* 3. 分模型明细行(模型名/Token/占比 + 同「模型排行」Token 模式一致的四段构成进度条,不显示多余分组标题);
|
||||
* 4. 底部四通道汇总(输入 / 缓存 / 思考 / 输出)。
|
||||
*/
|
||||
|
||||
import {
|
||||
h,
|
||||
patchAttr,
|
||||
patchClasses,
|
||||
patchKeyedList,
|
||||
patchStyleVar,
|
||||
patchText,
|
||||
} from '../../core/domPatch.js';
|
||||
import { formatTokensPrecise } from '../../core/formatters.js';
|
||||
import { t } from '../../i18n/index.js';
|
||||
import { createFourSegmentBar } from './FourSegmentBar.js';
|
||||
|
||||
function safeNonNeg(val) {
|
||||
const n = Number(val);
|
||||
return Number.isFinite(n) && n > 0 ? n : 0;
|
||||
}
|
||||
|
||||
function resolveSegmentChannels(seg) {
|
||||
const inputTokens = safeNonNeg(seg?.inputTokens);
|
||||
const cacheReadTokens = safeNonNeg(seg?.cacheReadTokens);
|
||||
const thinkingTokens = safeNonNeg(seg?.thinkingTokens);
|
||||
const responseTokens =
|
||||
seg?.responseTokens != null
|
||||
? safeNonNeg(seg.responseTokens)
|
||||
: Math.max(0, safeNonNeg(seg?.outputTokens) - thinkingTokens);
|
||||
return { inputTokens, cacheReadTokens, thinkingTokens, responseTokens };
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建可增量更新的消耗统计悬浮详情内容结构。
|
||||
*
|
||||
* @param {{ showModelDot?: boolean, monoTitle?: boolean }} [options]
|
||||
* @returns {{
|
||||
* children: HTMLElement[],
|
||||
* update: (payload: {
|
||||
* title?: string,
|
||||
* calls?: number,
|
||||
* totalTokens?: number,
|
||||
* costText?: string,
|
||||
* inputTokens?: number,
|
||||
* cacheReadTokens?: number,
|
||||
* thinkingTokens?: number,
|
||||
* responseTokens?: number,
|
||||
* outputTokens?: number,
|
||||
* segments?: Array<object>,
|
||||
* }) => void,
|
||||
* }}
|
||||
*/
|
||||
export function createConsumptionBreakdownContent({
|
||||
showModelDot = false,
|
||||
monoTitle = false,
|
||||
} = {}) {
|
||||
const titleEl = h('span', {
|
||||
className: monoTitle ? 'trend-tip-time text-mono' : 'trend-tip-time',
|
||||
});
|
||||
const callsEl = h('span', { className: 'trend-tip-calls text-mono' });
|
||||
const headEl = h('div', { className: 'trend-tip-head cons-tip-head' }, [titleEl, callsEl]);
|
||||
|
||||
const heroNumEl = h('span', { className: 'cons-tip-hero-num', text: '0' });
|
||||
const heroUnitEl = h('span', { className: 'cons-tip-hero-unit', text: ' TOKEN' });
|
||||
const tokensEl = h('strong', { className: 'trend-tip-tokens cons-tip-hero text-mono' }, [
|
||||
heroNumEl,
|
||||
heroUnitEl,
|
||||
]);
|
||||
const costEl = h('span', { className: 'trend-tip-cost text-mono' });
|
||||
const mainEl = h('div', { className: 'trend-tip-main cons-tip-main' }, [tokensEl, costEl]);
|
||||
|
||||
function createModelRow() {
|
||||
const dotEl = h('span', {
|
||||
className: 'dot-swatch cons-model-dot',
|
||||
hidden: !showModelDot,
|
||||
});
|
||||
const nameEl = h('span', { className: 'cons-pop-model-name' });
|
||||
const tokEl = h('span', { className: 'cons-pop-model-tok' });
|
||||
const pctEl = h('strong', { className: 'cons-pop-model-pct' });
|
||||
const segBar = createFourSegmentBar();
|
||||
const rowEl = h('div', { className: 'cons-pop-model-row' }, [
|
||||
h('div', { className: 'cons-pop-model-head' }, [
|
||||
h('span', { className: 'cons-pop-model-left' }, [dotEl, nameEl]),
|
||||
h('span', { className: 'cons-pop-model-right text-mono' }, [tokEl, pctEl]),
|
||||
]),
|
||||
segBar.el,
|
||||
]);
|
||||
return {
|
||||
el: rowEl,
|
||||
refs: { rowEl, dotEl, nameEl, tokEl, pctEl, segBar },
|
||||
};
|
||||
}
|
||||
|
||||
const modelsEl = h('div', { className: 'cons-pop-models', hidden: true });
|
||||
|
||||
const inLabelEl = h('span', { className: 'cons-pop-chan-label', text: t('cons.legInput') });
|
||||
const inValEl = h('strong', { className: 'cons-pop-chan-val text-mono', text: '0' });
|
||||
const cacheLabelEl = h('span', { className: 'cons-pop-chan-label', text: t('cons.legCache') });
|
||||
const cacheValEl = h('strong', { className: 'cons-pop-chan-val text-mono', text: '0' });
|
||||
const thinkLabelEl = h('span', { className: 'cons-pop-chan-label', text: t('cons.legThinking') });
|
||||
const thinkValEl = h('strong', { className: 'cons-pop-chan-val text-mono', text: '0' });
|
||||
const outLabelEl = h('span', { className: 'cons-pop-chan-label', text: t('cons.legOutput') });
|
||||
const outValEl = h('strong', { className: 'cons-pop-chan-val text-mono', text: '0' });
|
||||
|
||||
const channelsEl = h('div', { className: 'cons-pop-channels', hidden: true }, [
|
||||
h('div', { className: 'cons-pop-chan' }, [
|
||||
h('span', { className: 'cons-pop-chan-head' }, [
|
||||
h('span', { className: 'dot-swatch seg-input' }),
|
||||
inLabelEl,
|
||||
]),
|
||||
inValEl,
|
||||
]),
|
||||
h('div', { className: 'cons-pop-chan' }, [
|
||||
h('span', { className: 'cons-pop-chan-head' }, [
|
||||
h('span', { className: 'dot-swatch seg-cached' }),
|
||||
cacheLabelEl,
|
||||
]),
|
||||
cacheValEl,
|
||||
]),
|
||||
h('div', { className: 'cons-pop-chan' }, [
|
||||
h('span', { className: 'cons-pop-chan-head' }, [
|
||||
h('span', { className: 'dot-swatch seg-thinking' }),
|
||||
thinkLabelEl,
|
||||
]),
|
||||
thinkValEl,
|
||||
]),
|
||||
h('div', { className: 'cons-pop-chan' }, [
|
||||
h('span', { className: 'cons-pop-chan-head' }, [
|
||||
h('span', { className: 'dot-swatch seg-output' }),
|
||||
outLabelEl,
|
||||
]),
|
||||
outValEl,
|
||||
]),
|
||||
]);
|
||||
|
||||
function update(payload = {}) {
|
||||
patchText(titleEl, payload.title || '--');
|
||||
patchText(
|
||||
callsEl,
|
||||
t('cons.callsCount', { calls: Math.max(0, Math.floor(Number(payload.calls) || 0)) })
|
||||
);
|
||||
const totalTokens = safeNonNeg(payload.totalTokens);
|
||||
patchText(heroNumEl, formatTokensPrecise(totalTokens));
|
||||
patchText(heroUnitEl, ' TOKEN');
|
||||
patchText(costEl, payload.costText || '');
|
||||
|
||||
const rows = Array.isArray(payload.segments) ? payload.segments : [];
|
||||
patchAttr(modelsEl, 'hidden', rows.length === 0);
|
||||
patchKeyedList(modelsEl, rows, {
|
||||
keyFn: (r) => r.key,
|
||||
sigFn: (r) =>
|
||||
`${showModelDot ? 1 : 0}:${r.key}:${r.label}:${r.color || ''}:${r.tokText}:${r.pctText}:${r.isOther ? 1 : 0}:${r.tok || 0}:${r.inputTokens || 0}:${r.cacheReadTokens || 0}:${r.thinkingTokens || 0}:${r.responseTokens ?? ''}:${r.outputTokens ?? ''}`,
|
||||
createRow: createModelRow,
|
||||
updateRow: (rRefs, r) => {
|
||||
patchClasses(rRefs.rowEl, { 'is-other': Boolean(r.isOther) });
|
||||
patchAttr(rRefs.dotEl, 'hidden', !showModelDot);
|
||||
if (showModelDot) {
|
||||
patchStyleVar(rRefs.dotEl, '--dot-color', r.color);
|
||||
}
|
||||
patchText(rRefs.nameEl, r.label);
|
||||
patchText(rRefs.tokEl, r.tokText);
|
||||
patchText(rRefs.pctEl, r.pctText);
|
||||
|
||||
const segTok = safeNonNeg(r.tok);
|
||||
const pct = Math.max(0, Math.min(100, Number(r.pct) || 0));
|
||||
const scaleRatio = segTok > 0 ? Math.min(1, Math.max(0.008, pct / 100)) : 0;
|
||||
const ch = resolveSegmentChannels(r);
|
||||
const chSum = ch.inputTokens + ch.cacheReadTokens + ch.thinkingTokens + ch.responseTokens;
|
||||
if (chSum > 0) {
|
||||
rRefs.segBar.update({
|
||||
inputTokens: ch.inputTokens,
|
||||
cacheReadTokens: ch.cacheReadTokens,
|
||||
thinkingTokens: ch.thinkingTokens,
|
||||
responseTokens: ch.responseTokens,
|
||||
scaleRatio,
|
||||
});
|
||||
} else if (segTok > 0) {
|
||||
rRefs.segBar.update({
|
||||
inputTokens: 0,
|
||||
cacheReadTokens: segTok,
|
||||
thinkingTokens: 0,
|
||||
responseTokens: 0,
|
||||
scaleRatio,
|
||||
});
|
||||
} else {
|
||||
rRefs.segBar.update({
|
||||
inputTokens: 0,
|
||||
cacheReadTokens: 0,
|
||||
thinkingTokens: 0,
|
||||
responseTokens: 0,
|
||||
scaleRatio: 0,
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const hasExplicitChannels =
|
||||
payload.inputTokens !== undefined ||
|
||||
payload.cacheReadTokens !== undefined ||
|
||||
payload.thinkingTokens !== undefined ||
|
||||
payload.responseTokens !== undefined ||
|
||||
payload.outputTokens !== undefined;
|
||||
let inTok = safeNonNeg(payload.inputTokens);
|
||||
let cacheTok = safeNonNeg(payload.cacheReadTokens);
|
||||
let thinkTok = safeNonNeg(payload.thinkingTokens);
|
||||
let respTok =
|
||||
payload.responseTokens != null
|
||||
? safeNonNeg(payload.responseTokens)
|
||||
: Math.max(0, safeNonNeg(payload.outputTokens) - thinkTok);
|
||||
let hasChannels = hasExplicitChannels;
|
||||
|
||||
if (!hasChannels && rows.length > 0) {
|
||||
let segIn = 0;
|
||||
let segCache = 0;
|
||||
let segThink = 0;
|
||||
let segResp = 0;
|
||||
for (const seg of rows) {
|
||||
const ch = resolveSegmentChannels(seg);
|
||||
segIn += ch.inputTokens;
|
||||
segCache += ch.cacheReadTokens;
|
||||
segThink += ch.thinkingTokens;
|
||||
segResp += ch.responseTokens;
|
||||
}
|
||||
if (segIn + segCache + segThink + segResp > 0) {
|
||||
inTok = segIn;
|
||||
cacheTok = segCache;
|
||||
thinkTok = segThink;
|
||||
respTok = segResp;
|
||||
hasChannels = true;
|
||||
}
|
||||
}
|
||||
|
||||
const showChannels = totalTokens > 0 && hasChannels;
|
||||
patchAttr(channelsEl, 'hidden', !showChannels);
|
||||
if (showChannels) {
|
||||
patchText(inLabelEl, t('cons.legInput'));
|
||||
patchText(cacheLabelEl, t('cons.legCache'));
|
||||
patchText(thinkLabelEl, t('cons.legThinking'));
|
||||
patchText(outLabelEl, t('cons.legOutput'));
|
||||
patchText(inValEl, formatTokensPrecise(inTok));
|
||||
patchText(cacheValEl, formatTokensPrecise(cacheTok));
|
||||
patchText(thinkValEl, formatTokensPrecise(thinkTok));
|
||||
patchText(outValEl, formatTokensPrecise(respTok));
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
children: [headEl, mainEl, modelsEl, channelsEl],
|
||||
update,
|
||||
};
|
||||
}
|
||||
@@ -51,12 +51,36 @@ function sameStringArray(a, b) {
|
||||
return true;
|
||||
}
|
||||
|
||||
export function filterSelectOptionsByQuery(options = [], rawQuery = '') {
|
||||
const q = String(rawQuery || '').trim().toLowerCase();
|
||||
if (!q) return options;
|
||||
const terms = q.split(/\s+/).filter(Boolean);
|
||||
if (terms.length === 0) return options;
|
||||
const out = [];
|
||||
for (let i = 0; i < options.length; i++) {
|
||||
const opt = options[i];
|
||||
if (!opt) continue;
|
||||
const haystack =
|
||||
`${opt.label || ''} ${opt.meta || ''} ${opt.title || ''} ${opt.value || ''}`.toLowerCase();
|
||||
let matched = true;
|
||||
for (let k = 0; k < terms.length; k++) {
|
||||
if (!haystack.includes(terms[k])) {
|
||||
matched = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (matched) out.push(opt);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export const CustomSelect = defineComponent({
|
||||
name: 'CustomSelect',
|
||||
setup({ getProps, setProps, emit, onCleanup }) {
|
||||
let isOpen = false;
|
||||
let focusedIndex = -1;
|
||||
let lastOpenMenuLayoutSig = '';
|
||||
let searchQuery = '';
|
||||
|
||||
const initialIcon = getProps().icon;
|
||||
const leadIcon = createSvgIcon(initialIcon || 'bolt', { size: 13 });
|
||||
@@ -81,11 +105,61 @@ export const CustomSelect = defineComponent({
|
||||
[leadIcon, triggerLabel, chevronIcon]
|
||||
);
|
||||
|
||||
const menuEl = h('div', {
|
||||
className: 'select-menu',
|
||||
role: 'listbox',
|
||||
hidden: true,
|
||||
const searchIcon = createSvgIcon('search', { size: 12, className: 'select-search-icon' });
|
||||
const searchInput = h('input', {
|
||||
type: 'text',
|
||||
className: 'select-search-input',
|
||||
autocomplete: 'off',
|
||||
spellcheck: 'false',
|
||||
placeholder: getProps().searchPlaceholder || t('select.searchPlaceholder'),
|
||||
onClick: (e) => e.stopPropagation(),
|
||||
onInput: (e) => {
|
||||
searchQuery = String(e?.target?.value ?? searchInput.value ?? '');
|
||||
focusedIndex = 0;
|
||||
renderMenuOptions();
|
||||
},
|
||||
onKeydown: handleKeydown,
|
||||
});
|
||||
const searchClearBtn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'select-search-clear',
|
||||
hidden: true,
|
||||
'aria-label': t('select.clearSearch'),
|
||||
onClick: (e) => {
|
||||
e.stopPropagation();
|
||||
clearSearchQuery(true);
|
||||
},
|
||||
},
|
||||
[createSvgIcon('close', { size: 10 })]
|
||||
);
|
||||
const searchWrap = h(
|
||||
'div',
|
||||
{
|
||||
className: 'select-search-wrap',
|
||||
hidden: true,
|
||||
onClick: (e) => e.stopPropagation(),
|
||||
},
|
||||
[searchIcon, searchInput, searchClearBtn]
|
||||
);
|
||||
|
||||
const optionsListEl = h('div', { className: 'select-options-list' });
|
||||
const emptyHintEl = h('div', {
|
||||
className: 'select-empty text-muted',
|
||||
hidden: true,
|
||||
text: t('select.noMatches'),
|
||||
});
|
||||
|
||||
const menuEl = h(
|
||||
'div',
|
||||
{
|
||||
className: 'select-menu',
|
||||
role: 'listbox',
|
||||
hidden: true,
|
||||
},
|
||||
[searchWrap, optionsListEl, emptyHintEl]
|
||||
);
|
||||
|
||||
const initialClass = [
|
||||
'custom-select',
|
||||
@@ -96,6 +170,28 @@ export const CustomSelect = defineComponent({
|
||||
.join(' ');
|
||||
const rootEl = h('div', { className: initialClass }, [triggerBtn, menuEl]);
|
||||
|
||||
function isSearchActiveForOptions(options) {
|
||||
const { searchable = false, searchThreshold = 6 } = getProps();
|
||||
return Boolean(searchable) && options.length >= Math.max(1, Number(searchThreshold) || 6);
|
||||
}
|
||||
|
||||
function getVisibleOptions() {
|
||||
const opts = getProps().options || [];
|
||||
if (!isSearchActiveForOptions(opts) || !searchQuery.trim()) return opts;
|
||||
return filterSelectOptionsByQuery(opts, searchQuery);
|
||||
}
|
||||
|
||||
function clearSearchQuery(refocus = false) {
|
||||
if (!searchQuery && !searchInput.value) return;
|
||||
searchQuery = '';
|
||||
searchInput.value = '';
|
||||
focusedIndex = 0;
|
||||
renderMenuOptions();
|
||||
if (refocus && typeof searchInput.focus === 'function') {
|
||||
searchInput.focus();
|
||||
}
|
||||
}
|
||||
|
||||
function getSelectedSet() {
|
||||
const { multiple, modelValue, options = [], allValue = '' } = getProps();
|
||||
if (!multiple) {
|
||||
@@ -109,7 +205,7 @@ export const CustomSelect = defineComponent({
|
||||
positionAnchoredPopup(rootEl, triggerBtn, menuEl, {
|
||||
margin: 6,
|
||||
gap: 4,
|
||||
maxHeight: 220,
|
||||
maxHeight: isSearchActiveForOptions(getProps().options || []) ? 268 : 220,
|
||||
minFlipSpace: 140,
|
||||
});
|
||||
}
|
||||
@@ -117,7 +213,7 @@ export const CustomSelect = defineComponent({
|
||||
let boundReposition = false;
|
||||
function handleViewportChange(e) {
|
||||
if (!isOpen) return;
|
||||
if (e?.type === 'scroll' && e.target === menuEl) return;
|
||||
if (e?.type === 'scroll' && (e.target === menuEl || e.target === optionsListEl)) return;
|
||||
positionMenu();
|
||||
}
|
||||
|
||||
@@ -136,7 +232,8 @@ export const CustomSelect = defineComponent({
|
||||
}
|
||||
|
||||
function buildMenuLayoutSig(options = [], labelText = '') {
|
||||
let sig = `${labelText}|${options.length}`;
|
||||
const searchShown = isSearchActiveForOptions(options) ? 1 : 0;
|
||||
let sig = `${labelText}|${searchShown}|${searchQuery}|${options.length}`;
|
||||
for (let i = 0; i < options.length; i++) {
|
||||
const o = options[i];
|
||||
sig += `|${o?.value ?? ''}:${o?.label ?? ''}:${o?.meta ?? ''}`;
|
||||
@@ -144,9 +241,11 @@ export const CustomSelect = defineComponent({
|
||||
return sig;
|
||||
}
|
||||
|
||||
function toggleOpen(nextOpen) {
|
||||
function toggleOpen(nextOpen, { focusSearch = false } = {}) {
|
||||
isOpen = Boolean(nextOpen);
|
||||
if (isOpen) {
|
||||
searchQuery = '';
|
||||
searchInput.value = '';
|
||||
const opts = getProps().options || [];
|
||||
const selSet = getSelectedSet();
|
||||
focusedIndex = Math.max(
|
||||
@@ -156,6 +255,8 @@ export const CustomSelect = defineComponent({
|
||||
renderMenuOptions();
|
||||
lastOpenMenuLayoutSig = buildMenuLayoutSig(opts, triggerLabel.textContent || '');
|
||||
} else {
|
||||
searchQuery = '';
|
||||
searchInput.value = '';
|
||||
lastOpenMenuLayoutSig = '';
|
||||
}
|
||||
patchClasses(rootEl, { 'is-open': isOpen });
|
||||
@@ -165,6 +266,13 @@ export const CustomSelect = defineComponent({
|
||||
setRepositionListeners(isOpen);
|
||||
if (isOpen) {
|
||||
positionMenu();
|
||||
if (focusSearch && isSearchActiveForOptions(getProps().options || [])) {
|
||||
queueMicrotask(() => {
|
||||
if (isOpen && typeof searchInput.focus === 'function') {
|
||||
searchInput.focus();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -216,42 +324,69 @@ export const CustomSelect = defineComponent({
|
||||
}
|
||||
|
||||
function handleKeydown(e) {
|
||||
const opts = getProps().options || [];
|
||||
if (!opts.length) return;
|
||||
const fromSearchInput = e?.target === searchInput;
|
||||
const visibleOpts = getVisibleOptions();
|
||||
|
||||
if (e.key === 'ArrowDown') {
|
||||
if (!visibleOpts.length && isOpen) return;
|
||||
e.preventDefault();
|
||||
if (!isOpen) {
|
||||
toggleOpen(true);
|
||||
} else {
|
||||
focusedIndex = (focusedIndex + 1) % opts.length;
|
||||
} else if (visibleOpts.length > 0) {
|
||||
focusedIndex = (focusedIndex + 1) % visibleOpts.length;
|
||||
renderMenuOptions();
|
||||
menuEl.children[focusedIndex]?.scrollIntoView?.({ block: 'nearest' });
|
||||
optionsListEl.children[focusedIndex]?.scrollIntoView?.({ block: 'nearest' });
|
||||
}
|
||||
} else if (e.key === 'ArrowUp') {
|
||||
if (!visibleOpts.length && isOpen) return;
|
||||
e.preventDefault();
|
||||
if (!isOpen) {
|
||||
toggleOpen(true);
|
||||
} else {
|
||||
focusedIndex = (focusedIndex - 1 + opts.length) % opts.length;
|
||||
} else if (visibleOpts.length > 0) {
|
||||
focusedIndex = (focusedIndex - 1 + visibleOpts.length) % visibleOpts.length;
|
||||
renderMenuOptions();
|
||||
menuEl.children[focusedIndex]?.scrollIntoView?.({ block: 'nearest' });
|
||||
optionsListEl.children[focusedIndex]?.scrollIntoView?.({ block: 'nearest' });
|
||||
}
|
||||
} else if ((e.key === 'Enter' || (e.key === ' ' && isOpen && getProps().multiple)) && isOpen) {
|
||||
} else if (
|
||||
(e.key === 'Enter' || (!fromSearchInput && e.key === ' ' && isOpen && getProps().multiple)) &&
|
||||
isOpen
|
||||
) {
|
||||
if (!visibleOpts.length) return;
|
||||
e.preventDefault();
|
||||
const target = opts[focusedIndex];
|
||||
const target = visibleOpts[focusedIndex] || visibleOpts[0];
|
||||
if (target) chooseOption(target);
|
||||
} else if (e.key === 'Escape' && isOpen) {
|
||||
e.preventDefault();
|
||||
toggleOpen(false);
|
||||
if (fromSearchInput && searchQuery) {
|
||||
clearSearchQuery(true);
|
||||
} else {
|
||||
toggleOpen(false);
|
||||
if (fromSearchInput && typeof triggerBtn.focus === 'function') {
|
||||
triggerBtn.focus();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function renderMenuOptions() {
|
||||
const { options = [], multiple = false } = getProps();
|
||||
const { options = [], multiple = false, searchPlaceholder } = getProps();
|
||||
const showSearch = isSearchActiveForOptions(options);
|
||||
const visibleOpts = getVisibleOptions();
|
||||
if (focusedIndex >= visibleOpts.length) {
|
||||
focusedIndex = visibleOpts.length > 0 ? 0 : -1;
|
||||
}
|
||||
patchAttr(searchWrap, 'hidden', !showSearch);
|
||||
patchClasses(menuEl, { 'has-search': showSearch });
|
||||
if (showSearch) {
|
||||
patchAttr(searchInput, 'placeholder', searchPlaceholder || t('select.searchPlaceholder'));
|
||||
patchAttr(searchClearBtn, 'hidden', !searchQuery);
|
||||
patchAttr(searchClearBtn, 'aria-label', t('select.clearSearch'));
|
||||
}
|
||||
patchText(emptyHintEl, t('select.noMatches'));
|
||||
patchAttr(emptyHintEl, 'hidden', !showSearch || visibleOpts.length > 0);
|
||||
const selSet = getSelectedSet();
|
||||
patchAttr(menuEl, 'aria-multiselectable', multiple ? 'true' : null);
|
||||
patchKeyedList(menuEl, options, {
|
||||
patchKeyedList(optionsListEl, visibleOpts, {
|
||||
keyFn: (opt) => opt.value,
|
||||
sigFn: (opt, idx) =>
|
||||
`${multiple}::${opt.value}::${opt.label}::${opt.meta || ''}::${Boolean(opt.disabled)}::${selSet.has(opt.value)}::${idx === focusedIndex}`,
|
||||
@@ -384,10 +519,12 @@ export const CustomSelect = defineComponent({
|
||||
|
||||
return {
|
||||
el: rootEl,
|
||||
refs: { triggerBtn, triggerLabel, menuEl },
|
||||
refs: { triggerBtn, triggerLabel, menuEl, searchInput, optionsListEl },
|
||||
onPropsChange: syncTriggerAndMenu,
|
||||
methods: {
|
||||
close: () => toggleOpen(false),
|
||||
open: () => toggleOpen(true),
|
||||
openAndFocusSearch: () => toggleOpen(true, { focusSearch: true }),
|
||||
},
|
||||
};
|
||||
},
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
speedReasonText,
|
||||
} from '../../core/formatters.js';
|
||||
import { getEffectiveLocale, t } from '../../i18n/index.js';
|
||||
import { createSvgIcon, patchSvgIcon } from '../../icons/SvgIcon.js';
|
||||
import {
|
||||
DEFAULT_STEP_COLUMN_KEYS,
|
||||
STEP_COLUMN_REGISTRY,
|
||||
@@ -389,6 +390,8 @@ export const StepTableWidget = defineComponent({
|
||||
typeof props.onSelectAgentScopes === 'function' ? props.onSelectAgentScopes : null;
|
||||
const onVirtualHeightChange =
|
||||
typeof props.onVirtualHeightChange === 'function' ? props.onVirtualHeightChange : null;
|
||||
const onSortChange =
|
||||
typeof props.onSortChange === 'function' ? props.onSortChange : null;
|
||||
|
||||
const stepsTheadRow = h('tr');
|
||||
const stepsThead = h('thead', {}, [stepsTheadRow]);
|
||||
@@ -397,16 +400,72 @@ export const StepTableWidget = defineComponent({
|
||||
function syncTableHeaderColumns(colKeys, headerCtx = {}) {
|
||||
const locale = getEffectiveLocale();
|
||||
const fmtKey = normalizeClientStepTokenComboFormat(headerCtx?.stepTokenComboFormat);
|
||||
const activeSortKey = String(headerCtx?.sortKey || '');
|
||||
const activeSortDir = headerCtx?.sortDir === 'asc' || headerCtx?.sortDir === 'desc'
|
||||
? headerCtx.sortDir
|
||||
: '';
|
||||
const ctx = { stepTokenComboFormat: fmtKey };
|
||||
patchKeyedList(stepsTheadRow, colKeys, {
|
||||
keyFn: (colKey) => colKey,
|
||||
sigFn: (colKey) => `${locale}:${colKey}:${fmtKey}:${STEP_COLUMN_REGISTRY[colKey].thLabel(ctx)}`,
|
||||
sigFn: (colKey) => {
|
||||
const isSorted = activeSortKey === colKey && Boolean(activeSortDir);
|
||||
return `${locale}:${colKey}:${fmtKey}:${STEP_COLUMN_REGISTRY[colKey].thLabel(ctx)}:${onSortChange ? 1 : 0}:${isSorted ? activeSortDir : ''}`;
|
||||
},
|
||||
createRow: (colKey) => {
|
||||
const th = h('th', { text: STEP_COLUMN_REGISTRY[colKey].thLabel(ctx) });
|
||||
return { el: th, refs: { th } };
|
||||
const labelSpan = h('span', {
|
||||
className: 'step-th-label',
|
||||
text: STEP_COLUMN_REGISTRY[colKey].thLabel(ctx),
|
||||
});
|
||||
const sortIcon = createSvgIcon('chevron-down', {
|
||||
size: 10,
|
||||
className: 'step-sort-icon',
|
||||
});
|
||||
patchAttr(sortIcon, 'hidden', true);
|
||||
const innerWrap = h('span', { className: 'step-th-inner' }, [labelSpan, sortIcon]);
|
||||
const th = h('th', {}, [innerWrap]);
|
||||
return { el: th, refs: { th, labelSpan, sortIcon } };
|
||||
},
|
||||
updateRow: (refs, colKey) => {
|
||||
patchText(refs.th, STEP_COLUMN_REGISTRY[colKey].thLabel(ctx));
|
||||
const labelText = STEP_COLUMN_REGISTRY[colKey].thLabel(ctx);
|
||||
patchText(refs.labelSpan, labelText);
|
||||
const sortable = Boolean(
|
||||
onSortChange && typeof STEP_COLUMN_REGISTRY[colKey]?.sortValue === 'function'
|
||||
);
|
||||
const isSorted = sortable && activeSortKey === colKey && Boolean(activeSortDir);
|
||||
patchClasses(refs.th, {
|
||||
'is-sortable': sortable,
|
||||
'is-sorted': isSorted,
|
||||
});
|
||||
patchAttr(
|
||||
refs.th,
|
||||
'aria-sort',
|
||||
isSorted ? (activeSortDir === 'asc' ? 'ascending' : 'descending') : sortable ? 'none' : null
|
||||
);
|
||||
patchAttr(
|
||||
refs.th,
|
||||
'title',
|
||||
sortable ? t('steps.sortClickTip', { col: labelText }) : null
|
||||
);
|
||||
patchAttr(refs.sortIcon, 'hidden', !isSorted);
|
||||
if (isSorted) {
|
||||
patchSvgIcon(refs.sortIcon, activeSortDir === 'asc' ? 'chevron-up' : 'chevron-down');
|
||||
}
|
||||
refs.th.onclick = sortable
|
||||
? () => {
|
||||
const defaultDir = STEP_COLUMN_REGISTRY[colKey]?.defaultSortDir || 'desc';
|
||||
let nextKey = colKey;
|
||||
let nextDir = defaultDir;
|
||||
if (activeSortKey === colKey) {
|
||||
if (activeSortDir === defaultDir) {
|
||||
nextDir = defaultDir === 'desc' ? 'asc' : 'desc';
|
||||
} else {
|
||||
nextKey = '';
|
||||
nextDir = '';
|
||||
}
|
||||
}
|
||||
onSortChange(nextKey, nextDir);
|
||||
}
|
||||
: null;
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -1414,6 +1473,8 @@ export const StepTableWidget = defineComponent({
|
||||
displaySettings = {},
|
||||
allConversationSteps = null,
|
||||
allowNewRowFade = false,
|
||||
sortKey = '',
|
||||
sortDir = '',
|
||||
} = {}
|
||||
) {
|
||||
const normCascadeId = String(cascadeId || '');
|
||||
@@ -1476,11 +1537,15 @@ export const StepTableWidget = defineComponent({
|
||||
|
||||
const colOrderSig = colKeys.join(',');
|
||||
const normTokenFmt = normalizeClientStepTokenComboFormat(stepTokenComboFormat);
|
||||
const normSortKey = String(sortKey || '');
|
||||
const normSortDir = sortDir === 'asc' || sortDir === 'desc' ? sortDir : '';
|
||||
const isCustomSorted = Boolean(normSortKey && normSortDir);
|
||||
const effectiveTurnRail = Boolean(showStepTurnRail && !isCustomSorted);
|
||||
const renderOptions = JSON.stringify([
|
||||
cascadeId, locale, colOrderSig, effectiveScopes, hasSubagents, isMergedMultiAgents,
|
||||
showStepTurnRail, showStepAgentBadge, showStepSpeedColor, normTokenFmt,
|
||||
effectiveTurnRail, showStepAgentBadge, showStepSpeedColor, normTokenFmt,
|
||||
displaySettings.modelDisplayMode, displaySettings.showUpstreamModel,
|
||||
displaySettings.orchestratorIdMode,
|
||||
displaySettings.orchestratorIdMode, normSortKey, normSortDir,
|
||||
]);
|
||||
if (
|
||||
lastRenderOptions === renderOptions &&
|
||||
@@ -1497,7 +1562,11 @@ export const StepTableWidget = defineComponent({
|
||||
|
||||
syncFontScaleIfChanged();
|
||||
const wantedSet = new Set(colKeys);
|
||||
syncTableHeaderColumns(colKeys, { stepTokenComboFormat: normTokenFmt });
|
||||
syncTableHeaderColumns(colKeys, {
|
||||
stepTokenComboFormat: normTokenFmt,
|
||||
sortKey: normSortKey,
|
||||
sortDir: normSortDir,
|
||||
});
|
||||
|
||||
const showAgentBadge = Boolean(hasSubagents && showStepAgentBadge);
|
||||
const cellCtx = {
|
||||
@@ -1513,7 +1582,7 @@ export const StepTableWidget = defineComponent({
|
||||
|
||||
const useRootTurn = Boolean(hasSubagents && isMergedMultiAgents);
|
||||
let railActive = false;
|
||||
if (showStepTurnRail) {
|
||||
if (effectiveTurnRail) {
|
||||
for (let i = 0; i < tableSteps.length; i++) {
|
||||
const st = tableSteps[i];
|
||||
const tIdx = useRootTurn ? (st?.rootTurnIndex ?? st?.turnIndex) : st?.turnIndex;
|
||||
@@ -1566,7 +1635,7 @@ export const StepTableWidget = defineComponent({
|
||||
cellCtx,
|
||||
railActive,
|
||||
showAgentBadge,
|
||||
showStepTurnRail,
|
||||
showStepTurnRail: effectiveTurnRail,
|
||||
useRootTurn,
|
||||
isVirtualized,
|
||||
hasReasonFlags,
|
||||
|
||||
Reference in New Issue
Block a user