fix(ui): prevent titlebar menu switch flicker and overlay focus-tooltip races

- Suppress deferred Radix `onCloseAutoFocus` focus restoration in `TitleMenus` when switching between sibling menus (or opening a dialog) so the closing menu's `setTimeout(0)` refocus no longer triggers `onFocusOutside` on the newly opened menu
- Guard `TitleMenus` `onOpenChange` by active menu ownership, block sibling-trigger `onPointerDownOutside` races, add 300ms hover-click guard (primary button without Ctrl), RTL-aware `ArrowLeft`/`ArrowRight` navigation, `--wails-draggable: no-drag` on `.titlebar-menus`, and instant lateral menu-switch transitions
- Keep `Tip` permanently controlled in `controls.tsx` to eliminate uncontrolled/controlled `useControllableState` warnings and stuck ghost tooltips when toggled via `disabled`
- Guard both VMPage `⋯` menus (toolbar + SSH) and Sidebar `ContextMenu` against pointer-close tooltip pops and dialog focus fighting, and reset menu/dialog state on VM switch
- Improve `Modal` `onOpenAutoFocus` to skip disabled/hidden/unchecked-radio inputs with `preventScroll`, fall back to the dialog container instead of the `✕` close tooltip, and exclude `.dialog`/`.menu` containers from `:focus-visible` ring overrides in `app.css`
This commit is contained in:
Dnyo666 committed 2026-11-30 17:14:23 +08:00
1 parent 655f015038
commit 371eb11629
6 files changed
+266 -42

No files matched your search

+20 -2
View File
@@ -46,6 +46,7 @@ export const Sidebar: React.FC<Props> = ({
}) => {
const tr = (k: I18nKey) => t(locale, k)
const listRef = useRef<HTMLDivElement>(null)
const ctxOpenedByPointerRef = useRef(false)
const ids = [...vms.map((v) => v.name), INSTALLERS_ID, PLUGINS_ID, HOST_ID, SETTINGS_ID, ABOUT_ID]
// Listbox keyboard model: ↑/↓/Home/End move selection and focus together.
@@ -129,9 +130,26 @@ export const Sidebar: React.FC<Props> = ({
if (!onVMContextAction) return trigger
return (
<Ctx.Root key={vm.name}>
<Ctx.Trigger asChild>{trigger}</Ctx.Trigger>
<Ctx.Trigger
asChild
onContextMenu={(e) => {
ctxOpenedByPointerRef.current = e.button === 2 && (e.clientX !== 0 || e.clientY !== 0)
}}
>
{trigger}
</Ctx.Trigger>
<Ctx.Portal>
<Ctx.Content className="menu">
<Ctx.Content
className="menu"
onCloseAutoFocus={(e) => {
if (
ctxOpenedByPointerRef.current
|| document.querySelector('[role="dialog"], [role="alertdialog"]')
) {
e.preventDefault()
}
}}
>
{stopped && (
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'start')}>
<Play size={14} /> {tr('start')}
+115 -8
View File
@@ -1,6 +1,6 @@
import * as Menu from '@radix-ui/react-dropdown-menu'
import { Check, PanelLeft } from 'lucide-react'
import React, { useState } from 'react'
import React, { useRef, useState } from 'react'
import { I18nKey, t } from '../i18n'
import { Locale } from '../types'
import { Tip } from '../ui/controls'
@@ -10,6 +10,11 @@ import { VMAction } from './VMPage'
export const REPO_URL = 'https://github.com/Nwflower/Reims-Go'
const MENU_IDS = ['vm', 'view', 'help'] as const
type MenuId = (typeof MENU_IDS)[number]
const HOVER_CLICK_GUARD_MS = 300
interface Props {
locale: Locale
sidebarOpen: boolean
@@ -42,7 +47,17 @@ export const TitleMenus: React.FC<Props> = ({
vm, onNewVM, onVMAction, onVMSettings, onVMDelete, onNavigate, onOpenURL, appVersion,
}) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const [open, setOpen] = useState<string | null>(null)
const [menuState, setMenuState] = useState<{ id: MenuId | null; switched: boolean }>({ id: null, switched: false })
const openRef = useRef<MenuId | null>(null)
const navRef = useRef<HTMLElement>(null)
const hoverOpenedRef = useRef<{ id: MenuId; at: number } | null>(null)
const openedByPointerRef = useRef(false)
const pointerClosedRef = useRef(false)
const setActiveMenu = (next: MenuId | null, switched: boolean) => {
openRef.current = next
setMenuState({ id: next, switched })
}
const running = vm?.state === 'running'
const stopped = vm?.state === 'stopped'
@@ -64,19 +79,111 @@ export const TitleMenus: React.FC<Props> = ({
)
// `indented`: the menu has check marks, so every row shares their indent.
const menu = (id: string, label: string, content: React.ReactNode, indented = false) => (
<Menu.Root modal={false} open={open === id} onOpenChange={(o) => setOpen(o ? id : null)}>
const menu = (id: MenuId, label: string, content: React.ReactNode, indented = false) => (
<Menu.Root
modal={false}
open={menuState.id === id}
onOpenChange={(o) => {
if (o) {
hoverOpenedRef.current = null
pointerClosedRef.current = false
setActiveMenu(id, openRef.current !== null && openRef.current !== id)
} else if (openRef.current === id) {
hoverOpenedRef.current = null
setActiveMenu(null, false)
}
}}
>
<Menu.Trigger asChild>
<button
type="button"
className="titlebar-menu"
onPointerEnter={() => { if (open && open !== id) setOpen(id) }}
onPointerEnter={(e) => {
if (e.pointerType !== 'mouse') return
if (openRef.current && openRef.current !== id) {
openedByPointerRef.current = true
pointerClosedRef.current = false
hoverOpenedRef.current = { id, at: performance.now() }
setActiveMenu(id, true)
}
}}
onPointerDown={(e) => {
if (e.button === 0 && !e.ctrlKey) {
openedByPointerRef.current = true
}
const h = hoverOpenedRef.current
if (
e.pointerType === 'mouse'
&& e.button === 0
&& !e.ctrlKey
&& openRef.current === id
&& h
&& h.id === id
&& performance.now() - h.at < HOVER_CLICK_GUARD_MS
) {
hoverOpenedRef.current = null
e.preventDefault()
}
}}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ' || e.key === 'ArrowDown') {
openedByPointerRef.current = false
}
}}
>
{label}
</button>
</Menu.Trigger>
<Menu.Portal>
<Menu.Content className={`menu titlebar-menu-content${indented ? ' menu-indented' : ''}`} align="start" sideOffset={4} collisionPadding={8}>
<Menu.Content
className={`menu titlebar-menu-content${indented ? ' menu-indented' : ''}`}
data-menubar-switch={menuState.id === id && menuState.switched ? 'true' : undefined}
align="start"
sideOffset={4}
collisionPadding={8}
onPointerDownCapture={(e) => {
if (!(e.target as HTMLElement | null)?.closest('[data-disabled]')) {
pointerClosedRef.current = true
}
}}
onKeyDownCapture={() => {
pointerClosedRef.current = false
}}
onPointerDownOutside={(e) => {
const target = e.target as Node | null
if (target && navRef.current?.contains(target)) {
e.preventDefault()
return
}
pointerClosedRef.current = true
}}
onCloseAutoFocus={(e) => {
// Prevent Radix's deferred setTimeout(0) focus restoration from pulling focus
// back to the old trigger when switching to a sibling menu (which triggers
// onFocusOutside on the newly opened menu), when closed via pointer, or when
// an item opens a modal dialog.
if (
openRef.current !== null
|| openedByPointerRef.current
|| pointerClosedRef.current
|| document.querySelector('[role="dialog"], [role="alertdialog"]')
) {
e.preventDefault()
}
}}
onKeyDown={(e) => {
if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return
e.preventDefault()
const isRTL = navRef.current ? getComputedStyle(navRef.current).direction === 'rtl' : false
const delta = (e.key === 'ArrowRight') !== isRTL ? 1 : -1
const idx = MENU_IDS.indexOf(id)
const nextId = MENU_IDS[(idx + delta + MENU_IDS.length) % MENU_IDS.length]
hoverOpenedRef.current = null
openedByPointerRef.current = false
pointerClosedRef.current = false
setActiveMenu(nextId, true)
}}
>
{content}
</Menu.Content>
</Menu.Portal>
@@ -85,7 +192,7 @@ export const TitleMenus: React.FC<Props> = ({
return (
<div className="titlebar-left" onDoubleClick={(e) => e.stopPropagation()}>
<Tip label={tr(sidebarOpen ? 'hideSidebar' : 'showSidebar')} shortcut="Ctrl+B">
<Tip label={tr(sidebarOpen ? 'hideSidebar' : 'showSidebar')} shortcut="Ctrl+B" disabled={menuState.id !== null}>
<button
type="button"
className="titlebar-icon"
@@ -96,7 +203,7 @@ export const TitleMenus: React.FC<Props> = ({
<PanelLeft size={16} aria-hidden="true" />
</button>
</Tip>
<nav className="titlebar-menus" aria-label={tr('menuBar')}>
<nav ref={navRef} className="titlebar-menus" aria-label={tr('menuBar')}>
{menu('vm', tr('menuVM'), (
<>
{item(tr('newVMEllipsis'), onNewVM, { shortcut: 'Ctrl+N' })}
+93 -13
View File
@@ -160,12 +160,17 @@ export const VMPage: React.FC<Props> = ({
const shownName = displayName || name
const [editingName, setEditingName] = useState(false)
const [nameDraft, setNameDraft] = useState('')
useEffect(() => { setEditingName(false) }, [name])
const startRename = () => { setNameDraft(shownName); setEditingName(true) }
// From the More menu: keep the menu from pulling focus back to its button,
// which would blur (and so save) the name field the moment it appears.
// which would blur (and so save) the name field or pop the trigger's tooltip.
const renameFromMenu = useRef(false)
const nameInputRef = useRef<HTMLInputElement>(null)
const [moreMenuOpen, setMoreMenuOpen] = useState(false)
const moreOpenedByPointer = useRef(false)
const morePointerClosed = useRef(false)
const [sshMenuOpen, setSshMenuOpen] = useState(false)
const sshOpenedByPointer = useRef(false)
const sshPointerClosed = useRef(false)
const saveName = async () => {
setEditingName(false)
let next = nameDraft.trim()
@@ -183,6 +188,12 @@ export const VMPage: React.FC<Props> = ({
const [sshUser, setSshUser] = useState('')
const [sshUserDialog, setSshUserDialog] = useState(false)
const [sshUserDraft, setSshUserDraft] = useState('')
useEffect(() => {
setEditingName(false)
setMoreMenuOpen(false)
setSshMenuOpen(false)
setSshUserDialog(false)
}, [name])
useEffect(() => {
let live = true
api.GetVMSSHUser(name).then((u) => { if (live) setSshUser(u ?? '') }).catch(() => { if (live) setSshUser('') })
@@ -337,10 +348,26 @@ export const VMPage: React.FC<Props> = ({
// "More" menu, grouped by purpose; destructive items last (docs/design-guidelines.md §5.2).
const menu = (
<Menu.Root>
<Tip label={tr('more')}>
<Menu.Root
open={moreMenuOpen}
onOpenChange={(o) => {
if (o) morePointerClosed.current = false
setMoreMenuOpen(o)
}}
>
<Tip label={tr('more')} disabled={moreMenuOpen}>
<Menu.Trigger asChild>
<button type="button" className="icon-btn" aria-label={tr('more')}>
<button
type="button"
className="icon-btn"
aria-label={tr('more')}
onPointerDown={() => { moreOpenedByPointer.current = true }}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ' || e.key === 'ArrowDown') {
moreOpenedByPointer.current = false
}
}}
>
<Ellipsis size={15} />
</button>
</Menu.Trigger>
@@ -351,11 +378,27 @@ export const VMPage: React.FC<Props> = ({
align="end"
sideOffset={4}
collisionPadding={8}
onPointerDownCapture={(e) => {
if (!(e.target as HTMLElement | null)?.closest('[data-disabled]')) {
morePointerClosed.current = true
}
}}
onKeyDownCapture={() => { morePointerClosed.current = false }}
onPointerDownOutside={() => { morePointerClosed.current = true }}
onCloseAutoFocus={(e) => {
if (!renameFromMenu.current) return
renameFromMenu.current = false
e.preventDefault()
nameInputRef.current?.focus()
if (renameFromMenu.current) {
renameFromMenu.current = false
e.preventDefault()
nameInputRef.current?.focus()
return
}
if (
moreOpenedByPointer.current
|| morePointerClosed.current
|| document.querySelector('[role="dialog"], [role="alertdialog"]')
) {
e.preventDefault()
}
}}
>
{running && (
@@ -841,16 +884,53 @@ export const VMPage: React.FC<Props> = ({
<Button icon={<Terminal size={13} aria-hidden="true" />} onClick={openSSHTerminal}>
{tr('sshOpenTerminal')}
</Button>
<Menu.Root>
<Tip label={tr('sshMore')}>
<Menu.Root
open={sshMenuOpen}
onOpenChange={(o) => {
if (o) sshPointerClosed.current = false
setSshMenuOpen(o)
}}
>
<Tip label={tr('sshMore')} disabled={sshMenuOpen}>
<Menu.Trigger asChild>
<button type="button" className="icon-btn sm" aria-label={tr('sshMore')}>
<button
type="button"
className="icon-btn sm"
aria-label={tr('sshMore')}
onPointerDown={() => { sshOpenedByPointer.current = true }}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ' || e.key === 'ArrowDown') {
sshOpenedByPointer.current = false
}
}}
>
<Ellipsis size={14} />
</button>
</Menu.Trigger>
</Tip>
<Menu.Portal>
<Menu.Content className="menu" align="end" sideOffset={4} collisionPadding={8}>
<Menu.Content
className="menu"
align="end"
sideOffset={4}
collisionPadding={8}
onPointerDownCapture={(e) => {
if (!(e.target as HTMLElement | null)?.closest('[data-disabled]')) {
sshPointerClosed.current = true
}
}}
onKeyDownCapture={() => { sshPointerClosed.current = false }}
onPointerDownOutside={() => { sshPointerClosed.current = true }}
onCloseAutoFocus={(e) => {
if (
sshOpenedByPointer.current
|| sshPointerClosed.current
|| document.querySelector('[role="dialog"], [role="alertdialog"]')
) {
e.preventDefault()
}
}}
>
<Menu.Item className="menu-item" onSelect={writeSSHConfig}>
<FileCode2 size={14} /> {tr('sshWriteConfig')}
</Menu.Item>
+6 -5
View File
@@ -34,7 +34,7 @@ button { font: inherit; color: inherit; touch-action: manipulation; }
h1, h2, h3, p { margin: 0; }
:focus { outline: none; }
:focus-visible { box-shadow: var(--focus-ring); border-radius: var(--r-md); }
:focus-visible:not(.dialog):not(.menu) { box-shadow: var(--focus-ring); border-radius: var(--r-md); }
::-webkit-scrollbar { width: 8px; height: 8px; }
::-webkit-scrollbar-track { background: transparent; }
@@ -80,8 +80,8 @@ h1, h2, h3, p { margin: 0; }
}
.titlebar-right { display: flex; align-items: center; height: 100%; gap: var(--sp-1); --wails-draggable: no-drag; }
/* Left of the title bar: sidebar toggle + a small menu bar. Only the controls
opt out of window dragging; the gaps between them still move the window. */
/* Left of the title bar: sidebar toggle + a small menu bar. Controls and the
menu bar group opt out of window dragging so sweeping across menus stays smooth. */
.titlebar-left { display: flex; align-items: center; gap: 2px; height: 100%; margin-left: calc(var(--sp-2) * -1); }
.titlebar-icon, .titlebar-menu {
--wails-draggable: no-drag;
@@ -94,7 +94,7 @@ h1, h2, h3, p { margin: 0; }
.titlebar-icon:hover, .titlebar-menu:hover { background: var(--surface-hover); color: var(--text); }
.titlebar-menu[data-state="open"] { background: var(--surface-active); color: var(--text); }
.titlebar-icon:active, .titlebar-menu:active { transform: scale(0.96); }
.titlebar-menus { display: flex; align-items: center; gap: 2px; }
.titlebar-menus { display: flex; align-items: center; gap: 2px; --wails-draggable: no-drag; }
.titlebar-menu-content { min-width: 220px; }
/* Menu rows with a trailing shortcut, check marks and group labels. */
@@ -1312,6 +1312,7 @@ button.status-issue + .status-metric { margin-left: 6px; }
.overlay { animation: fade-in var(--dur) var(--ease-out) both; }
.dialog { animation: pop-in var(--dur-modal) var(--ease-out) both; }
.menu { transform-origin: var(--radix-dropdown-menu-content-transform-origin, top); animation: menu-in 160ms var(--ease-out) both; }
.menu[data-menubar-switch="true"] { animation: none; }
.tooltip { animation: tip-in 125ms var(--ease-out) both; }
.tooltip[data-state="instant-open"] { animation-duration: 0ms; }
.pane-anim { display: flex; flex-direction: column; gap: 20px; animation: rise-in var(--dur) var(--ease-out) both; }
@@ -1818,6 +1819,6 @@ button.status-issue + .status-metric { margin-left: 6px; }
cannot override them even with !important (§5.1, B7/M15). */
@layer host-guard {
.rg-p-titlebar { --wails-draggable: drag !important; }
:focus-visible { box-shadow: var(--focus-ring) !important; }
:focus-visible:not(.dialog):not(.menu) { box-shadow: var(--focus-ring) !important; }
.icon-btn, .win-btn { min-width: 28px !important; min-height: 28px !important; }
}
+18 -11
View File
@@ -10,21 +10,28 @@ interface TipProps {
label: string
shortcut?: string
side?: 'top' | 'bottom' | 'left' | 'right'
disabled?: boolean
children: React.ReactElement
}
/** Tooltip around a single focusable child. */
export const Tip: React.FC<TipProps> = ({ label, shortcut, side = 'bottom', children }) => (
<RTooltip.Root>
<RTooltip.Trigger asChild>{children}</RTooltip.Trigger>
<RTooltip.Portal>
<RTooltip.Content className="tooltip" side={side} sideOffset={6} collisionPadding={8}>
{label}
{shortcut && <kbd>{shortcut}</kbd>}
</RTooltip.Content>
</RTooltip.Portal>
</RTooltip.Root>
)
export const Tip: React.FC<TipProps> = ({ label, shortcut, side = 'bottom', disabled, children }) => {
const [open, setOpen] = React.useState(false)
React.useEffect(() => {
if (disabled) setOpen(false)
}, [disabled])
return (
<RTooltip.Root open={disabled ? false : open} onOpenChange={(next) => setOpen(disabled ? false : next)}>
<RTooltip.Trigger asChild>{children}</RTooltip.Trigger>
<RTooltip.Portal>
<RTooltip.Content className="tooltip" side={side} sideOffset={6} collisionPadding={8}>
{label}
{shortcut && <kbd>{shortcut}</kbd>}
</RTooltip.Content>
</RTooltip.Portal>
</RTooltip.Root>
)
}
type ButtonVariant = 'secondary' | 'primary' | 'danger' | 'ghost'
+14 -3
View File
@@ -23,10 +23,21 @@ export const Modal: React.FC<Props> = ({ title, subtitle, closeLabel, dismissabl
<RDialog.Content
className={className ? `dialog ${className}` : 'dialog'}
onInteractOutside={(e) => e.preventDefault()}
// Focus the first form field rather than ✕, so the close tooltip doesn't pop on open.
// Focus the first enabled form field, or the dialog container itself when there is
// none, so the top-right ✕ close button's tooltip never pops on open.
onOpenAutoFocus={(e) => {
const first = (e.currentTarget as HTMLElement | null)?.querySelector<HTMLElement>('input, select, textarea')
if (first) { e.preventDefault(); first.focus() }
const root = e.currentTarget as HTMLElement | null
if (!root) return
e.preventDefault()
const first = root.querySelector<HTMLElement>(
'input:not(:disabled):not([type="hidden"]):not([type="radio"]:not(:checked)), select:not(:disabled), textarea:not(:disabled)',
)
if (first) {
first.focus({ preventScroll: true })
}
if (!root.contains(document.activeElement)) {
root.focus({ preventScroll: true })
}
}}
>
<div className="dialog-head">