refactor(desktop): organize lib modules by domain

This commit is contained in:
t8y2 committed 2026-07-04 13:53:52 +08:00
1 parent 90f0594e93
commit 7e7c4944e9
700 files changed
+1292 -1264

No files matched your search

@@ -0,0 +1,242 @@
import { SIDEBAR_TREE_ROW_HEIGHT, type FlatTreeNode } from "@/composables/useFlatTree";
import type { QueryTab, TreeNode } from "@/types/database";
export type ActiveTabSidebarTarget =
| {
type: "table";
connectionId: string;
database: string;
schema?: string;
tableName: string;
}
| {
type: "mongo-collection";
connectionId: string;
database: string;
collectionName: string;
}
| {
type: "mongo-gridfs";
connectionId: string;
database: string;
}
| {
type: "vector-collection";
connectionId: string;
collectionName: string;
}
| {
type: "etcd-root";
connectionId: string;
}
| {
type: "zookeeper-root";
connectionId: string;
}
| {
type: "mq-tenant";
connectionId: string;
tenant: string;
}
| {
type: "nacos-namespace";
connectionId: string;
namespace: string;
}
| {
type: "query-context";
connectionId: string;
database: string;
schema?: string;
}
| {
type: "saved-sql-file";
savedSqlId: string;
};
export function activeTabSidebarTarget(tab: QueryTab | undefined | null): ActiveTabSidebarTarget | null {
if (!tab) return null;
if (tab.mode === "data") {
const tableName = tab.tableMeta?.tableName || tab.title;
if (!tableName) return null;
return {
type: "table",
connectionId: tab.connectionId,
database: tab.database,
schema: tab.tableMeta?.schema ?? tab.schema,
tableName,
};
}
if (tab.mode === "mongo") {
const collectionName = tab.sql || tab.title.split(".").pop() || tab.title;
if (!collectionName) return null;
return {
type: "mongo-collection",
connectionId: tab.connectionId,
database: tab.database,
collectionName,
};
}
if (tab.mode === "mongo-bucket") {
return {
type: "mongo-gridfs",
connectionId: tab.connectionId,
database: tab.database,
};
}
if (tab.mode === "mongo-gridfs") {
return {
type: "mongo-gridfs",
connectionId: tab.connectionId,
database: tab.database,
};
}
if (tab.mode === "vector") {
const collectionName = tab.sql || tab.title;
if (!collectionName) return null;
return {
type: "vector-collection",
connectionId: tab.connectionId,
collectionName,
};
}
if (tab.mode === "etcd") {
return { type: "etcd-root", connectionId: tab.connectionId };
}
if (tab.mode === "zookeeper") {
return { type: "zookeeper-root", connectionId: tab.connectionId };
}
if (tab.mode === "mq" && tab.mqTenant) {
return { type: "mq-tenant", connectionId: tab.connectionId, tenant: tab.mqTenant };
}
if (tab.mode === "nacos") {
return { type: "nacos-namespace", connectionId: tab.connectionId, namespace: tab.nacosNamespace || "" };
}
if (tab.savedSqlId) {
return { type: "saved-sql-file", savedSqlId: tab.savedSqlId };
}
if (tab.mode === "query") {
if (!tab.connectionId || !tab.database) return null;
return {
type: "query-context",
connectionId: tab.connectionId,
database: tab.database,
schema: tab.schema,
};
}
return null;
}
function schemaMatches(node: TreeNode, schema: string | undefined): boolean {
if (!schema) return true;
return (node.schema || "") === schema;
}
export function matchesTarget(node: TreeNode, target: ActiveTabSidebarTarget): boolean {
if (target.type === "mongo-collection") {
if (node.type === "elasticsearch-index") {
return node.connectionId === target.connectionId && node.label === target.collectionName;
}
return node.type === "mongo-collection" && node.connectionId === target.connectionId && node.database === target.database && node.label === target.collectionName;
}
if (target.type === "mongo-gridfs") {
return node.type === "mongo-gridfs" && node.connectionId === target.connectionId && node.database === target.database;
}
if (target.type === "vector-collection") {
return node.type === "vector-collection" && node.connectionId === target.connectionId && node.label === target.collectionName;
}
if (target.type === "query-context") {
if (target.schema) {
return node.type === "schema" && node.connectionId === target.connectionId && node.database === target.database && node.label === target.schema;
}
return node.type === "database" && node.connectionId === target.connectionId && node.label === target.database;
}
if (target.type === "etcd-root") {
return node.type === "etcd-root" && node.connectionId === target.connectionId;
}
if (target.type === "zookeeper-root") {
return node.type === "zookeeper-root" && node.connectionId === target.connectionId;
}
if (target.type === "mq-tenant") {
return node.type === "mq-tenant" && node.connectionId === target.connectionId && (node.mqTenant || node.label) === target.tenant;
}
if (target.type === "nacos-namespace") {
return node.type === "nacos-namespace" && node.connectionId === target.connectionId && (node.nacosNamespace || "") === target.namespace;
}
if (target.type === "saved-sql-file") {
return node.type === "saved-sql-file" && node.savedSqlId === target.savedSqlId;
}
return (node.type === "table" || node.type === "view" || node.type === "materialized_view") && node.connectionId === target.connectionId && node.database === target.database && schemaMatches(node, target.schema) && node.label === target.tableName;
}
export function findSidebarNodeForActiveTab(tab: QueryTab | undefined | null, flatNodes: readonly FlatTreeNode[]): FlatTreeNode | null {
const target = activeTabSidebarTarget(tab);
if (!target) return null;
return findSidebarNodeForTarget(target, flatNodes);
}
export function findSidebarNodeForTarget(target: ActiveTabSidebarTarget, flatNodes: readonly FlatTreeNode[]): FlatTreeNode | null {
return flatNodes.find((item) => matchesTarget(item.node, target)) ?? null;
}
export function shouldScrollActiveSidebarSelection(options: { activeTabId: string | null | undefined; previousActiveTabId: string | null | undefined; autoSelectEnabled: boolean; previousAutoSelectEnabled: boolean | undefined }): boolean {
if (!options.autoSelectEnabled) return false;
return options.activeTabId !== options.previousActiveTabId || (options.autoSelectEnabled && options.previousAutoSelectEnabled === false);
}
export function scrollTopForSidebarNode(options: { index: number; currentScrollTop: number; viewportHeight: number; rowHeight?: number; topOcclusionHeight?: number }): number {
const rowHeight = options.rowHeight ?? SIDEBAR_TREE_ROW_HEIGHT;
if (options.index < 0 || options.viewportHeight <= 0) return options.currentScrollTop;
const rowTop = options.index * rowHeight;
const rowBottom = rowTop + rowHeight;
const viewportTop = options.currentScrollTop + (options.topOcclusionHeight ?? 0);
const viewportBottom = options.currentScrollTop + options.viewportHeight;
if (rowTop < viewportTop) return Math.max(0, rowTop - (options.topOcclusionHeight ?? 0));
if (rowBottom > viewportBottom) return Math.max(0, rowBottom - options.viewportHeight);
return options.currentScrollTop;
}
export function findNodePathForActiveTab(tab: QueryTab | undefined | null, treeNodes: readonly TreeNode[]): TreeNode[] | null {
const target = activeTabSidebarTarget(tab);
if (!target) return null;
return findNodePathForTarget(target, treeNodes);
}
export function findNodePathForTarget(target: ActiveTabSidebarTarget, treeNodes: readonly TreeNode[]): TreeNode[] | null {
return findPath(treeNodes, (node) => matchesTarget(node, target));
}
function findPath(nodes: readonly TreeNode[], predicate: (node: TreeNode) => boolean, path: TreeNode[] = []): TreeNode[] | null {
for (const node of nodes) {
const currentPath = [...path, node];
if (predicate(node)) return currentPath;
if (node.children) {
const result = findPath(node.children, predicate, currentPath);
if (result) return result;
}
}
return null;
}
@@ -0,0 +1,47 @@
import type { TreeNode } from "@/types/database";
type ConnectionTreeNode = TreeNode & { connectionId: string };
export function isConnectionNode(node: TreeNode): node is ConnectionTreeNode {
return node.type === "connection" && !!node.connectionId;
}
function selectedConnectionActionTargets(currentNode: TreeNode, selectedNodes: TreeNode[]): ConnectionTreeNode[] {
if (!isConnectionNode(currentNode)) return [];
const selectedContainsCurrent = selectedNodes.some((node) => node.id === currentNode.id);
if (selectedNodes.length > 1 && selectedContainsCurrent && selectedNodes.every(isConnectionNode)) {
return selectedNodes;
}
return [currentNode];
}
export function selectedConnectionDeleteTargets(currentNode: TreeNode, selectedNodes: TreeNode[]): ConnectionTreeNode[] {
return selectedConnectionActionTargets(currentNode, selectedNodes);
}
export function selectedConnectionDuplicateTargets(currentNode: TreeNode, selectedNodes: TreeNode[]): ConnectionTreeNode[] {
return selectedConnectionActionTargets(currentNode, selectedNodes);
}
export function selectedConnectionClipboardTargets(currentNode: TreeNode, selectedNodes: TreeNode[]): ConnectionTreeNode[] {
return selectedConnectionActionTargets(currentNode, selectedNodes);
}
export function selectedConnectionEditTarget(currentNode: TreeNode, selectedNodes: TreeNode[]): ConnectionTreeNode | null {
if (!isConnectionNode(currentNode)) return null;
const selectedContainsCurrent = selectedNodes.some((node) => node.id === currentNode.id);
if (selectedNodes.length > 1 && selectedContainsCurrent) return null;
return currentNode;
}
export function selectedConnectionClipboardNodes(selectedNodes: TreeNode[]): ConnectionTreeNode[] {
if (selectedNodes.length === 0 || !selectedNodes.every(isConnectionNode)) return [];
return selectedNodes;
}
export function connectionPasteTargetGroupId(node: TreeNode | null | undefined, groupIdForConnection: (connectionId: string) => string | null): string | null {
if (!node) return null;
if (node.type === "connection-group") return node.id;
if (isConnectionNode(node)) return groupIdForConnection(node.connectionId);
return null;
}
@@ -0,0 +1,9 @@
import type { TreeNode } from "@/types/database";
export function isSidebarDatabaseOpened(node: TreeNode, isTreeNodeChildrenLoaded: (nodeId: string) => boolean): boolean {
return (node.type === "database" || node.type === "mongo-db") && !!node.connectionId && node.database != null && isTreeNodeChildrenLoaded(node.id);
}
export function canCloseSidebarDatabaseConnection(node: TreeNode, isTreeNodeChildrenLoaded: (nodeId: string) => boolean): boolean {
return node.type === "database" && !!node.connectionId && node.database != null && isTreeNodeChildrenLoaded(node.id);
}
@@ -0,0 +1,3 @@
export function shouldMeasureSidebarLabelOverflow(options: { hasDetailTooltip: boolean; isRenaming: boolean; usesFullWidthLabel: boolean }): boolean {
return !options.isRenaming && !options.hasDetailTooltip && !options.usesFullWidthLabel;
}
@@ -0,0 +1,325 @@
import type { ConnectionConfig, ConnectionGroup, SidebarLayout, SidebarOrderEntry, TreeNode } from "@/types/database";
import { uuid } from "@/lib/common/utils";
export function emptyLayout(): SidebarLayout {
return { groups: [], order: [] };
}
function entryChildren(entry: Extract<SidebarOrderEntry, { type: "group" }>): SidebarOrderEntry[] {
return entry.children ?? entry.connectionIds?.map((id) => ({ type: "connection" as const, id })) ?? [];
}
function normalizeEntry(entry: SidebarOrderEntry, validIds: Set<string>, validGroups: Set<string>, seenConnections: Set<string>, seenGroups: Set<string>): SidebarOrderEntry | null {
if (entry.type === "connection") {
if (!validIds.has(entry.id) || seenConnections.has(entry.id)) return null;
seenConnections.add(entry.id);
return { type: "connection", id: entry.id };
}
if (!validGroups.has(entry.id) || seenGroups.has(entry.id)) return null;
seenGroups.add(entry.id);
const children = entryChildren(entry)
.map((child) => normalizeEntry(child, validIds, validGroups, seenConnections, seenGroups))
.filter(Boolean) as SidebarOrderEntry[];
return { type: "group", id: entry.id, children };
}
export function reconcileLayout(connectionIds: string[], layout: SidebarLayout | null): SidebarLayout {
if (!layout) {
return {
groups: [],
order: connectionIds.map((id) => ({ type: "connection" as const, id })),
};
}
const validIds = new Set(connectionIds);
const validGroups = new Set(layout.groups.map((group) => group.id));
const seenConnections = new Set<string>();
const seenGroups = new Set<string>();
const order = layout.order.map((entry) => normalizeEntry(entry, validIds, validGroups, seenConnections, seenGroups)).filter(Boolean) as SidebarOrderEntry[];
for (const id of connectionIds) {
if (!seenConnections.has(id)) {
order.push({ type: "connection", id });
}
}
const usedGroupIds = new Set<string>();
const collectGroups = (entries: SidebarOrderEntry[]) => {
for (const entry of entries) {
if (entry.type !== "group") continue;
usedGroupIds.add(entry.id);
collectGroups(entryChildren(entry));
}
};
collectGroups(order);
const groups = layout.groups.filter((group) => usedGroupIds.has(group.id));
return { groups, order };
}
export function remapSidebarLayoutConnectionIds(layout: SidebarLayout, connectionIdMap: Map<string, string>): SidebarLayout {
const remapEntries = (entries: SidebarOrderEntry[]): SidebarOrderEntry[] =>
entries.flatMap((entry): SidebarOrderEntry[] => {
if (entry.type === "connection") {
const id = connectionIdMap.get(entry.id);
return id ? [{ type: "connection", id }] : [];
}
const children = entryChildren(entry).flatMap((child): SidebarOrderEntry[] => remapEntries([child]));
return [{ type: "group", id: entry.id, children }];
});
return {
groups: layout.groups.map((group) => ({ ...group })),
order: remapEntries(layout.order),
};
}
function makeConnectionNode(config: ConnectionConfig, pinned: boolean): TreeNode {
return {
id: config.id,
label: config.name,
type: "connection",
connectionId: config.id,
isExpanded: false,
children: [],
pinned,
};
}
function orderPinnedFirst(nodes: TreeNode[]): TreeNode[] {
const pinned: TreeNode[] = [];
const unpinned: TreeNode[] = [];
for (const node of nodes) {
if (node.pinned) pinned.push(node);
else unpinned.push(node);
}
return [...pinned, ...unpinned];
}
export function buildTreeNodesFromLayout(layout: SidebarLayout, connections: ConnectionConfig[], pinnedIds: Set<string>): TreeNode[] {
const configMap = new Map(connections.map((connection) => [connection.id, connection]));
const groupMap = new Map(layout.groups.map((group) => [group.id, group]));
const build = (entries: SidebarOrderEntry[]): TreeNode[] => {
const nodes: TreeNode[] = [];
for (const entry of entries) {
if (entry.type === "connection") {
const config = configMap.get(entry.id);
if (config) nodes.push(makeConnectionNode(config, pinnedIds.has(entry.id)));
continue;
}
const group = groupMap.get(entry.id);
if (!group) continue;
nodes.push({
id: group.id,
label: group.name,
type: "connection-group",
pinned: pinnedIds.has(group.id),
isExpanded: !group.collapsed,
children: orderPinnedFirst(build(entryChildren(entry))),
});
}
return nodes;
};
return orderPinnedFirst(build(layout.order));
}
export function findConnectionLocation(layout: SidebarLayout, connectionId: string): { entries: SidebarOrderEntry[]; entryIndex: number; groupId?: string } | null {
const visit = (entries: SidebarOrderEntry[], groupId?: string): { entries: SidebarOrderEntry[]; entryIndex: number; groupId?: string } | null => {
for (let i = 0; i < entries.length; i++) {
const entry = entries[i];
if (entry.type === "connection" && entry.id === connectionId) return { entries, entryIndex: i, groupId };
if (entry.type === "group") {
const found = visit(entryChildren(entry), entry.id);
if (found) return found;
}
}
return null;
};
return visit(layout.order);
}
function findGroupEntry(entries: SidebarOrderEntry[], groupId: string): Extract<SidebarOrderEntry, { type: "group" }> | null {
for (const entry of entries) {
if (entry.type !== "group") continue;
if (entry.id === groupId) return entry;
const found = findGroupEntry(entryChildren(entry), groupId);
if (found) return found;
}
return null;
}
function cloneEntries(entries: SidebarOrderEntry[]): SidebarOrderEntry[] {
return entries.map((entry) => (entry.type === "group" ? { type: "group", id: entry.id, children: cloneEntries(entryChildren(entry)) } : { ...entry }));
}
function removeEntry(entries: SidebarOrderEntry[], id: string): SidebarOrderEntry | null {
for (let i = 0; i < entries.length; i++) {
const entry = entries[i];
if ((entry.type === "connection" && entry.id === id) || (entry.type === "group" && entry.id === id)) {
entries.splice(i, 1);
return entry;
}
if (entry.type === "group") {
const removed = removeEntry(entry.children ?? [], id);
if (removed) return removed;
}
}
return null;
}
function removeConnectionFromEntries(entries: SidebarOrderEntry[], connectionId: string): SidebarOrderEntry[] {
const next = cloneEntries(entries);
removeEntry(next, connectionId);
return next;
}
function containsGroup(entry: SidebarOrderEntry, groupId: string): boolean {
if (entry.type !== "group") return false;
if (entry.id === groupId) return true;
return entryChildren(entry).some((child) => containsGroup(child, groupId));
}
function expandGroup(layout: SidebarLayout, groupId: string): SidebarLayout {
return {
...layout,
groups: layout.groups.map((group) => (group.id === groupId ? { ...group, collapsed: false } : group)),
};
}
export function moveConnectionToGroup(layout: SidebarLayout, connectionId: string, targetGroupId: string | null): SidebarLayout {
const order = removeConnectionFromEntries(layout.order, connectionId);
const entry: SidebarOrderEntry = { type: "connection", id: connectionId };
if (targetGroupId) {
const group = findGroupEntry(order, targetGroupId);
if (group) {
group.children = [...(group.children ?? []), entry];
return { ...expandGroup(layout, targetGroupId), order };
}
}
order.push(entry);
return { ...layout, order };
}
export type DropPosition = "before" | "after" | "inside";
export function reorderEntry(layout: SidebarLayout, draggedId: string, targetId: string, position: DropPosition): SidebarLayout {
if (draggedId === targetId) return layout;
const order = cloneEntries(layout.order);
const dragged = removeEntry(order, draggedId);
if (!dragged) return layout;
if (dragged.type === "group" && containsGroup(dragged, targetId)) return layout;
if (position === "inside") {
const targetGroup = findGroupEntry(order, targetId);
if (targetGroup) {
targetGroup.children = [...(targetGroup.children ?? []), dragged];
return { ...layout, order };
}
}
const insertNear = (entries: SidebarOrderEntry[]): boolean => {
for (let i = 0; i < entries.length; i++) {
const entry = entries[i];
if ((entry.type === "connection" && entry.id === targetId) || (entry.type === "group" && entry.id === targetId)) {
entries.splice(position === "after" ? i + 1 : i, 0, dragged);
return true;
}
if (entry.type === "group" && insertNear(entry.children ?? [])) return true;
}
return false;
};
if (!insertNear(order)) order.push(dragged);
return { ...layout, order };
}
export function createGroup(layout: SidebarLayout, name: string, parentGroupId?: string | null): { layout: SidebarLayout; groupId: string } {
const groupId = uuid();
const group: ConnectionGroup = { id: groupId, name, collapsed: false };
const order = cloneEntries(layout.order);
const entry: SidebarOrderEntry = { type: "group", id: groupId, children: [] };
let parentFound = false;
if (parentGroupId) {
const parent = findGroupEntry(order, parentGroupId);
if (parent) {
parent.children = [...(parent.children ?? []), entry];
parentFound = true;
} else {
order.push(entry);
}
} else {
order.push(entry);
}
return {
groupId,
layout: {
groups: [...layout.groups, group].map((current) => (parentFound && current.id === parentGroupId ? { ...current, collapsed: false } : current)),
order,
},
};
}
export function renameGroup(layout: SidebarLayout, groupId: string, name: string): SidebarLayout {
return {
...layout,
groups: layout.groups.map((group) => (group.id === groupId ? { ...group, name } : group)),
};
}
export function deleteGroup(layout: SidebarLayout, groupId: string): SidebarLayout {
const order = cloneEntries(layout.order);
const removeGroup = (entries: SidebarOrderEntry[]): boolean => {
for (let i = 0; i < entries.length; i++) {
const entry = entries[i];
if (entry.type === "group" && entry.id === groupId) {
entries.splice(i, 1, ...entryChildren(entry));
return true;
}
if (entry.type === "group") {
const removed = removeGroup(entry.children ?? []);
if (removed) return true;
}
}
return false;
};
const removed = removeGroup(order);
return {
groups: removed ? layout.groups.filter((group) => group.id !== groupId) : layout.groups,
order,
};
}
export function toggleGroupCollapsed(layout: SidebarLayout, groupId: string): SidebarLayout {
return {
...layout,
groups: layout.groups.map((group) => (group.id === groupId ? { ...group, collapsed: !group.collapsed } : group)),
};
}
export function collapseAllGroups(layout: SidebarLayout): SidebarLayout {
return {
...layout,
groups: layout.groups.map((group) => (group.collapsed ? group : { ...group, collapsed: true })),
};
}
export function removeConnectionFromSidebarLayout(layout: SidebarLayout, connectionId: string): SidebarLayout {
return { ...layout, order: removeConnectionFromEntries(layout.order, connectionId) };
}
export function appendConnectionToLayout(layout: SidebarLayout, connectionId: string, groupId?: string | null): SidebarLayout {
return moveConnectionToGroup(layout, connectionId, groupId ?? null);
}
@@ -0,0 +1,75 @@
import type { DatabaseType, TreeNode } from "@/types/database";
const sidebarTreeCollator = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" });
function sortByLabel(nodes: readonly TreeNode[]): TreeNode[] {
return [...nodes].sort((left, right) => sidebarTreeCollator.compare(left.label, right.label));
}
function sortRecursive(node: TreeNode, databaseType?: DatabaseType): TreeNode {
const children = node.children ? sortSidebarTreeChildrenForParent(node, node.children, databaseType) : node.children;
const hiddenChildren = node.hiddenChildren ? sortSidebarTreeChildrenForParent(node, node.hiddenChildren, databaseType) : node.hiddenChildren;
if (children === node.children && hiddenChildren === node.hiddenChildren) return node;
return {
...node,
children,
hiddenChildren,
};
}
export function sortSidebarTreeChildrenForParent(parent: Pick<TreeNode, "type">, children: readonly TreeNode[], databaseType?: DatabaseType): TreeNode[] {
const normalized = children.map((child) => sortRecursive(child, databaseType));
if (parent.type === "mongo-db") {
const gridFsNodes = normalized.filter((child) => child.type === "mongo-gridfs");
const collections = normalized.filter((child) => child.type !== "mongo-gridfs");
return [...gridFsNodes, ...sortByLabel(collections)];
}
if (parent.type === "mongo-buckets") {
return sortByLabel(normalized);
}
if (parent.type === "connection") {
const savedSqlNodes = normalized.filter((child) => child.type === "saved-sql-root");
const userAdminNodes = normalized.filter((child) => child.type === "user-admin");
const regularChildren = normalized.filter((child) => child.type !== "user-admin" && child.type !== "saved-sql-root");
const withConnectionUtilityOrder = (children: TreeNode[]) => [...savedSqlNodes, ...children, ...userAdminNodes];
if (databaseType === "mongodb" || databaseType === "elasticsearch" || databaseType === "qdrant" || databaseType === "milvus" || databaseType === "weaviate" || databaseType === "chromadb") {
return withConnectionUtilityOrder(sortByLabel(regularChildren));
}
if (databaseType === "duckdb") {
const schemas = sortByLabel(regularChildren.filter((child) => child.type === "schema"));
const databases = sortByLabel(regularChildren.filter((child) => child.type === "database"));
const rest = regularChildren.filter((child) => child.type !== "schema" && child.type !== "database");
return withConnectionUtilityOrder([...schemas, ...databases, ...rest]);
}
if (regularChildren.every((child) => child.type === "database")) {
return withConnectionUtilityOrder(sortByLabel(regularChildren));
}
if (regularChildren.every((child) => child.type === "schema")) {
return withConnectionUtilityOrder(sortByLabel(regularChildren));
}
return withConnectionUtilityOrder(regularChildren);
}
if (parent.type === "database") {
if (databaseType === "sqlserver") {
const objectGroups = normalized.filter((child) => child.type.startsWith("group-"));
const schemas = sortByLabel(normalized.filter((child) => child.type === "schema"));
const rest = normalized.filter((child) => !child.type.startsWith("group-") && child.type !== "schema");
return [...objectGroups, ...schemas, ...rest];
}
if (normalized.every((child) => child.type === "schema")) {
return sortByLabel(normalized);
}
}
return normalized;
}
@@ -0,0 +1,24 @@
type RenameInput = Pick<HTMLInputElement, "focus" | "select">;
type FrameScheduler = (callback: () => void) => number;
type PendingRenameFocusRestore = { value: boolean };
const scheduleAnimationFrame: FrameScheduler = (callback) => {
if (typeof requestAnimationFrame === "function") {
return requestAnimationFrame(callback);
}
return setTimeout(callback, 0) as unknown as number;
};
export function focusSidebarRenameInput(getInput: () => RenameInput | undefined, schedule: FrameScheduler = scheduleAnimationFrame) {
schedule(() => {
const input = getInput();
input?.focus();
input?.select();
});
}
export function shouldPreventRenameCloseAutoFocus(pending: PendingRenameFocusRestore): boolean {
if (!pending.value) return false;
pending.value = false;
return true;
}
@@ -0,0 +1,68 @@
import { parseSlashDelimitedRegexQuery } from "@/lib/common/searchPattern";
export type SidebarSearchMatchKind = "exact" | "prefix" | "word-prefix" | "substring" | "abbreviation" | "fuzzy" | "regex";
export interface SidebarSearchMatch {
kind: SidebarSearchMatchKind;
score: number;
}
export type SidebarLabelMatcher = (label: string) => SidebarSearchMatch | null;
function isWordBoundary(text: string, index: number): boolean {
if (index === 0) return true;
const prev = text[index - 1];
return prev === "_" || prev === "-" || prev === "." || prev === " " || prev === "/" || prev === "\\";
}
function matchesWordPrefix(text: string, query: string): boolean {
for (let i = 0; i < text.length; i++) {
if (isWordBoundary(text, i) && text.startsWith(query, i)) return true;
}
return false;
}
function matchesAbbreviation(text: string, query: string): boolean {
let j = 0;
for (let i = 0; i < text.length && j < query.length; i++) {
if (isWordBoundary(text, i) && text[i] === query[j]) j++;
}
return j === query.length;
}
function matchesSubsequence(text: string, query: string): boolean {
if (query.length < 2 || query.length > text.length) return false;
let j = 0;
for (let i = 0; i < text.length && j < query.length; i++) {
if (isWordBoundary(text, i) && i > 0) {
j = 0;
}
if (text[i] === query[j]) j++;
}
return j === query.length;
}
function matchSidebarLabelWithRegex(label: string, query: string, regex: RegExp | null): SidebarSearchMatch | null {
if (!query) return null;
if (regex) return regex.test(label) ? { kind: "regex", score: 95 } : null;
if (label === query) return { kind: "exact", score: 100 };
if (label.startsWith(query)) return { kind: "prefix", score: 90 };
if (matchesWordPrefix(label, query)) return { kind: "word-prefix", score: 80 };
if (label.includes(query)) return { kind: "substring", score: 70 };
if (query.length >= 2 && matchesAbbreviation(label, query)) return { kind: "abbreviation", score: 60 };
if (matchesSubsequence(label, query)) return { kind: "fuzzy", score: 40 };
return null;
}
export function createSidebarLabelMatcher(query: string): SidebarLabelMatcher {
const regex = parseSlashDelimitedRegexQuery(query);
return (label) => matchSidebarLabelWithRegex(label, query, regex);
}
export function matchSidebarLabel(label: string, query: string): SidebarSearchMatch | null {
return matchSidebarLabelWithRegex(label, query, parseSlashDelimitedRegexQuery(query));
}
@@ -0,0 +1,72 @@
import type { TreeNode, TreeNodeType } from "@/types/database";
import { createSidebarLabelMatcher, type SidebarLabelMatcher } from "@/lib/sidebar/sidebarSearch";
const preserveMatchedSubtreeTypes = new Set(["connection", "database", "schema", "table", "view"]);
const normalizedLabelCache = new WeakMap<TreeNode, { label: string; normalized: string }>();
function bestMatch(matchLabel: SidebarLabelMatcher, label: string, comment?: string | null) {
const lm = matchLabel(label);
if (!comment) return lm;
const cm = matchLabel(comment.toLowerCase());
if (lm && cm) return lm.score >= cm.score ? lm : cm;
return lm ?? cm;
}
function normalizedLabel(node: TreeNode): string {
const cached = normalizedLabelCache.get(node);
if (cached?.label === node.label) return cached.normalized;
const normalized = node.label.toLowerCase();
normalizedLabelCache.set(node, { label: node.label, normalized });
return normalized;
}
export function filterSidebarTree(nodes: TreeNode[], query: string, collapsedIds: ReadonlySet<string>, searchableNodeTypes?: ReadonlySet<TreeNodeType>): TreeNode[] {
return filterSidebarTreeWithMatcher(nodes, createSidebarLabelMatcher(query), collapsedIds, searchableNodeTypes);
}
function filterSidebarTreeWithMatcher(nodes: TreeNode[], matchLabel: SidebarLabelMatcher, collapsedIds: ReadonlySet<string>, searchableNodeTypes?: ReadonlySet<TreeNodeType>): TreeNode[] {
const filteredNodes: { node: TreeNode; score: number }[] = [];
for (const node of nodes) {
if (node.type === "object-browser" && node.hiddenChildren) {
const matches = node.hiddenChildren.map((child) => ({ node: child, score: matchLabel(normalizedLabel(child))?.score ?? 0 })).filter((match) => match.score > 0);
filteredNodes.push(...matches);
continue;
}
const label = normalizedLabel(node);
const canSelfMatch = !searchableNodeTypes || searchableNodeTypes.has(node.type);
const selfMatch = canSelfMatch ? bestMatch(matchLabel, label, node.comment) : null;
const preservesSubtree = !!selfMatch && preserveMatchedSubtreeTypes.has(node.type);
const filteredChildren = preservesSubtree ? node.children : node.children ? filterSidebarTreeWithMatcher(node.children, matchLabel, collapsedIds, searchableNodeTypes) : undefined;
if (selfMatch || (filteredChildren && filteredChildren.length > 0)) {
if (!node.children) {
filteredNodes.push({ node, score: selfMatch?.score ?? 0 });
} else {
const children = filteredChildren ?? [];
filteredNodes.push({
node: {
...node,
children,
isLoading: node.isLoading,
isExpanded: children.length > 0 && !collapsedIds.has(node.id),
},
score: selfMatch?.score ?? 0,
});
}
}
}
filteredNodes.sort((a, b) => b.score - a.score);
return filteredNodes.map((match) => match.node);
}
export function filterSidebarSearchRootsByConnectionState(nodes: TreeNode[], connectedIds: ReadonlySet<string>): TreeNode[] {
return nodes.filter((node) => {
if (node.type === "connection-group" || node.type === "connection") return true;
return node.connectionId ? connectedIds.has(node.connectionId) : true;
});
}
@@ -0,0 +1,19 @@
export function normalizeSidebarHiddenTablePrefixes(value: unknown): string[] {
const rawPrefixes = typeof value === "string" ? value.split(/\r?\n/) : Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
const seen = new Set<string>();
const prefixes: string[] = [];
for (const rawPrefix of rawPrefixes) {
const prefix = rawPrefix.trim();
if (!prefix || seen.has(prefix)) continue;
seen.add(prefix);
prefixes.push(prefix);
}
return prefixes.sort((a, b) => b.length - a.length);
}
export function sidebarDisplayTableName(name: string, prefixes: readonly string[]): string {
const prefix = [...prefixes].sort((a, b) => b.length - a.length).find((item) => name.startsWith(item) && name.length > item.length);
return prefix ? `...${name.slice(prefix.length)}` : name;
}
@@ -0,0 +1,17 @@
import type { TreeNode } from "@/types/database";
export function collapseExpandedTreeNodes(nodes: TreeNode[]): number {
let collapsedCount = 0;
for (const node of nodes) {
if (node.isExpanded) {
node.isExpanded = false;
collapsedCount += 1;
}
if (node.children?.length) {
collapsedCount += collapseExpandedTreeNodes(node.children);
}
}
return collapsedCount;
}
@@ -0,0 +1,9 @@
import type { InjectionKey } from "vue";
import type { TreeNode } from "@/types/database";
export interface SidebarTreeContext {
getVisibleNodes: () => TreeNode[];
getVisibleNodeIndex: (id: string) => number;
}
export const sidebarTreeContextKey: InjectionKey<SidebarTreeContext> = Symbol("sidebar-tree-context");
@@ -0,0 +1,69 @@
import type { TreeNodeType } from "@/types/database";
const leafTypes: Set<TreeNodeType> = new Set([
"column",
"index",
"fkey",
"trigger",
"procedure",
"function",
"package",
"package-body",
"object-browser",
"redis-db",
"mq-tenant",
"zookeeper-root",
"mongo-gridfs",
"mongo-bucket",
"vector-collection",
"elasticsearch-index",
"user-admin",
"saved-sql-file",
"load-more",
]);
const fullWidthLabelTypes: Set<TreeNodeType> = new Set(["table", "view", "materialized_view", "mongo-collection", "mongo-bucket", "vector-collection", "elasticsearch-index"]);
const emptyContainerTypes: Set<TreeNodeType> = new Set(["saved-sql-root", "saved-sql-folder"]);
const pinnableTypes: Set<TreeNodeType> = new Set([
"connection-group",
"database",
"linked-server",
"linked-server-catalog",
"linked-server-schema",
"schema",
"table",
"view",
"materialized_view",
"redis-db",
"mongo-db",
"mongo-gridfs",
"mongo-bucket",
"mongo-collection",
"vector-collection",
"elasticsearch-index",
"nacos-namespace",
]);
export function treeItemPaddingLeft(depth: number): string {
return `${depth * 16 + 8}px`;
}
export function usesFullWidthTreeLabel(type: TreeNodeType, allowHorizontalScroll: boolean): boolean {
return allowHorizontalScroll && fullWidthLabelTypes.has(type);
}
export function canTreeNodeExpand(type: TreeNodeType): boolean {
return !leafTypes.has(type);
}
export function canTreeNodeShowExpander({ type, childCount }: { type: TreeNodeType; childCount?: number }): boolean {
if (!canTreeNodeExpand(type)) return false;
if (childCount === 0 && emptyContainerTypes.has(type)) return false;
return true;
}
export function canTreeNodePin(type: TreeNodeType): boolean {
return pinnableTypes.has(type);
}
@@ -0,0 +1,21 @@
import type { TreeNode } from "@/types/database";
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 treeSelectionRangeIdsByIndex(visibleNodes: TreeNode[], currentIndex: number, anchorIndex: number, currentId?: string): string[] {
if (anchorIndex < 0 || currentIndex < 0) return currentId ? [currentId] : [];
const start = Math.min(anchorIndex, currentIndex);
const end = Math.max(anchorIndex, currentIndex);
return visibleNodes.slice(start, end + 1).map((node) => node.id);
}
export function treeSelectionRangeIds(visibleNodes: TreeNode[], currentId: string, anchorId?: string | null, selectedId?: string | null): string[] {
const anchor = anchorId || selectedId || currentId;
const anchorIndex = visibleNodes.findIndex((node) => node.id === anchor);
const currentIndex = visibleNodes.findIndex((node) => node.id === currentId);
return treeSelectionRangeIdsByIndex(visibleNodes, currentIndex, anchorIndex, currentId);
}
@@ -0,0 +1,25 @@
export interface SidebarTypeSearchKeyEvent {
key: string;
ctrlKey?: boolean;
metaKey?: boolean;
altKey?: boolean;
isComposing?: boolean;
}
export function isEditableSidebarTypeSearchTarget(target: EventTarget | null): boolean {
if (!(target instanceof HTMLElement)) return false;
return !!target.closest("input, textarea, select, [contenteditable='true'], .cm-editor");
}
export function sidebarTypeSearchNextQuery(currentQuery: string, event: SidebarTypeSearchKeyEvent): string | null {
if (event.ctrlKey || event.metaKey || event.altKey || event.isComposing) return null;
if (event.key === "Backspace") {
if (!currentQuery) return null;
return currentQuery.slice(0, -1);
}
if (event.key.length !== 1) return null;
if (event.key === " " && !currentQuery.trim()) return null;
return `${currentQuery}${event.key}`;
}
@@ -0,0 +1,72 @@
import type { ObjectSourceKind, TreeNode, TreeNodeType } from "@/types/database";
import { matchesShortcut, type ShortcutLikeEvent } from "@/lib/editor/keyboardShortcuts";
export type TreeNodeRowAction = "open-data" | "toggle" | "none";
export type TreeNodeRowDoubleClickAction = "open-data" | "open-object-browser" | "open-object-browser-and-expand" | "open-source" | "open-saved-sql" | "toggle" | "none";
export type SidebarSelectionCopyAction = "copy-name" | "none";
export type SidebarActivation = "single" | "double";
const dataNodeTypes = new Set<TreeNodeType>(["table", "view", "materialized_view"]);
const documentBrowserNodeTypes = new Set<TreeNodeType>(["mongo-collection", "mongo-bucket"]);
const toggleLeafNodeTypes = new Set<TreeNodeType>(["redis-db", "mq-tenant", "etcd-root", "zookeeper-root", "mongo-gridfs", "mongo-collection", "mongo-bucket", "vector-collection", "elasticsearch-index", "user-admin"]);
const objectBrowserNodeTypes = new Set<TreeNodeType>(["database", "schema", "object-browser"]);
const sourceNodeTypes = new Set<TreeNodeType>(["materialized_view", "procedure", "function", "sequence", "package", "package-body"]);
const savedSqlNodeTypes = new Set<TreeNodeType>(["saved-sql-file"]);
const tableChildGroupNodeTypes = new Set<TreeNodeType>(["group-columns", "group-indexes", "group-fkeys", "group-triggers", "group-partitions"]);
const databaseChildGroupNodeTypes = new Set<TreeNodeType>(["group-tables", "group-views", "group-materialized-views", "group-procedures", "group-functions", "group-sequences", "group-packages"]);
export function objectSourceKindForTreeNode(type: TreeNodeType): ObjectSourceKind | null {
if (type === "view") return "VIEW";
if (type === "materialized_view") return "MATERIALIZED_VIEW";
if (type === "procedure") return "PROCEDURE";
if (type === "function") return "FUNCTION";
if (type === "sequence") return "SEQUENCE";
if (type === "package") return "PACKAGE";
if (type === "package-body") return "PACKAGE_BODY";
return null;
}
export function isDocumentBrowserTreeNode(type: TreeNodeType): boolean {
return documentBrowserNodeTypes.has(type);
}
export function treeNodeRowAction(type: TreeNodeType, canExpand: boolean, activation: SidebarActivation = "single"): TreeNodeRowAction {
if (activation === "double") return "none";
if (dataNodeTypes.has(type)) return "open-data";
if (toggleLeafNodeTypes.has(type)) return "toggle";
if (canExpand) return "toggle";
return "none";
}
export function shouldRunTreeNodeRowAction(action: TreeNodeRowAction, clickDetail: number): boolean {
if (action === "none") return false;
return action === "toggle" || clickDetail <= 1;
}
export function treeNodeRowDoubleClickAction(type: TreeNodeType, canOpenObjectBrowser: boolean, activation: SidebarActivation = "single", canExpand = false): TreeNodeRowDoubleClickAction {
if (activation === "double") {
if (dataNodeTypes.has(type)) return "open-data";
if (sourceNodeTypes.has(type)) return "open-source";
if (savedSqlNodeTypes.has(type)) return "open-saved-sql";
if (toggleLeafNodeTypes.has(type)) return "toggle";
if (canOpenObjectBrowser && objectBrowserNodeTypes.has(type) && canExpand) return "open-object-browser-and-expand";
if (canOpenObjectBrowser && objectBrowserNodeTypes.has(type)) return "open-object-browser";
if (canExpand) return "toggle";
}
if (canOpenObjectBrowser && objectBrowserNodeTypes.has(type)) return "open-object-browser";
return "none";
}
export function sidebarSelectionCopyAction(event: ShortcutLikeEvent): SidebarSelectionCopyAction {
return matchesShortcut(event, "Mod+C") ? "copy-name" : "none";
}
export function copyNameForTreeNode(node: TreeNode): string {
if (tableChildGroupNodeTypes.has(node.type) && node.tableName) return node.tableName;
if (databaseChildGroupNodeTypes.has(node.type)) return node.schema || node.database || node.label;
if (node.type === "column") {
if (node.meta && "name" in node.meta) return node.meta.name;
return node.label.replace(/\s+\(.+\)$/, "");
}
return node.label;
}
@@ -0,0 +1,39 @@
import type { TreeNode } from "@/types/database";
export const DEFAULT_DATABASE_TREE_LABEL = "tree.defaultDatabase";
export function hasTreeNodeDatabaseContext(node: Pick<TreeNode, "database">): node is Pick<TreeNode, "database"> & {
database: string;
} {
return node.database != null;
}
function schemaCacheKey(...parts: string[]): string {
return parts.map((part) => encodeURIComponent(part)).join(":");
}
export function treeNodeSchemaCachePrefix(node: TreeNode): string | null {
if (node.type === "connection" && node.connectionId) {
return `${schemaCacheKey(node.connectionId)}:`;
}
if (node.type === "database" && node.connectionId && hasTreeNodeDatabaseContext(node)) {
return `${schemaCacheKey(node.connectionId, node.database)}:`;
}
if (node.type === "schema" && node.connectionId && hasTreeNodeDatabaseContext(node) && node.schema) {
return `${schemaCacheKey(node.connectionId, node.database, node.schema)}:`;
}
return null;
}
export function normalizeCataloglessDatabaseNodes(nodes: TreeNode[]): TreeNode[] {
return nodes.map((node) => {
const normalized = node.type === "database" && node.database === "" && !node.label.trim() ? { ...node, label: DEFAULT_DATABASE_TREE_LABEL } : node;
return normalized.children
? {
...normalized,
children: normalizeCataloglessDatabaseNodes(normalized.children),
}
: normalized;
});
}
@@ -0,0 +1,14 @@
import type { TreeNode } from "@/types/database";
export function findDatabaseTreeNode(nodes: TreeNode[], connectionId: string, database: string): TreeNode | null {
for (const node of nodes) {
if (node.type === "database" && node.connectionId === connectionId && node.database === database) {
return node;
}
if (node.children) {
const found = findDatabaseTreeNode(node.children, connectionId, database);
if (found) return found;
}
}
return null;
}