mirror of
https://github.com/t8y2/dbx.git
synced 2026-11-23 12:52:23 +08:00
feat(editor): configurable shortcut to commit the active transaction (#14311)
* feat(editor): configurable shortcut to commit the active transaction * chore(i18n): autofill new translations --------- Co-authored-by: dbx-i18n-bot <github-actions[bot]@users.noreply.github.com> Co-authored-by: zipg <4047349+zipg@users.noreply.github.com>
This commit is contained in:
19 files changed
+74
-11
No files matched your search
@@ -151,6 +151,7 @@ import {
|
||||
isCloseTabShortcut,
|
||||
isReopenClosedTabShortcut,
|
||||
isCloseWindowShortcut,
|
||||
isCommitTransactionShortcut,
|
||||
isDisconnectAllActiveConnectionsShortcut,
|
||||
isEditTableStructureShortcut,
|
||||
isExecuteSqlInNewResultTabShortcut,
|
||||
@@ -5077,6 +5078,12 @@ async function handleKeydown(e: KeyboardEvent) {
|
||||
}
|
||||
if (!showSettingsPage.value && !showPluginCenter.value && !showDriverStore.value) {
|
||||
const target = e.target instanceof Element ? e.target : null;
|
||||
const canUseShortcut = !target?.closest('[role="dialog"], [role="alertdialog"], input, textarea, [contenteditable="true"]:not(.cm-content)');
|
||||
if (!e.repeat && canUseShortcut && isCommitTransactionShortcut(e, shortcuts) && contentAreaRef.value?.commitTransaction()) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
return;
|
||||
}
|
||||
const copyResultColumn = copyResultColumnIndexFromShortcut(e, shortcuts);
|
||||
if (copyResultColumn !== null && !target?.closest('[role="dialog"], [role="alertdialog"], input, textarea') && contentAreaRef.value?.copyResultColumn(copyResultColumn)) {
|
||||
e.preventDefault();
|
||||
|
||||
@@ -85,6 +85,7 @@ defineExpose({
|
||||
focusWhere: () => activeSurfaceRef.value?.focusWhere() ?? false,
|
||||
openGoToColumn: () => activeSurfaceRef.value?.openGoToColumn() ?? false,
|
||||
openTableStructureEditor: (initialTab?: TableInfoTab) => activeSurfaceRef.value?.openTableStructureEditor?.(initialTab) ?? false,
|
||||
commitTransaction: () => toolbarRef.value?.commitFromToolbar() ?? false,
|
||||
copyResultColumn: (column: number) => {
|
||||
const cell = firstResultCellValue(activeTab.value?.result, column);
|
||||
if (!cell) return false;
|
||||
|
||||
@@ -437,6 +437,12 @@ const showTxnActions = computed(() => {
|
||||
if (props.stickyProvenReadOnlyState) return isTransactionActive.value && props.txnPossiblyDirty === true;
|
||||
return isTransactionActive.value;
|
||||
});
|
||||
const canCommit = computed(() => supportsTransaction.value && showTxnActions.value && !props.activeTab.isExecuting && !props.activeTab.isCancelling && !props.activeTab.isExplaining && props.activeTab.txnStatus !== "ending" && props.activeTab.txnStatus !== "opening");
|
||||
function commitFromToolbar() {
|
||||
if (!canCommit.value) return false;
|
||||
emit("commit");
|
||||
return true;
|
||||
}
|
||||
const transactionTooltip = computed(() => {
|
||||
if (hasOpenAutoCommitTransaction.value) return t("settings.keepExplicitTransactionInAutoCommitDescription");
|
||||
if (props.activeConnection?.db_type === "sqlserver" && isManualTransactionMode.value) {
|
||||
@@ -640,6 +646,7 @@ const databasePickerRef = ref<InstanceType<typeof SearchableSelect> | null>(null
|
||||
const schemaPickerRef = ref<InstanceType<typeof SearchableSelect> | null>(null);
|
||||
|
||||
defineExpose({
|
||||
commitFromToolbar,
|
||||
openConnectionPicker: () => connectionPickerRef.value?.openDropdown() ?? false,
|
||||
openDatabasePicker: () => databasePickerRef.value?.openDropdown() ?? false,
|
||||
openSchemaPicker: () => schemaPickerRef.value?.openDropdown() ?? false,
|
||||
@@ -1047,14 +1054,7 @@ defineExpose({
|
||||
<!-- Commit button (only when a transaction action is warranted) -->
|
||||
<Tooltip v-if="showTxnActions">
|
||||
<TooltipTrigger as-child>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
class="h-6 w-6 text-green-600 hover:bg-green-500/10 hover:text-green-700 dark:text-green-300 dark:hover:text-green-200"
|
||||
:disabled="activeTab.isExecuting || activeTab.txnStatus === 'ending' || activeTab.txnStatus === 'opening'"
|
||||
:aria-label="t('toolbar.commit')"
|
||||
@click="emit('commit')"
|
||||
>
|
||||
<Button variant="ghost" size="icon" class="h-6 w-6 text-green-600 hover:bg-green-500/10 hover:text-green-700 dark:text-green-300 dark:hover:text-green-200" :disabled="!canCommit" :aria-label="t('toolbar.commit')" @click="commitFromToolbar">
|
||||
<Check class="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
|
||||
@@ -82,6 +82,7 @@ defineExpose({
|
||||
openDatabasePicker: () => activeEditorGroup()?.openDatabasePicker() ?? false,
|
||||
openSchemaPicker: () => activeEditorGroup()?.openSchemaPicker() ?? false,
|
||||
openTableStructureEditor: (initialTab?: TableInfoTab) => activeEditorGroup()?.openTableStructureEditor?.(initialTab) ?? false,
|
||||
commitTransaction: () => activeEditorGroup()?.commitTransaction() ?? false,
|
||||
copyResultColumn: (column: number) => activeEditorGroup()?.copyResultColumn(column) ?? false,
|
||||
refreshData: (target: Element | null = null) => {
|
||||
const element = commandTargetElement(target);
|
||||
|
||||
+14
-3
@@ -85,7 +85,7 @@ describe("EditorToolbar commit/rollback visibility", () => {
|
||||
});
|
||||
});
|
||||
|
||||
async function mountToolbar(props: { dbType: string; stickyProvenReadOnlyState: boolean; txnPossiblyDirty?: boolean; txnSessionId?: string; txnStatus?: string; isExecuting?: boolean }) {
|
||||
async function mountToolbar(props: { dbType: string; stickyProvenReadOnlyState: boolean; txnPossiblyDirty?: boolean; txnSessionId?: string; txnStatus?: string; isExecuting?: boolean; onCommit?: () => void }) {
|
||||
const connectionStore = useConnectionStore();
|
||||
connectionStore.connections = [
|
||||
{
|
||||
@@ -98,6 +98,7 @@ describe("EditorToolbar commit/rollback visibility", () => {
|
||||
|
||||
const host = createHost();
|
||||
const app = createApp(EditorToolbar, {
|
||||
onCommit: props.onCommit,
|
||||
activeTab: {
|
||||
id: "tab-1",
|
||||
title: "SQL",
|
||||
@@ -125,14 +126,24 @@ describe("EditorToolbar commit/rollback visibility", () => {
|
||||
});
|
||||
app.use(pinia);
|
||||
app.use(i18n);
|
||||
app.mount(host);
|
||||
const toolbar = app.mount(host) as InstanceType<typeof EditorToolbar>;
|
||||
await nextTick();
|
||||
return host;
|
||||
return Object.assign(host, { toolbar });
|
||||
}
|
||||
|
||||
const commitSelector = `button[aria-label="toolbar.commit"]`;
|
||||
const rollbackSelector = `button[aria-label="toolbar.rollback"]`;
|
||||
|
||||
it.each([false, true])("uses the toolbar commit guard while isExecuting=%s", async (isExecuting) => {
|
||||
const onCommit = vi.fn();
|
||||
const host = await mountToolbar({ dbType: "mysql", stickyProvenReadOnlyState: true, txnPossiblyDirty: true, txnSessionId: "txn-1", isExecuting, onCommit });
|
||||
|
||||
expect(host.querySelector<HTMLButtonElement>(commitSelector)?.disabled).toBe(isExecuting);
|
||||
expect(host.toolbar.commitFromToolbar()).toBe(!isExecuting);
|
||||
expect(onCommit).toHaveBeenCalledTimes(isExecuting ? 0 : 1);
|
||||
host.remove();
|
||||
});
|
||||
|
||||
it.each([undefined, "active-session"])("only opens independent multi-db transactions when the source has no active session (%s)", async (txnSessionId) => {
|
||||
const host = await mountToolbar({ dbType: "oceanbase-oracle", stickyProvenReadOnlyState: true, txnSessionId });
|
||||
const multiDb = host.querySelector<HTMLButtonElement>('button[aria-label="toolbar.multiDbExecute"]');
|
||||
|
||||
@@ -11549,6 +11549,7 @@ export default {
|
||||
shortcutZoomOutUi: "Zoom out UI",
|
||||
shortcutResetUiZoom: "Reset UI zoom",
|
||||
shortcutRefreshData: "Refresh data",
|
||||
shortcutCommitTransaction: "Commit transaction",
|
||||
shortcutCopyResultColumn1: "Copy column 1 of first result row",
|
||||
shortcutCopyResultColumn2: "Copy column 2 of first result row",
|
||||
shortcutCopyResultColumn3: "Copy column 3 of first result row",
|
||||
|
||||
@@ -11191,6 +11191,7 @@ export default withEnglishFallback({
|
||||
shortcutExecuteAllSql: "Ejecutar todo el SQL",
|
||||
showConnectionGroupPath: "Mostrar la ruta completa del grupo de la conexión de consulta",
|
||||
showConnectionGroupPathDescription: "Cuando está activado, el selector de conexiones de la esquina superior derecha de la página de consulta mostrará la ruta completa del grupo antes del nombre de la conexión; cuando está desactivado, solo mostrará el nombre de la conexión.",
|
||||
shortcutCommitTransaction: "Confirmar transacción",
|
||||
shortcutCopyResultColumn1: "Copiar la columna 1 del resultado de la primera fila",
|
||||
shortcutCopyResultColumn2: "Copiar la columna 2 del resultado de la primera fila",
|
||||
shortcutCopyResultColumn3: "Copiar la columna 3 del resultado de la primera fila",
|
||||
|
||||
@@ -10906,6 +10906,7 @@ export default withEnglishFallback({
|
||||
shortcutExecuteAllSql: "Esegui tutto il SQL",
|
||||
showConnectionGroupPath: "Mostra il percorso completo del gruppo per le connessioni query",
|
||||
showConnectionGroupPathDescription: "Se attivato, il selettore di connessione nell'angolo in alto a destra della pagina query mostrerà il percorso completo del gruppo prima del nome della connessione; se disattivato, mostrerà solo il nome della connessione.",
|
||||
shortcutCommitTransaction: "Conferma transazione",
|
||||
shortcutCopyResultColumn1: "Copia la colonna 1 del risultato della prima riga",
|
||||
shortcutCopyResultColumn2: "Copia la colonna 2 del risultato della prima riga",
|
||||
shortcutCopyResultColumn3: "Copia la colonna 3 del risultato della prima riga",
|
||||
|
||||
@@ -10932,6 +10932,7 @@ export default withEnglishFallback({
|
||||
shortcutExecuteAllSql: "すべての SQL を実行",
|
||||
showConnectionGroupPath: "クエリ接続の完全なグループパスを表示",
|
||||
showConnectionGroupPathDescription: "有効にすると、クエリページ右上の接続セレクターで接続名の前に完全なグループパスが表示されます。無効にすると接続名のみが表示されます。",
|
||||
shortcutCommitTransaction: "トランザクションをコミット",
|
||||
shortcutCopyResultColumn1: "結果の1行目の1列目をコピー",
|
||||
shortcutCopyResultColumn2: "結果の1行目の2列目をコピー",
|
||||
shortcutCopyResultColumn3: "結果の1行目の3列目をコピー",
|
||||
|
||||
@@ -11009,6 +11009,7 @@ export default withEnglishFallback({
|
||||
shortcutExecuteAllSql: "모든 SQL 실행",
|
||||
showConnectionGroupPath: "쿼리 연결의 전체 그룹 경로 표시",
|
||||
showConnectionGroupPathDescription: "활성화하면 쿼리 페이지 오른쪽 위의 연결 선택기에서 연결 이름 앞에 전체 그룹 경로를 표시합니다. 비활성화하면 연결 이름만 표시합니다.",
|
||||
shortcutCommitTransaction: "트랜잭션 커밋",
|
||||
shortcutCopyResultColumn1: "첫 번째 행 결과의 1열 복사",
|
||||
shortcutCopyResultColumn2: "첫 번째 행 결과의 2열 복사",
|
||||
shortcutCopyResultColumn3: "첫 번째 행 결과의 3열 복사",
|
||||
|
||||
@@ -10901,6 +10901,7 @@ export default withEnglishFallback({
|
||||
shortcutExecuteAllSql: "Executar todo o SQL",
|
||||
showConnectionGroupPath: "Mostrar caminho completo do grupo da conexão de consulta",
|
||||
showConnectionGroupPathDescription: "Quando ativado, o seletor de conexão no canto superior direito da página de consulta exibirá o caminho completo do grupo antes do nome da conexão; quando desativado, exibirá apenas o nome da conexão.",
|
||||
shortcutCommitTransaction: "Confirmar transação",
|
||||
shortcutCopyResultColumn1: "Copiar a coluna 1 do resultado da primeira linha",
|
||||
shortcutCopyResultColumn2: "Copiar a coluna 2 do resultado da primeira linha",
|
||||
shortcutCopyResultColumn3: "Copiar a coluna 3 do resultado da primeira linha",
|
||||
|
||||
@@ -12496,6 +12496,7 @@ export default withEnglishFallback({
|
||||
deepLinkConnectionConfirmModeUpdateDescription: "Ссылки с id сразу обновляют сохранённое подключение; для новых подключений по-прежнему открывается диалоговое окно для подтверждения.",
|
||||
deepLinkConnectionConfirmModeAll: "Все ссылки подключения",
|
||||
deepLinkConnectionConfirmModeAllDescription: "Новые подключения и ссылки обновления с id сохраняются сразу, без подтверждения. Если предварительно заполненные параметры не проходят проверку, диалоговое окно останется открытым, и вы сможете дополнить их вручную.",
|
||||
shortcutCommitTransaction: "Зафиксировать транзакцию",
|
||||
shortcutCopyResultColumn1: "Копировать 1-й столбец результата первой строки",
|
||||
shortcutCopyResultColumn2: "Копировать 2-й столбец результата первой строки",
|
||||
shortcutCopyResultColumn3: "Копировать 3-й столбец результата первой строки",
|
||||
|
||||
@@ -12858,6 +12858,7 @@ export default withEnglishFallback({
|
||||
deepLinkConnectionConfirmModeUpdateDescription: "ลิงก์ที่มี id จะอัปเดตการเชื่อมต่อที่บันทึกไว้โดยตรง ส่วนการเชื่อมต่อใหม่ยังคงเปิดป๊อปอัปเพื่อรอการยืนยัน",
|
||||
deepLinkConnectionConfirmModeAll: "ลิงก์การเชื่อมต่อทั้งหมด",
|
||||
deepLinkConnectionConfirmModeAllDescription: "การเชื่อมต่อใหม่และลิงก์อัปเดตที่มี id จะถูกบันทึกโดยตรงโดยไม่ต้องยืนยันอีก หากการตรวจสอบพารามิเตอร์ที่กรอกล่วงหน้าไม่ผ่าน ป๊อปอัปจะยังคงเปิดอยู่ และคุณสามารถกรอกข้อมูลให้ครบด้วยตนเองต่อไปได้",
|
||||
shortcutCommitTransaction: "คอมมิตธุรกรรม",
|
||||
shortcutCopyResultColumn1: "คัดลอกคอลัมน์ที่ 1 ของผลลัพธ์แถวแรก",
|
||||
shortcutCopyResultColumn2: "คัดลอกคอลัมน์ที่ 2 ของผลลัพธ์แถวแรก",
|
||||
shortcutCopyResultColumn3: "คัดลอกคอลัมน์ที่ 3 ของผลลัพธ์แถวแรก",
|
||||
|
||||
@@ -11515,6 +11515,7 @@ export default withEnglishFallback({
|
||||
shortcutZoomOutUi: "缩小全局界面",
|
||||
shortcutResetUiZoom: "重置全局界面缩放",
|
||||
shortcutRefreshData: "刷新数据",
|
||||
shortcutCommitTransaction: "提交事务",
|
||||
shortcutCopyResultColumn1: "复制第一行结果的第 1 列",
|
||||
shortcutCopyResultColumn2: "复制第一行结果的第 2 列",
|
||||
shortcutCopyResultColumn3: "复制第一行结果的第 3 列",
|
||||
|
||||
@@ -10023,6 +10023,7 @@ export default withEnglishFallback({
|
||||
linuxFloatingFrameDescription: "在支援的桌面上自動啟用透明邊框。視窗閃爍時可關閉,套用並重新啟動 DBX 後生效。環境變數設定優先。",
|
||||
showConnectionGroupPath: "顯示查詢連線完整群組路徑",
|
||||
showConnectionGroupPathDescription: "開啟後,查詢頁面右上角的連線選擇器會在連線名稱前顯示完整群組路徑;關閉後僅顯示連線名稱。",
|
||||
shortcutCommitTransaction: "提交交易",
|
||||
shortcutCopyResultColumn1: "複製結果第一列的第 1 欄",
|
||||
shortcutCopyResultColumn2: "複製結果第一列的第 2 欄",
|
||||
shortcutCopyResultColumn3: "複製結果第一列的第 3 欄",
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
isCaretBrowsingShortcut,
|
||||
shouldBlockCaretBrowsing,
|
||||
isConvertNamingStyleShortcut,
|
||||
isCommitTransactionShortcut,
|
||||
copyResultColumnIndexFromShortcut,
|
||||
isEditCellShortcut,
|
||||
isEditSidebarTableStructureShortcut,
|
||||
@@ -345,6 +346,17 @@ describe("keyboard shortcut matching", () => {
|
||||
expect(matcher({ key, altKey: true, isComposing: true }, shortcuts)).toBe(false);
|
||||
expect(matcher({ key, altKey: true })).toBe(false);
|
||||
});
|
||||
|
||||
it("matches only the configured commit-transaction shortcut", () => {
|
||||
const shortcuts = { commitTransaction: "Shift+Mod+C" } as const;
|
||||
|
||||
expect(isCommitTransactionShortcut({ key: "C", ctrlKey: true, shiftKey: true }, shortcuts)).toBe(true);
|
||||
expect(isCommitTransactionShortcut({ key: "C", ctrlKey: true, shiftKey: true })).toBe(false);
|
||||
expect(isCommitTransactionShortcut({ key: "C", ctrlKey: true }, shortcuts)).toBe(false);
|
||||
expect(isCommitTransactionShortcut({ key: "C", shiftKey: true }, shortcuts)).toBe(false);
|
||||
expect(isCommitTransactionShortcut({ key: "C", ctrlKey: true, shiftKey: true }, { commitTransaction: "" })).toBe(false);
|
||||
expect(isCommitTransactionShortcut({ key: "C", ctrlKey: true, shiftKey: true, isComposing: true }, shortcuts)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("copyResultColumnIndexFromShortcut", () => {
|
||||
|
||||
@@ -54,6 +54,16 @@ describe("shortcutRegistry editor actions", () => {
|
||||
];
|
||||
const sidebarShortcutActionIds: ShortcutActionId[] = ["copySidebarSelection", "pasteSidebarSelection", "editSidebarConnection", "disconnectSidebarConnection", "viewTableDdl", "editSidebarTableStructure"];
|
||||
|
||||
it("registers commit transaction as an unassigned global shortcut", () => {
|
||||
expect(SHORTCUT_DEFINITIONS.find((item) => item.id === "commitTransaction")).toMatchObject({
|
||||
id: "commitTransaction",
|
||||
labelKey: "settings.shortcutCommitTransaction",
|
||||
scope: "global",
|
||||
defaultShortcut: "",
|
||||
});
|
||||
expect(normalizeShortcutSettings().commitTransaction).toBe("");
|
||||
});
|
||||
|
||||
it("registers convert-selection-to-delimited as an editor shortcut", () => {
|
||||
expect(SHORTCUT_DEFINITIONS.find((item) => item.id === "convertSelectionToDelimited")).toMatchObject({
|
||||
id: "convertSelectionToDelimited",
|
||||
|
||||
@@ -335,6 +335,10 @@ export function isRefreshDataShortcut(event: ShortcutLikeEvent, shortcuts?: Part
|
||||
return matchesShortcut(event, actionShortcut("refreshData", shortcuts));
|
||||
}
|
||||
|
||||
export function isCommitTransactionShortcut(event: ShortcutLikeEvent, shortcuts?: Partial<ShortcutSettings>): boolean {
|
||||
return matchesShortcut(event, actionShortcut("commitTransaction", shortcuts));
|
||||
}
|
||||
|
||||
/**
|
||||
* Sidebar tree refresh predates the configurable `refreshData` binding and also
|
||||
* accepted Ctrl/Cmd+R. Keep that alias only while the user runs the default
|
||||
|
||||
@@ -121,6 +121,7 @@ export type ShortcutActionId =
|
||||
| "createSidebarDatabase"
|
||||
| "sendSelectionToAi"
|
||||
| "sqlIntentionActions"
|
||||
| "commitTransaction"
|
||||
| "copyResultColumn1"
|
||||
| "copyResultColumn2"
|
||||
| "copyResultColumn3"
|
||||
@@ -794,6 +795,12 @@ export const SHORTCUT_DEFINITIONS: ShortcutDefinition[] = [
|
||||
scope: "global",
|
||||
defaultShortcut: "F5",
|
||||
},
|
||||
{
|
||||
id: "commitTransaction",
|
||||
labelKey: "settings.shortcutCommitTransaction",
|
||||
scope: "global",
|
||||
defaultShortcut: "",
|
||||
},
|
||||
{
|
||||
id: "copyResultColumn1",
|
||||
labelKey: "settings.shortcutCopyResultColumn1",
|
||||
|
||||
Reference in new issue
Block a user