feat(config): group connection export selection

This commit is contained in:
onenewcode authored and GitHub committed 2026-10-02 23:46:01 +08:00
1 parent ef16749339
commit fdb8e37a48
4 files changed
+151 -16

No files matched your search

@@ -1,19 +1,20 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, ref, watch } from "vue"; import { computed, ref, watch } from "vue";
import { useI18n } from "vue-i18n"; import { useI18n } from "vue-i18n";
import { Loader2 } from "@lucide/vue"; import { ChevronDown, ChevronRight, Folder, Loader2 } from "@lucide/vue";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"; import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { ScrollArea } from "@/components/ui/scroll-area"; import { ScrollArea } from "@/components/ui/scroll-area";
import DatabaseIcon from "@/components/icons/DatabaseIcon.vue"; import DatabaseIcon from "@/components/icons/DatabaseIcon.vue";
import { connectionDriverLabel, connectionEndpointLabel, connectionIconType } from "@/lib/connection/connectionPresentation"; import { connectionDriverLabel, connectionEndpointLabel, connectionIconType } from "@/lib/connection/connectionPresentation";
import type { ConnectionConfig } from "@/types/database"; import type { ConnectionConfig, SidebarLayout, SidebarOrderEntry } from "@/types/database";
const props = defineProps<{ const props = defineProps<{
open: boolean; open: boolean;
mode: "export" | "import"; mode: "export" | "import";
busy?: boolean; busy?: boolean;
connections: ConnectionConfig[]; connections: ConnectionConfig[];
layout?: SidebarLayout | null;
}>(); }>();
const emit = defineEmits<{ const emit = defineEmits<{
@@ -23,6 +24,7 @@ const emit = defineEmits<{
const { t } = useI18n(); const { t } = useI18n();
const selectedIds = ref<string[]>([]); const selectedIds = ref<string[]>([]);
const expandedGroupIds = ref<Set<string>>(new Set());
const dialogOpen = computed({ const dialogOpen = computed({
get: () => props.open, get: () => props.open,
@@ -36,10 +38,62 @@ const connectionIds = computed(() => props.connections.map((connection) => conne
const selectedCount = computed(() => selectedIds.value.length); const selectedCount = computed(() => selectedIds.value.length);
const canConfirm = computed(() => selectedCount.value > 0); const canConfirm = computed(() => selectedCount.value > 0);
type TreeRow = { type: "group"; id: string; name: string; depth: number } | { type: "connection"; id: string; depth: number };
function entryChildren(entry: Extract<SidebarOrderEntry, { type: "group" }>): SidebarOrderEntry[] {
return entry.children ?? entry.connectionIds?.map((id) => ({ type: "connection" as const, id })) ?? [];
}
const connectionIdSet = computed(() => new Set(connectionIds.value));
const groupNames = computed(() => new Map((props.layout?.groups ?? []).map((group) => [group.id, group.name])));
const groupConnectionIds = computed(() => {
const result = new Map<string, string[]>();
const collect = (entry: SidebarOrderEntry): string[] => {
if (entry.type === "connection") return connectionIdSet.value.has(entry.id) ? [entry.id] : [];
const ids = entryChildren(entry).flatMap(collect);
result.set(entry.id, ids);
return ids;
};
for (const entry of props.layout?.order ?? []) collect(entry);
return result;
});
const treeRows = computed<TreeRow[]>(() => {
if (!props.layout?.order?.length) return props.connections.map((connection) => ({ type: "connection", id: connection.id, depth: 0 }));
const rows: TreeRow[] = [];
const coveredConnections = new Set<string>();
const renderedConnections = new Set<string>();
const visit = (entries: SidebarOrderEntry[], depth: number) => {
for (const entry of entries) {
if (entry.type === "connection") {
if (!connectionIdSet.value.has(entry.id) || renderedConnections.has(entry.id)) continue;
renderedConnections.add(entry.id);
rows.push({ type: "connection", id: entry.id, depth });
continue;
}
const ids = groupConnectionIds.value.get(entry.id) ?? [];
const name = groupNames.value.get(entry.id);
if (!name || ids.length === 0) continue;
rows.push({ type: "group", id: entry.id, name, depth });
for (const connectionId of ids) coveredConnections.add(connectionId);
if (expandedGroupIds.value.has(entry.id)) visit(entryChildren(entry), depth + 1);
}
};
visit(props.layout.order, 0);
for (const connection of props.connections) {
if (!coveredConnections.has(connection.id) && !renderedConnections.has(connection.id)) rows.push({ type: "connection", id: connection.id, depth: 0 });
}
return rows;
});
watch( watch(
() => [props.open, props.connections] as const, () => [props.open, props.connections] as const,
([open]) => { ([open]) => {
if (open) selectedIds.value = [...connectionIds.value]; if (open) {
selectedIds.value = [...connectionIds.value];
expandedGroupIds.value = new Set(props.layout?.groups.map((group) => group.id) ?? []);
}
}, },
{ immediate: true }, { immediate: true },
); );
@@ -64,6 +118,33 @@ function deselectAll() {
selectedIds.value = []; selectedIds.value = [];
} }
function toggleGroupExpanded(id: string) {
const expanded = new Set(expandedGroupIds.value);
if (expanded.has(id)) expanded.delete(id);
else expanded.add(id);
expandedGroupIds.value = expanded;
}
function groupSelectionState(id: string) {
const ids = groupConnectionIds.value.get(id) ?? [];
const selected = ids.filter((connectionId) => selectedIds.value.includes(connectionId)).length;
return { checked: ids.length > 0 && selected === ids.length, indeterminate: selected > 0 && selected < ids.length, disabled: ids.length === 0 };
}
function toggleGroup(id: string, checked: boolean) {
const descendants = groupConnectionIds.value.get(id) ?? [];
const selected = new Set(selectedIds.value);
for (const connectionId of descendants) {
if (checked) selected.add(connectionId);
else selected.delete(connectionId);
}
selectedIds.value = connectionIds.value.filter((connectionId) => selected.has(connectionId));
}
function connectionById(id: string) {
return props.connections.find((connection) => connection.id === id);
}
function confirm() { function confirm() {
if (!canConfirm.value || props.busy) return; if (!canConfirm.value || props.busy) return;
emit("confirm", [...selectedIds.value]); emit("confirm", [...selectedIds.value]);
@@ -95,14 +176,32 @@ function connectionMeta(connection: ConnectionConfig) {
<div v-if="connections.length === 0" class="px-3 py-8 text-center text-sm text-muted-foreground"> <div v-if="connections.length === 0" class="px-3 py-8 text-center text-sm text-muted-foreground">
{{ t("configExport.noConnections") }} {{ t("configExport.noConnections") }}
</div> </div>
<label v-for="connection in connections" :key="connection.id" class="flex cursor-pointer items-start gap-3 border-b px-3 py-2 last:border-b-0 hover:bg-muted/50"> <template v-for="row in treeRows" :key="`${row.type}:${row.id}`">
<input type="checkbox" class="mt-1 accent-primary shrink-0" :checked="isSelected(connection.id)" :disabled="busy" @change="toggle(connection.id, ($event.target as HTMLInputElement).checked)" /> <div v-if="row.type === 'group'" class="flex items-center gap-2 border-b px-3 py-2 hover:bg-muted/50" :style="{ paddingLeft: `${12 + row.depth * 20}px` }">
<DatabaseIcon :db-type="connectionIconType(connection)" class="mt-0.5 h-4 w-4 shrink-0" /> <button type="button" class="flex h-4 w-4 shrink-0 items-center justify-center text-muted-foreground" :disabled="busy" :aria-label="row.name" :aria-expanded="expandedGroupIds.has(row.id)" @click="toggleGroupExpanded(row.id)">
<span class="min-w-0 flex-1"> <ChevronDown v-if="expandedGroupIds.has(row.id)" class="h-3.5 w-3.5" />
<span class="block truncate text-sm font-medium">{{ connection.name }}</span> <ChevronRight v-else class="h-3.5 w-3.5" />
<span class="block truncate text-xs text-muted-foreground">{{ connectionMeta(connection) }}</span> </button>
</span> <input
</label> type="checkbox"
class="accent-primary shrink-0"
:checked="groupSelectionState(row.id).checked"
:indeterminate="groupSelectionState(row.id).indeterminate"
:disabled="busy || groupSelectionState(row.id).disabled"
@change="toggleGroup(row.id, ($event.target as HTMLInputElement).checked)"
/>
<Folder class="h-4 w-4 shrink-0 text-muted-foreground" />
<span class="min-w-0 flex-1 truncate text-sm font-medium">{{ row.name }}</span>
</div>
<label v-else-if="connectionById(row.id)" class="flex cursor-pointer items-start gap-3 border-b px-3 py-2 last:border-b-0 hover:bg-muted/50" :style="{ paddingLeft: `${48 + row.depth * 20}px` }">
<input type="checkbox" class="mt-1 accent-primary shrink-0" :checked="isSelected(row.id)" :disabled="busy" @change="toggle(row.id, ($event.target as HTMLInputElement).checked)" />
<DatabaseIcon :db-type="connectionIconType(connectionById(row.id)!)" class="mt-0.5 h-4 w-4 shrink-0" />
<span class="min-w-0 flex-1">
<span class="block truncate text-sm font-medium">{{ connectionById(row.id)!.name }}</span>
<span class="block truncate text-xs text-muted-foreground">{{ connectionMeta(connectionById(row.id)!) }}</span>
</span>
</label>
</template>
</ScrollArea> </ScrollArea>
</div> </div>
@@ -3,7 +3,7 @@
import { createApp, defineComponent, h, nextTick, type App } from "vue"; import { createApp, defineComponent, h, nextTick, type App } from "vue";
import { afterEach, describe, expect, it, vi } from "vitest"; import { afterEach, describe, expect, it, vi } from "vitest";
import i18n from "@/i18n"; import i18n from "@/i18n";
import type { ConnectionConfig } from "@/types/database"; import type { ConnectionConfig, SidebarLayout } from "@/types/database";
vi.mock("@/components/ui/dialog", async () => { vi.mock("@/components/ui/dialog", async () => {
const { defineComponent, h } = await import("vue"); const { defineComponent, h } = await import("vue");
@@ -176,4 +176,34 @@ describe("ConfigConnectionSelectDialog", () => {
expect(document.body.textContent).toContain(longHost); expect(document.body.textContent).toContain(longHost);
expect([...document.body.querySelectorAll("button")].some((button) => button.textContent?.includes("Next"))).toBe(true); expect([...document.body.querySelectorAll("button")].some((button) => button.textContent?.includes("Next"))).toBe(true);
}); });
it("selects the connections inside a group from the tree", async () => {
i18n.global.locale.value = "en";
const layout: SidebarLayout = {
groups: [{ id: "production", name: "Production", collapsed: false }],
order: [
{ type: "group", id: "production", children: [{ type: "connection", id: "a" }] },
{ type: "connection", id: "b" },
],
};
const { onConfirm } = await mountDialog({
open: true,
mode: "export",
connections: [conn("a", "Alpha"), conn("b", "Beta")],
layout,
});
expect(document.body.textContent).toContain("Production");
const deselect = [...document.body.querySelectorAll("button")].find((button) => button.textContent?.includes("Deselect all"));
deselect?.click();
await nextTick();
const checkboxes = [...document.querySelectorAll<HTMLInputElement>("input[type='checkbox']")];
expect(checkboxes).toHaveLength(3);
checkboxes[0].click();
await nextTick();
expect(document.body.textContent).toContain("1 / 2");
const confirm = [...document.body.querySelectorAll("button")].find((button) => button.textContent?.includes("Next"));
confirm?.click();
expect(onConfirm).toHaveBeenCalledWith(["a"]);
});
}); });
@@ -351,6 +351,7 @@ watch(
:mode="dialogs.configConnectionSelectMode.value" :mode="dialogs.configConnectionSelectMode.value"
:busy="dialogs.applyingImportSelection.value" :busy="dialogs.applyingImportSelection.value"
:connections="dialogs.configConnectionSelectList.value" :connections="dialogs.configConnectionSelectList.value"
:layout="dialogs.configConnectionSelectLayout.value"
@update:open="dialogs.onConfigConnectionSelectOpenChange" @update:open="dialogs.onConfigConnectionSelectOpenChange"
@confirm="dialogs.onConfigConnectionSelectConfirm" @confirm="dialogs.onConfigConnectionSelectConfirm"
/> />
@@ -38,6 +38,7 @@ const pendingImportContent = ref("");
const showConfigConnectionSelectDialog = ref(false); const showConfigConnectionSelectDialog = ref(false);
const configConnectionSelectMode = ref<"export" | "import">("export"); const configConnectionSelectMode = ref<"export" | "import">("export");
const configConnectionSelectList = ref<ConnectionConfig[]>([]); const configConnectionSelectList = ref<ConnectionConfig[]>([]);
const configConnectionSelectLayout = ref<SidebarLayout | null>(null);
const pendingExportConnectionIds = ref<string[]>([]); const pendingExportConnectionIds = ref<string[]>([]);
const pendingImportPreview = ref<ConnectionConfigBundle | null>(null); const pendingImportPreview = ref<ConnectionConfigBundle | null>(null);
const pendingImportSource = ref<"dbx" | "navicat" | "dbeaver" | "datagrip">("dbx"); const pendingImportSource = ref<"dbx" | "navicat" | "dbeaver" | "datagrip">("dbx");
@@ -396,18 +397,21 @@ export function useDialogSources() {
pendingImportPreview.value = null; pendingImportPreview.value = null;
pendingImportSource.value = "dbx"; pendingImportSource.value = "dbx";
configConnectionSelectList.value = []; configConnectionSelectList.value = [];
configConnectionSelectLayout.value = null;
configPassphraseError.value = ""; configPassphraseError.value = "";
} }
function clearPendingExportState() { function clearPendingExportState() {
pendingExportConnectionIds.value = []; pendingExportConnectionIds.value = [];
configConnectionSelectList.value = []; configConnectionSelectList.value = [];
configConnectionSelectLayout.value = null;
configPassphraseError.value = ""; configPassphraseError.value = "";
} }
function openConnectionSelect(mode: "export" | "import", connections: ConnectionConfig[]) { function openConnectionSelect(mode: "export" | "import", connections: ConnectionConfig[], layout?: SidebarLayout | null) {
configConnectionSelectMode.value = mode; configConnectionSelectMode.value = mode;
configConnectionSelectList.value = connections; configConnectionSelectList.value = connections;
configConnectionSelectLayout.value = layout ?? null;
showConfigConnectionSelectDialog.value = true; showConfigConnectionSelectDialog.value = true;
} }
@@ -435,7 +439,7 @@ export function useDialogSources() {
// Config export/import helpers // Config export/import helpers
function onExportClick() { function onExportClick() {
clearPendingExportState(); clearPendingExportState();
openConnectionSelect("export", connectionStore.connections); openConnectionSelect("export", connectionStore.connections, connectionStore.sidebarLayout);
} }
function onExportConnectionsSelected(connectionIds: string[]) { function onExportConnectionsSelected(connectionIds: string[]) {
@@ -516,7 +520,7 @@ export function useDialogSources() {
const preview = await connectionStore.parseConnectionsImport(result.content, null); const preview = await connectionStore.parseConnectionsImport(result.content, null);
pendingImportPreview.value = preview; pendingImportPreview.value = preview;
if (source === "dbx") { if (source === "dbx") {
openConnectionSelect("import", preview.connections); openConnectionSelect("import", preview.connections, preview.layout);
return; return;
} }
const { count, layout } = await connectionStore.applyConnectionsImport(preview); const { count, layout } = await connectionStore.applyConnectionsImport(preview);
@@ -533,7 +537,7 @@ export function useDialogSources() {
pendingImportPreview.value = preview; pendingImportPreview.value = preview;
showConfigPassphraseDialog.value = false; showConfigPassphraseDialog.value = false;
configPassphraseError.value = ""; configPassphraseError.value = "";
openConnectionSelect("import", preview.connections); openConnectionSelect("import", preview.connections, preview.layout);
} catch (e: any) { } catch (e: any) {
configPassphraseError.value = e?.message === "wrong_passphrase" ? t("configExport.wrongPassphrase") : e?.message === "crypto_unavailable" ? t("configExport.cryptoUnavailable") : e?.message || String(e); configPassphraseError.value = e?.message === "wrong_passphrase" ? t("configExport.wrongPassphrase") : e?.message === "crypto_unavailable" ? t("configExport.cryptoUnavailable") : e?.message || String(e);
} }
@@ -611,6 +615,7 @@ export function useDialogSources() {
applyingImportSelection, applyingImportSelection,
configConnectionSelectMode, configConnectionSelectMode,
configConnectionSelectList, configConnectionSelectList,
configConnectionSelectLayout,
transferPrefillConnectionId, transferPrefillConnectionId,
transferPrefillDatabase, transferPrefillDatabase,
transferPrefillCatalog, transferPrefillCatalog,