fix(editor): keep Cmd+H for macOS hide instead of replace

This commit is contained in:
Abeautifulsnow authored and GitHub committed 2026-09-15 12:09:04 +08:00
1 parent a9cf5822fa
commit 3f74195835
21 files changed
+558 -100

No files matched your search

@@ -0,0 +1,161 @@
// @vitest-environment happy-dom
// pi-lens-ignore: typescript:2307
import { afterEach, describe, expect, it, vi } from "vitest";
// CodeMirror reads `navigator.platform` once at module load to decide how `Mod`
// expands (`browser.mac ? "mac" : …` in @codemirror/view), so the harness stubs
// the navigator and re-imports the packages — same approach as
// queryEditorExecutionShortcutWebKit.spec.ts.
const macNavigator = {
maxTouchPoints: 0,
platform: "MacIntel",
userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 Version/18.6 Safari/605.1.15",
vendor: "Apple Computer, Inc.",
};
const winNavigator = {
maxTouchPoints: 0,
platform: "Win32",
userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/140.0.0.0 Safari/537.36",
vendor: "",
};
interface MacKeyInit {
key: string;
code: string;
keyCode: number;
altKey?: boolean;
metaKey?: boolean;
ctrlKey?: boolean;
shiftKey?: boolean;
}
function keyEvent(init: MacKeyInit): KeyboardEvent {
const event = new KeyboardEvent("keydown", { bubbles: true, cancelable: true, ...init });
// KeyboardEvent's init dict ignores keyCode, but CodeMirror's macOS
// Option-letter fallback matches on `base[keyCode]` (⌥F arrives as key "ƒ"),
// which a real webview always provides.
Object.defineProperty(event, "keyCode", { get: () => init.keyCode });
return event;
}
async function createMacSearchHarness() {
vi.stubGlobal("navigator", macNavigator);
vi.resetModules();
const [{ EditorState }, { EditorView, keymap }, { createQueryEditorSearchKeymap }] = await Promise.all([import("@codemirror/state"), import("@codemirror/view"), import("../../editor/queryEditorSearchKeymap")]);
const openSearch = vi.fn(() => true);
const openReplace = vi.fn(() => true);
const root = document.createElement("div");
document.body.append(root);
const view = new EditorView({
parent: root,
state: EditorState.create({
// No explicit platform: this exercises the production wiring, where the
// editor surface passes options only and the keymap reads the navigator.
extensions: [keymap.of(createQueryEditorSearchKeymap({ openSearch, openReplace, isReadOnly: () => false }))],
}),
});
return { view, openSearch, openReplace };
}
// Composed regression for the *configurable* replace path (#9068 config layer):
// normalizeShortcutSettings must repair a synced `replace: "Mod+H"` to the mac
// default `Mod+R`, so the replace bindings+handler built from the normalized
// value can no longer consume ⌘H — while the same normalized "Mod+H" on Win32
// (where it means Ctrl+H) must still consume Ctrl+H. Runs under a stubbed mac
// navigator, so CodeMirror resolves Mod→Meta for the keymap and matchesShortcut
// resolves Mod→Meta for the DOM handler, exactly like production on a mac.
async function createReservedKeyHarness(platform: "mac" | "win") {
vi.stubGlobal("navigator", platform === "mac" ? macNavigator : winNavigator);
vi.resetModules();
const [{ EditorState, Prec }, { EditorView, keymap }, { normalizeShortcutSettings }, { createQueryEditorReplaceShortcutBindings, createQueryEditorReplaceShortcutHandler }] = await Promise.all([
import("@codemirror/state"),
import("@codemirror/view"),
import("../../editor/shortcutRegistry"),
import("../../editor/queryEditorSearchKeymap"),
]);
const shortcut = normalizeShortcutSettings({ replace: "Mod+H" }, platform === "mac" ? "MacIntel" : "Win32").replace;
const openReplace = vi.fn(() => true);
const view = new EditorView({
parent: document.createElement("div"),
state: EditorState.create({
extensions: [
Prec.high(
EditorView.domEventHandlers({
keydown: createQueryEditorReplaceShortcutHandler({ shortcut, openReplace, isReadOnly: () => false }),
}),
),
Prec.high(keymap.of(createQueryEditorReplaceShortcutBindings(shortcut, openReplace))),
],
}),
});
return { shortcut, view, openReplace };
}
afterEach(() => {
document.body.innerHTML = "";
vi.unstubAllGlobals();
});
describe("QueryEditor search keymap on macOS", () => {
it("opens replace with the platform shortcut (⌥⌘F) instead of ⌘H", async () => {
const { view, openReplace } = await createMacSearchHarness();
const event = keyEvent({ key: "ƒ", code: "KeyF", keyCode: 70, altKey: true, metaKey: true });
view.contentDOM.dispatchEvent(event);
expect(openReplace).toHaveBeenCalledOnce();
expect(event.defaultPrevented).toBe(true);
view.destroy();
});
it("leaves ⌘H to the system so macOS can hide the app", async () => {
const { view, openReplace } = await createMacSearchHarness();
const event = keyEvent({ key: "h", code: "KeyH", keyCode: 72, metaKey: true });
view.contentDOM.dispatchEvent(event);
expect(openReplace).not.toHaveBeenCalled();
// Not consumed: the key event must reach AppKit's Hide menu equivalent.
expect(event.defaultPrevented).toBe(false);
view.destroy();
});
it("still opens search with ⌘F", async () => {
const { view, openSearch } = await createMacSearchHarness();
const event = keyEvent({ key: "f", code: "KeyF", keyCode: 70, metaKey: true });
view.contentDOM.dispatchEvent(event);
expect(openSearch).toHaveBeenCalledOnce();
expect(event.defaultPrevented).toBe(true);
view.destroy();
});
it("a configurable replace that was synced as ⌘H is repaired and no longer consumes ⌘H", async () => {
const { shortcut, view, openReplace } = await createReservedKeyHarness("mac");
// normalizeShortcutSettings({ replace: "Mod+H" }, "MacIntel") must repair to Mod+R.
expect(shortcut).toBe("Mod+R");
const event = keyEvent({ key: "h", code: "KeyH", keyCode: 72, metaKey: true });
view.contentDOM.dispatchEvent(event);
expect(openReplace).not.toHaveBeenCalled();
expect(event.defaultPrevented).toBe(false);
view.destroy();
});
it("on Win32 the same synced Mod+H (Ctrl+H) stays a live replace shortcut", async () => {
const { shortcut, view, openReplace } = await createReservedKeyHarness("win");
expect(shortcut).toBe("Mod+H");
const event = keyEvent({ key: "h", code: "KeyH", keyCode: 72, ctrlKey: true });
view.contentDOM.dispatchEvent(event);
expect(openReplace).toHaveBeenCalledOnce();
expect(event.defaultPrevented).toBe(true);
view.destroy();
});
});
@@ -1,4 +1,5 @@
import { matchesShortcut } from "@/lib/editor/keyboardShortcuts";
import { isMacShortcutPlatform } from "@/lib/editor/shortcutDisplay";
import { shortcutToCodeMirrorKey } from "@/lib/editor/shortcutRegistry";
// pi-lens-ignore: typescript:2307
import type { KeyBinding } from "@codemirror/view";
@@ -9,7 +10,22 @@ interface QueryEditorSearchKeymapOptions {
isReadOnly: () => boolean;
}
export function createQueryEditorSearchKeymap(options: QueryEditorSearchKeymapOptions): KeyBinding[] {
/**
* CodeMirror key for the built-in replace fallback (the non-configurable alias
* that keeps replace reachable when the user clears the `replace` shortcut).
*
* macOS must not bind `Mod-h`: ⌘H is the system-wide Hide-App shortcut, and
* because this binding calls `preventDefault()` the event never reaches AppKit,
* so the menu's Hide key equivalent cannot fire and DBX becomes impossible to
* hide with the standard shortcut (#9068). macOS therefore uses the platform's
* conventional find-and-replace key — ⌥⌘F, as in VS Code and TextEdit —
* while Windows/Linux keep Ctrl+H.
*/
export function replaceFallbackKey(platform = globalThis.navigator?.platform || ""): string {
return isMacShortcutPlatform(platform) ? "Alt-Mod-f" : "Mod-h";
}
export function createQueryEditorSearchKeymap(options: QueryEditorSearchKeymapOptions, platform = globalThis.navigator?.platform || ""): KeyBinding[] {
return [
{
key: "Mod-f",
@@ -17,7 +33,7 @@ export function createQueryEditorSearchKeymap(options: QueryEditorSearchKeymapOp
run: options.openSearch,
},
{
key: "Mod-h",
key: replaceFallbackKey(platform),
preventDefault: true,
// Consume the shortcut in previews without exposing mutation controls.
run: () => options.isReadOnly() || options.openReplace(),
@@ -1,4 +1,4 @@
import { isMacShortcutPlatform, parseShortcutStrokes, shortcutDisplayParts } from "@/lib/editor/shortcutDisplay";
import { isMacShortcutPlatform, parseShortcutParts, parseShortcutStrokes, shortcutDisplayParts } from "@/lib/editor/shortcutDisplay";
export type ShortcutActionId =
| "executeSql"
@@ -644,6 +644,7 @@ export function needsTabNavigationHistoryShortcutMigration(settings?: Partial<Sh
}
export function normalizeShortcutSettings(settings?: Partial<ShortcutSettings>, platform = globalThis.navigator?.platform || ""): ShortcutSettings {
const reservedKeyRepairedActionIds = new Set<ShortcutActionId>();
const normalized = Object.fromEntries(
SHORTCUT_DEFINITIONS.map((definition) => {
const configuredValue = settings?.[definition.id];
@@ -661,6 +662,14 @@ export function normalizeShortcutSettings(settings?: Partial<ShortcutSettings>,
configured = definition.defaultShortcut;
}
const normalized = definition.inputKind === "modifier-only" ? normalizeModifierOnlyShortcut(configured, definition.defaultShortcut) : configured;
// 用户显式配置(或云同步带入)的 macOS 保留键会重新劫持 ⌘H(#9068 的
// 配置层复现:CodeMirror 对匹配的绑定 preventDefault,AppKit 菜单的 Hide
// key equivalent 永远收不到),因此解析后如果命中保留键,则回退到该动作
// 的平台默认值——而非清空——与上面云同步跨平台默认值的修复行为保持一致。
if (isReservedShortcut(normalized, platform)) {
reservedKeyRepairedActionIds.add(definition.id);
return [definition.id, platformDefault];
}
return [definition.id, normalized];
}),
) as ShortcutSettings;
@@ -679,6 +688,21 @@ export function normalizeShortcutSettings(settings?: Partial<ShortcutSettings>,
if (occupiedByExistingAction) normalized[actionId] = "";
}
// 修复后的平台默认值如果被同一作用域内另一动作的显式配置占用,则清空而非套用:
// 默认值不是用户的选择,强加回去会让用户刻意绑定的动作变得不可达——运行时的
// keymap 先匹配先执行(QueryEditor.vue 中 find 绑定注册在 formatSql 之前,
// 二者默认都是 Mod+F 时 formatSql 永远轮不到)。用户显式配置必须赢,
// 占用者只统计显式配置(hasExplicitShortcut),默认值之间的“占位”不算。
// 与上面 TAB_NAVIGATION_HISTORY_ACTIONS 的占用判定同构;清空后由上方
// copyCurrentRow/editTableStructure 迁移与 tab 导航占位判定依赖的值均不受影响。
for (const actionId of reservedKeyRepairedActionIds) {
const definition = SHORTCUT_DEFINITIONS.find((item) => item.id === actionId);
if (!definition) continue;
const repairedValue = normalized[actionId];
const occupiedByExistingAction = SHORTCUT_DEFINITIONS.some((item) => item.id !== actionId && item.scope === definition.scope && hasExplicitShortcut(settings, item.id) && shortcutsUseSameKeys(normalized[item.id], repairedValue, platform));
if (occupiedByExistingAction) normalized[actionId] = "";
}
return normalized;
}
@@ -705,6 +729,47 @@ export function formatShortcut(shortcut: string, platform = globalThis.navigator
.join("+");
}
// macOS 上由系统/应用菜单占用的快捷键(DBX 自己的应用子菜单,
// src-tauri/src/lib.rs):
// Mod+H Hide,⌘H
// Alt+Mod+H Hide Others,⌥⌘H
// Web 视图中任何绑定只要 preventDefault 都会挡住 AppKit 的菜单 key
// equivalent —— 这正是 #9068 里 ⌘H 打开替换面板、应用无法隐藏的机制,
// 所以配置层必须把这些键从所有可绑定动作中排除出去。
// 刻意不包含 ⌘M(Minimize)与 ⌘Q(Quit):它们不在报告的问题范围内,
// 加入会静默解绑已有用户配置;将来如需覆盖,扩展该集合即可。
export const MACOS_RESERVED_SHORTCUTS: ReadonlySet<string> = new Set(["Mod+H", "Alt+Mod+H"]);
// 本模块内的规范比较形式:在 macOS 分支上(isReservedShortcut 已短路掉非 mac
// 平台),Mod 永远是 ⌘,因此把 Meta/Cmd 别名写成 Mod 后再解析为 Meta,与
// Ctrl/Control 区分开——不能复用 canonicalShortcutKey,它按 "Win32" 把 Mod
// 展开为 Ctrl,会把 ⌃H 误判成 ⌘H。修饰键排序、键名小写,使
// Alt+Mod+H 与 Mod+Alt+H 归一为同一个串。
function macCanonicalShortcut(shortcut: string): string {
// 保留键判定必须先 trim:配置层消费时会对值做 trim(createQueryEditorReplaceShortcutHandler
// 等),手工编辑设置 JSON 时误留的前后空白不能成为绕过保留键判定的途径。
const parts = parseShortcutParts(shortcut.replace(/\b(?:Meta|Cmd)\b/g, "Mod").trim());
if (parts.length === 0) return "";
const key = parts[parts.length - 1] ?? "";
const modifiers = parts
.slice(0, -1)
.map((modifier) => (modifier === "Mod" ? "Meta" : modifier === "Control" ? "Ctrl" : modifier))
.sort()
.join("+");
return `${modifiers}${modifiers ? "+" : ""}${key}`.toLowerCase();
}
export function isReservedShortcut(shortcut: string, platform = globalThis.navigator?.platform || ""): boolean {
// 仅 macOS 保留:Mod+H 在 Windows/Linux 上展开为 Ctrl+H(正常的替换键),
// 必须原样保留。该短路条件必须先于下面的比较执行。
if (!shortcut || !isMacShortcutPlatform(platform)) return false;
const canonical = macCanonicalShortcut(shortcut);
for (const reserved of MACOS_RESERVED_SHORTCUTS) {
if (macCanonicalShortcut(reserved) === canonical) return true;
}
return false;
}
export function findShortcutConflict(actionId: ShortcutActionId, shortcut: string, shortcuts: ShortcutSettings, platform = globalThis.navigator?.platform || ""): ShortcutActionId | null {
if (!shortcut) return null;
const definition = SHORTCUT_DEFINITIONS.find((item) => item.id === actionId);