Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): 柱图浮层分离悬停与聚焦、实时测量并补读屏明细

Dash751a43a5ec31
diff --git a/apps/desktop/src/renderer/components/settings/usage/UsageBarsTooltip.tsx b/apps/desktop/src/renderer/components/settings/usage/UsageBarsTooltip.tsx
index 58796d15be..ed420abbde 100644
--- a/apps/desktop/src/renderer/components/settings/usage/UsageBarsTooltip.tsx
+++ b/apps/desktop/src/renderer/components/settings/usage/UsageBarsTooltip.tsx
@@ -37,10 +37,12 @@ export interface UsageBarsTooltipData {
day: string;
tokens: number;
segments: UsageBarsTooltipSegment[];
- /** 当前柱子的点击区域 (视口坐标), 决定水平位置。 */
- anchor: DOMRect;
- /** 整个绘图区 (视口坐标), 决定上下位置 —— 浮层不遮挡其它柱子。 */
- plot: DOMRect;
+ /** 当前柱子点击区域的实时测量(视口坐标),决定水平位置。 */
+ measureAnchor: () => DOMRect | null;
+ /** 整个绘图区的实时测量(视口坐标),决定上下位置 —— 浮层不遮挡其它柱子。 */
+ measurePlot: () => DOMRect | null;
+ /** 滚动 / 尺寸变化计数:变化时重新测量。 */
+ layoutTick: number;
}
/** 行按 token 降序; 超出 MAX_ROWS 的尾部合并计数。 */
@@ -86,16 +88,24 @@ export function UsageBarsTooltip({
setPosition(null);
return;
}
+ const anchor = data.measureAnchor();
+ const plot = data.measurePlot();
+ if (!anchor || !plot) {
+ setPosition(null);
+ return;
+ }
const { width, height } = el.getBoundingClientRect();
const viewportWidth = document.documentElement.clientWidth;
- const centerX = data.anchor.left + data.anchor.width / 2;
+ const centerX = anchor.left + anchor.width / 2;
const left = Math.min(
Math.max(centerX - width / 2, VIEWPORT_MARGIN_PX),
viewportWidth - width - VIEWPORT_MARGIN_PX,
);
- const above = data.plot.top - GAP_PX - height;
- const top = above >= VIEWPORT_MARGIN_PX ? above : data.plot.bottom + GAP_PX;
- setPosition((prev) => ({ left, top, glide: prev !== null }));
+ const above = plot.top - GAP_PX - height;
+ const top = above >= VIEWPORT_MARGIN_PX ? above : plot.bottom + GAP_PX;
+ setPosition((prev) =>
+ prev && prev.left === left && prev.top === top ? prev : { left, top, glide: prev !== null },
+ );
}, [data]);
if (!data) return null;
@@ -108,7 +118,6 @@ export function UsageBarsTooltip({
weekday: 'short',
}).format(new Date(year, (month ?? 1) - 1, day ?? 1));
const { rows, hiddenCount, hiddenTokens } = tooltipRows(data.segments);
- const barSegments = [...data.segments].sort((a, b) => b.tokens - a.tokens);
return createPortal(
<div
@@ -132,14 +141,21 @@ export function UsageBarsTooltip({
{data.tokens > 0 ? (
<>
+ {/* 与明细同口径:前 MAX_ROWS 个模型各占一段,其余合成一段中性色,段数有上限不会被裁掉。 */}
<div className="mt-2.5 flex h-1 gap-px overflow-hidden rounded-[2px]">
- {barSegments.map((s) => (
+ {rows.map((s) => (
<span
key={s.key}
- className="h-full min-w-[2px]"
+ className="h-full"
style={{ flexGrow: s.tokens, flexBasis: 0, backgroundColor: s.color }}
/>
))}
+ {hiddenTokens > 0 ? (
+ <span
+ className="h-full bg-current opacity-40"
+ style={{ flexGrow: hiddenTokens, flexBasis: 0 }}
+ />
+ ) : null}
</div>
<div className="mt-2.5 grid grid-cols-[auto_minmax(0,1fr)_auto_auto] items-center gap-x-2 gap-y-1.5 text-12 leading-none">
{rows.map((s) => (
diff --git a/apps/desktop/src/renderer/components/settings/usage/UsageTokenBars.tsx b/apps/desktop/src/renderer/components/settings/usage/UsageTokenBars.tsx
index 739fd21e98..67b86a6538 100644
--- a/apps/desktop/src/renderer/components/settings/usage/UsageTokenBars.tsx
+++ b/apps/desktop/src/renderer/components/settings/usage/UsageTokenBars.tsx
@@ -15,7 +15,7 @@
* 不再用原生 title —— 原生提示无法排版配色, 也不给每根柱子各挂一个 Radix 实例。
*/
-import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import React, { useEffect, useId, useMemo, useReducer, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { formatCompactTokens } from '@/lib/usageFormat';
@@ -133,40 +133,42 @@ export function UsageTokenBars({
}, [modelDaily, colorOrder, todayKey, t]);
const plotRef = useRef<HTMLDivElement>(null);
- // 只记住悬停的是哪一天和位置; 浮层内容每次渲染从当前 bars 取, 数据刷新时同步更新。
- const [hover, setHover] = useState<{ day: string; anchor: DOMRect; plot: DOMRect } | null>(null);
- const showTooltip = useCallback((day: string, target: HTMLElement) => {
- const plot = plotRef.current;
- if (!plot) return;
- setHover({ day, anchor: target.getBoundingClientRect(), plot: plot.getBoundingClientRect() });
- }, []);
- const hideTooltip = useCallback(() => setHover(null), []);
- // fixed 定位的浮层不随页面滚动: 滚动或窗口尺寸变化时直接收起, 不留在错位置。
+ const descriptionIdBase = useId();
+ // 悬停与键盘聚焦是两个独立的触发源:任一仍有效就显示,悬停优先。只记「哪一天」,
+ // 坐标由浮层在布局阶段按当前 DOM 测量 —— 数据刷新或重排后不会停在旧位置。
+ const [hoverDay, setHoverDay] = useState<string | null>(null);
+ const [focusDay, setFocusDay] = useState<string | null>(null);
+ const activeDay = hoverDay ?? focusDay;
+ // fixed 定位的浮层不随页面滚动:滚动或窗口尺寸变化时重新测量,跟随柱子。
+ const [layoutTick, remeasure] = useReducer((tick: number) => tick + 1, 0);
useEffect(() => {
- if (!hover) return;
- window.addEventListener('scroll', hideTooltip, true);
- window.addEventListener('resize', hideTooltip);
+ if (!activeDay) return;
+ window.addEventListener('scroll', remeasure, true);
+ window.addEventListener('resize', remeasure);
return () => {
- window.removeEventListener('scroll', hideTooltip, true);
- window.removeEventListener('resize', hideTooltip);
+ window.removeEventListener('scroll', remeasure, true);
+ window.removeEventListener('resize', remeasure);
};
- }, [hover, hideTooltip]);
- const hoveredBar = hover ? bars.list.find((b) => b.day === hover.day) : undefined;
- const tooltip: UsageBarsTooltipData | null =
- hover && hoveredBar
- ? {
- day: hoveredBar.day,
- tokens: hoveredBar.tokens,
- segments: hoveredBar.segments.map((s) => ({
- key: s.rank,
- label: s.label,
- tokens: s.tokens,
- color: usageHistoryModelColor(s.rank, colorOrder.length),
- })),
- anchor: hover.anchor,
- plot: hover.plot,
- }
- : null;
+ }, [activeDay]);
+ const activeBar = activeDay ? bars.list.find((b) => b.day === activeDay) : undefined;
+ const tooltip: UsageBarsTooltipData | null = activeBar
+ ? {
+ day: activeBar.day,
+ tokens: activeBar.tokens,
+ segments: activeBar.segments.map((s) => ({
+ key: s.rank,
+ label: s.label,
+ tokens: s.tokens,
+ color: usageHistoryModelColor(s.rank, colorOrder.length),
+ })),
+ layoutTick,
+ measureAnchor: () =>
+ plotRef.current
+ ?.querySelector<HTMLElement>(`[data-day="${activeBar.day}"]`)
+ ?.getBoundingClientRect() ?? null,
+ measurePlot: () => plotRef.current?.getBoundingClientRect() ?? null,
+ }
+ : null;
const ticks = niceTicks(bars.max);
const recentWeekStart = shiftDayKeyLocal(todayKey, -6);
@@ -200,7 +202,7 @@ export function UsageTokenBars({
<div
ref={plotRef}
className="usage-token-plot flex h-full items-end gap-[3px]"
- onPointerLeave={hideTooltip}
+ onPointerLeave={() => setHoverDay(null)}
>
{bars.list.map((b) => {
const ratio = bars.max > 0 ? b.tokens / bars.max : 0;
@@ -216,10 +218,13 @@ export function UsageTokenBars({
key={b.day}
type="button"
data-day={b.day}
- onPointerEnter={(event) => showTooltip(b.day, event.currentTarget)}
- onFocus={(event) => showTooltip(b.day, event.currentTarget)}
- onBlur={hideTooltip}
+ onPointerEnter={() => setHoverDay(b.day)}
+ onFocus={() => setFocusDay(b.day)}
+ onBlur={() => setFocusDay((day) => (day === b.day ? null : day))}
aria-label={`${dateFormatter.format(parseDayKeyLocal(b.day))} · ${usageSummary}`}
+ aria-describedby={
+ b.segments.length > 0 ? `${descriptionIdBase}-${b.day}` : undefined
+ }
aria-pressed={selectedDay === b.day}
data-highlighted={
selectedDay
@@ -263,6 +268,24 @@ export function UsageTokenBars({
</div>
</div>
</div>
+ {/* 逐日模型明细的读屏文本:浮层 aria-hidden,原生 title 的这部分信息由它承接。 */}
+ <div className="sr-only">
+ {bars.list
+ .filter((b) => b.segments.length > 0)
+ .map((b) => (
+ <span key={b.day} id={`${descriptionIdBase}-${b.day}`}>
+ {[...b.segments]
+ .sort((x, y) => y.tokens - x.tokens)
+ .map(
+ (s) =>
+ `${s.label}: ${t('usageDashboard.tokensOnly', {
+ tokens: formatCompactTokens(s.tokens),
+ })}`,
+ )
+ .join('; ')}
+ </span>
+ ))}
+ </div>
<UsageBarsTooltip data={tooltip} />
</div>
);
diff --git a/apps/desktop/src/renderer/components/settings/usage/__tests__/usageBarsTooltip.test.tsx b/apps/desktop/src/renderer/components/settings/usage/__tests__/usageBarsTooltip.test.tsx
index 68c9b2acca..480455dc8f 100644
--- a/apps/desktop/src/renderer/components/settings/usage/__tests__/usageBarsTooltip.test.tsx
+++ b/apps/desktop/src/renderer/components/settings/usage/__tests__/usageBarsTooltip.test.tsx
@@ -1,18 +1,21 @@
// @vitest-environment jsdom
import React from 'react';
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
-import { afterEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { UsageTokenBars } from '../UsageTokenBars';
import { tooltipRows } from '../UsageBarsTooltip';
vi.mock('react-i18next', () => ({
useTranslation: () => ({
- t: (key: string, opts?: { count?: number }) =>
- opts?.count !== undefined ? `${key}:${opts.count}` : key,
+ t: (key: string, opts?: { count?: number; tokens?: string }) =>
+ opts?.count !== undefined
+ ? `${key}:${opts.count}`
+ : opts?.tokens !== undefined
+ ? `${opts.tokens} tokens`
+ : key,
i18n: { language: 'en' },
}),
}));
-afterEach(cleanup);
const money = {
amount: 0,
@@ -20,8 +23,8 @@ const money = {
approximate: false,
kind: 'actual-cost' as const,
};
-const row = (model: string, tokens: number) => ({
- day: '2026-09-26',
+const row = (model: string, tokens: number, day = '2026-09-26') => ({
+ day,
agentKind: 'codex' as const,
model,
tokens,
@@ -30,6 +33,59 @@ const row = (model: string, tokens: number) => ({
subscriptionEstimateMoney: money,
});
+// jsdom 没有布局:按元素身份给出可控的视口坐标。
+const rects = new Map<string, Partial<DOMRect>>();
+function rectFor(el: Element): DOMRect {
+ const key =
+ el.getAttribute('data-testid') === 'usage-bars-tooltip'
+ ? 'tooltip'
+ : el.classList.contains('usage-token-plot')
+ ? 'plot'
+ : (el.getAttribute('data-day') ?? '');
+ const r = { left: 0, top: 0, width: 0, height: 0, ...(rects.get(key) ?? {}) };
+ return {
+ ...r,
+ right: r.left + r.width,
+ bottom: r.top + r.height,
+ x: r.left,
+ y: r.top,
+ toJSON: () => r,
+ } as DOMRect;
+}
+
+beforeEach(() => {
+ rects.clear();
+ rects.set('tooltip', { width: 240, height: 150 });
+ rects.set('plot', { left: 100, top: 400, width: 800, height: 96 });
+ vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function (
+ this: HTMLElement,
+ ) {
+ return rectFor(this);
+ });
+ Object.defineProperty(document.documentElement, 'clientWidth', {
+ configurable: true,
+ value: 1000,
+ });
+});
+afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+});
+
+function renderBars(modelDaily = [row('small', 100), row('big', 900)]) {
+ return render(
+ <UsageTokenBars
+ modelDaily={modelDaily}
+ colorOrder={['codex big', 'codex small']}
+ todayKey="2026-09-26"
+ onDayClick={vi.fn()}
+ />,
+ );
+}
+const bar = (view: ReturnType<typeof render>, day = '2026-09-26') =>
+ view.container.querySelector<HTMLButtonElement>(`button[data-day="${day}"]`)!;
+const tooltipTransform = () => screen.getByTestId('usage-bars-tooltip').style.transform;
+
describe('usage bars tooltip', () => {
it('orders rows by tokens and folds the tail beyond six models', () => {
const segments = [1, 9, 3, 7, 5, 2, 8, 4].map((tokens) => ({
@@ -44,41 +100,84 @@ describe('usage bars tooltip', () => {
expect(hiddenTokens).toBe(3);
});
- it('replaces the native title with one shared tooltip on hover and focus', () => {
- const view = render(
- <UsageTokenBars
- modelDaily={[row('small', 100), row('big', 900)]}
- colorOrder={['codex big', 'codex small']}
- todayKey="2026-09-26"
- onDayClick={vi.fn()}
- />,
- );
- const bar = view.container.querySelector<HTMLButtonElement>('button[data-day="2026-09-26"]')!;
- expect(bar.hasAttribute('title')).toBe(false);
- expect(screen.queryByTestId('usage-bars-tooltip')).toBeNull();
+ it('replaces the native title with one shared tooltip and keeps model detail accessible', () => {
+ const view = renderBars();
+ const target = bar(view);
+ expect(target.hasAttribute('title')).toBe(false);
+ const description = document.getElementById(target.getAttribute('aria-describedby')!);
+ expect(description?.textContent).toBe('big: 900 tokens; small: 100 tokens');
- fireEvent.pointerOver(bar);
+ fireEvent.pointerOver(target);
const tooltip = screen.getByTestId('usage-bars-tooltip');
expect(tooltip.getAttribute('aria-hidden')).toBe('true');
const text = tooltip.textContent ?? '';
expect(text.indexOf('big')).toBeLessThan(text.indexOf('small'));
expect(text).toContain('90%');
expect(text).toContain('10%');
+ });
+
+ it('keeps the tooltip while either hover or focus is still active', () => {
+ const view = renderBars();
+ const target = bar(view);
+ const plot = target.parentElement!;
- fireEvent.pointerOut(bar.parentElement!, { relatedTarget: document.body });
+ fireEvent.focus(target);
+ fireEvent.pointerOver(target);
+ fireEvent.pointerOut(plot, { relatedTarget: document.body });
+ expect(screen.getByTestId('usage-bars-tooltip')).toBeTruthy();
+ fireEvent.blur(target);
expect(screen.queryByTestId('usage-bars-tooltip')).toBeNull();
- fireEvent.focus(bar);
+ fireEvent.pointerOver(target);
+ fireEvent.focus(target);
+ fireEvent.blur(target);
expect(screen.getByTestId('usage-bars-tooltip')).toBeTruthy();
- fireEvent.blur(bar);
+ fireEvent.pointerOut(plot, { relatedTarget: document.body });
expect(screen.queryByTestId('usage-bars-tooltip')).toBeNull();
});
- it('shows the empty-day message for a day without usage', () => {
+ it('centres above the plot, clamps to the viewport and flips below without room', () => {
+ const view = renderBars([row('big', 900), row('big', 300, '2026-09-25')]);
+ rects.set('2026-09-26', { left: 500, top: 470, width: 10, height: 26 });
+ rects.set('2026-09-25', { left: 990, top: 470, width: 10, height: 26 });
+
+ fireEvent.pointerOver(bar(view));
+ // centre 505 - 240 / 2 = 385; 400 - 8 - 150 = 242
+ expect(tooltipTransform()).toBe('translate3d(385px, 242px, 0)');
+ expect(screen.getByTestId('usage-bars-tooltip').dataset.glide).toBeUndefined();
+
+ fireEvent.pointerOver(bar(view, '2026-09-25'));
+ // clamped to 1000 - 240 - 8
+ expect(tooltipTransform()).toBe('translate3d(752px, 242px, 0)');
+ expect(screen.getByTestId('usage-bars-tooltip').dataset.glide).toBe('true');
+
+ rects.set('plot', { left: 100, top: 100, width: 800, height: 96 });
+ fireEvent.scroll(window);
+ // 100 - 8 - 150 < 8 → below the plot: 196 + 8
+ expect(tooltipTransform()).toBe('translate3d(752px, 204px, 0)');
+ });
+
+ it('caps the share bar at six model segments plus one merged remainder', () => {
+ const models = Array.from({ length: 10 }, (_, i) => row(`m${i}`, (i + 1) * 10));
const view = render(
- <UsageTokenBars modelDaily={[]} colorOrder={[]} todayKey="2026-09-26" onDayClick={vi.fn()} />,
+ <UsageTokenBars
+ modelDaily={models}
+ colorOrder={models.map((m) => `codex ${m.model}`)}
+ todayKey="2026-09-26"
+ onDayClick={vi.fn()}
+ />,
+ );
+ fireEvent.pointerOver(bar(view));
+ const shareBar = screen.getByTestId('usage-bars-tooltip').querySelector('.h-1')!;
+ expect(shareBar.children).toHaveLength(7);
+ expect(screen.getByTestId('usage-bars-tooltip').textContent).toContain(
+ 'usageHistory.daily.tooltip.more:4',
);
- fireEvent.pointerOver(view.container.querySelector('button[data-day="2026-09-20"]')!);
+ });
+
+ it('shows the empty-day message for a day without usage', () => {
+ const view = renderBars([]);
+ fireEvent.pointerOver(bar(view, '2026-09-20'));
expect(screen.getByTestId('usage-bars-tooltip').textContent).toContain(
'usageHistory.heatmap.emptyCell',
);
diff --git a/docs/design-rules/usage-history-charts.md b/docs/design-rules/usage-history-charts.md
index 00800f09a5..69baf76fcd 100644
--- a/docs/design-rules/usage-history-charts.md
+++ b/docs/design-rules/usage-history-charts.md
@@ -17,17 +17,17 @@
## 每日柱图悬停浮层(2026-09-26 所有者要求)
-所有者认为原生 title 提示「不好看、没有设计感」,每日 token 柱图改用自绘浮层 `UsageBarsTooltip`,热力图仍保留原生 title。整张图共用一个浮层实例,悬停或键盘聚焦柱子时显示,离开绘图区、失焦、滚动或窗口尺寸变化时收起。
+所有者认为原生 title 提示「不好看、没有设计感」,每日 token 柱图改用自绘浮层 `UsageBarsTooltip`,热力图仍保留原生 title。整张图共用一个浮层实例。悬停与键盘聚焦是两个独立触发源,任一仍有效即显示(悬停优先);指针离开绘图区且没有聚焦柱子、或失焦且没有悬停时收起。滚动、窗口尺寸变化与数据刷新时按当前布局重新测量并跟随柱子。
| 层 | 规格 |
| --- | --- |
| 容器 | `--tooltip-bg` / `--tooltip-text`(两模式同为深底白字,沿用共享 Tooltip),12px 圆角、`--shadow-menu` 投影加 10% `--tooltip-text` 发丝内描边(Dark 下与卡片底色区分),内边距 12×10px,宽 220–320px |
| 头部 | 日期(含星期,11px,60% 不透明度);当日总量 16px / 500 等宽数字,单位 11px 弱化 |
-| 占比条 | 4px 高、2px 圆角的横向分段,颜色与柱段相同,按 token 降序,段间 1px 间隔 |
+| 占比条 | 4px 高、2px 圆角的横向分段,颜色与柱段相同,按 token 降序,段间 1px 间隔;与明细同口径只画前 6 个模型,其余合成一段 40% 不透明度的中性段,不会因模型多而被裁掉 |
| 明细 | 8×8px、2px 圆角色块 · 模型名(截断)· token(500,等宽右对齐)· 占比(50% 不透明度);按 token 降序,最多 6 行,其余折叠为「另有 N 个模型」 |
| 位置与动效 | portal + fixed,优先置于绘图区上方,空间不足翻到下方,水平以柱子为中心并夹在视口内;入场 `animate-fade-in`,在柱子之间以 `--motion-fast` 平滑跟随,首次定位与减少动态效果时不过渡 |
-浮层 `aria-hidden`,读屏仍读柱子按钮的日期与总量标签。色块与占比条沿用 `usage-token-bar` 的 2px 数据图元角,不是新的形状登记。
+浮层 `aria-hidden`:柱子按钮的 `aria-label` 给出日期与总量,逐模型明细经 `aria-describedby` 指向同组件内的 `sr-only` 文本,承接原生 title 的信息。色块与占比条沿用 `usage-token-bar` 的 2px 数据图元角,不是新的形状登记。
## 页面排版(2026-09-08 所有者反馈)