feat(editor): add goto line input with Ctrl+G and Cmd-Alt-G

This commit is contained in:
zipg authored and GitHub committed 2026-09-21 12:50:40 +08:00
1 parent 556c313880
commit f8ee34f937
24 files changed
+667 -2

No files matched your search

@@ -0,0 +1,57 @@
import { describe, expect, it } from "vitest";
import { currentEditorLineNumber, resolveEditorGotoLine, type EditorGotoLineDocument } from "@/lib/editor/editorGotoLine";
/** 用固定行宽(10 字符/行)的桩对象代替 CodeMirror 的 Text。 */
function makeDoc(lines: number): EditorGotoLineDocument & { lineAt(position: number): { number: number } } {
return {
lines,
line: (number: number) => ({ number, from: (number - 1) * 10 }),
lineAt: (position: number) => ({ number: Math.floor(position / 10) + 1 }),
};
}
describe("resolveEditorGotoLine", () => {
it("解析合法行号并给出该行起始偏移", () => {
const doc = makeDoc(150);
expect(resolveEditorGotoLine("1", doc)).toEqual({ ok: true, line: 1, from: 0 });
expect(resolveEditorGotoLine("42", doc)).toEqual({ ok: true, line: 42, from: 410 });
expect(resolveEditorGotoLine("150", doc)).toEqual({ ok: true, line: 150, from: 1490 });
});
it("忽略首尾空白", () => {
expect(resolveEditorGotoLine(" 7 ", makeDoc(10))).toEqual({ ok: true, line: 7, from: 60 });
});
it("空输入按 empty 处理", () => {
expect(resolveEditorGotoLine("", makeDoc(10))).toEqual({ ok: false, reason: "empty" });
expect(resolveEditorGotoLine(" ", makeDoc(10))).toEqual({ ok: false, reason: "empty" });
});
it("非十进制数字按 invalid 处理", () => {
for (const value of ["abc", "1.5", "1e3", "+1", "-1", "12", "1 2", "0x10"]) {
expect(resolveEditorGotoLine(value, makeDoc(10))).toEqual({ ok: false, reason: "invalid" });
}
});
it("越界行号按 out-of-range 处理", () => {
const doc = makeDoc(10);
expect(resolveEditorGotoLine("0", doc)).toEqual({ ok: false, reason: "out-of-range" });
expect(resolveEditorGotoLine("11", doc)).toEqual({ ok: false, reason: "out-of-range" });
expect(resolveEditorGotoLine("999999999999999999999", doc)).toEqual({ ok: false, reason: "out-of-range" });
});
it("单行文档只接受第 1 行", () => {
const doc = makeDoc(1);
expect(resolveEditorGotoLine("1", doc)).toEqual({ ok: true, line: 1, from: 0 });
expect(resolveEditorGotoLine("2", doc)).toEqual({ ok: false, reason: "out-of-range" });
});
});
describe("currentEditorLineNumber", () => {
it("返回光标所在行号", () => {
const doc = makeDoc(20);
expect(currentEditorLineNumber(doc, 0)).toBe(1);
expect(currentEditorLineNumber(doc, 95)).toBe(10);
expect(currentEditorLineNumber(doc, 199)).toBe(20);
});
});
@@ -6,6 +6,7 @@ import {
findCrossScopeShortcutConflicts,
findShortcutConflict,
formatShortcut,
gotoLineDefaultShortcut,
isReservedShortcut,
MACOS_RESERVED_SHORTCUTS,
normalizeModifierOnlyShortcut,
@@ -483,6 +484,48 @@ describe("shortcutRegistry editor actions", () => {
});
});
describe("gotoLine", () => {
it("resolves the platform default and maps it to the CodeMirror key", () => {
// macOS 的 ⌃G 已分配给「选中下一个相同词」(JetBrains 风格),沿用
// CodeMirror 搜索键位里原本就指向 gotoLine 的 ⌘⌥G;Windows/Linux 用
// VS Code / SSMS 惯例的 Ctrl+G。
expect(gotoLineDefaultShortcut("MacIntel")).toBe("Mod+Alt+G");
expect(gotoLineDefaultShortcut("Win32")).toBe("Mod+G");
expect(gotoLineDefaultShortcut("Linux x86_64")).toBe("Mod+G");
expect(shortcutToCodeMirrorKey(gotoLineDefaultShortcut("MacIntel"))).toBe("Mod-Alt-g");
expect(shortcutToCodeMirrorKey(gotoLineDefaultShortcut("Win32"))).toBe("Mod-g");
});
it("registers an editor-scope definition with the settings label", () => {
expect(SHORTCUT_DEFINITIONS.find((item) => item.id === "gotoLine")).toMatchObject({
id: "gotoLine",
labelKey: "settings.shortcutGotoLine",
scope: "editor",
});
expect(DEFAULT_SHORTCUT_SETTINGS.gotoLine).toBe(gotoLineDefaultShortcut());
});
it("re-resolves a cloud-synced default from the other platform", () => {
// 云同步会把另一平台的默认值当成显式配置带过来,解析后必须回到本机平台默认。
expect(normalizeShortcutSettings({ gotoLine: "Mod+Alt+G" }, "Win32").gotoLine).toBe("Mod+G");
expect(normalizeShortcutSettings({ gotoLine: "Mod+G" }, "MacIntel").gotoLine).toBe("Mod+Alt+G");
// 用户真正自定义的组合原样保留,清空仍然表示「不绑定」。
expect(normalizeShortcutSettings({ gotoLine: "Alt+Mod+Shift+L" }, "Win32").gotoLine).toBe("Alt+Mod+Shift+L");
expect(normalizeShortcutSettings({ gotoLine: "" }, "Win32").gotoLine).toBe("");
});
it("never collides with the same-scope selection-occurrence shortcuts", () => {
// 非 mac 的 Mod+G 展开后是 Ctrl+G,恰好等于 mac 上
// addNextSelectionOccurrence 的默认键;两者分属不同平台,不能互相判为冲突。
for (const platform of ["MacIntel", "Win32", "Linux x86_64"]) {
const shortcuts = normalizeShortcutSettings(undefined, platform);
expect(shortcuts.gotoLine).toBe(gotoLineDefaultShortcut(platform));
expect(findShortcutConflict("gotoLine", shortcuts.gotoLine, shortcuts, platform)).toBeNull();
expect(findShortcutConflict("addNextSelectionOccurrence", shortcuts.addNextSelectionOccurrence, shortcuts, platform)).toBeNull();
}
});
});
describe("countShortcutConflictPairs", () => {
it("counts an unordered pair once even though the map is bidirectional", () => {
expect(countShortcutConflictPairs({ find: "focusSearch", focusSearch: "find" })).toBe(1);
@@ -0,0 +1,33 @@
/**
* 「跳转到行」输入解析。
*
* 只做两件事:把用户在跳转框里输入的内容解析成行号,并给出该行在文档中的起始
* 偏移。与 CodeMirror 解耦(只依赖 `lines` / `line()` 这两个成员),这样既能直
* 接接收 `Text`,也能在单测里用最简桩对象覆盖边界情况。
*/
export interface EditorGotoLineDocument {
readonly lines: number;
line(number: number): { readonly number: number; readonly from: number };
}
export type EditorGotoLineFailure = "empty" | "invalid" | "out-of-range";
export type EditorGotoLineResolution = { ok: true; line: number; from: number } | { ok: false; reason: EditorGotoLineFailure };
/** 只接受十进制数字:`+1`、`1.5`、`1e3`、全角数字等一律视为无效输入。 */
const DECIMAL_DIGITS = /^\d+$/;
export function resolveEditorGotoLine(input: string, doc: EditorGotoLineDocument): EditorGotoLineResolution {
const trimmed = input.trim();
if (!trimmed) return { ok: false, reason: "empty" };
if (!DECIMAL_DIGITS.test(trimmed)) return { ok: false, reason: "invalid" };
const line = Number.parseInt(trimmed, 10);
if (!Number.isSafeInteger(line) || line < 1 || line > doc.lines) return { ok: false, reason: "out-of-range" };
return { ok: true, line, from: doc.line(line).from };
}
/** 跳转框的预填值:当前光标所在行(VS Code 同样的行为,直接回车即回到原处)。 */
export function currentEditorLineNumber(doc: EditorGotoLineDocument & { lineAt(position: number): { readonly number: number } }, position: number): number {
return doc.lineAt(position).number;
}
@@ -66,6 +66,7 @@ export type ShortcutActionId =
| "zoomOutUi"
| "resetUiZoom"
| "find"
| "gotoLine"
| "replace"
| "refreshData"
| "toggleResultsPane"
@@ -127,6 +128,14 @@ export function toggleAiPanelDefaultShortcut(platform = globalThis.navigator?.pl
return isMacShortcutPlatform(platform) ? "Ctrl+Mod+I" : "Ctrl+Alt+I";
}
// 「跳转到行」的平台默认键。Windows/Linux 上用 Ctrl+G,与 VS Code / SSMS /
// DataGrip 的惯例一致(编辑器内查找下一个仍有 F3 与搜索面板回车);
// macOS 的 Ctrl+G 已分配给「选中下一个相同词」(JetBrains 风格),因此沿用
// CodeMirror 搜索键位里原本就指向 gotoLine 的 ⌘⌥G。
export function gotoLineDefaultShortcut(platform = globalThis.navigator?.platform || ""): string {
return isMacShortcutPlatform(platform) ? "Mod+Alt+G" : "Mod+G";
}
const PLATFORM_DEFAULT_SHORTCUTS: Partial<Record<ShortcutActionId, ReadonlySet<string>>> = {
closeOtherTabs: new Set(["Alt+Mod+W", "Shift+Alt+W"]),
navigateTabHistoryBack: new Set(["Ctrl+Alt+ArrowLeft", "Mod+Alt+ArrowLeft"]),
@@ -134,6 +143,7 @@ const PLATFORM_DEFAULT_SHORTCUTS: Partial<Record<ShortcutActionId, ReadonlySet<s
addNextSelectionOccurrence: new Set(["Ctrl+G", "Alt+J"]),
selectAllSelectionOccurrences: new Set(["Ctrl+Mod+G", "Ctrl+Alt+Shift+J"]),
toggleAiPanel: new Set(["Ctrl+Mod+I", "Ctrl+Alt+I"]),
gotoLine: new Set(["Mod+G", "Mod+Alt+G"]),
};
const LEGACY_CLOSE_TAB_DEFAULT = "Meta+W";
const LEGACY_COPY_CURRENT_ROW_DEFAULT = "Mod+D";
@@ -531,6 +541,12 @@ export const SHORTCUT_DEFINITIONS: ShortcutDefinition[] = [
scope: "editor",
defaultShortcut: "Mod+F",
},
{
id: "gotoLine",
labelKey: "settings.shortcutGotoLine",
scope: "editor",
defaultShortcut: gotoLineDefaultShortcut(),
},
{
id: "replace",
labelKey: "settings.shortcutReplace",
@@ -652,6 +668,7 @@ function shortcutDefaultForPlatform(definition: ShortcutDefinition, platform: st
if (definition.id === "addNextSelectionOccurrence") return selectionOccurrenceDefaultShortcut("addNextSelectionOccurrence", platform);
if (definition.id === "selectAllSelectionOccurrences") return selectionOccurrenceDefaultShortcut("selectAllSelectionOccurrences", platform);
if (definition.id === "closeOtherTabs") return closeOtherTabsDefaultShortcut(platform);
if (definition.id === "gotoLine") return gotoLineDefaultShortcut(platform);
if (definition.id === "navigateTabHistoryBack") return tabNavigationHistoryDefaultShortcut("back", platform);
if (definition.id === "navigateTabHistoryForward") return tabNavigationHistoryDefaultShortcut("forward", platform);
if (definition.id === "toggleAiPanel") return toggleAiPanelDefaultShortcut(platform);
@@ -698,7 +715,10 @@ export function normalizeShortcutSettings(settings?: Partial<ShortcutSettings>,
normalized.copyCurrentRow = LEGACY_COPY_CURRENT_ROW_DEFAULT;
}
for (const actionId of TAB_NAVIGATION_HISTORY_ACTIONS) {
// gotoLine 的平台默认键(Win/Linux 为 Ctrl+G)在该动作引入前是其他动作可合法
// 显式绑定的自由键位;无显式配置的默认值与同作用域显式绑定同键时同样让位,
// 否则运行时 keymap 先注册的 gotoLine 会遮蔽用户的显式配置。
for (const actionId of [...TAB_NAVIGATION_HISTORY_ACTIONS, "gotoLine"] as ShortcutActionId[]) {
if (hasExplicitShortcut(settings, actionId)) continue;
const definition = SHORTCUT_DEFINITIONS.find((item) => item.id === actionId);
if (!definition) continue;