Files
Netcatty/components/settings/tabs/SettingsShortcutsTab.tsx
T
陈大猫andClaude Opus 4.7 ea5320d94a Fix #954: unify Tooltip styling + replace native selects (#961)
* Fix #954: unify Tooltip styling + replace native selects

Replace native HTML title= tooltips and native <select> dropdowns
with the existing Radix-based Tooltip / Select components so they
share the app's rounded styling, theme tokens and i18n pipeline.
Adds a global TooltipProvider in AppWithProviders so every
descendant Tooltip works without a per-file Provider wrapper.

Scope (driven by the issue #954 examples and "全部都处理" follow-up):

- TerminalLayer toolbar: Add Terminal / Split View / SFTP / Scripts
  / Theme / AI Chat / Move panel / Close panel.
- TopTabs middle bar: quick switcher, more tabs, AI assistant, theme
  toggle, settings; window-control buttons (min/max/close), tray
  close and hotkey reset/disable have their native title dropped per
  the user's explicit opt-out ("可以不用Tooltip,直接全局禁用
  原生title 属性").
- AI panels: AIChatSidePanel session history / new chat / delete,
  ConversationExport, AgentSelector, ChatInput attach / expand /
  permission, ModelSelector, ProviderCard, ai-elements/tool-call.
- SFTP: SftpSidePanel header, SftpBreadcrumb, SftpFileRow,
  SftpPaneToolbar, SftpTabBar, SftpTransferQueue.
- Settings: SettingsPage close, SettingsAppearanceTab theme/accent
  swatches, SettingsFileAssociationsTab edit/remove, SettingsSystemTab
  crash-log paths and global hotkey reset.
- Host vault: HostDetailsPanel (clear / suggestions / show-password /
  key path / browse key), GroupDetailsPanel, KnownHostsManager,
  ConnectionLogsManager, KeychainManager, SyncStatusButton,
  CloudSyncSettings, LogView, QuickSwitcher, ScriptsSidePanel,
  Terminal status bar copy-host + broadcast/focus, ZmodemProgressIndicator.
- Terminal subcomponents: HostKeywordHighlightPopover, TerminalComposeBar,
  TerminalConnectionDialog, TerminalSearchBar.
- Editor: TextEditorPane (subtitle, search, wrap, promote-to-tab).
- TrayPanel session rows and port-forwarding rows.

Native <select> migrated to custom Select component:
- SerialConnectModal (data bits, stop bits, parity, flow control)
- SerialHostDetailsPanel (same four fields)
- HostDetailsPanel backspace behavior
- GroupDetailsPanel backspace behavior
- SettingsTerminalTab local shell picker
- terminal/ThemeSidePanel font weight

Hardcoded English strings extracted to i18n. New keys for both
en and zh-CN: terminal.layer.*, topTabs.*, ai.chat.* (sessionHistory,
attach, collapse, expand, enableAgent), zmodem.*, settings.shortcuts.
resetToDefault. Inline help text on SnippetsManager package-name input
removed because the same hint is already shown in a visible <p> below
the input.

Existing per-file <TooltipProvider> wrappers (SnippetsManager,
ScriptsSidePanel, SelectHostPanel, RuleCard, HostDetailsPanel proxy
section) are left in place — they nest harmlessly under the global
provider and stay self-sufficient for component tests.

Tests:
- tsc clean for changed files (pre-existing repo-wide errors
  unrelated to this PR).
- All 802 tests pass (3 skipped pre-existing).
- HostDetailsPanel.proxyProfile.test and TextEditorPane.test
  updated to wrap with TooltipProvider, matching the runtime
  context now needed by the migrated components.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* Fix #954: wrap Settings + Tray windows with TooltipProvider

Settings and the tray panel mount as separate Electron windows with
their own React root in index.tsx, so they do not inherit the global
TooltipProvider added under AppWithProviders. After the unified
Tooltip migration, any settings tab that used a Tooltip (Appearance,
Application, FileAssociations, System, Shortcuts, Terminal, AI
ProviderCard, AI ModelSelector) — and TrayPanel — threw
"Tooltip must be used within TooltipProvider" and rendered nothing.

Wrap both branches with TooltipProvider at the same level as
ToastProvider in index.tsx.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-12 20:14:24 +08:00

258 lines
11 KiB
TypeScript

import React, { useCallback, useEffect, useMemo, useState } from "react";
import { Ban, RotateCcw } from "lucide-react";
import type { HotkeyScheme, KeyBinding } from "../../../domain/models";
import { keyEventToString } from "../../../domain/models";
import { useI18n } from "../../../application/i18n/I18nProvider";
import { cn } from "../../../lib/utils";
import { Button } from "../../ui/button";
import { SectionHeader, Select, SettingsTabContent, SettingRow } from "../settings-ui";
export default function SettingsShortcutsTab(props: {
hotkeyScheme: HotkeyScheme;
setHotkeyScheme: (scheme: HotkeyScheme) => void;
keyBindings: KeyBinding[];
updateKeyBinding?: (bindingId: string, scheme: "mac" | "pc", newKey: string) => void;
resetKeyBinding?: (bindingId: string, scheme?: "mac" | "pc") => void;
resetAllKeyBindings: () => void;
setIsHotkeyRecording?: (isRecording: boolean) => void;
}) {
const {
hotkeyScheme,
setHotkeyScheme,
keyBindings,
updateKeyBinding,
resetKeyBinding,
resetAllKeyBindings,
setIsHotkeyRecording,
} = props;
const { t } = useI18n();
const [recordingBindingId, setRecordingBindingId] = useState<string | null>(null);
const [recordingScheme, setRecordingScheme] = useState<"mac" | "pc" | null>(null);
const cancelRecording = useCallback(() => {
setRecordingBindingId(null);
setRecordingScheme(null);
}, []);
const getSpecialSuffix = useCallback(
(bindingId: string): string | null => {
const binding = keyBindings.find((b) => b.id === bindingId);
if (!binding) return null;
const currentKey = hotkeyScheme === "mac" ? binding.mac : binding.pc;
if (currentKey.includes("[1...9]")) return "[1...9]";
if (currentKey.includes("arrows")) return "arrows";
return null;
},
[keyBindings, hotkeyScheme],
);
useEffect(() => {
if (!recordingBindingId || !recordingScheme) return;
const specialSuffix = getSpecialSuffix(recordingBindingId);
const handleKeyDown = (e: KeyboardEvent) => {
e.preventDefault();
e.stopPropagation();
if (e.key === "Escape") {
cancelRecording();
return;
}
if (specialSuffix) {
if (["Meta", "Control", "Alt", "Shift"].includes(e.key)) return;
const parts: string[] = [];
if (recordingScheme === "mac") {
if (e.metaKey) parts.push("⌘");
if (e.ctrlKey) parts.push("⌃");
if (e.altKey) parts.push("⌥");
if (e.shiftKey) parts.push("Shift");
} else {
if (e.ctrlKey) parts.push("Ctrl");
if (e.altKey) parts.push("Alt");
if (e.shiftKey) parts.push("Shift");
if (e.metaKey) parts.push("Win");
}
const modifierString = parts.length > 0 ? `${parts.join(" + ")} + ` : "";
const fullKeyString = modifierString + specialSuffix;
updateKeyBinding?.(recordingBindingId, recordingScheme, fullKeyString);
cancelRecording();
return;
}
if (["Meta", "Control", "Alt", "Shift"].includes(e.key)) return;
const keyString = keyEventToString(e, recordingScheme === "mac");
updateKeyBinding?.(recordingBindingId, recordingScheme, keyString);
cancelRecording();
};
const handleClick = () => {
cancelRecording();
};
const timer = setTimeout(() => {
window.addEventListener("click", handleClick, true);
}, 100);
window.addEventListener("keydown", handleKeyDown, true);
return () => {
clearTimeout(timer);
window.removeEventListener("keydown", handleKeyDown, true);
window.removeEventListener("click", handleClick, true);
};
}, [recordingBindingId, recordingScheme, updateKeyBinding, cancelRecording, getSpecialSuffix]);
useEffect(() => {
const isRecording = Boolean(recordingBindingId && recordingScheme);
setIsHotkeyRecording?.(isRecording);
return () => {
setIsHotkeyRecording?.(false);
};
}, [recordingBindingId, recordingScheme, setIsHotkeyRecording]);
const categories = useMemo(() => ["tabs", "terminal", "navigation", "app", "sftp"] as const, []);
return (
<SettingsTabContent value="shortcuts">
<SectionHeader title={t("settings.shortcuts.section.scheme")} />
<div className="space-y-0 divide-y divide-border rounded-lg border bg-card px-4">
<SettingRow
label={t("settings.shortcuts.scheme.label")}
description={t("settings.shortcuts.scheme.desc")}
>
<Select
value={hotkeyScheme}
options={[
{ value: "disabled", label: t("settings.shortcuts.scheme.disabled") },
{ value: "mac", label: t("settings.shortcuts.scheme.mac") },
{ value: "pc", label: t("settings.shortcuts.scheme.pc") },
]}
onChange={(v) => setHotkeyScheme(v as HotkeyScheme)}
className="w-32"
/>
</SettingRow>
</div>
{hotkeyScheme !== "disabled" && (
<>
<div className="flex items-center justify-between">
<SectionHeader title={t("settings.shortcuts.section.custom")} className="mb-0" />
<Button
variant="ghost"
size="sm"
onClick={resetAllKeyBindings}
className="text-xs gap-1"
>
<RotateCcw size={12} /> {t("settings.shortcuts.resetAll")}
</Button>
</div>
{categories.map((category) => {
const categoryBindings = keyBindings.filter((kb) => kb.category === category);
if (categoryBindings.length === 0) return null;
return (
<div key={category}>
<h4 className="text-xs font-medium text-muted-foreground uppercase tracking-wide mb-2">
{t(`settings.shortcuts.category.${category}`)}
</h4>
<div className="space-y-0 divide-y divide-border rounded-lg border bg-card">
{categoryBindings.map((binding) => {
const currentKey = hotkeyScheme === "mac" ? binding.mac : binding.pc;
const specialSuffix = currentKey.includes("[1...9]")
? "[1...9]"
: currentKey.includes("arrows")
? "arrows"
: null;
const isSpecialBinding = !!specialSuffix;
const modifierPrefix = isSpecialBinding
? currentKey.replace(specialSuffix!, "").trim().replace(/\+\s*$/, "").trim()
: null;
const isRecordingThis = recordingBindingId === binding.id;
const scheme = hotkeyScheme === "mac" ? "mac" : "pc";
return (
<div key={binding.id} className="flex items-center justify-between px-4 py-2">
<span className="text-sm">{t(`settings.shortcuts.binding.${binding.id}`) !== `settings.shortcuts.binding.${binding.id}` ? t(`settings.shortcuts.binding.${binding.id}`) : binding.label}</span>
<div className="flex items-center gap-2">
{isSpecialBinding ? (
<div className="flex items-center gap-1">
<button
onClick={(e) => {
e.stopPropagation();
setRecordingBindingId(binding.id);
setRecordingScheme(scheme);
}}
className={cn(
"px-2 py-1 text-xs font-mono rounded border transition-colors min-w-[60px] text-center",
isRecordingThis
? "border-primary bg-primary/10 animate-pulse"
: "border-border hover:border-primary/50",
)}
>
{isRecordingThis
? t("settings.shortcuts.recording")
: modifierPrefix || t("settings.shortcuts.none")}
</button>
<span className="text-xs text-muted-foreground">+</span>
<span className="px-2 py-1 text-xs font-mono rounded border border-border bg-muted/30 text-muted-foreground">
{specialSuffix}
</span>
</div>
) : (
<button
onClick={(e) => {
e.stopPropagation();
setRecordingBindingId(binding.id);
setRecordingScheme(scheme);
}}
className={cn(
"px-2 py-1 text-xs font-mono rounded border transition-colors min-w-[80px] text-center",
isRecordingThis
? "border-primary bg-primary/10 animate-pulse"
: "border-border hover:border-primary/50",
)}
>
{isRecordingThis
? t("settings.shortcuts.recording")
: currentKey === "Disabled"
? t("settings.shortcuts.scheme.disabled")
: currentKey || t("settings.shortcuts.scheme.disabled")}
</button>
)}
{!isSpecialBinding && (
<button
onClick={() => updateKeyBinding?.(binding.id, scheme, "Disabled")}
className="p-1 hover:bg-muted rounded"
aria-label={t("settings.shortcuts.setDisabled")}
>
<Ban size={12} />
</button>
)}
<button
onClick={() => resetKeyBinding?.(binding.id, scheme)}
className="p-1 hover:bg-muted rounded"
aria-label={t("settings.shortcuts.resetToDefault")}
>
<RotateCcw size={12} />
</button>
</div>
</div>
);
})}
</div>
</div>
);
})}
</>
)}
</SettingsTabContent>
);
}