fix(sidebar): improve connection multi-select actions

This commit is contained in:
zipg authored and GitHub committed 2026-08-12 20:17:57 +08:00
1 parent 668c5ddadb
commit 105920047a
24 files changed
+510 -44

No files matched your search

@@ -0,0 +1,23 @@
import { describe, expect, it, vi } from "vitest";
import { disconnectSidebarConnections } from "@/lib/sidebar/sidebarConnectionDisconnect";
describe("sidebar connection disconnect", () => {
it("attempts every connection and reports success", async () => {
const disconnect = vi.fn().mockResolvedValue(undefined);
const result = await disconnectSidebarConnections(["conn-1", "conn-2"], disconnect);
expect(disconnect.mock.calls).toEqual([["conn-1"], ["conn-2"]]);
expect(result).toEqual({ succeeded: 2, failed: 0, firstError: undefined });
});
it("continues after a failure and retains the first error", async () => {
const firstError = new Error("first failed");
const disconnect = vi.fn().mockRejectedValueOnce(firstError).mockResolvedValueOnce(undefined).mockRejectedValueOnce(new Error("last failed"));
const result = await disconnectSidebarConnections(["conn-1", "conn-2", "conn-3"], disconnect);
expect(disconnect).toHaveBeenCalledTimes(3);
expect(result).toEqual({ succeeded: 1, failed: 2, firstError });
});
});
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { applyConnectionMultiSelection, connectionMultiSelectionAfterToggle, emptyConnectionMultiSelection, releaseConnectionFromMultiSelection } from "@/lib/sidebar/sidebarConnectionMultiSelect";
import { applyConnectionMultiSelection, applyTreeNodeSelection, connectionMultiSelectionAfterToggle, emptyConnectionMultiSelection, isExitConnectionMultiSelectionShortcut, releaseConnectionFromMultiSelection } from "@/lib/sidebar/sidebarConnectionMultiSelect";
import type { ConnectionMultiSelection, ConnectionMultiSelectionTarget } from "@/lib/sidebar/sidebarConnectionMultiSelect";
function tick(selection: ConnectionMultiSelection, ...connectionIds: string[]): ConnectionMultiSelection {
@@ -11,6 +11,21 @@ function target(): ConnectionMultiSelectionTarget {
}
describe("connection multi-selection", () => {
it("uses plain Escape to exit connection multi-select", () => {
const event = (key: string, modifiers: Partial<Pick<KeyboardEvent, "metaKey" | "ctrlKey" | "altKey" | "shiftKey">> = {}) => ({
key,
metaKey: false,
ctrlKey: false,
altKey: false,
shiftKey: false,
...modifiers,
});
expect(isExitConnectionMultiSelectionShortcut(event("Escape"))).toBe(true);
expect(isExitConnectionMultiSelectionShortcut(event("Escape", { metaKey: true }))).toBe(false);
expect(isExitConnectionMultiSelectionShortcut(event("Enter"))).toBe(false);
});
it("adds each ticked connection to the running selection", () => {
const selection = tick(emptyConnectionMultiSelection(), "conn-1", "conn-2", "conn-3");
@@ -49,6 +64,24 @@ describe("connection multi-selection", () => {
});
});
it("enables checkbox mode for a modifier-key selection containing only connections", () => {
const store = target();
applyTreeNodeSelection(store, { nodeIds: ["conn-1", "conn-2"], activeNodeId: "conn-2", anchorNodeId: "conn-2" }, new Set(["conn-1", "conn-2"]));
expect(store.selectedTreeNodeIds).toEqual(["conn-1", "conn-2"]);
expect(store.connectionMultiSelectActive).toBe(true);
});
it("keeps mixed modifier-key selections out of connection checkbox mode", () => {
const store = target();
applyTreeNodeSelection(store, { nodeIds: ["conn-1", "database-1"], activeNodeId: "database-1", anchorNodeId: "conn-1" }, new Set(["conn-1", "conn-2"]));
expect(store.selectedTreeNodeIds).toEqual(["conn-1", "database-1"]);
expect(store.connectionMultiSelectActive).toBe(false);
});
it("clears every tree selection field when the selection is released", () => {
const store = target();
applyConnectionMultiSelection(store, tick(emptyConnectionMultiSelection(), "conn-1"));
@@ -1,5 +1,5 @@
import { describe, expect, it, vi } from "vitest";
import { copySelectedConnectionsToClipboards, selectedConnectionDeleteTargets, selectedConnectionDuplicateTargets } from "@/lib/sidebar/sidebarConnectionSelection";
import { copySelectedConnectionsToClipboards, selectedConnectionDeleteTargets, selectedConnectionDisconnectTargets, selectedConnectionDuplicateTargets } from "@/lib/sidebar/sidebarConnectionSelection";
import type { TreeNode } from "@/types/database";
function node(id: string, type: TreeNode["type"] = "connection"): TreeNode {
@@ -31,6 +31,14 @@ describe("sidebar connection selection", () => {
const selected = [current, node("conn-2")];
expect(selectedConnectionDuplicateTargets(current, selected)).toEqual(selectedConnectionDeleteTargets(current, selected));
expect(selectedConnectionDisconnectTargets(current, selected)).toEqual(selectedConnectionDeleteTargets(current, selected));
});
it("disconnects only the right-clicked connection when it is outside the selection", () => {
const current = node("conn-3");
const selected = [node("conn-1"), node("conn-2")];
expect(selectedConnectionDisconnectTargets(current, selected).map((item) => item.connectionId)).toEqual(["conn-3"]);
});
it("copies selected connection names to the system clipboard for the sidebar copy shortcut", () => {
@@ -0,0 +1,59 @@
import { describe, expect, it } from "vitest";
import { filterSidebarModifierSelectionIds, selectedSidebarBatchTargets, supportsSidebarModifierSelection } from "@/lib/sidebar/sidebarTreeSelection";
import type { TreeNode } from "@/types/database";
function node(id: string, type: TreeNode["type"]): TreeNode {
return { id, label: id, type };
}
describe("sidebar modifier selection", () => {
it("disables modifier selection for database, schema, and object-group nodes", () => {
expect(supportsSidebarModifierSelection(node("database-1", "database"))).toBe(false);
expect(supportsSidebarModifierSelection(node("schema-1", "schema"))).toBe(false);
expect(supportsSidebarModifierSelection(node("tables-1", "group-tables"))).toBe(false);
expect(supportsSidebarModifierSelection(node("views-1", "group-views"))).toBe(false);
});
it("keeps nodes with existing connection and object bulk actions selectable", () => {
expect(supportsSidebarModifierSelection(node("connection-1", "connection"))).toBe(true);
expect(supportsSidebarModifierSelection(node("table-1", "table"))).toBe(true);
expect(supportsSidebarModifierSelection(node("index-1", "index"))).toBe(true);
});
it("excludes containers reached indirectly by a modifier selection", () => {
const nodes = [node("tables-1", "group-tables"), node("table-1", "table"), node("schema-1", "schema"), node("database-1", "database"), node("table-2", "table")];
expect(
filterSidebarModifierSelectionIds(
nodes,
nodes.map((item) => item.id),
),
).toEqual(["table-1", "table-2"]);
});
});
describe("sidebar batch action targets", () => {
const table = (id: string, connectionId = "connection-1", database = "database-1"): TreeNode => ({
id,
label: id,
type: "table",
connectionId,
database,
});
it("keeps selected tables from the same database when the context target is selected", () => {
const first = table("table-1");
const second = table("table-2");
expect(selectedSidebarBatchTargets(second, [first, second], () => true)).toEqual([first, second]);
});
it("rejects stale, cross-database, and unsupported selections", () => {
const first = table("table-1");
const second = table("table-2");
expect(selectedSidebarBatchTargets(table("outside"), [first, second], () => true)).toEqual([]);
expect(selectedSidebarBatchTargets(second, [first, table("other", "connection-1", "database-2")], () => true)).toEqual([]);
expect(selectedSidebarBatchTargets(second, [first, second], (target) => target.id !== second.id)).toEqual([]);
});
});
@@ -0,0 +1,16 @@
export interface SidebarConnectionDisconnectResult {
succeeded: number;
failed: number;
firstError?: unknown;
}
export async function disconnectSidebarConnections(connectionIds: readonly string[], disconnect: (connectionId: string) => Promise<unknown>): Promise<SidebarConnectionDisconnectResult> {
const results = await Promise.allSettled(connectionIds.map((connectionId) => disconnect(connectionId)));
const failures = results.filter((result): result is PromiseRejectedResult => result.status === "rejected");
return {
succeeded: results.length - failures.length,
failed: failures.length,
firstError: failures[0]?.reason,
};
}
@@ -21,6 +21,16 @@ export type ConnectionMultiSelectionTarget = {
connectionMultiSelectActive: boolean;
};
export type TreeNodeSelection = {
nodeIds: string[];
activeNodeId: string | null;
anchorNodeId: string | null;
};
export function isExitConnectionMultiSelectionShortcut(event: Pick<KeyboardEvent, "key" | "metaKey" | "ctrlKey" | "altKey" | "shiftKey">): boolean {
return event.key === "Escape" && !event.metaKey && !event.ctrlKey && !event.altKey && !event.shiftKey;
}
export function emptyConnectionMultiSelection(): ConnectionMultiSelection {
return { connectionIds: [], activeConnectionId: null, anchorConnectionId: null, active: false };
}
@@ -51,6 +61,18 @@ export function applyConnectionMultiSelection(target: ConnectionMultiSelectionTa
target.connectionMultiSelectActive = selection.active;
}
/**
* Keep modifier-key connection selection aligned with the checkbox mode. Mixed
* tree selections remain regular tree selections because connection-only bulk
* actions must never consume database or object nodes.
*/
export function applyTreeNodeSelection(target: ConnectionMultiSelectionTarget, selection: TreeNodeSelection, connectionIds: ReadonlySet<string>): void {
target.selectedTreeNodeIds = selection.nodeIds;
target.selectedTreeNodeId = selection.activeNodeId;
target.treeSelectionAnchorId = selection.anchorNodeId;
target.connectionMultiSelectActive = selection.nodeIds.length > 0 && selection.nodeIds.every((id) => connectionIds.has(id));
}
export function releaseConnectionFromMultiSelection(target: ConnectionMultiSelectionTarget, connectionId: string): void {
if (!target.connectionMultiSelectActive || !target.selectedTreeNodeIds.includes(connectionId)) return;
@@ -24,6 +24,10 @@ export function selectedConnectionDuplicateTargets(currentNode: TreeNode, select
return selectedConnectionActionTargets(currentNode, selectedNodes);
}
export function selectedConnectionDisconnectTargets(currentNode: TreeNode, selectedNodes: TreeNode[]): ConnectionTreeNode[] {
return selectedConnectionActionTargets(currentNode, selectedNodes);
}
export function selectedConnectionClipboardTargets(currentNode: TreeNode, selectedNodes: TreeNode[]): ConnectionTreeNode[] {
return selectedConnectionActionTargets(currentNode, selectedNodes);
}
@@ -1,11 +1,28 @@
import type { TreeNode } from "@/types/database";
export function supportsSidebarModifierSelection(node: Pick<TreeNode, "type">): boolean {
return node.type !== "database" && node.type !== "schema" && !node.type.startsWith("group-");
}
export function filterSidebarModifierSelectionIds(nodes: readonly TreeNode[], nodeIds: readonly string[]): string[] {
const selectableIds = new Set(nodes.filter(supportsSidebarModifierSelection).map((node) => node.id));
return nodeIds.filter((id) => selectableIds.has(id));
}
export function selectedTreeNodesInVisibleOrder(visibleNodes: TreeNode[], selectedIds: Iterable<string>): TreeNode[] {
const ids = new Set(selectedIds);
if (!ids.size) return [];
return visibleNodes.filter((node) => ids.has(node.id));
}
export function selectedSidebarBatchTargets(activeNode: TreeNode, selectedNodes: readonly TreeNode[], canUseTarget: (node: TreeNode) => boolean): TreeNode[] {
if (selectedNodes.length <= 1 || !selectedNodes.some((node) => node.id === activeNode.id)) return [];
const first = selectedNodes[0];
if (!first?.connectionId || !first.database || !selectedNodes.every((node) => node.type === first.type)) return [];
if (!selectedNodes.every((node) => node.connectionId === first.connectionId && node.database === first.database && canUseTarget(node))) return [];
return [...selectedNodes];
}
export function treeSelectionRangeIdsByIndex(visibleNodes: TreeNode[], currentIndex: number, anchorIndex: number, currentId?: string): string[] {
if (anchorIndex < 0 || currentIndex < 0) return currentId ? [currentId] : [];
const start = Math.min(anchorIndex, currentIndex);