feat(sidebar): decompose tree item runtime

This commit is contained in:
t8y2 committed 2026-07-16 22:52:10 +08:00
1 parent 1688ba74cd
commit 6660957153
38 files changed
+6498 -5294

No files matched your search

@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import type { TreeNode } from "@/types/database";
import { createSidebarActionRequest, createSidebarActionTarget, findSidebarActionTarget } from "@/lib/sidebar/sidebarActionTarget";
import { createSidebarActionRequest, createSidebarActionTarget, findSidebarActionTarget, releaseRemovedSidebarActionTarget } from "@/lib/sidebar/sidebarActionTarget";
function tableNode(): TreeNode {
return {
@@ -52,6 +52,21 @@ describe("sidebar action targets", () => {
expect(findSidebarActionTarget([], target)).toBeNull();
});
it("releases a removed active node's child tree", () => {
const node = tableNode();
const released = releaseRemovedSidebarActionTarget(node, [node.id]);
expect(released).not.toBe(node);
expect(released.children).toBeUndefined();
expect(released.hiddenChildren).toBeUndefined();
});
it("keeps an active node that was not removed", () => {
const node = tableNode();
expect(releaseRemovedSidebarActionTarget(node, ["other-node"])).toBe(node);
});
it("resolves targets stored only in hidden children", () => {
const node = tableNode();
const target = createSidebarActionTarget(node);
@@ -0,0 +1,29 @@
import { describe, expect, it } from "vitest";
import type { TreeNode } from "@/types/database";
import { allDatabasesExportSourceForNode, databaseExportSourceForNode, sidebarStructureExportTargets } from "@/lib/sidebar/sidebarExportRuntime";
describe("sidebar export runtime", () => {
it("prepares database and table export sources", () => {
expect(databaseExportSourceForNode({ id: "schema", label: "public", type: "schema", connectionId: "c1", database: "db", schema: "public" })).toEqual({
connectionId: "c1",
database: "db",
schema: "public",
});
expect(databaseExportSourceForNode({ id: "table", label: "users", type: "table", connectionId: "c1", database: "db", schema: "public" })).toEqual({
connectionId: "c1",
database: "db",
schema: "public",
tableName: "users",
});
expect(allDatabasesExportSourceForNode({ id: "c1", label: "Connection", type: "connection", connectionId: "c1" })).toEqual({ connectionId: "c1", database: "", allDatabases: true });
});
it("freezes the accepted structure selection before export work starts", () => {
const first: TreeNode = { id: "t1", label: "one", type: "table", connectionId: "c1", database: "db" };
const second: TreeNode = { id: "t2", label: "two", type: "view", connectionId: "c1", database: "db" };
const group: TreeNode = { id: "group", label: "Tables", type: "group-tables", children: [first, second] };
expect(sidebarStructureExportTargets(first, [group], [first.id, second.id])).toEqual([first, second]);
expect(sidebarStructureExportTargets(first, [group], [second.id])).toEqual([first]);
});
});
@@ -0,0 +1,36 @@
import { describe, expect, it } from "vitest";
import type { ContextMenuItem } from "@/components/ui/CustomContextMenu.vue";
import type { TreeNode, TreeNodeType } from "@/types/database";
import { createSidebarMenuContext, normalizeSidebarMenuDescriptors } from "@/lib/sidebar/sidebarTreeMenuDescriptors";
const representativeTypes: TreeNodeType[] = ["connection", "database", "schema", "table", "column", "mongo-db", "mongo-collection", "redis-db", "nacos-namespace"];
describe("sidebar tree menu descriptors", () => {
it.each(representativeTypes)("normalizes stable descriptors for %s", (type) => {
const node: TreeNode = { id: `${type}-1`, label: type, type };
const items: ContextMenuItem[] = [
{ label: "Open", action: () => undefined },
{ label: "", separator: true },
{ label: "More", children: [{ label: "Delete", variant: "destructive" }] },
];
const descriptors = normalizeSidebarMenuDescriptors(createSidebarMenuContext(node, [node.id]), items);
expect(descriptors).toEqual([
expect.objectContaining({ id: `${type}:0`, label: "Open", disabled: false, separator: false, variant: "default" }),
expect.objectContaining({ id: `${type}:1`, separator: true }),
expect.objectContaining({ id: `${type}:2`, children: [expect.objectContaining({ id: `${type}:2.0`, label: "Delete", variant: "destructive" })] }),
]);
});
it("freezes the accepted target and selection", () => {
const node: TreeNode = { id: "table-1", label: "before", type: "table" };
const selection = [node.id];
const context = createSidebarMenuContext(node, selection, "postgres");
node.label = "after";
selection.push("table-2");
expect(context.target.label).toBe("before");
expect(context.selectedNodeIds).toEqual(["table-1"]);
expect(Object.isFrozen(context)).toBe(true);
});
});
@@ -0,0 +1,65 @@
import { describe, expect, it, vi } from "vitest";
import type { TreeNode } from "@/types/database";
import { createSidebarSelectionSnapshot, createSidebarTreeRuntime, type SidebarTreeRuntimeHost } from "@/lib/sidebar/sidebarTreeRuntime";
function node(id: string, label = id): TreeNode {
return { id, label, type: "table", connectionId: "connection-1", database: "database-1" };
}
function host(): SidebarTreeRuntimeHost {
return {
buildContextMenu: vi.fn(() => []),
handleRowClick: vi.fn(),
handleRowDoubleClick: vi.fn(),
handleRowKeydown: vi.fn(),
openDataInNewTab: vi.fn(),
requestPaste: vi.fn(() => false),
toggleNode: vi.fn(),
};
}
describe("sidebar tree runtime", () => {
it("keeps target and selection snapshots immutable", () => {
const first = node("table-1", "before");
const second = node("table-2");
const selectedIds = [first.id];
const snapshot = createSidebarSelectionSnapshot([first, second], selectedIds);
first.label = "after";
selectedIds.push(second.id);
expect(snapshot.ids).toEqual(["table-1"]);
expect(snapshot.targets).toEqual([expect.objectContaining({ id: "table-1", label: "before" })]);
expect(Object.isFrozen(snapshot)).toBe(true);
expect(Object.isFrozen(snapshot.ids)).toBe(true);
expect(Object.isFrozen(snapshot.targets)).toBe(true);
});
it("shares one host across many row consumers", () => {
const runtime = createSidebarTreeRuntime();
const runtimeHost = host();
runtime.bindHost(runtimeHost);
for (let index = 0; index < 100; index += 1) runtime.handleRowClick(node(`table-${index}`), 1);
expect(runtime.diagnostics.hostBindings).toBe(1);
expect(runtimeHost.handleRowClick).toHaveBeenCalledTimes(100);
});
it("rejects superseded and disposed generations without affecting another runtime", () => {
const runtime = createSidebarTreeRuntime();
const otherRuntime = createSidebarTreeRuntime();
const first = runtime.beginAction();
const unrelated = otherRuntime.beginAction();
const second = runtime.beginAction();
expect(runtime.isCurrent(first)).toBe(false);
expect(runtime.isCurrent(second)).toBe(true);
expect(otherRuntime.isCurrent(unrelated)).toBe(true);
runtime.dispose();
expect(runtime.isCurrent(second)).toBe(false);
expect(otherRuntime.isCurrent(unrelated)).toBe(true);
});
});
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { doubleClickRowAction, resolveRowClickAction, shouldDeferSingleClick, singleClickRowAction, type ObjectBrowserRowAction } from "@/lib/table/objectBrowserRowAction";
import { doubleClickRowAction, resolveRowClickAction, shouldDeferSingleClick, singleClickRowAction } from "@/lib/table/objectBrowserRowAction";
import type { ObjectBrowserRow } from "@/lib/table/objectBrowserRows";
function row(type: ObjectBrowserRow["type"], name = "test"): ObjectBrowserRow {
@@ -70,7 +70,7 @@ export function defaultSqliteBackupFileName(config: Pick<ConnectionConfig, "host
function sanitizeFileName(fileName: string): string {
return fileName
.replace(/[<>:"/\\|?*\u0000-\u001f]/g, "_")
.replace(/[<>:"/\\|?*\p{Cc}]/gu, "_")
.trim()
.replace(/[. ]+$/g, "");
}
@@ -1168,7 +1168,7 @@ export function findGeneratorKey(columnName: string, dataType: string, isAutoInc
const isDateTime = type.includes("date") || type.includes("timestamp") || type === "time";
const isBinary = type.includes("binary") || type.includes("blob") || type.includes("bytea");
const isBoolType = type === "bool" || type === "boolean" || type === "bit" || type === "tinyint(1)";
const isBoolName = /^(is|has|had|can|did|enable|disable|allow|use|visible|deleted|active|flag)[_\-]?/i.test(columnName);
const isBoolName = /^(is|has|had|can|did|enable|disable|allow|use|visible|deleted|active|flag)[_-]?/i.test(columnName);
if (isNumeric || isDateTime || isBinary) {
if (type.includes("serial")) return "sequence";
if (isBoolType || (isNumeric && isBoolName)) return "enum";
@@ -1388,7 +1388,7 @@ export function defaultGeneratorParams(_columnName: string, attrs: ColumnAttrs,
const t = attrs.dataType.toLowerCase();
const isNum = t.includes("int") || t.includes("bool") || t.includes("decimal") || t.includes("numeric") || t.includes("float") || t.includes("double") || t === "real";
const isBoolType = t === "bool" || t === "boolean" || t === "bit" || t === "tinyint(1)";
const isBoolName = /^(is|has|had|can|did|enable|disable|allow|use|visible|deleted|active|flag)[_\-]?/i.test(_columnName);
const isBoolName = /^(is|has|had|can|did|enable|disable|allow|use|visible|deleted|active|flag)[_-]?/i.test(_columnName);
if (isBoolType || (isNum && isBoolName)) {
params.values = "0\n1";
} else if (isNum) {
@@ -23,7 +23,8 @@ export function mysqlCleartextPasswordAuthEnabled(params: string | undefined): b
export function setMysqlCleartextPasswordAuthEnabled(params: string | undefined, enabled: boolean): string {
const parsed = new URLSearchParams((params || "").trim().replace(/^\?/, ""));
for (const key of [...parsed.keys()]) {
// Snapshot keys because deleting from URLSearchParams during live iteration can skip duplicates.
for (const key of Array.from(parsed.keys())) {
if (isMysqlCleartextPasswordParam(key)) parsed.delete(key);
}
if (enabled) parsed.set(MYSQL_CLEAR_TEXT_PARAM, "true");
+1 -1
View File
@@ -84,7 +84,7 @@ function withDuplicateSuffix(fileName: string, index: number): string {
function sanitizePathStem(value: string): string {
return value
.trim()
.replace(/[<>:"/\\|?*\u0000-\u001f]+/g, "-")
.replace(/[<>:"/\\|?*\p{Cc}]+/gu, "-")
.replace(/\s+/g, "-")
.replace(/-+/g, "-")
.replace(/^[-.\s]+|[-.\s]+$/g, "")
+1 -1
View File
@@ -85,7 +85,7 @@ export function resolveNacosConfigCopyText(selectionText: string, editorText: st
export function sanitizeNacosConfigFileNameSegment(value: string): string {
const sanitized = value
.trim()
.replace(/[<>:"/\\|?*\x00-\x1f]/g, "_")
.replace(/[<>:"/\\|?*\p{Cc}]/gu, "_")
.replace(/\s+/g, " ")
.replace(/^[._\s-]+/, "")
.replace(/\.+$/, "");
@@ -36,6 +36,11 @@ export function createSidebarActionTarget(node: TreeNode): SidebarActionTarget {
return Object.freeze({ ...node, children: undefined, hiddenChildren: undefined, meta });
}
export function releaseRemovedSidebarActionTarget(node: TreeNode, removedNodeIds: readonly string[]): TreeNode {
if (!removedNodeIds.includes(node.id)) return node;
return { ...createSidebarActionTarget(node) };
}
export function createSidebarActionRequest<TPayload>(node: TreeNode, selectedNodeIds: readonly string[], payload: TPayload): SidebarActionRequest<TPayload> {
return Object.freeze({
target: createSidebarActionTarget(node),
@@ -153,7 +153,7 @@ export function runSidebarDataOpenImmediately(optionsOrRunner: SidebarDataOpenOp
}
export function cancelPendingSidebarDataOpen() {
for (const request of [...requests.values()]) cancelRequest(request);
for (const request of Array.from(requests.values())) cancelRequest(request);
latestSupersedingRequestId = 0;
}
@@ -0,0 +1,43 @@
import type { TreeNode } from "@/types/database";
export interface SidebarDatabaseExportSource {
connectionId: string;
database: string;
schema?: string;
tableName?: string;
tableNames?: string[];
allDatabases?: boolean;
}
export function databaseExportSourceForNode(node: TreeNode): SidebarDatabaseExportSource | null {
if (!node.connectionId || !node.database) return null;
const objectNode = node.type === "table" || node.type === "view" || node.type === "materialized_view";
return {
connectionId: node.connectionId,
database: node.database,
schema: node.type === "schema" || objectNode ? node.schema : undefined,
tableName: objectNode ? node.label : undefined,
};
}
export function allDatabasesExportSourceForNode(node: TreeNode): SidebarDatabaseExportSource | null {
if (node.type !== "connection" || !node.connectionId) return null;
return { connectionId: node.connectionId, database: "", allDatabases: true };
}
export function sidebarStructureExportTargets(activeNode: TreeNode, treeNodes: readonly TreeNode[], selectedNodeIds: readonly string[]): Array<TreeNode & { connectionId: string; database: string }> {
const canExport = (node: TreeNode): node is TreeNode & { connectionId: string; database: string } => (node.type === "table" || node.type === "view" || node.type === "materialized_view") && !!node.connectionId && !!node.database;
if (!canExport(activeNode)) return [];
const selected = new Set(selectedNodeIds);
const targets: Array<TreeNode & { connectionId: string; database: string }> = [];
const visit = (nodes: readonly TreeNode[]) => {
for (const node of nodes) {
if (selected.has(node.id) && canExport(node)) targets.push(node);
if (node.children) visit(node.children);
if (node.hiddenChildren) visit(node.hiddenChildren);
}
};
visit(treeNodes);
return targets.length > 1 && targets.some((node) => node.id === activeNode.id) ? targets : [activeNode];
}
@@ -0,0 +1,44 @@
import type { ContextMenuItem } from "@/components/ui/CustomContextMenu.vue";
import type { DatabaseType, TreeNode, TreeNodeType } from "@/types/database";
import { createSidebarActionTarget, type SidebarActionTarget } from "./sidebarActionTarget";
export type SidebarMenuActionId = `${TreeNodeType}:${string}`;
export interface SidebarMenuContext {
readonly target: SidebarActionTarget;
readonly selectedNodeIds: readonly string[];
readonly databaseType?: DatabaseType;
}
export interface SidebarMenuDescriptor {
readonly id: SidebarMenuActionId;
readonly label: string;
readonly disabled: boolean;
readonly separator: boolean;
readonly variant: "default" | "destructive";
readonly children: readonly SidebarMenuDescriptor[];
}
export function createSidebarMenuContext(node: TreeNode, selectedNodeIds: readonly string[], databaseType?: DatabaseType): SidebarMenuContext {
return Object.freeze({
target: createSidebarActionTarget(node),
selectedNodeIds: Object.freeze([...selectedNodeIds]),
databaseType,
});
}
export function normalizeSidebarMenuDescriptors(context: SidebarMenuContext, items: readonly ContextMenuItem[]): readonly SidebarMenuDescriptor[] {
const normalize = (entries: readonly ContextMenuItem[], parentPath: string): SidebarMenuDescriptor[] =>
entries.map((item, index) => {
const path = parentPath ? `${parentPath}.${index}` : String(index);
return Object.freeze({
id: `${context.target.type}:${path}` as SidebarMenuActionId,
label: item.label,
disabled: item.disabled === true,
separator: item.separator === true,
variant: item.variant ?? "default",
children: Object.freeze(normalize(item.children ?? [], path)),
});
});
return Object.freeze(normalize(items, ""));
}
@@ -0,0 +1,116 @@
import type { ComponentPublicInstance, InjectionKey } from "vue";
import type { ContextMenuItem } from "@/components/ui/CustomContextMenu.vue";
import type { TreeNode } from "@/types/database";
import { createSidebarActionTarget, type SidebarActionTarget } from "./sidebarActionTarget";
export interface SidebarSelectionSnapshot {
readonly ids: readonly string[];
readonly targets: readonly SidebarActionTarget[];
}
export interface SidebarTreeRuntimeGeneration {
readonly runtimeId: symbol;
readonly generation: number;
}
export interface SidebarTreeRuntimeHost {
buildContextMenu(node: TreeNode): ContextMenuItem[];
handleRowClick(node: TreeNode, clickDetail: number): void;
handleRowDoubleClick(node: TreeNode, event: MouseEvent): void;
handleRowKeydown(node: TreeNode, event: KeyboardEvent): void;
openDataInNewTab(node: TreeNode): void;
requestPaste(node: TreeNode): boolean;
toggleNode(node: TreeNode): void;
}
export type SidebarTreeRuntimeHostInstance = ComponentPublicInstance & SidebarTreeRuntimeHost;
export interface SidebarTreeRuntime {
readonly runtimeId: symbol;
readonly diagnostics: {
readonly hostBindings: number;
readonly menuBuilds: number;
};
bindHost(host: SidebarTreeRuntimeHost | null): void;
beginAction(): SidebarTreeRuntimeGeneration;
isCurrent(token: SidebarTreeRuntimeGeneration): boolean;
buildContextMenu(node: TreeNode): ContextMenuItem[];
handleRowClick(node: TreeNode, clickDetail: number): void;
handleRowDoubleClick(node: TreeNode, event: MouseEvent): void;
handleRowKeydown(node: TreeNode, event: KeyboardEvent): void;
openDataInNewTab(node: TreeNode): void;
requestPaste(node: TreeNode): boolean;
toggleNode(node: TreeNode): void;
dispose(): void;
}
export const sidebarTreeRuntimeKey: InjectionKey<SidebarTreeRuntime> = Symbol("sidebar-tree-runtime");
export function createSidebarSelectionSnapshot(nodes: readonly TreeNode[], selectedIds: readonly string[]): SidebarSelectionSnapshot {
const selected = new Set(selectedIds);
const targets = nodes.filter((node) => selected.has(node.id)).map(createSidebarActionTarget);
return Object.freeze({
ids: Object.freeze([...selectedIds]),
targets: Object.freeze(targets),
});
}
export function createSidebarTreeRuntime(): SidebarTreeRuntime {
const runtimeId = Symbol("sidebar-tree-runtime-instance");
let host: SidebarTreeRuntimeHost | null = null;
let generation = 0;
let disposed = false;
let hostBindings = 0;
let menuBuilds = 0;
function currentHost(): SidebarTreeRuntimeHost | null {
return disposed ? null : host;
}
return {
runtimeId,
get diagnostics() {
return { hostBindings, menuBuilds };
},
bindHost(nextHost) {
if (disposed) return;
host = nextHost;
if (nextHost) hostBindings += 1;
},
beginAction() {
generation += 1;
return Object.freeze({ runtimeId, generation });
},
isCurrent(token) {
return !disposed && token.runtimeId === runtimeId && token.generation === generation;
},
buildContextMenu(node) {
menuBuilds += 1;
return currentHost()?.buildContextMenu(node) ?? [];
},
handleRowClick(node, clickDetail) {
currentHost()?.handleRowClick(node, clickDetail);
},
handleRowDoubleClick(node, event) {
currentHost()?.handleRowDoubleClick(node, event);
},
handleRowKeydown(node, event) {
currentHost()?.handleRowKeydown(node, event);
},
openDataInNewTab(node) {
currentHost()?.openDataInNewTab(node);
},
requestPaste(node) {
return currentHost()?.requestPaste(node) ?? false;
},
toggleNode(node) {
currentHost()?.toggleNode(node);
},
dispose() {
if (disposed) return;
disposed = true;
generation += 1;
host = null;
},
};
}