feat(editor): add goto line input with Ctrl+G and Cmd-Alt-G
This commit is contained in:
24 files changed
+667
-2
No files matched your search
@@ -0,0 +1,116 @@
|
||||
<script setup lang="ts">
|
||||
import { nextTick, ref } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { ArrowRightToLine } from "@lucide/vue";
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import { currentEditorLineNumber, resolveEditorGotoLine } from "@/lib/editor/editorGotoLine";
|
||||
|
||||
const props = defineProps<{
|
||||
view: EditorView | null;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
open: [];
|
||||
close: [];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const gotoLineVisible = ref(false);
|
||||
const gotoLineInput = ref("");
|
||||
const gotoLineError = ref("");
|
||||
const gotoLineInputRef = ref<HTMLInputElement>();
|
||||
|
||||
function focusInput() {
|
||||
void nextTick(() => {
|
||||
const input = gotoLineInputRef.value;
|
||||
if (!input) return;
|
||||
input.focus();
|
||||
input.select();
|
||||
});
|
||||
}
|
||||
|
||||
function openGotoLine(): boolean {
|
||||
const view = props.view;
|
||||
if (!view) return false;
|
||||
gotoLineVisible.value = true;
|
||||
gotoLineError.value = "";
|
||||
// 预填当前行:直接回车即回到原处,符合 VS Code 的跳转框行为。
|
||||
gotoLineInput.value = String(currentEditorLineNumber(view.state.doc, view.state.selection.main.head));
|
||||
emit("open");
|
||||
focusInput();
|
||||
return true;
|
||||
}
|
||||
|
||||
function closeGotoLine(): boolean {
|
||||
if (!gotoLineVisible.value) return false;
|
||||
gotoLineVisible.value = false;
|
||||
gotoLineError.value = "";
|
||||
emit("close");
|
||||
props.view?.focus();
|
||||
return true;
|
||||
}
|
||||
|
||||
function gotoLine(): boolean {
|
||||
const view = props.view;
|
||||
if (!view) return false;
|
||||
const resolution = resolveEditorGotoLine(gotoLineInput.value, view.state.doc);
|
||||
if (!resolution.ok) {
|
||||
gotoLineError.value = resolution.reason === "empty" ? t("editor.gotoLine.empty") : t("editor.gotoLine.outOfRange", { total: view.state.doc.lines });
|
||||
gotoLineInputRef.value?.focus();
|
||||
return false;
|
||||
}
|
||||
const line = view.state.doc.line(resolution.line);
|
||||
view.dispatch({ selection: { anchor: line.from }, scrollIntoView: true, userEvent: "select.gotoLine" });
|
||||
closeGotoLine();
|
||||
return true;
|
||||
}
|
||||
|
||||
function onGotoLineKeydown(event: KeyboardEvent) {
|
||||
// 输入法组合中的回车用于确认候选词,不能当作提交。
|
||||
if (event.isComposing) return;
|
||||
if (event.key === "Enter") {
|
||||
event.preventDefault();
|
||||
gotoLine();
|
||||
return;
|
||||
}
|
||||
if (event.key === "Escape") {
|
||||
event.preventDefault();
|
||||
closeGotoLine();
|
||||
return;
|
||||
}
|
||||
if (gotoLineError.value) gotoLineError.value = "";
|
||||
}
|
||||
|
||||
defineExpose({
|
||||
openGotoLine,
|
||||
closeGotoLine,
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Transition enter-active-class="transition-[transform,opacity] duration-150 will-change-[transform,opacity]" leave-active-class="transition-[transform,opacity] duration-100 will-change-[transform,opacity]" enter-from-class="opacity-0 -translate-y-1" leave-to-class="opacity-0 -translate-y-1">
|
||||
<div v-if="gotoLineVisible" class="editor-goto-line-panel absolute right-4 top-3 z-[9999] isolate flex items-center gap-1 rounded-lg border border-border bg-popover p-1.5 text-popover-foreground shadow-xl ring-1 ring-border/60">
|
||||
<span class="flex h-7 w-7 shrink-0 items-center justify-center text-muted-foreground" :title="t('editor.gotoLine.placeholder')" aria-hidden="true">
|
||||
<ArrowRightToLine class="h-4 w-4" />
|
||||
</span>
|
||||
<div class="flex h-8 w-40 items-center rounded-md border border-input bg-background focus-within:border-ring focus-within:ring-1 focus-within:ring-ring" :class="gotoLineError && 'border-destructive focus-within:border-destructive'">
|
||||
<input
|
||||
ref="gotoLineInputRef"
|
||||
v-model="gotoLineInput"
|
||||
inputmode="numeric"
|
||||
autocapitalize="off"
|
||||
autocorrect="off"
|
||||
spellcheck="false"
|
||||
class="h-full min-w-0 flex-1 bg-transparent px-2 text-sm text-foreground outline-none placeholder:text-muted-foreground"
|
||||
:placeholder="t('editor.gotoLine.placeholder')"
|
||||
:aria-label="t('editor.gotoLine.placeholder')"
|
||||
:aria-invalid="!!gotoLineError"
|
||||
@keydown="onGotoLineKeydown"
|
||||
/>
|
||||
<span class="shrink-0 pr-2 text-xs text-muted-foreground">{{ t("editor.gotoLine.total", { total: view?.state.doc.lines ?? 0 }) }}</span>
|
||||
</div>
|
||||
<span v-if="gotoLineError" class="max-w-48 shrink-0 text-xs text-destructive" aria-live="polite">{{ gotoLineError }}</span>
|
||||
</div>
|
||||
</Transition>
|
||||
</template>
|
||||
@@ -23,6 +23,7 @@ import type { EditorState, Text } from "@codemirror/state";
|
||||
import type { EditorView as EditorViewType } from "@codemirror/view";
|
||||
import { search as cmSearch } from "@codemirror/search";
|
||||
import EditorSearchPanel from "./EditorSearchPanel.vue";
|
||||
import EditorGotoLinePanel from "./EditorGotoLinePanel.vue";
|
||||
import SqlExecutionTargetPicker from "./SqlExecutionTargetPicker.vue";
|
||||
import DelimitedListDialog from "./DelimitedListDialog.vue";
|
||||
import CodeSnapshotDialog from "@/components/codeSnapshot/CodeSnapshotDialog.vue";
|
||||
@@ -525,6 +526,7 @@ const gestureStartFontSize = ref(settingsStore.editorSettings.fontSize);
|
||||
const isGestureZooming = ref(false);
|
||||
|
||||
const searchPanelRef = ref<InstanceType<typeof EditorSearchPanel>>();
|
||||
const gotoLinePanelRef = ref<InstanceType<typeof EditorGotoLinePanel>>();
|
||||
const selectedSql = ref("");
|
||||
const executableSql = ref("");
|
||||
const previewContextSql = ref("");
|
||||
@@ -2560,6 +2562,7 @@ function runKeymapExtension(codeMirrorKeymap: (typeof import("@codemirror/view")
|
||||
run: toggleSelectedBatchColumnSelection,
|
||||
},
|
||||
...binding(shortcuts.find, openSearch),
|
||||
...binding(shortcuts.gotoLine, openGotoLine),
|
||||
...replaceShortcutBindings,
|
||||
...executeInNewResultTabBindings,
|
||||
...executeBindings,
|
||||
@@ -8248,6 +8251,10 @@ function openSearch(): boolean {
|
||||
return searchPanelRef.value?.openSearch() ?? false;
|
||||
}
|
||||
|
||||
function openGotoLine(): boolean {
|
||||
return gotoLinePanelRef.value?.openGotoLine() ?? false;
|
||||
}
|
||||
|
||||
function openReplace(): boolean {
|
||||
if (props.readOnly) return false;
|
||||
return searchPanelRef.value?.openReplace() ?? false;
|
||||
@@ -8335,7 +8342,8 @@ defineExpose({
|
||||
/>
|
||||
</CustomContextMenu>
|
||||
<div v-show="queryEditorDropCaret" data-query-editor-drop-caret class="pointer-events-none absolute z-20 w-0.5 rounded-full bg-primary/70" :style="queryEditorDropCaretStyle" />
|
||||
<EditorSearchPanel ref="searchPanelRef" :view="view" />
|
||||
<EditorSearchPanel ref="searchPanelRef" :view="view" @open="gotoLinePanelRef?.closeGotoLine()" />
|
||||
<EditorGotoLinePanel ref="gotoLinePanelRef" :view="view" @open="searchPanelRef?.closeSearch()" />
|
||||
<SqlExecutionTargetPicker v-if="pickerVisible" :candidates="pickerCandidates" :active-index="pickerActiveIndex" :anchor="pickerAnchor" @update:active-index="onPickerActiveIndexChange" @confirm="onPickerConfirm" @cancel="closePicker" />
|
||||
<DelimitedListDialog v-model:open="delimitedListOpen" :selected-text="delimitedListSelectedText" @confirm="applyDelimitedListResult" />
|
||||
<CodeSnapshotDialog v-model:open="codeSnapshotOpen" :source="codeSnapshotSource" />
|
||||
|
||||
@@ -0,0 +1,279 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { createApp, defineComponent, h, nextTick, type App } from "vue";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("vue-i18n", () => ({
|
||||
useI18n: () => ({ t: (key: string) => key }),
|
||||
}));
|
||||
|
||||
import EditorGotoLinePanel from "@/components/editor/EditorGotoLinePanel.vue";
|
||||
|
||||
interface PanelHandle {
|
||||
openGotoLine: () => boolean;
|
||||
closeGotoLine: () => boolean;
|
||||
}
|
||||
|
||||
interface MountedPanel {
|
||||
view: EditorView;
|
||||
handle: () => PanelHandle;
|
||||
onOpen: ReturnType<typeof vi.fn>;
|
||||
onClose: ReturnType<typeof vi.fn>;
|
||||
panel: () => HTMLElement | null;
|
||||
input: () => HTMLInputElement;
|
||||
errorText: () => string;
|
||||
}
|
||||
|
||||
const mounted: Array<{ app: App; host: HTMLElement; view?: EditorView }> = [];
|
||||
|
||||
function mountPanel(docLines = 20): MountedPanel {
|
||||
let instance: PanelHandle | null = null;
|
||||
const onOpen = vi.fn();
|
||||
const onClose = vi.fn();
|
||||
// The editor has to be attached to the document: CodeMirror's focus() is a no-op
|
||||
// on detached content (mirrors what QueryEditor.vue always renders).
|
||||
const editorHost = document.createElement("div");
|
||||
document.body.append(editorHost);
|
||||
const view = new EditorView({
|
||||
parent: editorHost,
|
||||
state: EditorState.create({ doc: Array.from({ length: docLines }, (_, index) => `line ${index + 1}`).join("\n") }),
|
||||
});
|
||||
const host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
const app = createApp(
|
||||
defineComponent({
|
||||
setup() {
|
||||
return () =>
|
||||
h(EditorGotoLinePanel, {
|
||||
view,
|
||||
onOpen,
|
||||
onClose,
|
||||
ref: (el) => {
|
||||
if (el) instance = el as unknown as PanelHandle;
|
||||
},
|
||||
});
|
||||
},
|
||||
}),
|
||||
);
|
||||
app.mount(host);
|
||||
mounted.push({ app, host, view });
|
||||
return {
|
||||
view,
|
||||
handle: () => {
|
||||
if (!instance) throw new Error("panel not mounted");
|
||||
return instance;
|
||||
},
|
||||
onOpen,
|
||||
onClose,
|
||||
panel: () => host.querySelector<HTMLElement>(".editor-goto-line-panel"),
|
||||
input: () => {
|
||||
const input = host.querySelector<HTMLInputElement>("input");
|
||||
if (!input) throw new Error("goto-line input not rendered");
|
||||
return input;
|
||||
},
|
||||
errorText: () => host.querySelector('[aria-live="polite"]')?.textContent?.trim() ?? "",
|
||||
};
|
||||
}
|
||||
|
||||
function setInputValue(input: HTMLInputElement, value: string) {
|
||||
input.value = value;
|
||||
input.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
}
|
||||
|
||||
/** Vue's <Transition> keeps the leaving node in the DOM until the leave hook settles. */
|
||||
async function settleLeave(panel: () => HTMLElement | null, timeoutMs = 1000) {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
while (panel() && Date.now() < deadline) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
await nextTick();
|
||||
}
|
||||
}
|
||||
|
||||
function pressKey(input: HTMLInputElement, key: string) {
|
||||
input.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true }));
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
for (const { app, host, view } of mounted.splice(0)) {
|
||||
app.unmount();
|
||||
host.remove();
|
||||
view?.dom.parentElement?.remove();
|
||||
view?.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
describe("EditorGotoLinePanel", () => {
|
||||
it("stays closed until opened and prefills the caret line", async () => {
|
||||
const { view, handle, onOpen, panel, input } = mountPanel(20);
|
||||
view.dispatch({ selection: { anchor: view.state.doc.line(5).from + 3 } });
|
||||
|
||||
expect(panel()).toBeNull();
|
||||
|
||||
expect(handle().openGotoLine()).toBe(true);
|
||||
await nextTick();
|
||||
|
||||
expect(panel()).not.toBeNull();
|
||||
expect(input().value).toBe("5");
|
||||
expect(document.activeElement).toBe(input());
|
||||
expect(onOpen).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("jumps to the typed line, scrolls it into view, and closes", async () => {
|
||||
const { view, handle, onClose, panel, input } = mountPanel(20);
|
||||
handle().openGotoLine();
|
||||
await nextTick();
|
||||
|
||||
setInputValue(input(), "12");
|
||||
await nextTick();
|
||||
pressKey(input(), "Enter");
|
||||
await settleLeave(panel);
|
||||
|
||||
const target = view.state.doc.line(12);
|
||||
expect(view.state.selection.main.head).toBe(target.from);
|
||||
expect(view.state.selection.main.empty).toBe(true);
|
||||
expect(panel()).toBeNull();
|
||||
expect(onClose).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("keeps the caret in place and shows a hint for an out-of-range line", async () => {
|
||||
const { view, handle, panel, input, errorText } = mountPanel(20);
|
||||
const before = view.state.selection.main.head;
|
||||
handle().openGotoLine();
|
||||
await nextTick();
|
||||
|
||||
setInputValue(input(), "999");
|
||||
await nextTick();
|
||||
pressKey(input(), "Enter");
|
||||
await nextTick();
|
||||
|
||||
expect(view.state.selection.main.head).toBe(before);
|
||||
expect(panel()).not.toBeNull();
|
||||
expect(errorText()).toBe("editor.gotoLine.outOfRange");
|
||||
expect(document.activeElement).toBe(input());
|
||||
});
|
||||
|
||||
it("rejects non-numeric input, zero, and negative numbers", async () => {
|
||||
const { view, handle, panel, input, errorText } = mountPanel(20);
|
||||
const before = view.state.selection.main.head;
|
||||
handle().openGotoLine();
|
||||
await nextTick();
|
||||
|
||||
for (const value of ["abc", "1.5", "1e3", "+5", "-5"]) {
|
||||
setInputValue(input(), value);
|
||||
await nextTick();
|
||||
pressKey(input(), "Enter");
|
||||
await nextTick();
|
||||
expect(view.state.selection.main.head).toBe(before);
|
||||
expect(panel()).not.toBeNull();
|
||||
expect(errorText()).toBe("editor.gotoLine.outOfRange");
|
||||
}
|
||||
});
|
||||
|
||||
it("asks for a line number when the field is cleared", async () => {
|
||||
const { view, handle, panel, input, errorText } = mountPanel(20);
|
||||
const before = view.state.selection.main.head;
|
||||
handle().openGotoLine();
|
||||
await nextTick();
|
||||
|
||||
setInputValue(input(), " ");
|
||||
await nextTick();
|
||||
pressKey(input(), "Enter");
|
||||
await nextTick();
|
||||
|
||||
expect(view.state.selection.main.head).toBe(before);
|
||||
expect(panel()).not.toBeNull();
|
||||
expect(errorText()).toBe("editor.gotoLine.empty");
|
||||
});
|
||||
|
||||
it("clears a previous hint as soon as the input changes", async () => {
|
||||
const { handle, input, errorText } = mountPanel(20);
|
||||
handle().openGotoLine();
|
||||
await nextTick();
|
||||
|
||||
setInputValue(input(), "999");
|
||||
await nextTick();
|
||||
pressKey(input(), "Enter");
|
||||
await nextTick();
|
||||
expect(errorText()).toBe("editor.gotoLine.outOfRange");
|
||||
|
||||
pressKey(input(), "9");
|
||||
await nextTick();
|
||||
expect(errorText()).toBe("");
|
||||
});
|
||||
|
||||
it("cancels on Escape and returns focus to the editor", async () => {
|
||||
const { view, handle, panel, onClose, onOpen, input } = mountPanel(20);
|
||||
const before = view.state.selection.main.head;
|
||||
handle().openGotoLine();
|
||||
await nextTick();
|
||||
|
||||
pressKey(input(), "Escape");
|
||||
await settleLeave(panel);
|
||||
|
||||
expect(panel()).toBeNull();
|
||||
expect(view.state.selection.main.head).toBe(before);
|
||||
expect(onClose).toHaveBeenCalledOnce();
|
||||
expect(onOpen).toHaveBeenCalledOnce();
|
||||
expect(view.dom.contains(document.activeElement)).toBe(true);
|
||||
});
|
||||
|
||||
it("ignores the Enter that confirms an IME composition", async () => {
|
||||
const { view, handle, panel, input } = mountPanel(20);
|
||||
const before = view.state.selection.main.head;
|
||||
handle().openGotoLine();
|
||||
await nextTick();
|
||||
|
||||
setInputValue(input(), "12");
|
||||
await nextTick();
|
||||
input().dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true, isComposing: true } as KeyboardEventInit));
|
||||
await nextTick();
|
||||
|
||||
expect(view.state.selection.main.head).toBe(before);
|
||||
expect(panel()).not.toBeNull();
|
||||
});
|
||||
|
||||
it("reports failure instead of opening when there is no editor view", async () => {
|
||||
const onOpen = vi.fn();
|
||||
let instance: PanelHandle | null = null;
|
||||
const host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
const app = createApp(
|
||||
defineComponent({
|
||||
setup() {
|
||||
return () =>
|
||||
h(EditorGotoLinePanel, {
|
||||
view: null,
|
||||
onOpen,
|
||||
ref: (el) => {
|
||||
if (el) instance = el as unknown as PanelHandle;
|
||||
},
|
||||
});
|
||||
},
|
||||
}),
|
||||
);
|
||||
app.mount(host);
|
||||
mounted.push({ app, host });
|
||||
|
||||
expect((instance as unknown as PanelHandle).openGotoLine()).toBe(false);
|
||||
expect(onOpen).not.toHaveBeenCalled();
|
||||
expect(host.querySelector(".editor-goto-line-panel")).toBeNull();
|
||||
});
|
||||
|
||||
it("closes a previously opened panel from the exposed handle", async () => {
|
||||
const { handle, panel } = mountPanel(20);
|
||||
handle().openGotoLine();
|
||||
await nextTick();
|
||||
expect(panel()).not.toBeNull();
|
||||
|
||||
expect(handle().closeGotoLine()).toBe(true);
|
||||
await settleLeave(panel);
|
||||
expect(panel()).toBeNull();
|
||||
expect(handle().closeGotoLine()).toBe(false);
|
||||
});
|
||||
});
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const queryEditorSource = readFileSync(new URL("../QueryEditor.vue", import.meta.url), "utf8");
|
||||
|
||||
describe("QueryEditor goto-line wiring", () => {
|
||||
it("binds the platform goto-line shortcut next to find, before formatSql", () => {
|
||||
const gotoLineIndex = queryEditorSource.indexOf("...binding(shortcuts.gotoLine, openGotoLine),");
|
||||
const findIndex = queryEditorSource.indexOf("...binding(shortcuts.find, openSearch),");
|
||||
const formatIndex = queryEditorSource.indexOf("...binding(shortcuts.formatSql,");
|
||||
|
||||
expect(findIndex).toBeGreaterThan(-1);
|
||||
expect(gotoLineIndex).toBeGreaterThan(findIndex);
|
||||
// 非 mac 上 Ctrl+G 同时是 CodeMirror 内置的 find-next,运行时的 Prec.high
|
||||
// keymap 先匹配先执行,因此跳转绑定必须注册在搜索键位之前。
|
||||
expect(formatIndex).toBeGreaterThan(gotoLineIndex);
|
||||
});
|
||||
|
||||
it("routes the panel toggles through the exposed handles", () => {
|
||||
expect(queryEditorSource).toContain("function openGotoLine(): boolean {\n return gotoLinePanelRef.value?.openGotoLine() ?? false;\n}");
|
||||
expect(queryEditorSource).toContain('<EditorGotoLinePanel ref="gotoLinePanelRef" :view="view" @open="searchPanelRef?.closeSearch()" />');
|
||||
expect(queryEditorSource).toContain('<EditorSearchPanel ref="searchPanelRef" :view="view" @open="gotoLinePanelRef?.closeGotoLine()" />');
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user