🐛 fix(vscode): 悬停提示不用原生 title,webview 统一用自绘提示框,代码阅读的种类图标停上去能看到种类名

VS Code 1.139 带的 Electron 43 在 macOS 上只在鼠标压着带 title 的元素自身边缘时才弹原生提示,
停在它里面的图标、文字上不弹(electron/electron#49843,Electron 38 起)。种类图标 20px 的框
几乎被 16px 的图形占满,所以基本看不到种类名;块右上角按钮同样受影响。页面上核对过:图标中心点
命中的是图标里的线条,没有盖在上面的东西。

- components/ui/tooltip.tsx 改成整页只挂一次的 TooltipHost:元素只写 data-tooltip,事件统一交给它;
  样子照 VS Code 悬停框(editorHoverWidget 那组变量、widget-shadow 阴影),停 500ms 才弹、弹着时换元素
  立刻换,移开 / 按下 / 按键 / 滚动收起;键盘聚焦立刻弹,提示不是元素自己的名字时挂 aria-describedby
- 代码阅读里所有 title(种类图标、块按钮、筛选栏、问答区、中文名的「原名」)改成 data-tooltip;
  SelectMenu 的 title 属性改名 tooltip;看板工单详情原来包一层的 Tooltip 也改成 data-tooltip
- 何时弹 / 收的规则抽成纯函数加测试;更新代码阅读 spec
This commit is contained in:
cruldra committed 2026-09-27 21:21:13 +08:00
1 parent 15790ce7c8
commit ec34ace7cf
17 files changed
+399 -187

No files matched your search

@@ -42,14 +42,14 @@ describe('块下面的问答区', () => {
expect(html.match(/data-history=""/g)).toHaveLength(2)
expect(text(html)).toContain('为什么普通用户不能看别人的资料?3 天前')
expect(text(html)).toContain('UserRole 还有哪些角色?昨天')
expect(html.match(/title="已理解,删除" aria-label="已理解,删除"/g)).toHaveLength(2)
expect(html.match(/data-tooltip="已理解,删除" aria-label="已理解,删除"/g)).toHaveLength(2)
expect(text(html)).toContain('这是权限控制:不是管理员、又不是查自己时抛 Forbidden。')
expect(html).toContain('<hr class="cr-qa-divider"/>')
expect(html).toContain('data-current=""')
expect(html).toContain('data-streaming=""><p><code>Forbidden</code> 定义在 <strong>core</strong></p>')
expect(text(html)).toContain('读取 exceptions.py')
expect(html).toContain('placeholder="继续问… Enter 发送,Esc 收起"')
expect(html).toContain('title="停止" aria-label="停止"')
expect(html).toContain('data-tooltip="停止" aria-label="停止"')
expect(html).not.toContain('aria-label="发送"')
})
@@ -80,7 +80,7 @@ describe('块下面的问答区', () => {
const trigger = row.slice(row.lastIndexOf('<button', select), row.indexOf('</button>', select))
expect(trigger).toContain('aria-haspopup="listbox"')
expect(trigger).toContain('aria-expanded="false"')
expect(trigger).toContain('title="用哪个 Claude Code 配置(profile)回答,下一个问题起用它"')
expect(trigger).toContain('data-tooltip="用哪个 Claude Code 配置(profile)回答,下一个问题起用它"')
expect(text(trigger)).toBe('sonnet')
const none = render({ open: true, profiles: { options: [], selected: '' } })
expect(text(none.slice(none.indexOf('cr-qa-profile')))).toContain('默认')
+10 -10
View File
@@ -19,11 +19,11 @@ function Thumbs({ urls, pending, onOpen, onRemove }: { urls: string[], pending?:
{urls.map((url, index) => (
// 同一张图可能贴两次、地址一样;缩略图没有自己的状态,按位置认就行
<span key={index} className="cr-qa-thumb">
<button type="button" className="cr-qa-thumb-open" title="看大图" aria-label={`看第 ${index + 1} 张图片的大图`} onClick={() => onOpen(url)}>
<button type="button" className="cr-qa-thumb-open" data-tooltip="看大图" aria-label={`看第 ${index + 1} 张图片的大图`} onClick={() => onOpen(url)}>
<img src={url} alt="" />
</button>
{onRemove && (
<button type="button" className="cr-qa-thumb-remove" title="去掉这张图片" aria-label={`去掉第 ${index + 1} 张图片`} onClick={() => onRemove(index)}>
<button type="button" className="cr-qa-thumb-remove" data-tooltip="去掉这张图片" aria-label={`去掉第 ${index + 1} 张图片`} onClick={() => onRemove(index)}>
<X size={10} strokeWidth={2.4} aria-hidden />
</button>
)}
@@ -55,7 +55,7 @@ function ImagePreview({ url, onClose }: { url: string, onClose: () => void }): R
return createPortal(
<div className="cr-qa-lightbox" role="dialog" aria-modal="true" aria-label="图片大图" onClick={onClose} onKeyDown={onKeyDown}>
<img src={url} alt="" />
<button ref={close} type="button" className="cr-qa-lightbox-close" title="关闭(Esc)" aria-label="关闭大图">
<button ref={close} type="button" className="cr-qa-lightbox-close" data-tooltip="关闭(Esc)" aria-label="关闭大图">
<X size={16} strokeWidth={1.8} aria-hidden />
</button>
</div>,
@@ -71,16 +71,16 @@ function HistoryItem({ entry, now, onDelete, onOpenImage }: { entry: QaEntryView
<div className="cr-qa-entry" data-history="">
<div className="cr-qa-head">
<Sparkles size={12} strokeWidth={1.8} className="cr-qa-icon" aria-hidden />
<button type="button" className="cr-qa-question" aria-expanded={expanded} title={expanded ? '收起回答' : '展开整段回答'} onClick={toggle}>
<button type="button" className="cr-qa-question" aria-expanded={expanded} data-tooltip={expanded ? '收起回答' : '展开整段回答'} onClick={toggle}>
{entry.question}
</button>
<span className="cr-qa-when">
<time dateTime={entry.createdAt} title={new Date(entry.createdAt).toLocaleString()}>
<time dateTime={entry.createdAt} data-tooltip={new Date(entry.createdAt).toLocaleString()}>
{relativeTime(entry.createdAt, now)}
</time>
{entry.profile && <span title="用这个 Claude Code 配置(profile)答的">{` · ${entry.profile}`}</span>}
{entry.profile && <span data-tooltip="用这个 Claude Code 配置(profile)答的">{` · ${entry.profile}`}</span>}
</span>
<button type="button" className="cr-tool cr-qa-delete" title="已理解,删除" aria-label="已理解,删除" onClick={onDelete}>
<button type="button" className="cr-tool cr-qa-delete" data-tooltip="已理解,删除" aria-label="已理解,删除" onClick={onDelete}>
<Trash2 size={13} strokeWidth={1.8} aria-hidden />
</button>
</div>
@@ -218,17 +218,17 @@ function AskInput({ running, first, profiles, onSelectProfile, onAsk, onStop, on
options={profiles.options.map(option => ({ value: option.id, label: option.label }))}
onChange={onSelectProfile}
placeholder="默认"
title="用哪个 Claude Code 配置(profile)回答,下一个问题起用它"
tooltip="用哪个 Claude Code 配置(profile)回答,下一个问题起用它"
className="cr-qa-profile"
/>
{running
? (
<button type="button" className="cr-tool" title="停止" aria-label="停止" onClick={() => onStop(running.askId)}>
<button type="button" className="cr-tool" data-tooltip="停止" aria-label="停止" onClick={() => onStop(running.askId)}>
<CircleStop size={14} strokeWidth={1.8} aria-hidden />
</button>
)
: (
<button type="button" className="cr-tool" title="发送(Enter)" aria-label="发送" disabled={value.trim() === ''} onClick={send}>
<button type="button" className="cr-tool" data-tooltip="发送(Enter)" aria-label="发送" disabled={value.trim() === ''} onClick={send}>
<SendHorizontal size={14} strokeWidth={1.8} aria-hidden />
</button>
)}
@@ -15,7 +15,8 @@ describe('块右上角的图标按钮', () => {
expect(html).toMatch(/^<div[^>]* role="group" aria-label="块操作"/)
expect(visibleText(html)).toBe('')
expect(html.match(/<button/g)).toHaveLength(1)
expect(html).toContain(`title="${label}" aria-label="${label}"`)
expect(html).toContain(`data-tooltip="${label}" aria-label="${label}"`)
expect(html).not.toContain(' title=')
expect(html).toMatch(/<button[^>]*><svg/)
expect(html.includes('data-active')).toBe(editing)
})
@@ -25,9 +26,9 @@ describe('块右上角的图标按钮', () => {
expect(visibleText(html)).toBe('')
const buttons = [...html.matchAll(/<button[^>]*>/g)].map(match => match[0])
expect(buttons).toHaveLength(2)
expect(buttons[0]).toContain('title="问 AI" aria-label="问 AI"')
expect(buttons[0]).toContain('data-tooltip="问 AI" aria-label="问 AI"')
expect(buttons[0]).toContain(`aria-expanded="${asking}"`)
expect(buttons[0].includes('data-active')).toBe(asking)
expect(buttons[1]).toContain('title="编辑"')
expect(buttons[1]).toContain('data-tooltip="编辑"')
})
})
@@ -2,7 +2,7 @@ import type { ReactElement } from 'react'
import { Eye, Pencil, Sparkles } from 'lucide-react'
/**
* 块右上角的一排图标按钮(普通块、属性表、库规则的卡片共用):只放图标,名字写在悬停提示(title)和读屏用的 aria-label 里。
* 块右上角的一排图标按钮(普通块、属性表、库规则的卡片共用):只放图标,名字写在悬停提示(data-tooltip)和读屏用的 aria-label 里。
* 「问 AI」:点开 / 收起块下面的问答区,展开时带按下的底色。
* 「编辑 / 预览」切换:预览时是铅笔「编辑」,编辑时是眼睛「预览」、带按下的底色。
*/
@@ -23,7 +23,7 @@ export function BlockTools({ editing, onToggleEdit, asking, onToggleAsk }: {
type="button"
className="cr-tool flex h-5 w-6 items-center justify-center rounded"
data-active={asking ? '' : undefined}
title="问 AI"
data-tooltip="问 AI"
aria-label="问 AI"
aria-expanded={asking === true}
onClick={onToggleAsk}
@@ -35,7 +35,7 @@ export function BlockTools({ editing, onToggleEdit, asking, onToggleAsk }: {
type="button"
className="cr-tool flex h-5 w-6 items-center justify-center rounded"
data-active={editing ? '' : undefined}
title={label}
data-tooltip={label}
aria-label={label}
onClick={onToggleEdit}
>
@@ -43,7 +43,7 @@ export function FilterBar({ attributes, excluded, view, highlight, onChange, tra
<span className="ml-auto flex h-6 min-w-0 items-center gap-1.5 pl-2 text-xs whitespace-nowrap text-[var(--vscode-descriptionForeground)]">
{highlight && (
<>
<span className="cr-occurrence-name max-w-[240px] min-w-0 truncate" data-occurrence="normal" title={highlight.name}>{highlight.name}</span>
<span className="cr-occurrence-name max-w-[240px] min-w-0 truncate" data-occurrence="normal" data-tooltip={highlight.name}>{highlight.name}</span>
<span aria-hidden>·</span>
{occurrenceCount(highlight)}
<span className="mx-1.5 h-3 border-l border-[var(--vscode-panel-border)]" aria-hidden />
@@ -66,7 +66,7 @@ export function FilterBar({ attributes, excluded, view, highlight, onChange, tra
value={translatorId}
options={translators.map(t => ({ value: t.id, label: t.label }))}
onChange={onSelectTranslator}
title="选择翻译方式"
tooltip="选择翻译方式"
className="w-36 text-left"
/>
</span>
@@ -165,7 +165,7 @@ function FacetMenu({ facet, onToggle, onSetAll }: {
aria-haspopup="listbox"
aria-expanded={open}
aria-controls={open ? listId : undefined}
title={label.text}
data-tooltip={label.text}
onClick={() => open ? setOpen(false) : openAt(0)}
onKeyDown={onButtonKeyDown}
>
@@ -31,7 +31,7 @@ export function SegmentText({ segments }: { segments: Inline[] }): ReactElement
data-occurrence={highlight && segmentOccurrence(piece, highlight.occurrences)}
data-current={highlight && isCurrent(piece, highlight) ? '' : undefined}
data-name={shown?.name}
title={shown && `原名 ${piece.text}`}
data-tooltip={shown && `原名 ${piece.text}`}
>
{shown ? shown.name : piece.text}
{shown?.definition && <span className="cr-original">{piece.text}</span>}
@@ -53,7 +53,7 @@ describe('页面上的中文名', () => {
{ text: 'ADMIN', role: 'variable', offset: 130 },
], [USE, ADMIN])
expect(html.replace(/<[^>]*>/g, '')).toBe('如果 当前用户.role 不等于 UserRole.管理员')
expect(html).toContain('<span class="cr-role-variable" data-offset="90" data-name="当前用户" title="原名 current_user">当前用户</span>')
expect(html).toContain('<span class="cr-role-variable" data-offset="90" data-name="当前用户" data-tooltip="原名 current_user">当前用户</span>')
expect(html).toContain('<span class="cr-role-variable" data-offset="103">role</span>')
expect(html).not.toContain('cr-original')
})
@@ -63,8 +63,8 @@ describe('页面上的中文名', () => {
{ text: 'current_user', role: 'variable', offset: 40 },
{ style: 'iteration', label: '列表', segments: [{ text: 'ADMIN', role: 'variable', offset: 130 }] },
], [CURRENT_USER, ADMIN])
expect(html).toContain('data-offset="40" data-name="当前用户" title="原名 current_user">当前用户<span class="cr-original">current_user</span></span>')
expect(html).toContain('data-offset="130" data-name="管理员" title="原名 ADMIN">管理员</span>')
expect(html).toContain('data-offset="40" data-name="当前用户" data-tooltip="原名 current_user">当前用户<span class="cr-original">current_user</span></span>')
expect(html).toContain('data-offset="130" data-name="管理员" data-tooltip="原名 ADMIN">管理员</span>')
})
it('单击显示成中文名的名字:筛选栏写中文名,当前那一处按点中的下标认', () => {
@@ -41,10 +41,11 @@ describe('块的种类图标', () => {
}
})
it('只画图标不带字,名字在悬停提示和 aria-label 里;20px 的框、16px 的图形', () => {
it('只画图标不带字,名字在悬停提示(data-tooltip,不用原生 title)和 aria-label 里;20px 的框、16px 的图形', () => {
const html = render({ kind: 'function' }, '函数')
expect(visibleText(html)).toBe('')
expect(html).toMatch(/^<span class="cr-kind [^"]*size-5[^"]*" role="img" title="函数" aria-label="函数"><svg/)
expect(html).toMatch(/^<span class="cr-kind [^"]*size-5[^"]*" role="img" data-tooltip="函数" aria-label="函数"><svg/)
expect(html).not.toContain(' title=')
expect(html).toContain('lucide-square-function')
expect(html).toContain('width="16" height="16"')
})
@@ -52,6 +53,6 @@ describe('块的种类图标', () => {
it('库规则的卡片用规则给的图标,名字是规则给的', () => {
const html = render({ kind: 'sqlalchemy.table', badge: { label: '数据表', color: { dark: '#e8a860', light: '#a3590d' }, icon: 'database' } }, '数据表')
expect(html).toContain('lucide-database')
expect(html).toContain('title="数据表" aria-label="数据表"')
expect(html).toContain('data-tooltip="数据表" aria-label="数据表"')
})
})
@@ -82,12 +82,12 @@ export const KIND_ICONS: Record<BlockKind, KindIconName> = {
/**
* 块左边的种类:只画图标,和一行字等高(20px 的框、16px 的图形),颜色是种类色(--kind)。图标是库规则给的(badge.icon),
* 没有就是内置种类的(KIND_ICONS,没带 badge 的块 kind 是 BlockKind);名字(翻译插件给种类起的,库规则的种类是规则给的)
* 写在悬停提示(title)和读屏念的 aria-label 里。
* 写在悬停提示(data-tooltip,见 components/ui/tooltip.tsx)和读屏念的 aria-label 里。
*/
export function KindIcon({ block, name }: { block: Pick<BlockView, 'kind' | 'badge'>, name: string }): ReactElement {
const Icon = KIND_ICON_COMPONENTS[block.badge?.icon ?? KIND_ICONS[block.kind as BlockKind]]
return (
<span className="cr-kind flex size-5 shrink-0 items-center justify-center" role="img" title={name} aria-label={name}>
<span className="cr-kind flex size-5 shrink-0 items-center justify-center" role="img" data-tooltip={name} aria-label={name}>
<Icon size={16} strokeWidth={2.2} aria-hidden />
</span>
)
@@ -1,6 +1,7 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import { ErrorBoundary } from '@/components/ErrorBoundary'
import { TooltipHost } from '@/components/ui/tooltip'
import { App } from './App'
import './codeReader.css'
@@ -8,6 +9,7 @@ ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<ErrorBoundary>
<App />
<TooltipHost />
</ErrorBoundary>
</React.StrictMode>,
)
@@ -9,7 +9,6 @@ import { isSessionMissing } from '../lib/missingSession'
import { toReadOnlySchema } from '../lib/readOnlySchema'
import { COLUMN_LABELS, COLUMN_ORDER } from '../types'
import { PropertyGrid } from './property-grid'
import { Tooltip } from './ui/tooltip'
/** 会话 id 在共享状态里、本机却没有会话文件时,各会话行的统一说明。 */
const MISSING_SESSION_DESC = '本机没有该会话文件(会话在别的机器上创建),无法 resume'
@@ -839,86 +838,81 @@ export function IssueDetailPanel({
</span>
)
: null}
<Tooltip label="在浏览器里打开">
<button
type="button"
onClick={() => onOpenInBrowser(issue.htmlUrl)}
className="inline-flex shrink-0 items-center gap-1 rounded border border-[var(--vscode-panel-border)] px-2 py-1 text-xs hover:bg-black/10 dark:hover:bg-white/10"
>
<ExternalLink className="size-3.5" />
{issue.source === 'youtrack' ? '在 YouTrack 打开' : '在 Gitea 打开'}
</button>
</Tooltip>
<button
type="button"
data-tooltip="在浏览器里打开"
onClick={() => onOpenInBrowser(issue.htmlUrl)}
className="inline-flex shrink-0 items-center gap-1 rounded border border-[var(--vscode-panel-border)] px-2 py-1 text-xs hover:bg-black/10 dark:hover:bg-white/10"
>
<ExternalLink className="size-3.5" />
{issue.source === 'youtrack' ? '在 YouTrack 打开' : '在 Gitea 打开'}
</button>
{/* Close/delete write to gitea by number — hide for youtrack cards to
avoid acting on a gitea issue of the same number. */}
{issue.source !== 'youtrack' && !readOnly && (
<>
{issue.handoffAttachmentId && me !== undefined && (issue.assignees ?? []).includes(me) && (
<Tooltip label={`接管 ${issue.handoffFrom ?? '?'} 的移交`}>
<button
type="button"
disabled={isHandoffRunning(issue.number)}
onClick={() => onAcceptHandoff(issue.number)}
aria-label="接管"
className="inline-flex shrink-0 items-center gap-1 rounded border border-green-500/60 bg-green-500/10 px-2 py-1 text-xs text-green-500 hover:bg-green-500/20 disabled:opacity-50"
>
{isHandoffRunning(issue.number) ? <Loader2 className="size-3.5 animate-spin" /> : <Download className="size-3.5" />}
接管
</button>
</Tooltip>
<button
type="button"
data-tooltip={`接管 ${issue.handoffFrom ?? '?'} 的移交`}
disabled={isHandoffRunning(issue.number)}
onClick={() => onAcceptHandoff(issue.number)}
aria-label="接管"
className="inline-flex shrink-0 items-center gap-1 rounded border border-green-500/60 bg-green-500/10 px-2 py-1 text-xs text-green-500 hover:bg-green-500/20 disabled:opacity-50"
>
{isHandoffRunning(issue.number) ? <Loader2 className="size-3.5 animate-spin" /> : <Download className="size-3.5" />}
接管
</button>
)}
{!issue.handoffAttachmentId && issue.column !== 'done' && ((issue.assignees ?? []).length === 0 || (me !== undefined && (issue.assignees ?? []).includes(me))) && (
<Tooltip label="移交给同事">
<button
type="button"
disabled={isHandoffRunning(issue.number)}
onClick={() => onStartHandoff(issue.number)}
aria-label="移交"
className="inline-flex shrink-0 items-center justify-center rounded border border-[var(--vscode-panel-border)] p-1 text-xs text-[var(--vscode-foreground)] hover:border-blue-500/60 hover:bg-blue-500/10 hover:text-blue-500 disabled:opacity-50"
>
{isHandoffRunning(issue.number) ? <Loader2 className="size-3.5 animate-spin" /> : <ArrowRightLeft className="size-3.5" />}
</button>
</Tooltip>
<button
type="button"
data-tooltip="移交给同事"
disabled={isHandoffRunning(issue.number)}
onClick={() => onStartHandoff(issue.number)}
aria-label="移交"
className="inline-flex shrink-0 items-center justify-center rounded border border-[var(--vscode-panel-border)] p-1 text-xs text-[var(--vscode-foreground)] hover:border-blue-500/60 hover:bg-blue-500/10 hover:text-blue-500 disabled:opacity-50"
>
{isHandoffRunning(issue.number) ? <Loader2 className="size-3.5 animate-spin" /> : <ArrowRightLeft className="size-3.5" />}
</button>
)}
{issue.handoffAttachmentId && !(me !== undefined && (issue.assignees ?? []).includes(me)) && (
<Tooltip label={`${issue.handoffFrom ?? '?'} 已移交,等 ${(issue.assignees ?? []).join(', ') || '?'} 接管`}>
<span className="inline-flex shrink-0 items-center rounded border border-[var(--vscode-panel-border)] px-1.5 py-0.5 text-[10px] opacity-70">
待接管
</span>
</Tooltip>
<span
className="inline-flex shrink-0 items-center rounded border border-[var(--vscode-panel-border)] px-1.5 py-0.5 text-[10px] opacity-70"
data-tooltip={`${issue.handoffFrom ?? '?'} 已移交,等 ${(issue.assignees ?? []).join(', ') || '?'} 接管`}
>
待接管
</span>
)}
{(issue.column === 'in-progress' || issue.column === 'review') && (
<Tooltip label="重置为待办(停会话、删 worktree 和未合并 PR)">
<button
type="button"
onClick={() => onResetToTodo(issue.number)}
aria-label="重置为待办"
className="inline-flex shrink-0 items-center justify-center rounded border border-[var(--vscode-panel-border)] p-1 text-xs text-[var(--vscode-foreground)] hover:border-yellow-500/60 hover:bg-yellow-500/10 hover:text-yellow-500"
>
<RotateCcw className="size-3.5" />
</button>
</Tooltip>
)}
<Tooltip label="关闭工单(Gitea 里可重开)">
<button
type="button"
onClick={() => onCloseIssue(issue.number)}
aria-label="关闭工单"
data-tooltip="重置为待办(停会话、删 worktree 和未合并 PR)"
onClick={() => onResetToTodo(issue.number)}
aria-label="重置为待办"
className="inline-flex shrink-0 items-center justify-center rounded border border-[var(--vscode-panel-border)] p-1 text-xs text-[var(--vscode-foreground)] hover:border-yellow-500/60 hover:bg-yellow-500/10 hover:text-yellow-500"
>
<CircleSlash className="size-3.5" />
<RotateCcw className="size-3.5" />
</button>
</Tooltip>
<Tooltip label="删除工单(不可撤销)">
<button
type="button"
onClick={() => issue && onDeleteIssue?.(issue.number)}
aria-label="删除工单"
className="inline-flex shrink-0 items-center justify-center rounded border border-[var(--vscode-panel-border)] p-1 text-xs text-[var(--vscode-foreground)] hover:border-red-500/60 hover:bg-red-500/10 hover:text-red-500"
>
<Trash2 className="size-3.5" />
</button>
</Tooltip>
)}
<button
type="button"
data-tooltip="关闭工单(Gitea 里可重开)"
onClick={() => onCloseIssue(issue.number)}
aria-label="关闭工单"
className="inline-flex shrink-0 items-center justify-center rounded border border-[var(--vscode-panel-border)] p-1 text-xs text-[var(--vscode-foreground)] hover:border-yellow-500/60 hover:bg-yellow-500/10 hover:text-yellow-500"
>
<CircleSlash className="size-3.5" />
</button>
<button
type="button"
data-tooltip="删除工单(不可撤销)"
onClick={() => issue && onDeleteIssue?.(issue.number)}
aria-label="删除工单"
className="inline-flex shrink-0 items-center justify-center rounded border border-[var(--vscode-panel-border)] p-1 text-xs text-[var(--vscode-foreground)] hover:border-red-500/60 hover:bg-red-500/10 hover:text-red-500"
>
<Trash2 className="size-3.5" />
</button>
</>
)}
</div>
@@ -424,7 +424,7 @@ function SessionRow({ session, profiles, onRename, onResume, onDelete, onCloseTa
<SelectMenu
value={pickedProfile}
onChange={setUserPicked}
title="换 profile 后点行打开;已打开的终端下次才生效"
tooltip="换 profile 后点行打开;已打开的终端下次才生效"
variant="ghost"
options={[
...(storedMissing
@@ -15,7 +15,7 @@ export interface SelectMenuProps {
options: SelectMenuOption[]
onChange: (value: string) => void
placeholder?: string
title?: string
tooltip?: string
disabled?: boolean
variant?: 'input' | 'ghost'
className?: string
@@ -60,7 +60,7 @@ export function SelectMenu({
options,
onChange,
placeholder = '请选择',
title,
tooltip,
disabled = false,
variant = 'input',
className,
@@ -265,7 +265,7 @@ export function SelectMenu({
ref={triggerRef}
type="button"
disabled={disabled}
title={title}
data-tooltip={tooltip}
aria-haspopup="listbox"
aria-expanded={open}
onClick={onTriggerClick}
@@ -334,8 +334,8 @@ export function SelectMenu({
<Check className="size-3.5" />
</span>
<span className="flex min-w-0 flex-col">
<span className="truncate" title={opt.label}>{opt.label}</span>
{opt.hint && <span className="truncate text-[10px] opacity-70" title={opt.hint}>{opt.hint}</span>}
<span className="truncate" data-tooltip={opt.label}>{opt.label}</span>
{opt.hint && <span className="truncate text-[10px] opacity-70" data-tooltip={opt.hint}>{opt.hint}</span>}
</span>
</button>
))}
@@ -0,0 +1,123 @@
import type { Tip, TooltipController } from './tooltip'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createTooltipController, placeTooltip, SHOW_DELAY_MS } from './tooltip'
interface Anchor { text: string }
const icon: Anchor = { text: '函数' }
const route: Anchor = { text: '接口' }
const blank: Anchor = { text: '' }
function setup(): { controller: TooltipController<Anchor>, changes: Array<Tip<Anchor> | null> } {
const changes: Array<Tip<Anchor> | null> = []
const controller = createTooltipController<Anchor>(anchor => anchor.text, tip => changes.push(tip))
return { controller, changes }
}
describe('悬停提示什么时候出、什么时候收', () => {
beforeEach(() => {
vi.useFakeTimers()
})
afterEach(() => {
vi.useRealTimers()
})
it('鼠标停在带提示的元素上,过一小会儿才弹', () => {
const { controller, changes } = setup()
controller.hover(icon)
vi.advanceTimersByTime(SHOW_DELAY_MS - 1)
expect(changes).toEqual([])
vi.advanceTimersByTime(1)
expect(changes).toEqual([{ anchor: icon, text: '函数' }])
})
it('在同一个元素里移动(划过图标的线条和空白)不重新计时', () => {
const { controller, changes } = setup()
controller.hover(icon)
vi.advanceTimersByTime(SHOW_DELAY_MS - 100)
controller.hover(icon)
vi.advanceTimersByTime(100)
expect(changes).toEqual([{ anchor: icon, text: '函数' }])
})
it('没等到就移开,不弹', () => {
const { controller, changes } = setup()
controller.hover(icon)
vi.advanceTimersByTime(SHOW_DELAY_MS / 2)
controller.hover(null)
vi.advanceTimersByTime(SHOW_DELAY_MS)
expect(changes).toEqual([])
})
it('弹着时移到另一个带提示的元素上立刻换,移到没有提示的地方就收', () => {
const { controller, changes } = setup()
controller.hover(icon)
vi.advanceTimersByTime(SHOW_DELAY_MS)
controller.hover(route)
expect(changes.at(-1)).toEqual({ anchor: route, text: '接口' })
controller.hover(null)
expect(changes.at(-1)).toBeNull()
controller.hover(icon)
expect(changes.at(-1)).toBeNull()
vi.advanceTimersByTime(SHOW_DELAY_MS)
expect(changes.at(-1)).toEqual({ anchor: icon, text: '函数' })
})
it('按下鼠标、按键、滚动就收;鼠标不离开这个元素不再弹,移出去再回来照常弹', () => {
const { controller, changes } = setup()
controller.hover(icon)
vi.advanceTimersByTime(SHOW_DELAY_MS)
controller.dismiss()
expect(changes.at(-1)).toBeNull()
controller.hover(icon)
vi.advanceTimersByTime(SHOW_DELAY_MS)
expect(changes.at(-1)).toBeNull()
controller.hover(null)
controller.hover(icon)
vi.advanceTimersByTime(SHOW_DELAY_MS)
expect(changes.at(-1)).toEqual({ anchor: icon, text: '函数' })
})
it('等着弹的时候按下鼠标,这次不弹了', () => {
const { controller, changes } = setup()
controller.hover(icon)
controller.dismiss()
vi.advanceTimersByTime(SHOW_DELAY_MS)
expect(changes).toEqual([])
})
it('键盘聚焦立刻弹,焦点离开就收;别的元素失焦不影响', () => {
const { controller, changes } = setup()
controller.focus(route)
expect(changes).toEqual([{ anchor: route, text: '接口' }])
controller.blur(icon)
expect(changes).toHaveLength(1)
controller.blur(route)
expect(changes.at(-1)).toBeNull()
})
it('提示文字是空的不弹', () => {
const { controller, changes } = setup()
controller.hover(blank)
vi.advanceTimersByTime(SHOW_DELAY_MS)
controller.focus(blank)
expect(changes).toEqual([])
})
})
describe('提示框放在哪', () => {
const size = { width: 40, height: 18 }
it('上方放得下就在上方,水平对着元素中间', () => {
expect(placeTooltip({ top: 100, bottom: 120, left: 50, width: 20 }, size, 900)).toEqual({ top: 76, left: 40 })
})
it('上方放不下翻到下方', () => {
expect(placeTooltip({ top: 10, bottom: 30, left: 50, width: 20 }, size, 900)).toEqual({ top: 36, left: 40 })
})
it('左右钳在视口里,贴边留 8px', () => {
expect(placeTooltip({ top: 100, bottom: 120, left: 0, width: 20 }, size, 900).left).toBe(8)
expect(placeTooltip({ top: 100, bottom: 120, left: 890, width: 10 }, size, 900).left).toBe(852)
})
})
+167 -80
View File
@@ -1,95 +1,182 @@
import type { ReactElement, ReactNode } from 'react'
import { useCallback, useEffect, useRef, useState } from 'react'
import type { ReactElement } from 'react'
import { useEffect, useId, useLayoutEffect, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
import { cn } from '@/lib/utils'
/** 悬停多久才弹,避免扫过一排按钮时闪一串气泡。 */
const SHOW_DELAY_MS = 300
/** 气泡与触发元素之间的间距。 */
/** 鼠标停多久才弹,扫过一排按钮、一行代码时不闪一串提示。 */
export const SHOW_DELAY_MS = 500
/** 提示框与元素之间的间距。 */
const GAP_PX = 6
/** 贴边留白,气泡不顶到 webview 边缘。 */
/** 贴边留白,提示框不顶到 webview 边缘。 */
const GUTTER_PX = 8
interface TooltipProps {
/** 气泡文案;为空则不弹。 */
label: ReactNode
children: ReactNode
className?: string
/** 正在显示的提示:挂在哪个元素上、写什么。 */
export interface Tip<A> {
anchor: A
text: string
}
export interface TooltipController<A> {
/** 鼠标移到这个带提示的元素上;null 是移到了没有提示的地方或移出页面 */
hover: (anchor: A | null) => void
/** 键盘把焦点移到这个带提示的元素上 */
focus: (anchor: A) => void
/** 焦点离开这个元素 */
blur: (anchor: A) => void
/** 按下鼠标、按键、滚动:收起,鼠标不离开眼下这个元素就不再弹 */
dismiss: () => void
dispose: () => void
}
/**
* 悬停提示气泡。
*
* 原生 `title` 在 webview 里延迟长、样式是系统的,暗色主题下很突兀,
* 这里自己渲染:portal 到 body,避开 overflow 容器裁剪;位置优先在上方,
* 上方放不下就翻到下方,左右钳在视口内。
* 悬停提示什么时候出、换成谁、什么时候收(不碰 DOM,TooltipHost 把页面事件喂进来):
* 鼠标停在带提示的元素上 SHOW_DELAY_MS 后出,已经出着时移到另一个上立刻换;键盘聚焦立刻出;移开、失焦、dismiss 就收。
*/
export function Tooltip({ label, children, className }: TooltipProps): ReactElement {
const [visible, setVisible] = useState(false)
const wrapRef = useRef<HTMLSpanElement | null>(null)
export function createTooltipController<A>(textOf: (anchor: A) => string, onChange: (tip: Tip<A> | null) => void): TooltipController<A> {
let hovered: A | null = null
let shown: Tip<A> | null = null
let timer: ReturnType<typeof setTimeout> | undefined
const set = (tip: Tip<A> | null): void => {
clearTimeout(timer)
timer = undefined
if (tip?.anchor === shown?.anchor && tip?.text === shown?.text)
return
shown = tip
onChange(tip)
}
const show = (anchor: A): void => {
const text = textOf(anchor)
set(text ? { anchor, text } : null)
}
const schedule = (anchor: A): void => {
clearTimeout(timer)
timer = setTimeout(show, SHOW_DELAY_MS, anchor)
}
return {
hover(anchor) {
if (anchor === hovered)
return
hovered = anchor
if (anchor === null)
set(null)
else if (shown)
show(anchor)
else
schedule(anchor)
},
focus: show,
blur(anchor) {
if (shown?.anchor === anchor)
set(null)
},
dismiss: () => set(null),
dispose: () => clearTimeout(timer),
}
}
/** 提示框放在哪:优先在元素上方,上方放不下翻到下方;水平对着元素中间,钳在视口内。 */
export function placeTooltip(
anchor: Pick<DOMRect, 'top' | 'bottom' | 'left' | 'width'>,
size: Pick<DOMRect, 'width' | 'height'>,
viewportWidth: number,
): { top: number, left: number } {
const above = anchor.top - size.height - GAP_PX
const centered = anchor.left + anchor.width / 2 - size.width / 2
return {
top: above >= GUTTER_PX ? above : anchor.bottom + GAP_PX,
left: Math.max(GUTTER_PX, Math.min(centered, viewportWidth - GUTTER_PX - size.width)),
}
}
/** 页面上带提示的元素:提示文字写在 data-tooltip 上。 */
function anchorOf(target: EventTarget | null): Element | null {
return target instanceof Element ? target.closest('[data-tooltip]:not([data-tooltip=""])') : null
}
/** 提示是不是已经是元素的名字(aria-label 或它的字):是就不再挂成描述,读屏不念两遍。 */
function isOwnName(anchor: Element, text: string): boolean {
return anchor.getAttribute('aria-label') === text || anchor.textContent?.trim() === text
}
/**
* 整个 webview 唯一的悬停提示:页面根上挂一次,元素只写 data-tooltip="提示"(名字照旧写在 aria-label 里)。
* 不用原生 title:macOS 上 VS Code 的 Electron 只在鼠标压着元素自身边缘时才弹原生提示,停在里面的图标、文字上不弹
* (electron/electron#49843),样式也是系统的。这里画成 VS Code 悬停框的样子(--vscode-editorHoverWidget-*),
* portal 到 body 不被 overflow 容器裁掉;键盘聚焦(:focus-visible)立刻弹,并用 aria-describedby 挂到元素上。
*/
export function TooltipHost(): ReactElement | null {
const id = useId()
const [tip, setTip] = useState<Tip<Element> | null>(null)
const bubbleRef = useRef<HTMLDivElement | null>(null)
const timerRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)
const hide = useCallback((): void => {
clearTimeout(timerRef.current)
setVisible(false)
}, [])
const show = useCallback((): void => {
if (!label)
return
clearTimeout(timerRef.current)
timerRef.current = setTimeout(() => {
if (wrapRef.current)
setVisible(true)
}, SHOW_DELAY_MS)
}, [label])
useEffect(() => () => clearTimeout(timerRef.current), [])
// 气泡先在左上角量一次尺寸再落位。必须量在 left:0:fixed 元素的可用宽度是
// 「视口宽 - left」,贴右边量会被挤窄、行数变多,按那个高度定位就会浮高一截。
useEffect(() => {
if (!visible)
return
const bubble = bubbleRef.current
const rect = wrapRef.current?.getBoundingClientRect()
if (!bubble || !rect)
return
const { width, height } = bubble.getBoundingClientRect()
const above = rect.top - height - GAP_PX
const top = above >= GUTTER_PX ? above : rect.bottom + GAP_PX
let left = rect.left + rect.width / 2 - width / 2
left = Math.max(GUTTER_PX, Math.min(left, window.innerWidth - GUTTER_PX - width))
bubble.style.top = `${top}px`
bubble.style.left = `${left}px`
bubble.style.visibility = 'visible'
}, [visible])
let described: Element | null = null
const controller = createTooltipController<Element>(
anchor => anchor.getAttribute('data-tooltip') ?? '',
(next) => {
described?.removeAttribute('aria-describedby')
described = next && !isOwnName(next.anchor, next.text) ? next.anchor : null
described?.setAttribute('aria-describedby', id)
setTip(next)
},
)
const onPointerOver = (event: PointerEvent): void => controller.hover(anchorOf(event.target))
const onPointerOut = (event: PointerEvent): void => {
if (event.relatedTarget === null)
controller.hover(null)
}
const onFocusIn = (event: FocusEvent): void => {
const anchor = anchorOf(event.target)
if (anchor && event.target instanceof Element && event.target.matches(':focus-visible'))
controller.focus(anchor)
}
const onFocusOut = (event: FocusEvent): void => {
const anchor = anchorOf(event.target)
if (anchor)
controller.blur(anchor)
}
const dismiss = (): void => controller.dismiss()
document.addEventListener('pointerover', onPointerOver)
document.addEventListener('pointerout', onPointerOut)
document.addEventListener('focusin', onFocusIn)
document.addEventListener('focusout', onFocusOut)
document.addEventListener('pointerdown', dismiss, true)
document.addEventListener('keydown', dismiss, true)
window.addEventListener('scroll', dismiss, true)
return () => {
document.removeEventListener('pointerover', onPointerOver)
document.removeEventListener('pointerout', onPointerOut)
document.removeEventListener('focusin', onFocusIn)
document.removeEventListener('focusout', onFocusOut)
document.removeEventListener('pointerdown', dismiss, true)
document.removeEventListener('keydown', dismiss, true)
window.removeEventListener('scroll', dismiss, true)
controller.dispose()
described?.removeAttribute('aria-describedby')
}
}, [id])
return (
<>
<span
ref={wrapRef}
className={cn('inline-flex shrink-0', className)}
onMouseEnter={show}
onMouseLeave={hide}
onMouseDown={hide}
onFocus={show}
onBlur={hide}
>
{children}
</span>
{visible && label && createPortal(
<div
ref={bubbleRef}
role="tooltip"
style={{ top: 0, left: 0, visibility: 'hidden' }}
className="pointer-events-none fixed z-50 max-w-[22rem] rounded border border-[var(--vscode-editorHoverWidget-border,var(--vscode-panel-border))] bg-[var(--vscode-editorHoverWidget-background,var(--vscode-editorWidget-background))] px-2 py-1 text-[11px] leading-tight break-words text-[var(--vscode-editorHoverWidget-foreground,var(--vscode-foreground))] shadow-md"
>
{label}
</div>,
document.body,
)}
</>
// 先在左上角量尺寸再落位:fixed 元素的可用宽度是「视口宽 - left」,贴右边量会被挤窄、行数变多,按那个高度定位就浮高一截
useLayoutEffect(() => {
const bubble = bubbleRef.current
if (!tip || !bubble)
return
Object.assign(bubble.style, { top: '0px', left: '0px' })
const { top, left } = placeTooltip(tip.anchor.getBoundingClientRect(), bubble.getBoundingClientRect(), window.innerWidth)
Object.assign(bubble.style, { top: `${top}px`, left: `${left}px`, visibility: 'visible' })
}, [tip])
return tip && createPortal(
<div
ref={bubbleRef}
id={id}
role="tooltip"
style={{ top: 0, left: 0, visibility: 'hidden' }}
className="pointer-events-none fixed z-50 max-w-[22rem] rounded border border-[var(--vscode-editorHoverWidget-border)] bg-[var(--vscode-editorHoverWidget-background)] px-2 py-1 text-[11px] leading-tight break-words text-[var(--vscode-editorHoverWidget-foreground)] shadow-[0_2px_8px_var(--vscode-widget-shadow)]"
>
{tip.text}
</div>,
document.body,
)
}
+2
View File
@@ -2,12 +2,14 @@ import React from 'react'
import ReactDOM from 'react-dom/client'
import { App } from './App'
import { ErrorBoundary } from './components/ErrorBoundary'
import { TooltipHost } from './components/ui/tooltip'
import './index.css'
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<ErrorBoundary>
<App />
<TooltipHost />
</ErrorBoundary>
</React.StrictMode>,
)