feat(editor): execute custom sql template by shortcut on selection

This commit is contained in:
Mo-Moore authored and GitHub committed 2026-08-28 14:27:55 +08:00
1 parent 60bfb41f13
commit 802019daa3
26 files changed
+878 -7

No files matched your search

@@ -99,6 +99,18 @@ describe("QueryEditor execution routing", () => {
expect(queryEditorSource).toContain("const cursor = line.to + insertion.length");
expect(queryEditorSource).not.toMatch(/key:\s*"Enter"[\s\S]{0,180}shift:\s*codeMirrorInsertNewlineKeepIndent/);
});
it("routes custom SQL shortcuts through selection-aware execution with dual keymap and DOM handlers", () => {
expect(queryEditorSource).toContain("function runSqlShortcutAction(");
expect(queryEditorSource).toContain("resolveSqlShortcutTemplate(action.sql, selected)");
expect(queryEditorSource).toContain("enabledSqlShortcutActions(settingsStore.editorSettings.sqlShortcuts)");
expect(queryEditorSource).toContain("isCharacterProducingShortcut(action.shortcut)");
expect(queryEditorSource).toContain("createQueryEditorSqlShortcutDomHandler(");
expect(queryEditorSource).toContain("shouldBlockExecutionShortcut(event, currentView)");
expect(queryEditorSource).toContain("if (props.readOnly) return true;");
expect(queryEditorSource).toContain("settingsStore.editorSettings.sqlShortcuts");
expect(queryEditorSource).toContain("runKeymapComp.reconfigure(runKeymapExtension(editorViewModule.keymap))");
});
});
describe("QueryEditor execution viewport ownership", () => {
@@ -0,0 +1,78 @@
import { describe, expect, it, vi } from "vitest";
import { matchesShortcut } from "@/lib/editor/keyboardShortcuts";
import { createQueryEditorSqlShortcutDomHandler, isCharacterProducingShortcut } from "@/lib/editor/queryEditorSqlShortcut";
import type { SqlShortcutAction } from "@/types/database";
// pi-lens-ignore: typescript:2307
import type { EditorView } from "@codemirror/view";
function action(id: string, shortcut: string, overrides: Partial<SqlShortcutAction> = {}): SqlShortcutAction {
return {
id,
label: id,
shortcut,
sql: "SELECT * FROM ${table}",
enabled: true,
...overrides,
};
}
describe("isCharacterProducingShortcut", () => {
it("treats Shift+letter shortcuts as character-producing", () => {
expect(isCharacterProducingShortcut("Shift+U")).toBe(true);
expect(isCharacterProducingShortcut("u")).toBe(true);
});
it("treats modifier shortcuts as non character-producing", () => {
expect(isCharacterProducingShortcut("Mod+Shift+9")).toBe(false);
expect(isCharacterProducingShortcut("Shift+Alt+U")).toBe(false);
expect(isCharacterProducingShortcut("Shift+Enter")).toBe(false);
});
});
describe("matchesShortcut for Shift+U", () => {
it("matches uppercase U with shift held", () => {
expect(matchesShortcut({ key: "U", shiftKey: true }, "Shift+U", "MacIntel")).toBe(true);
});
});
function keydownEvent(overrides: { key: string; shiftKey?: boolean; metaKey?: boolean; ctrlKey?: boolean; altKey?: boolean }) {
return {
...overrides,
preventDefault: vi.fn(),
};
}
describe("createQueryEditorSqlShortcutDomHandler", () => {
const view = {} as EditorView;
it("runs the action and prevents default when there is a selection", () => {
const runAction = vi.fn(() => true);
const handler = createQueryEditorSqlShortcutDomHandler(() => [action("a", "Shift+U")], runAction, "MacIntel");
const event = keydownEvent({ key: "U", shiftKey: true });
expect(handler(event as unknown as KeyboardEvent, view)).toBe(true);
expect(runAction).toHaveBeenCalledOnce();
expect(runAction).toHaveBeenCalledWith(expect.objectContaining({ id: "a" }), view, event);
expect(event.preventDefault).toHaveBeenCalled();
});
it("does not intercept when there is no selection", () => {
const runAction = vi.fn(() => false);
const handler = createQueryEditorSqlShortcutDomHandler(() => [action("a", "Shift+U")], runAction, "MacIntel");
const event = keydownEvent({ key: "U", shiftKey: true });
expect(handler(event as unknown as KeyboardEvent, view)).toBe(false);
expect(runAction).toHaveBeenCalledOnce();
expect(runAction).toHaveBeenCalledWith(expect.objectContaining({ id: "a" }), view, event);
expect(event.preventDefault).not.toHaveBeenCalled();
});
it("ignores non character-producing shortcuts", () => {
const runAction = vi.fn(() => true);
const handler = createQueryEditorSqlShortcutDomHandler(() => [action("a", "Mod+Shift+9")], runAction, "MacIntel");
const event = keydownEvent({ key: "9", metaKey: true, shiftKey: true });
expect(handler(event as unknown as KeyboardEvent, view)).toBe(false);
expect(runAction).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,92 @@
import { describe, expect, it } from "vitest";
import { DEFAULT_SHORTCUT_SETTINGS } from "@/lib/editor/shortcutRegistry";
import { enabledSqlShortcutActions, findSqlShortcutConflicts, hasSqlShortcutConflicts, resolveSqlShortcutTemplate } from "@/lib/sql/sqlShortcutActions";
import type { SqlShortcutAction } from "@/types/database";
function action(id: string, shortcut: string, overrides: Partial<SqlShortcutAction> = {}): SqlShortcutAction {
return {
id,
label: id,
shortcut,
sql: "SELECT * FROM ${table}",
enabled: true,
...overrides,
};
}
describe("resolveSqlShortcutTemplate", () => {
it("replaces ${table} with trimmed selection", () => {
expect(resolveSqlShortcutTemplate("SELECT * FROM ${table}", " orders ")).toBe("SELECT * FROM orders");
});
it("replaces all occurrences", () => {
expect(resolveSqlShortcutTemplate("SELECT * FROM ${table} JOIN ${table}", "public.users")).toBe("SELECT * FROM public.users JOIN public.users");
});
it("does not expand replacement patterns in the selection", () => {
expect(resolveSqlShortcutTemplate("SELECT * FROM ${table}", "a$&b")).toBe("SELECT * FROM a$&b");
expect(resolveSqlShortcutTemplate("SELECT * FROM ${table}", "x$'y")).toBe("SELECT * FROM x$'y");
expect(resolveSqlShortcutTemplate("${table} ${table}", "$`1")).toBe("$`1 $`1");
});
});
describe("enabledSqlShortcutActions", () => {
it("filters disabled and unbound actions", () => {
const actions = [action("a", "Mod+1"), action("b", "", { enabled: true }), action("c", "Mod+2", { enabled: false })];
expect(enabledSqlShortcutActions(actions).map((item) => item.id)).toEqual(["a"]);
});
});
describe("findSqlShortcutConflicts", () => {
it("detects duplicate custom shortcuts", () => {
const actions = [action("a", "Mod+Shift+1"), action("b", "Mod+Shift+1")];
expect(findSqlShortcutConflicts(actions, DEFAULT_SHORTCUT_SETTINGS)).toEqual(expect.arrayContaining(["a", "b"]));
expect(hasSqlShortcutConflicts(actions, DEFAULT_SHORTCUT_SETTINGS)).toBe(true);
});
it("detects duplicate custom shortcuts with different modifier order", () => {
const actions = [action("a", "Mod+Shift+1"), action("b", "Shift+Mod+1")];
expect(findSqlShortcutConflicts(actions, DEFAULT_SHORTCUT_SETTINGS)).toEqual(expect.arrayContaining(["a", "b"]));
});
it("detects conflicts with fixed editor shortcuts", () => {
const actions = [action("a", DEFAULT_SHORTCUT_SETTINGS.formatSql)];
expect(findSqlShortcutConflicts(actions, DEFAULT_SHORTCUT_SETTINGS)).toEqual(["a"]);
});
it("ignores disabled actions", () => {
const actions = [action("a", "Mod+Shift+1", { enabled: false }), action("b", "Mod+Shift+1")];
expect(findSqlShortcutConflicts(actions, DEFAULT_SHORTCUT_SETTINGS)).toEqual([]);
});
});
describe("normalizeSqlShortcuts", () => {
it("preserves a single shortcut through normalizeEditorSettings", async () => {
const { normalizeEditorSettings } = await import("@/stores/settingsStore");
const source = [action("count", "Mod+Shift+C", { label: "Count rows", sql: "SELECT COUNT(*) FROM ${table}" })];
const normalized = normalizeEditorSettings({ sqlShortcuts: source }).sqlShortcuts;
expect(normalized).toEqual([
{
id: "count",
label: "Count rows",
shortcut: "Mod+Shift+C",
sql: "SELECT COUNT(*) FROM ${table}",
enabled: true,
},
]);
});
it("keeps modifier-order variants when loading settings", async () => {
const { normalizeEditorSettings } = await import("@/stores/settingsStore");
const normalized = normalizeEditorSettings({
sqlShortcuts: [action("a", "Mod+Shift+1"), action("b", "Shift+Mod+1")],
}).sqlShortcuts;
expect(normalized).toHaveLength(2);
expect(normalized.map((item) => item.id)).toEqual(["a", "b"]);
});
it("blocks saving when canonical duplicates conflict at validation time", () => {
const actions = [action("a", "Mod+Shift+1"), action("b", "Shift+Mod+1")];
expect(hasSqlShortcutConflicts(actions, DEFAULT_SHORTCUT_SETTINGS)).toBe(true);
});
});
@@ -0,0 +1,30 @@
import { matchesShortcut } from "@/lib/editor/keyboardShortcuts";
import { parseShortcutParts } from "@/lib/editor/shortcutDisplay";
import { enabledSqlShortcutActions } from "@/lib/sql/sqlShortcutActions";
import type { SqlShortcutAction } from "@/types/database";
// pi-lens-ignore: typescript:2307
import type { EditorView } from "@codemirror/view";
const LETTER_KEY_RE = /^[A-Za-z]$/;
export function isCharacterProducingShortcut(shortcut: string): boolean {
const parts = parseShortcutParts(shortcut.trim());
if (parts.length === 0) return false;
const key = parts[parts.length - 1] ?? "";
if (!LETTER_KEY_RE.test(key)) return false;
const modifiers = new Set(parts.slice(0, -1));
return !modifiers.has("Mod") && !modifiers.has("Meta") && !modifiers.has("Ctrl") && !modifiers.has("Alt");
}
export function createQueryEditorSqlShortcutDomHandler(getActions: () => readonly SqlShortcutAction[], runAction: (action: SqlShortcutAction, view: EditorView, event: KeyboardEvent) => boolean, platform = globalThis.navigator?.platform || ""): (event: KeyboardEvent, view: EditorView) => boolean {
return (event, view) => {
for (const action of enabledSqlShortcutActions(getActions())) {
if (!isCharacterProducingShortcut(action.shortcut)) continue;
if (!matchesShortcut(event, action.shortcut, platform)) continue;
if (!runAction(action, view, event)) return false;
event.preventDefault();
return true;
}
return false;
};
}
@@ -48,6 +48,17 @@ export function shortcutDisplayParts(shortcut?: string, platform = globalThis.na
return shortcutDisplayOrder(parseShortcutParts(shortcut), platform);
}
export function canonicalShortcutKey(shortcut: string): string {
return shortcutDisplayParts(shortcut, "Win32")
.map((part) => {
if (part === "Mod") return "Ctrl";
if (part === "Plus") return "+";
return part;
})
.join("+")
.toLowerCase();
}
export function shortcutDisplayStrokes(shortcut?: string, platform = globalThis.navigator?.platform || ""): string[][] {
return parseShortcutStrokes(shortcut).map((parts) => shortcutDisplayOrder(parts, platform));
}
@@ -89,6 +89,7 @@ export const EDITOR_SETTINGS_DRAFT_KEYS = [
"updateDownloadSource",
"toolbarItems",
"snippets",
"sqlShortcuts",
"sqlVariableSubstitutionEnabled",
"sqlVariableSyntaxOverrides",
"continueOnErrorOnBatch",
@@ -215,6 +215,7 @@ export const SETTINGS_SEARCH_DEFINITIONS: readonly SettingsSearchDefinition[] =
{ id: "backups", category: "backups", titleKey: "databaseBackup.title", targetId: "backups", visible: desktopOnly },
{ id: "tunnels", category: "tunnels", titleKey: "settings.tunnelsTab", targetId: "tunnels" },
{ id: "shortcuts", category: "shortcuts", titleKey: "settings.shortcutsTab", targetId: "shortcuts" },
{ id: "sql-shortcuts", category: "shortcuts", titleKey: "settings.sqlShortcutsTitle", descriptionKey: "settings.sqlShortcutsDescription", targetId: "sql-shortcuts" },
{ id: "snippets", category: "snippets", titleKey: "settings.snippetsTab", descriptionKey: "settings.snippetsDescription", targetId: "snippets" },
{ id: "sync-webdav", category: "sync", titleKey: "settings.syncWebDavTitle", descriptionKey: "settings.syncWebDavDescription", targetId: "sync-webdav", route: { syncMethodTab: "webdav" } },
{ id: "sync-webdav-endpoint", category: "sync", titleKey: "settings.syncEndpoint", targetId: "sync-webdav", route: { syncMethodTab: "webdav" } },
@@ -0,0 +1,43 @@
import { canonicalShortcutKey } from "@/lib/editor/shortcutDisplay";
import { formatShortcut, SHORTCUT_DEFINITIONS, type ShortcutSettings } from "@/lib/editor/shortcutRegistry";
import type { SqlShortcutAction } from "@/types/database";
export const SQL_SHORTCUT_TABLE_TOKEN = "${table}";
export function resolveSqlShortcutTemplate(template: string, selectedTable: string): string {
return template.replace(/\$\{table\}/g, () => selectedTable.trim());
}
export function enabledSqlShortcutActions(actions: readonly SqlShortcutAction[]): SqlShortcutAction[] {
return actions.filter((action) => action.enabled !== false && action.shortcut.trim().length > 0);
}
function shortcutsUseSameKeys(first: string, second: string, platform = globalThis.navigator?.platform || ""): boolean {
if (!first || !second) return false;
if (canonicalShortcutKey(first) === canonicalShortcutKey(second)) return true;
return formatShortcut(first, platform).toLowerCase() === formatShortcut(second, platform).toLowerCase();
}
export function findSqlShortcutConflicts(actions: readonly SqlShortcutAction[], fixedShortcuts: ShortcutSettings, platform = globalThis.navigator?.platform || ""): string[] {
const conflicts = new Set<string>();
const editorFixedShortcuts = SHORTCUT_DEFINITIONS.filter((item) => item.scope === "editor" || item.scope === "global");
for (const action of actions) {
if (action.enabled === false || !action.shortcut.trim()) continue;
const duplicate = actions.find((other) => other.id !== action.id && other.enabled !== false && other.shortcut.trim() && shortcutsUseSameKeys(other.shortcut, action.shortcut, platform));
if (duplicate) {
conflicts.add(action.id);
conflicts.add(duplicate.id);
}
const fixedConflict = editorFixedShortcuts.find((item) => fixedShortcuts[item.id] && shortcutsUseSameKeys(fixedShortcuts[item.id], action.shortcut, platform));
if (fixedConflict) conflicts.add(action.id);
}
return [...conflicts];
}
export function hasSqlShortcutConflicts(actions: readonly SqlShortcutAction[], fixedShortcuts: ShortcutSettings, platform = globalThis.navigator?.platform || ""): boolean {
return findSqlShortcutConflicts(actions, fixedShortcuts, platform).length > 0;
}